@donotdev/functions 0.0.15 → 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 +2 -2
- package/src/firebase/baseFunction.ts +15 -4
- 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/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/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 +7 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/functions",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.16",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Backend functions for DoNotDev Framework - Firebase, Vercel, and platform-agnostic implementations for auth, billing, CRUD, and OAuth",
|
|
6
6
|
"main": "./lib/firebase/index.js",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"serve": "firebase emulators:start --only functions"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@donotdev/core": "^0.0.
|
|
50
|
+
"@donotdev/core": "^0.0.29",
|
|
51
51
|
"@donotdev/firebase": "^0.0.15",
|
|
52
52
|
"@donotdev/supabase": "^0.0.5"
|
|
53
53
|
},
|
|
@@ -171,9 +171,16 @@ export function createBaseFunction<TRequest, TResponse>(
|
|
|
171
171
|
userId: request.auth?.uid || 'anonymous',
|
|
172
172
|
hasData: request.data !== undefined && request.data !== null,
|
|
173
173
|
dataKeys: request.data ? Object.keys(request.data) : [],
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
174
|
+
// G73: Wrap in try-catch to avoid broken mid-JSON output on circular refs
|
|
175
|
+
dataPreview: (() => {
|
|
176
|
+
if (!request.data) return 'null';
|
|
177
|
+
try {
|
|
178
|
+
const json = JSON.stringify(request.data);
|
|
179
|
+
return json.length > 200 ? json.substring(0, 200) + '...' : json;
|
|
180
|
+
} catch {
|
|
181
|
+
return '[unserializable]';
|
|
182
|
+
}
|
|
183
|
+
})(),
|
|
177
184
|
});
|
|
178
185
|
|
|
179
186
|
// App Check monitoring (logs missing tokens for visibility)
|
|
@@ -258,7 +265,11 @@ export function createBaseFunction<TRequest, TResponse>(
|
|
|
258
265
|
? `ip_${getClientIp(request)}`
|
|
259
266
|
: `uid_${uid}`;
|
|
260
267
|
const rateLimitKey = `${operation}_${rateLimitIdentifier}`;
|
|
261
|
-
|
|
268
|
+
// G52: Guard against prototype pollution — only allow own properties on limits
|
|
269
|
+
const rateLimitConfig =
|
|
270
|
+
Object.hasOwn(limits!, operation)
|
|
271
|
+
? limits![operation as keyof typeof limits]
|
|
272
|
+
: limits!.api;
|
|
262
273
|
const rateLimitResult = await checkLimit!(
|
|
263
274
|
rateLimitKey,
|
|
264
275
|
rateLimitConfig
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { logger } from 'firebase-functions/v2';
|
|
12
13
|
import * as v from 'valibot';
|
|
13
14
|
|
|
14
15
|
import { DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
|
|
@@ -228,7 +229,11 @@ function createEntityLogicFactory(
|
|
|
228
229
|
);
|
|
229
230
|
|
|
230
231
|
if (checkResult.found && checkResult.findOrCreate) {
|
|
231
|
-
//
|
|
232
|
+
// G54: Log when returning existing document instead of creating new one
|
|
233
|
+
logger.info('[create_entity] findOrCreate: returning existing document', {
|
|
234
|
+
collection,
|
|
235
|
+
existingId: checkResult.existingDoc.id,
|
|
236
|
+
});
|
|
232
237
|
return checkResult.existingDoc;
|
|
233
238
|
}
|
|
234
239
|
// If found but not findOrCreate, checkUniqueKeys already threw an error
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { logger } from 'firebase-functions/v2';
|
|
12
13
|
import * as v from 'valibot';
|
|
13
14
|
|
|
14
15
|
import type { UserRole } from '@donotdev/core/server';
|
|
@@ -40,6 +41,12 @@ function deleteEntityLogicFactory(collection: string) {
|
|
|
40
41
|
) {
|
|
41
42
|
const { id } = data;
|
|
42
43
|
|
|
44
|
+
// G55: Warn when referenceMetadata is not configured — reference checking is skipped
|
|
45
|
+
logger.warn('[delete_entity] No referenceMetadata configured, skipping reference check', {
|
|
46
|
+
collection,
|
|
47
|
+
docId: id,
|
|
48
|
+
});
|
|
49
|
+
|
|
43
50
|
// Check for references to this document
|
|
44
51
|
const references = await findReferences(collection, id);
|
|
45
52
|
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { logger } from 'firebase-functions/v2';
|
|
12
13
|
import * as v from 'valibot';
|
|
13
14
|
|
|
14
15
|
import {
|
|
@@ -101,14 +102,16 @@ function listEntitiesLogicFactory(
|
|
|
101
102
|
) {
|
|
102
103
|
query = applyPublicCondition(query, ownership.publicCondition);
|
|
103
104
|
} else if (!isListCard && ownership.ownerFields.length > 0) {
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
const firstOwnerField = ownership.ownerFields[0];
|
|
107
|
-
query = query.where(firstOwnerField, '==', uid);
|
|
105
|
+
// G53: Multiple ownerFields are not supported in a single Firestore query.
|
|
106
|
+
// Throw an explicit error instead of silently degrading to first field only.
|
|
108
107
|
if (ownership.ownerFields.length > 1) {
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
throw new DoNotDevError(
|
|
109
|
+
`Multiple ownerFields (${ownership.ownerFields.join(', ')}) are not supported for Firestore list queries. Use a single ownerIds array field with array-contains instead.`,
|
|
110
|
+
'invalid-argument'
|
|
111
|
+
);
|
|
111
112
|
}
|
|
113
|
+
const firstOwnerField = ownership.ownerFields[0];
|
|
114
|
+
query = query.where(firstOwnerField, '==', uid);
|
|
112
115
|
}
|
|
113
116
|
}
|
|
114
117
|
|
|
@@ -181,6 +184,14 @@ function listEntitiesLogicFactory(
|
|
|
181
184
|
limit !== undefined && limit > 0
|
|
182
185
|
? Math.min(limit, MAX_LIST_LIMIT)
|
|
183
186
|
: MAX_LIST_LIMIT;
|
|
187
|
+
// G56: Warn when the requested limit exceeds MAX_LIST_LIMIT
|
|
188
|
+
if (limit !== undefined && limit > MAX_LIST_LIMIT) {
|
|
189
|
+
logger.warn(`[list_entities] Requested limit ${limit} exceeds MAX_LIST_LIMIT (${MAX_LIST_LIMIT}), capping`, {
|
|
190
|
+
requestedLimit: limit,
|
|
191
|
+
effectiveLimit,
|
|
192
|
+
collection,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
184
195
|
query = query.limit(effectiveLimit);
|
|
185
196
|
|
|
186
197
|
// Execute the query
|
|
@@ -209,7 +209,8 @@ function updateEntityLogicFactory(
|
|
|
209
209
|
throw new DoNotDevError('Entity not found', 'not-found');
|
|
210
210
|
}
|
|
211
211
|
|
|
212
|
-
// Get the current data and merge with the update payload
|
|
212
|
+
// Get the current data and merge with the update payload.
|
|
213
|
+
// Note: simple spread merge — concurrent partial updates use last-write-wins, no conflict detection.
|
|
213
214
|
const currentData = transformFirestoreData(doc.data());
|
|
214
215
|
const mergedData = { ...currentData, ...payload };
|
|
215
216
|
|
|
@@ -64,6 +64,15 @@ export async function updateUserSubscription(
|
|
|
64
64
|
throw new Error('Invalid subscription data: missing tier or status');
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
// G57: Warn when customerId is undefined — falling back to userId loses the
|
|
68
|
+
// Stripe customer ID, which makes future Stripe API calls unreliable.
|
|
69
|
+
if (!subscriptionData.customerId) {
|
|
70
|
+
console.warn(
|
|
71
|
+
`[updateUserSubscription] customerId is undefined for user ${userId}. ` +
|
|
72
|
+
`Falling back to userId. This may cause issues with Stripe API calls.`
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
67
76
|
const subscriptionClaims = {
|
|
68
77
|
tier: subscriptionData.tier,
|
|
69
78
|
subscriptionId: subscriptionData.subscriptionId || null,
|
|
@@ -48,10 +48,10 @@ class InMemoryIdempotency implements IdempotencyStore {
|
|
|
48
48
|
async markProcessed(eventId: string): Promise<void> {
|
|
49
49
|
this.store.add(eventId);
|
|
50
50
|
|
|
51
|
-
//
|
|
51
|
+
// G58: FIFO cleanup — delete the oldest (first-inserted) entry via iterator
|
|
52
52
|
if (this.store.size > 1000) {
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
53
|
+
const oldest = this.store.values().next().value;
|
|
54
|
+
if (oldest) this.store.delete(oldest);
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
}
|
|
@@ -108,6 +108,14 @@ export async function processWebhook(
|
|
|
108
108
|
return { success: true, message: 'Event already processed' };
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
// G59: Warn when authProvider is null — subscription update events will fail
|
|
112
|
+
if (!authProvider) {
|
|
113
|
+
logger.warn('[Webhook] authProvider is null — subscription-related events will fail', {
|
|
114
|
+
eventType: event.type,
|
|
115
|
+
eventId: event.id,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
111
119
|
// Route to handler
|
|
112
120
|
await routeEvent(event, config, updateSubscription, stripe, authProvider);
|
|
113
121
|
|
|
@@ -307,7 +315,16 @@ async function handleInvoicePaymentSucceeded(
|
|
|
307
315
|
// ✅ FIX: Fetch subscription to get metadata
|
|
308
316
|
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
|
309
317
|
const { userId, billingConfigKey } = subscription.metadata || {};
|
|
310
|
-
if (!userId || !billingConfigKey)
|
|
318
|
+
if (!userId || !billingConfigKey) {
|
|
319
|
+
// G60: Log when subscription metadata is missing — silent return loses the event
|
|
320
|
+
logger.error('[Webhook] Subscription metadata missing userId or billingConfigKey', {
|
|
321
|
+
subscriptionId,
|
|
322
|
+
hasUserId: !!userId,
|
|
323
|
+
hasBillingConfigKey: !!billingConfigKey,
|
|
324
|
+
operation: 'invoice_payment_succeeded_metadata_missing',
|
|
325
|
+
});
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
311
328
|
|
|
312
329
|
const billingItem = config[billingConfigKey];
|
|
313
330
|
if (!billingItem || billingItem.type !== 'StripeSubscription') return;
|
|
@@ -28,7 +28,8 @@ export type AuthProvider = 'firebase' | 'supabase';
|
|
|
28
28
|
* @author AMBROISE PARK Consulting
|
|
29
29
|
*/
|
|
30
30
|
export function assertAuthenticated(uid: string): string {
|
|
31
|
-
|
|
31
|
+
// G62: Validate uid is a non-empty string — reject non-string values at runtime
|
|
32
|
+
if (!uid || typeof uid !== 'string') {
|
|
32
33
|
throw new Error('Authentication required');
|
|
33
34
|
}
|
|
34
35
|
return uid;
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
import * as v from 'valibot';
|
|
13
13
|
|
|
14
|
+
import { DoNotDevError } from '@donotdev/core/server';
|
|
15
|
+
|
|
14
16
|
/**
|
|
15
17
|
* Validates environment variables required for Stripe
|
|
16
18
|
*
|
|
@@ -81,12 +83,13 @@ export function validateCollectionName(name: string): void {
|
|
|
81
83
|
* @author AMBROISE PARK Consulting
|
|
82
84
|
*/
|
|
83
85
|
export function validateDocument(data: any, schema?: any): void {
|
|
86
|
+
// G63: Throw DoNotDevError instead of plain Error for consistent error handling
|
|
84
87
|
if (!data || typeof data !== 'object') {
|
|
85
|
-
throw new
|
|
88
|
+
throw new DoNotDevError('Invalid document data', 'invalid-argument');
|
|
86
89
|
}
|
|
87
90
|
|
|
88
91
|
if (Array.isArray(data)) {
|
|
89
|
-
throw new
|
|
92
|
+
throw new DoNotDevError('Document data cannot be an array', 'invalid-argument');
|
|
90
93
|
}
|
|
91
94
|
|
|
92
95
|
// W1: Perform schema validation when a Valibot schema is supplied.
|
|
@@ -99,7 +102,11 @@ export function validateDocument(data: any, schema?: any): void {
|
|
|
99
102
|
`${issue.path?.map((p) => (p as any).key).join('.') || 'root'}: ${issue.message}`
|
|
100
103
|
)
|
|
101
104
|
.join('; ');
|
|
102
|
-
throw new
|
|
105
|
+
throw new DoNotDevError(
|
|
106
|
+
`Validation failed: ${messages}`,
|
|
107
|
+
'invalid-argument',
|
|
108
|
+
{ details: { validationErrors: result.issues } }
|
|
109
|
+
);
|
|
103
110
|
}
|
|
104
111
|
}
|
|
105
112
|
}
|
package/src/shared/utils.ts
CHANGED
|
@@ -109,7 +109,7 @@ export const stripe = new Proxy({} as Stripe, {
|
|
|
109
109
|
/**
|
|
110
110
|
* Assert that a user is authenticated from a Firebase callable auth context.
|
|
111
111
|
*
|
|
112
|
-
* @deprecated
|
|
112
|
+
* @deprecated Import `assertAuthenticated` from `@donotdev/functions/shared/utils/internal/auth` instead.
|
|
113
113
|
* This wrapper extracts uid from a Firebase callable auth context and delegates
|
|
114
114
|
* to the canonical version.
|
|
115
115
|
*
|
|
@@ -250,7 +250,7 @@ export function createErrorResponse(error: unknown): {
|
|
|
250
250
|
* Use `updateUserSubscription` from `shared/billing/helpers/updateUserSubscription.ts`
|
|
251
251
|
* (which requires an authProvider) instead.
|
|
252
252
|
*
|
|
253
|
-
* @deprecated
|
|
253
|
+
* @deprecated Import `updateUserSubscription` from `@donotdev/functions/shared/billing/helpers/updateUserSubscription`.
|
|
254
254
|
* @version 0.0.2
|
|
255
255
|
* @since 0.0.1
|
|
256
256
|
* @author AMBROISE PARK Consulting
|
|
@@ -270,7 +270,7 @@ export async function updateUserSubscription(
|
|
|
270
270
|
*
|
|
271
271
|
* C10: This was a silent no-op stub. Now throws to surface the missing implementation.
|
|
272
272
|
*
|
|
273
|
-
* @deprecated
|
|
273
|
+
* @deprecated Import from `@donotdev/functions/shared/billing/helpers` or implement directly using Firebase Admin SDK / Stripe API.
|
|
274
274
|
* @version 0.0.2
|
|
275
275
|
* @since 0.0.1
|
|
276
276
|
* @author AMBROISE PARK Consulting
|
|
@@ -287,7 +287,7 @@ export async function getUserSubscription(_firebaseUid: string): Promise<any> {
|
|
|
287
287
|
*
|
|
288
288
|
* C10: This was a silent no-op stub. Now throws to surface the missing implementation.
|
|
289
289
|
*
|
|
290
|
-
* @deprecated
|
|
290
|
+
* @deprecated Import `cancelUserSubscription` from `@donotdev/functions/shared/billing/helpers/subscriptionManagement`.
|
|
291
291
|
* @version 0.0.2
|
|
292
292
|
* @since 0.0.1
|
|
293
293
|
* @author AMBROISE PARK Consulting
|
|
@@ -307,7 +307,7 @@ export async function cancelUserSubscription(
|
|
|
307
307
|
*
|
|
308
308
|
* C10: This was a silent no-op stub. Now throws to surface the missing implementation.
|
|
309
309
|
*
|
|
310
|
-
* @deprecated
|
|
310
|
+
* @deprecated Handle via Stripe webhook events. Use `processWebhook` from `@donotdev/functions/shared/billing/webhookHandler`.
|
|
311
311
|
* @version 0.0.2
|
|
312
312
|
* @since 0.0.1
|
|
313
313
|
* @author AMBROISE PARK Consulting
|
|
@@ -326,7 +326,7 @@ export async function handleSubscriptionCancellation(
|
|
|
326
326
|
* Asserts that a user has admin privileges
|
|
327
327
|
* Uses role hierarchy: super > admin > user > guest
|
|
328
328
|
*
|
|
329
|
-
* @deprecated
|
|
329
|
+
* @deprecated Import `assertAdmin` from `@donotdev/functions/shared/utils/internal/auth` instead.
|
|
330
330
|
* This is a thin wrapper that delegates to the canonical provider-agnostic version.
|
|
331
331
|
*
|
|
332
332
|
* @version 0.0.3
|
|
@@ -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
|
|
@@ -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') {
|