forked from ritik4ever/stellar-goal-vault
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschemas.ts
More file actions
312 lines (272 loc) · 9.12 KB
/
Copy pathschemas.ts
File metadata and controls
312 lines (272 loc) · 9.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import { z } from "zod";
import { config } from "../config";
export const STELLAR_ACCOUNT_REGEX = /^G[A-Z2-7]{55}$/;
export const ASSET_CODE_REGEX = /^[A-Za-z0-9]{1,12}$/;
export const CAMPAIGN_ID_REGEX = /^[1-9]\d*$/;
export const TX_HASH_REGEX = /^[A-Fa-f0-9]{64}$/;
export const campaignIdSchema = z
.string()
.trim()
.regex(CAMPAIGN_ID_REGEX, "Campaign ID must be a positive integer.");
export const stellarAccountIdSchema = z
.string()
.trim()
.regex(
STELLAR_ACCOUNT_REGEX,
"Must be a valid Stellar account ID (starts with G and is exactly 56 characters).",
);
export const assetCodeSchema = z
.string()
.trim()
.regex(ASSET_CODE_REGEX, "Asset code must be 1-12 alphanumeric characters.")
.transform((value: string) => value.toUpperCase())
.refine((code: string) => config.allowedAssets.includes(code), {
message: `Asset code is not supported. Supported assets: ${config.allowedAssets.join(", ")}`,
});
export const positiveAmountSchema = z.coerce
.number()
.finite("Amount must be a valid number.")
.positive("Amount must be greater than zero.");
export const optionalPositiveIntSchema = z.coerce
.number()
.finite("Value must be a valid number.")
.int("Value must be an integer.")
.nonnegative("Value must be non-negative.")
.optional();
export const unixTimestampSchema = z.coerce
.number()
.int("deadline must be a valid UNIX timestamp in seconds.")
.positive("deadline must be a valid UNIX timestamp in seconds.");
function sanitizeInput(val: string): string {
return val
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/\//g, "/");
}
const containsSqlComment = (val: string) => /--|\/\*|\*\//.test(val);
const containsScriptTag = (val: string) => /<script/i.test(val);
export const createCampaignPayloadSchema = z.object({
creator: stellarAccountIdSchema,
title: z
.string()
.trim()
.min(4, "Title must be at least 4 characters.")
.max(80)
.refine((val) => val.trim().length >= 4, "Title cannot be only whitespace.")
.refine((val) => !containsScriptTag(val), "Title cannot contain script tags.")
.refine((val) => !containsSqlComment(val), "Title cannot contain SQL comment sequences.")
.transform((val) => sanitizeInput(val)),
description: z
.string()
.trim()
.min(20, "Description must be at least 20 characters.")
.max(500)
.refine((val) => !containsScriptTag(val), "Description cannot contain script tags.")
.refine((val) => !containsSqlComment(val), "Description cannot contain SQL comment sequences.")
.transform((val) => sanitizeInput(val)),
acceptedTokens: z
.array(assetCodeSchema)
.min(1, "At least one accepted token is required."),
targetAmount: positiveAmountSchema,
deadline: unixTimestampSchema,
metadata: z
.object({
imageUrl: z.string().url().optional(),
externalLink: z.string().url().optional(),
})
.optional(),
maxPerContributor: optionalPositiveIntSchema,
});
export const createPledgePayloadSchema = z.object({
contributor: stellarAccountIdSchema,
amount: positiveAmountSchema,
assetCode: assetCodeSchema,
});
export const reconcilePledgePayloadSchema = z.object({
contributor: stellarAccountIdSchema,
amount: positiveAmountSchema,
assetCode: assetCodeSchema,
transactionHash: z
.string()
.trim()
.regex(TX_HASH_REGEX, "transactionHash must be a 64-character hex hash."),
confirmedAt: unixTimestampSchema.optional(),
});
export const claimCampaignPayloadSchema = z.object({
creator: stellarAccountIdSchema,
transactionHash: z
.string()
.trim()
.regex(TX_HASH_REGEX, "transactionHash must be a 64-character hex hash."),
confirmedAt: unixTimestampSchema.optional(),
});
const stellarTransactionHashSchema = z
.string()
.trim()
.regex(/^[A-Fa-f0-9]{64}$/, "txHash must be a 64-character hex string.");
const sorobanRefundMetadataSchema = z.object({
txHash: stellarTransactionHashSchema,
contractId: z.string().trim().min(1, "contractId is required."),
networkPassphrase: z.string().trim().min(1, "networkPassphrase is required."),
rpcUrl: z.string().trim().url("rpcUrl must be a valid URL."),
walletAddress: stellarAccountIdSchema,
ledger: z.coerce.number().int().positive().optional(),
createdAt: unixTimestampSchema.optional(),
latestLedger: z.coerce.number().int().positive().optional(),
});
export const refundPayloadSchema = z.object({
contributor: stellarAccountIdSchema,
soroban: sorobanRefundMetadataSchema,
});
function singleCampaignListQueryParam(value: unknown): string | undefined {
if (value === undefined || value === null) {
return undefined;
}
const raw = Array.isArray(value) ? value[0] : value;
if (typeof raw !== "string" && typeof raw !== "number") {
return undefined;
}
const s = String(raw).trim();
return s === "" ? undefined : s;
}
function parsePositiveIntegerQueryParam(
value: unknown,
field: "page" | "limit" | "pageSize",
max?: number,
): { ok: true; value?: number } | { ok: false; issues: z.core.$ZodIssue[] } {
const raw = singleCampaignListQueryParam(value);
if (raw === undefined) {
return { ok: true };
}
const parsed = Number(raw);
const issues: z.core.$ZodIssue[] = [];
if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 1) {
issues.push({
code: "custom",
message: `${field} must be a positive integer.`,
path: [field],
});
} else if (max !== undefined && parsed > max) {
issues.push({
code: "custom",
message: `${field} must be an integer from 1 to ${max}.`,
path: [field],
});
}
if (issues.length > 0) {
return { ok: false, issues };
}
return { ok: true, value: parsed };
}
/**
* Parses optional `page` and `limit` for GET /api/campaigns.
* Omitting both means no pagination (caller lists the full filtered set).
* Supplying only one is invalid (400).
*/
export function parseCampaignListPaginationQuery(query: {
page?: unknown;
limit?: unknown;
}): { ok: true; page?: number; limit?: number } | { ok: false; issues: z.core.$ZodIssue[] } {
const pageStr = singleCampaignListQueryParam(query.page);
const limitStr = singleCampaignListQueryParam(query.limit);
if (pageStr === undefined && limitStr === undefined) {
return { ok: true };
}
if (pageStr === undefined || limitStr === undefined) {
return {
ok: false,
issues: [
{
code: "custom",
message: "Pagination requires both page and limit query parameters.",
path: pageStr === undefined ? ["page"] : ["limit"],
},
],
};
}
const pageNum = Number(pageStr);
const limitNum = Number(limitStr);
const issues: z.core.$ZodIssue[] = [];
if (!Number.isFinite(pageNum) || !Number.isInteger(pageNum) || pageNum < 1) {
issues.push({
code: "custom",
message: "page must be a positive integer.",
path: ["page"],
});
}
if (
!Number.isFinite(limitNum) ||
!Number.isInteger(limitNum) ||
limitNum < 1 ||
limitNum > 100
) {
issues.push({
code: "custom",
message: "limit must be an integer from 1 to 100.",
path: ["limit"],
});
}
if (issues.length > 0) {
return { ok: false, issues };
}
return { ok: true, page: pageNum, limit: limitNum };
}
export function parseHistoryPaginationQuery(query: {
page?: unknown;
pageSize?: unknown;
}): { ok: true; page: number; pageSize: number } | { ok: false; issues: z.core.$ZodIssue[] } {
const parsedPage = parsePositiveIntegerQueryParam(query.page, "page");
const parsedPageSize = parsePositiveIntegerQueryParam(query.pageSize, "pageSize", 100);
const issues: z.core.$ZodIssue[] = [];
if (!parsedPage.ok) {
issues.push(...parsedPage.issues);
}
if (!parsedPageSize.ok) {
issues.push(...parsedPageSize.issues);
}
if (issues.length > 0) {
return { ok: false, issues };
}
return {
ok: true,
page: parsedPage.ok ? (parsedPage.value ?? 1) : 1,
pageSize: parsedPageSize.ok ? (parsedPageSize.value ?? 20) : 20,
};
}
export function parsePledgeListPaginationQuery(query: {
page?: unknown;
limit?: unknown;
}): { ok: true; page: number; limit: number } | { ok: false; issues: z.core.$ZodIssue[] } {
const parsedPage = parsePositiveIntegerQueryParam(query.page, "page");
const parsedLimit = parsePositiveIntegerQueryParam(query.limit, "limit", 100);
const issues: z.core.$ZodIssue[] = [];
if (!parsedPage.ok) {
issues.push(...parsedPage.issues);
}
if (!parsedLimit.ok) {
issues.push(...parsedLimit.issues);
}
if (issues.length > 0) {
return { ok: false, issues };
}
return {
ok: true,
page: parsedPage.ok ? (parsedPage.value ?? 1) : 1,
limit: parsedLimit.ok ? (parsedLimit.value ?? 10) : 10,
};
}
export type ValidationIssue = {
field: string;
message: string;
};
export function zodIssuesToValidationIssues(issues: z.ZodIssue[]): ValidationIssue[] {
return issues.map((issue) => ({
field: issue.path.length > 0 ? issue.path.join(".") : "body",
message: issue.message,
}));
}
export function zodIssuesToErrorMessage(issues: z.ZodIssue[]): string {
return zodIssuesToValidationIssues(issues)
.map(({ field, message }) => `${field}: ${message}`)
.join("; ");
}