@donotdev/functions 0.0.14 → 0.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/firebase/index.js +1532 -575
- package/lib/firebase/index.js.map +4 -4
- package/lib/shared/index.js +333 -163
- package/lib/shared/index.js.map +4 -4
- package/lib/vercel/api/index.js +325 -190
- package/lib/vercel/api/index.js.map +4 -4
- package/package.json +4 -4
- package/src/firebase/baseFunction.ts +29 -6
- package/src/firebase/crud/create.ts +6 -1
- package/src/firebase/crud/delete.ts +7 -0
- package/src/firebase/crud/list.ts +17 -6
- package/src/firebase/crud/update.ts +2 -1
- package/src/shared/__tests__/errorHandling.test.ts +53 -72
- package/src/shared/billing/helpers/updateUserSubscription.ts +9 -0
- package/src/shared/billing/idempotency.ts +3 -3
- package/src/shared/billing/webhookHandler.ts +18 -1
- package/src/shared/errorHandling.ts +13 -79
- package/src/shared/utils/internal/auth.ts +2 -1
- package/src/shared/utils/internal/validation.ts +10 -3
- package/src/shared/utils.ts +6 -6
- package/src/supabase/baseFunction.ts +21 -2
- package/src/supabase/crud/create.ts +8 -3
- package/src/supabase/crud/delete.ts +7 -0
- package/src/supabase/crud/list.ts +24 -1
- package/src/supabase/crud/update.ts +3 -0
- package/src/supabase/utils/rateLimiter.ts +17 -6
- package/src/vercel/api/crud/get.ts +7 -2
- package/src/vercel/baseFunction.ts +37 -30
|
@@ -201,6 +201,16 @@ export function createSupabaseHandler<TReq, TRes>(
|
|
|
201
201
|
}
|
|
202
202
|
}
|
|
203
203
|
|
|
204
|
+
// G64: Reject oversized request bodies before parsing (1MB limit)
|
|
205
|
+
const contentLength = req.headers.get('content-length');
|
|
206
|
+
const MAX_BODY_SIZE = 1_048_576; // 1MB
|
|
207
|
+
if (contentLength && parseInt(contentLength, 10) > MAX_BODY_SIZE) {
|
|
208
|
+
return respond(
|
|
209
|
+
{ error: `Request body too large. Maximum size: ${MAX_BODY_SIZE} bytes` },
|
|
210
|
+
413
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
204
214
|
// Parse and validate request body
|
|
205
215
|
const body = await req.json().catch(() => ({}));
|
|
206
216
|
const validationResult = v.safeParse(schema, body);
|
|
@@ -293,6 +303,14 @@ function getEnv(key: string, defaultValue: string = ''): string {
|
|
|
293
303
|
);
|
|
294
304
|
}
|
|
295
305
|
|
|
306
|
+
// G65: Basic IP format validation (IPv4 or IPv6 pattern)
|
|
307
|
+
const IP_PATTERN =
|
|
308
|
+
/^(?:\d{1,3}\.){3}\d{1,3}$|^[0-9a-fA-F:]{2,45}$/;
|
|
309
|
+
|
|
310
|
+
function isValidIp(ip: string): boolean {
|
|
311
|
+
return IP_PATTERN.test(ip);
|
|
312
|
+
}
|
|
313
|
+
|
|
296
314
|
function getClientIp(req: Request): string {
|
|
297
315
|
// Try X-Forwarded-For first (common for proxied requests)
|
|
298
316
|
const forwardedFor = req.headers.get('x-forwarded-for');
|
|
@@ -305,12 +323,13 @@ function getClientIp(req: Request): string {
|
|
|
305
323
|
.map((ip) => ip.trim())
|
|
306
324
|
.filter(Boolean);
|
|
307
325
|
const lastIp = ips[ips.length - 1];
|
|
308
|
-
|
|
326
|
+
// G65: Validate IP format before using it
|
|
327
|
+
if (lastIp && isValidIp(lastIp)) return lastIp;
|
|
309
328
|
}
|
|
310
329
|
|
|
311
330
|
// Fallback to CF-Connecting-IP (Cloudflare) or other headers
|
|
312
331
|
const cfIp = req.headers.get('cf-connecting-ip');
|
|
313
|
-
if (cfIp) return cfIp;
|
|
332
|
+
if (cfIp && isValidIp(cfIp)) return cfIp;
|
|
314
333
|
|
|
315
334
|
return 'unknown';
|
|
316
335
|
}
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import * as v from 'valibot';
|
|
13
13
|
|
|
14
|
-
import { DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
|
|
14
|
+
import { DEFAULT_STATUS_VALUE, filterVisibleFields } from '@donotdev/core/server';
|
|
15
15
|
import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
|
|
16
16
|
|
|
17
17
|
import { defaultFieldMapper } from '@donotdev/supabase';
|
|
@@ -140,7 +140,7 @@ export function createSupabaseCreateEntity(
|
|
|
140
140
|
requestSchema,
|
|
141
141
|
async (data: CreateEntityRequest, ctx) => {
|
|
142
142
|
const { payload, idempotencyKey } = data;
|
|
143
|
-
const { uid, supabaseAdmin } = ctx;
|
|
143
|
+
const { uid, userRole, supabaseAdmin } = ctx;
|
|
144
144
|
|
|
145
145
|
// Idempotency check if key provided
|
|
146
146
|
if (idempotencyKey) {
|
|
@@ -174,7 +174,12 @@ export function createSupabaseCreateEntity(
|
|
|
174
174
|
);
|
|
175
175
|
|
|
176
176
|
if (checkResult.found && checkResult.findOrCreate) {
|
|
177
|
-
|
|
177
|
+
// G67: Apply same visibility filtering as normal create path
|
|
178
|
+
return filterVisibleFields(
|
|
179
|
+
checkResult.existingDoc,
|
|
180
|
+
documentSchema,
|
|
181
|
+
userRole
|
|
182
|
+
);
|
|
178
183
|
}
|
|
179
184
|
}
|
|
180
185
|
|
|
@@ -113,6 +113,13 @@ export function createSupabaseDeleteEntity(
|
|
|
113
113
|
const { id } = data;
|
|
114
114
|
const { supabaseAdmin } = ctx;
|
|
115
115
|
|
|
116
|
+
// G68: Warn when referenceMetadata.incoming is not configured
|
|
117
|
+
if (referenceMetadata && !referenceMetadata.incoming) {
|
|
118
|
+
console.warn(
|
|
119
|
+
`[delete_${collection}] referenceMetadata provided but incoming is undefined — reference check skipped`
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
116
123
|
// Check for references to this document
|
|
117
124
|
const references = await findReferences(
|
|
118
125
|
supabaseAdmin,
|
|
@@ -69,12 +69,29 @@ function decodeCursor(cursor: string): {
|
|
|
69
69
|
orderBy: Record<string, any>;
|
|
70
70
|
} {
|
|
71
71
|
try {
|
|
72
|
-
|
|
72
|
+
const parsed = JSON.parse(Buffer.from(cursor, 'base64').toString());
|
|
73
|
+
// G69: Validate decoded cursor has required fields and correct types
|
|
74
|
+
if (
|
|
75
|
+
!parsed ||
|
|
76
|
+
typeof parsed !== 'object' ||
|
|
77
|
+
typeof parsed.id !== 'string' ||
|
|
78
|
+
!parsed.id ||
|
|
79
|
+
typeof parsed.orderBy !== 'object' ||
|
|
80
|
+
parsed.orderBy === null ||
|
|
81
|
+
Array.isArray(parsed.orderBy)
|
|
82
|
+
) {
|
|
83
|
+
throw new DoNotDevError('Invalid cursor content', 'invalid-argument');
|
|
84
|
+
}
|
|
85
|
+
return parsed;
|
|
73
86
|
} catch (error) {
|
|
87
|
+
if (error instanceof DoNotDevError) throw error;
|
|
74
88
|
throw new DoNotDevError('Invalid cursor format', 'invalid-argument');
|
|
75
89
|
}
|
|
76
90
|
}
|
|
77
91
|
|
|
92
|
+
// G66: Validate field names — allow alphanumeric, underscore only. Reject prototype pollution vectors.
|
|
93
|
+
const SAFE_FIELD_NAME = /^[a-zA-Z][a-zA-Z0-9_]*$/;
|
|
94
|
+
|
|
78
95
|
/** Apply operator; column must already be backend (snake_case) name. */
|
|
79
96
|
function applyOperator(
|
|
80
97
|
query: any,
|
|
@@ -82,6 +99,12 @@ function applyOperator(
|
|
|
82
99
|
operator: string,
|
|
83
100
|
value: any
|
|
84
101
|
): any {
|
|
102
|
+
if (!SAFE_FIELD_NAME.test(column)) {
|
|
103
|
+
throw new DoNotDevError(
|
|
104
|
+
`Invalid field name: '${column}'`,
|
|
105
|
+
'invalid-argument'
|
|
106
|
+
);
|
|
107
|
+
}
|
|
85
108
|
switch (operator) {
|
|
86
109
|
case '==':
|
|
87
110
|
return query.eq(column, value);
|
|
@@ -139,6 +139,9 @@ export function createSupabaseUpdateEntity(
|
|
|
139
139
|
throw new DoNotDevError('Entity not found', 'not-found');
|
|
140
140
|
}
|
|
141
141
|
|
|
142
|
+
// G75: `existing` comes from DB in snake_case, converted to camelCase via fromBackendRow.
|
|
143
|
+
// `payload` arrives from the client in camelCase. The merge produces a camelCase object
|
|
144
|
+
// which is later converted back to snake_case via toBackendKeys before the UPDATE query.
|
|
142
145
|
const merged = {
|
|
143
146
|
...(mapper.fromBackendRow(existing) as Record<string, any>),
|
|
144
147
|
...payload,
|
|
@@ -200,12 +200,23 @@ export async function checkRateLimitWithPostgres(
|
|
|
200
200
|
});
|
|
201
201
|
|
|
202
202
|
if (error) {
|
|
203
|
-
//
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
error.message
|
|
207
|
-
|
|
208
|
-
|
|
203
|
+
// G70: Distinguish missing function from network/other errors for clearer diagnostics
|
|
204
|
+
const isNotFound =
|
|
205
|
+
error.code === '42883' ||
|
|
206
|
+
error.message?.includes('function') && error.message?.includes('does not exist');
|
|
207
|
+
if (isNotFound) {
|
|
208
|
+
console.error(
|
|
209
|
+
'[rateLimit] rate_limit_check function not found. ' +
|
|
210
|
+
'Deploy the required SQL migration (see RATE_LIMIT_CHECK_SQL).',
|
|
211
|
+
error.message
|
|
212
|
+
);
|
|
213
|
+
} else {
|
|
214
|
+
console.error(
|
|
215
|
+
'[rateLimit] rate_limit_check RPC failed (network/runtime error):',
|
|
216
|
+
error.message,
|
|
217
|
+
error.code
|
|
218
|
+
);
|
|
219
|
+
}
|
|
209
220
|
return failClosed();
|
|
210
221
|
}
|
|
211
222
|
|
|
@@ -35,8 +35,13 @@ export default async function handler(
|
|
|
35
35
|
|
|
36
36
|
const { schema, id } = req.query as unknown as GetEntityData<any>;
|
|
37
37
|
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
// G71: Validate query params are strings (Next.js can pass string[] for repeated params)
|
|
39
|
+
if (typeof id !== 'string' || !id) {
|
|
40
|
+
handleError(new Error('Missing or invalid id parameter'));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (!schema) {
|
|
44
|
+
handleError(new Error('Missing schema'));
|
|
40
45
|
}
|
|
41
46
|
|
|
42
47
|
// W22: Validate collection name from client-supplied schema
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import * as v from 'valibot';
|
|
13
13
|
|
|
14
|
-
import { handleError } from '../shared/errorHandling.js';
|
|
14
|
+
import { handleError, DoNotDevError } from '../shared/errorHandling.js';
|
|
15
15
|
import { recordPaymentMetrics } from '../shared/utils/internal/monitoring.js';
|
|
16
16
|
import {
|
|
17
17
|
checkRateLimitWithFirestore,
|
|
@@ -96,6 +96,13 @@ export function createVercelBaseFunction<TRequest, TResponse>(
|
|
|
96
96
|
// Call user's business logic
|
|
97
97
|
const result = await businessLogic(req, res, validatedData, { uid });
|
|
98
98
|
|
|
99
|
+
// G72: Warn if businessLogic returned undefined/null — may indicate a missing return
|
|
100
|
+
if (result === undefined || result === null) {
|
|
101
|
+
console.warn(
|
|
102
|
+
`[${operation}] businessLogic returned ${result} — ensure the handler returns a value or calls res.json() directly`
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
99
106
|
// W3: Only record metrics when explicitly enabled — avoids unconditional
|
|
100
107
|
// Firestore writes on every request.
|
|
101
108
|
if (process.env.ENABLE_METRICS === 'true') {
|
|
@@ -126,44 +133,44 @@ export function createVercelBaseFunction<TRequest, TResponse>(
|
|
|
126
133
|
});
|
|
127
134
|
}
|
|
128
135
|
|
|
129
|
-
//
|
|
130
|
-
|
|
136
|
+
// Classify error via shared handler, then map to HTTP response
|
|
137
|
+
try {
|
|
138
|
+
handleError(error);
|
|
139
|
+
} catch (classified) {
|
|
140
|
+
const errorResponse = classifiedToHttp(classified);
|
|
141
|
+
return res
|
|
142
|
+
.status(errorResponse.status)
|
|
143
|
+
.json({ error: errorResponse.message }) as TResponse;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Unreachable — handleError always throws. Fallback for TypeScript.
|
|
131
147
|
return res
|
|
132
|
-
.status(
|
|
133
|
-
.json({ error:
|
|
148
|
+
.status(500)
|
|
149
|
+
.json({ error: 'Internal server error' }) as TResponse;
|
|
134
150
|
}
|
|
135
151
|
};
|
|
136
152
|
}
|
|
137
153
|
|
|
138
|
-
/**
|
|
139
|
-
|
|
140
|
-
*/
|
|
141
|
-
function handleVercelError(error: unknown): {
|
|
154
|
+
/** Map a DoNotDevError code to an HTTP status + message */
|
|
155
|
+
function classifiedToHttp(error: unknown): {
|
|
142
156
|
status: number;
|
|
143
157
|
message: string;
|
|
144
158
|
} {
|
|
145
|
-
if (error instanceof
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
}
|
|
159
|
-
if (error.message.includes('already-exists')) {
|
|
160
|
-
return { status: 409, message: 'Resource already exists' };
|
|
161
|
-
}
|
|
162
|
-
if (error.message.includes('invalid-argument')) {
|
|
163
|
-
return { status: 400, message: error.message };
|
|
164
|
-
}
|
|
159
|
+
if (error instanceof DoNotDevError) {
|
|
160
|
+
const STATUS_MAP: Record<string, number> = {
|
|
161
|
+
'invalid-argument': 400,
|
|
162
|
+
'validation-failed': 400,
|
|
163
|
+
unauthenticated: 401,
|
|
164
|
+
'permission-denied': 403,
|
|
165
|
+
'not-found': 404,
|
|
166
|
+
'already-exists': 409,
|
|
167
|
+
'rate-limit-exceeded': 429,
|
|
168
|
+
'deadline-exceeded': 504,
|
|
169
|
+
unavailable: 503,
|
|
170
|
+
};
|
|
171
|
+
const status = STATUS_MAP[error.code] ?? 500;
|
|
172
|
+
return { status, message: error.message };
|
|
165
173
|
}
|
|
166
174
|
|
|
167
|
-
// Default to internal server error
|
|
168
175
|
return { status: 500, message: 'Internal server error' };
|
|
169
176
|
}
|