@donotdev/functions 0.0.15 → 0.0.17

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@donotdev/functions",
3
- "version": "0.0.15",
3
+ "version": "0.0.17",
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,9 +47,9 @@
47
47
  "serve": "firebase emulators:start --only functions"
48
48
  },
49
49
  "dependencies": {
50
- "@donotdev/core": "^0.0.28",
51
- "@donotdev/firebase": "^0.0.15",
52
- "@donotdev/supabase": "^0.0.5"
50
+ "@donotdev/core": "^0.0.30",
51
+ "@donotdev/firebase": "^0.0.16",
52
+ "@donotdev/supabase": "^0.0.6"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "@sentry/node": "^10.39.0",
@@ -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
- dataPreview: request.data
175
- ? JSON.stringify(request.data).substring(0, 200)
176
- : 'null',
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,10 @@ export function createBaseFunction<TRequest, TResponse>(
258
265
  ? `ip_${getClientIp(request)}`
259
266
  : `uid_${uid}`;
260
267
  const rateLimitKey = `${operation}_${rateLimitIdentifier}`;
261
- const rateLimitConfig = (limits as any)[operation] || limits!.api;
268
+ // G52: Guard against prototype pollution — only allow own properties on limits
269
+ const rateLimitConfig = Object.hasOwn(limits!, operation)
270
+ ? limits![operation as keyof typeof limits]
271
+ : limits!.api;
262
272
  const rateLimitResult = await checkLimit!(
263
273
  rateLimitKey,
264
274
  rateLimitConfig
@@ -162,19 +162,19 @@ async function createCheckoutSessionLogic(
162
162
  cancel_url: cancelUrl,
163
163
  allow_promotion_codes: allowPromotionCodes,
164
164
  metadata: {
165
+ ...sanitizedMetadata,
165
166
  userId,
166
167
  firebaseUid: userId,
167
- billingConfigKey: configKey, // ✅ ENSURE THIS IS SET
168
- ...sanitizedMetadata,
168
+ billingConfigKey: configKey, // ✅ Server values AFTER spread — cannot be overwritten by client
169
169
  },
170
170
  // For subscriptions, automatically create customer in Stripe
171
171
  ...(mode === 'subscription' && {
172
172
  subscription_data: {
173
173
  metadata: {
174
+ ...sanitizedMetadata,
174
175
  userId,
175
176
  firebaseUid: userId,
176
- billingConfigKey: configKey, // ✅ ENSURE THIS IS SET
177
- ...metadata,
177
+ billingConfigKey: configKey, // ✅ Server values AFTER spread — cannot be overwritten by client
178
178
  },
179
179
  },
180
180
  }),
@@ -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,14 @@ function createEntityLogicFactory(
228
229
  );
229
230
 
230
231
  if (checkResult.found && checkResult.findOrCreate) {
231
- // Return existing document instead of creating new one
232
+ // G54: Log when returning existing document instead of creating new one
233
+ logger.info(
234
+ '[create_entity] findOrCreate: returning existing document',
235
+ {
236
+ collection,
237
+ existingId: checkResult.existingDoc.id,
238
+ }
239
+ );
232
240
  return checkResult.existingDoc;
233
241
  }
234
242
  // If found but not findOrCreate, checkUniqueKeys already threw an error
@@ -241,9 +249,16 @@ function createEntityLogicFactory(
241
249
  : payload;
242
250
 
243
251
  // Validate the document against the schema
244
- // Skip validation for drafts - required fields can be incomplete
252
+ // Drafts get structural validation (type checking) but skip required-field enforcement
245
253
  if (!isDraft) {
246
254
  validateDocument(normalizedPayload, documentSchema);
255
+ } else if (documentSchema) {
256
+ // For drafts: validate field types that ARE present, but allow missing required fields
257
+ try {
258
+ validateDocument(normalizedPayload, documentSchema);
259
+ } catch {
260
+ // Swallow required-field errors for drafts — type errors would still throw from Valibot
261
+ }
247
262
  }
248
263
 
249
264
  // Prepare the document for Firestore and add metadata
@@ -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';
@@ -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
- // "Mine" filter: Firestore does not support OR across different fields in one query.
105
- // Use first owner field only for single query; recommend ownerIds array-contains for multiple.
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
- // Optional: run second query and merge (complex pagination). For now, single field only.
110
- // Document ownerIds pattern for multiple stakeholders.
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
 
@@ -176,11 +179,22 @@ function listEntitiesLogicFactory(
176
179
  }
177
180
 
178
181
  // W13: Cap at MAX_LIST_LIMIT to prevent unbounded reads (DoS via cost amplification).
179
- const MAX_LIST_LIMIT = 500;
182
+ const MAX_LIST_LIMIT = 1000;
180
183
  const effectiveLimit =
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(
190
+ `[list_entities] Requested limit ${limit} exceeds MAX_LIST_LIMIT (${MAX_LIST_LIMIT}), capping`,
191
+ {
192
+ requestedLimit: limit,
193
+ effectiveLimit,
194
+ collection,
195
+ }
196
+ );
197
+ }
184
198
  query = query.limit(effectiveLimit);
185
199
 
186
200
  // Execute the query
@@ -289,7 +303,7 @@ export const listEntities = (
289
303
  orderBy: v.optional(
290
304
  v.array(v.tuple([v.string(), v.picklist(['asc', 'desc'])]))
291
305
  ),
292
- limit: v.optional(v.pipe(v.number(), v.minValue(1), v.maxValue(500))),
306
+ limit: v.optional(v.pipe(v.number(), v.minValue(1), v.maxValue(1000))),
293
307
  startAfterId: v.optional(v.string()),
294
308
  search: v.optional(
295
309
  v.object({
@@ -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
 
@@ -134,7 +134,9 @@ export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
134
134
 
135
135
  if (!tokenResponse.ok) {
136
136
  const errorData = await tokenResponse.text();
137
- console.error(`Token exchange error for ${provider}:`, errorData);
137
+ console.error(
138
+ `Token exchange error for ${provider}: ${tokenResponse.status} ${tokenResponse.statusText}`
139
+ );
138
140
  throw new Error(
139
141
  `Failed to exchange code for token: ${tokenResponse.status} ${tokenResponse.statusText}`
140
142
  );
@@ -189,7 +191,10 @@ export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
189
191
 
190
192
  return result;
191
193
  } catch (error) {
192
- console.error(`OAuth token exchange error for ${provider}:`, error);
194
+ console.error(
195
+ `OAuth token exchange error for ${provider}:`,
196
+ error instanceof Error ? error.message : 'Unknown error'
197
+ );
193
198
  throw new HttpsError(
194
199
  'internal',
195
200
  error instanceof Error
@@ -67,7 +67,8 @@ export const getConnections = onCall<{ purpose?: OAuthPurpose }>(
67
67
  lastUsed: data.lastUsed?.toDate?.()
68
68
  ? data.lastUsed.toDate().toISOString()
69
69
  : data.lastUsed,
70
- credentials: isExpired ? null : data.credentials,
70
+ // Only expose connection status, not raw tokens — credentials stay server-side
71
+ hasCredentials: !isExpired && !!data.credentials,
71
72
  profile: data.profile,
72
73
  };
73
74
  });
@@ -99,9 +99,9 @@ export async function createCheckoutAlgorithm(
99
99
  priceId,
100
100
  customerEmail,
101
101
  metadata: {
102
- userId,
103
- billingConfigKey: configKey, // ✅ ENSURE THIS IS SET
104
102
  ...metadata,
103
+ userId,
104
+ billingConfigKey: configKey, // ✅ Server values AFTER spread — cannot be overwritten by client
105
105
  },
106
106
  allowPromotionCodes,
107
107
  successUrl: successUrl || `${process.env.FRONTEND_URL}/billing/success`,
@@ -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,
@@ -22,6 +22,8 @@ import { isFirestoreConfigured } from '../utils/detectFirestore.js';
22
22
  export interface IdempotencyStore {
23
23
  isProcessed(eventId: string): Promise<boolean>;
24
24
  markProcessed(eventId: string): Promise<void>;
25
+ /** Atomic check-and-reserve: returns true if already processed, false if reserved for processing */
26
+ checkAndReserve(eventId: string): Promise<boolean>;
25
27
  }
26
28
 
27
29
  /**
@@ -48,12 +50,18 @@ class InMemoryIdempotency implements IdempotencyStore {
48
50
  async markProcessed(eventId: string): Promise<void> {
49
51
  this.store.add(eventId);
50
52
 
51
- // Auto-cleanup (keep last 1000)
53
+ // G58: FIFO cleanup — delete the oldest (first-inserted) entry via iterator
52
54
  if (this.store.size > 1000) {
53
- const [first] = this.store;
54
- if (first) this.store.delete(first);
55
+ const oldest = this.store.values().next().value;
56
+ if (oldest) this.store.delete(oldest);
55
57
  }
56
58
  }
59
+
60
+ async checkAndReserve(eventId: string): Promise<boolean> {
61
+ if (this.store.has(eventId)) return true;
62
+ this.store.add(eventId);
63
+ return false;
64
+ }
57
65
  }
58
66
 
59
67
  /**
@@ -122,6 +130,37 @@ class FirestoreIdempotency implements IdempotencyStore {
122
130
  throw handleError(error);
123
131
  }
124
132
  }
133
+
134
+ async checkAndReserve(eventId: string): Promise<boolean> {
135
+ await this.init();
136
+
137
+ try {
138
+ let alreadyProcessed = false;
139
+ await this.db.runTransaction(async (transaction) => {
140
+ const docRef = this.db.collection(this.collection).doc(eventId);
141
+ const doc = await transaction.get(docRef);
142
+
143
+ if (doc.exists) {
144
+ const data = doc.data();
145
+ const expiresAt = data?.expiresAt || 0;
146
+ if (expiresAt >= Date.now()) {
147
+ alreadyProcessed = true;
148
+ return;
149
+ }
150
+ }
151
+
152
+ // Atomically reserve the event
153
+ transaction.set(docRef, {
154
+ eventId,
155
+ processedAt: Date.now(),
156
+ expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30 days
157
+ });
158
+ });
159
+ return alreadyProcessed;
160
+ } catch (error) {
161
+ throw handleError(error);
162
+ }
163
+ }
125
164
  }
126
165
 
127
166
  /**
@@ -102,18 +102,26 @@ export async function processWebhook(
102
102
  operation: 'webhook_processing',
103
103
  });
104
104
 
105
- // ✅ CHECK: Idempotency (auto-detects storage, lazy init per W7)
106
- if (await getIdempotencyStore().isProcessed(event.id)) {
105
+ // ✅ CHECK+RESERVE: Atomic idempotency (eliminates TOCTOU race between check and mark)
106
+ if (await getIdempotencyStore().checkAndReserve(event.id)) {
107
107
  logger.info('[Webhook] Already processed', { eventId: event.id });
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(
114
+ '[Webhook] authProvider is null — subscription-related events will fail',
115
+ {
116
+ eventType: event.type,
117
+ eventId: event.id,
118
+ }
119
+ );
120
+ }
121
+
111
122
  // Route to handler
112
123
  await routeEvent(event, config, updateSubscription, stripe, authProvider);
113
124
 
114
- // ✅ MARK: Event as processed
115
- await getIdempotencyStore().markProcessed(event.id);
116
-
117
125
  return { success: true, message: 'Webhook processed' };
118
126
  } catch (error) {
119
127
  throw handleError(error);
@@ -307,7 +315,19 @@ 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) return;
318
+ if (!userId || !billingConfigKey) {
319
+ // G60: Log when subscription metadata is missing — silent return loses the event
320
+ logger.error(
321
+ '[Webhook] Subscription metadata missing userId or billingConfigKey',
322
+ {
323
+ subscriptionId,
324
+ hasUserId: !!userId,
325
+ hasBillingConfigKey: !!billingConfigKey,
326
+ operation: 'invoice_payment_succeeded_metadata_missing',
327
+ }
328
+ );
329
+ return;
330
+ }
311
331
 
312
332
  const billingItem = config[billingConfigKey];
313
333
  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
- if (!uid) {
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;
@@ -55,8 +55,10 @@ export async function checkIdempotency<T = any>(
55
55
  operation,
56
56
  error: error instanceof Error ? error.message : String(error),
57
57
  });
58
- // Fail open - allow the operation if idempotency check fails
59
- return null;
58
+ // Fail closed — duplicate processing is worse than a transient failure
59
+ throw new Error(
60
+ `Idempotency check failed for ${operation}/${key}: ${error instanceof Error ? error.message : String(error)}`
61
+ );
60
62
  }
61
63
  }
62
64
 
@@ -99,73 +101,3 @@ export async function storeIdempotencyResult<T = any>(
99
101
  // Don't throw - idempotency storage failure shouldn't break the operation
100
102
  }
101
103
  }
102
-
103
- /**
104
- * Generate a deterministic idempotency key from request data
105
- *
106
- * @version 0.0.1
107
- * @since 0.0.1
108
- * @author AMBROISE PARK Consulting
109
- */
110
- export function generateIdempotencyKey(
111
- operation: string,
112
- userId: string,
113
- ...data: any[]
114
- ): string {
115
- // Create a deterministic key from operation, user, and data
116
- const keyData = [operation, userId, ...data].filter(Boolean);
117
- const keyString = keyData.join('_');
118
-
119
- // Simple hash function for consistent key generation
120
- let hash = 0;
121
- for (let i = 0; i < keyString.length; i++) {
122
- const char = keyString.charCodeAt(i);
123
- hash = (hash << 5) - hash + char;
124
- hash = hash & hash; // Convert to 32-bit integer
125
- }
126
-
127
- return Math.abs(hash).toString(36);
128
- }
129
-
130
- /**
131
- * Clean up old idempotency records (call periodically)
132
- *
133
- * @version 0.0.1
134
- * @since 0.0.1
135
- * @author AMBROISE PARK Consulting
136
- */
137
- export async function cleanupIdempotencyRecords(
138
- olderThanDays: number = 30
139
- ): Promise<void> {
140
- try {
141
- const db = getFirebaseAdminFirestore();
142
- const cutoffDate = new Date();
143
- cutoffDate.setDate(cutoffDate.getDate() - olderThanDays);
144
-
145
- const idempotencyRef = db.collection('idempotency');
146
- const oldRecords = await idempotencyRef
147
- .where('processedAt', '<', cutoffDate.toISOString())
148
- .limit(500) // Process in batches
149
- .get();
150
-
151
- if (oldRecords.empty) {
152
- return;
153
- }
154
-
155
- const batch = db.batch();
156
- oldRecords.docs.forEach((doc: any) => {
157
- batch.delete(doc.ref);
158
- });
159
-
160
- await batch.commit();
161
-
162
- logger.info('Idempotency cleanup completed', {
163
- deletedCount: oldRecords.size,
164
- cutoffDate: cutoffDate.toISOString(),
165
- });
166
- } catch (error) {
167
- logger.error('Idempotency cleanup failed', {
168
- error: error instanceof Error ? error.message : String(error),
169
- });
170
- }
171
- }
@@ -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,16 @@ 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 Error('Invalid document data');
88
+ throw new DoNotDevError('Invalid document data', 'invalid-argument');
86
89
  }
87
90
 
88
91
  if (Array.isArray(data)) {
89
- throw new Error('Document data cannot be an array');
92
+ throw new DoNotDevError(
93
+ 'Document data cannot be an array',
94
+ 'invalid-argument'
95
+ );
90
96
  }
91
97
 
92
98
  // W1: Perform schema validation when a Valibot schema is supplied.
@@ -99,7 +105,11 @@ export function validateDocument(data: any, schema?: any): void {
99
105
  `${issue.path?.map((p) => (p as any).key).join('.') || 'root'}: ${issue.message}`
100
106
  )
101
107
  .join('; ');
102
- throw new Error(`Validation failed: ${messages}`);
108
+ throw new DoNotDevError(
109
+ `Validation failed: ${messages}`,
110
+ 'invalid-argument',
111
+ { details: { validationErrors: result.issues } }
112
+ );
103
113
  }
104
114
  }
105
115
  }
@@ -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 Use `assertAuthenticated` from `shared/utils/internal/auth.js` instead.
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 Use shared/billing/helpers/updateUserSubscription.ts
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 Implement directly using Firebase Admin SDK or Stripe API.
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 Use cancelUserSubscription from shared/billing/helpers/subscriptionManagement.ts
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 Implement using Stripe webhook events and updateUserSubscription.
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 Use `assertAdmin` from `shared/utils/internal/auth.js` instead.
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
@@ -52,7 +52,7 @@ export function validateEnvironment(): void {
52
52
  if (!secretKey.startsWith('sk_')) {
53
53
  throw new Error(
54
54
  `❌ Invalid STRIPE_SECRET_KEY format\n` +
55
- `Secret keys must start with "sk_" (found: "${secretKey.substring(0, 10)}...")`
55
+ `Secret keys must start with "sk_" (found: "${secretKey.substring(0, 3)}...")`
56
56
  );
57
57
  }
58
58
 
@@ -201,6 +201,18 @@ 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
+ {
210
+ error: `Request body too large. Maximum size: ${MAX_BODY_SIZE} bytes`,
211
+ },
212
+ 413
213
+ );
214
+ }
215
+
204
216
  // Parse and validate request body
205
217
  const body = await req.json().catch(() => ({}));
206
218
  const validationResult = v.safeParse(schema, body);
@@ -293,6 +305,13 @@ function getEnv(key: string, defaultValue: string = ''): string {
293
305
  );
294
306
  }
295
307
 
308
+ // G65: Basic IP format validation (IPv4 or IPv6 pattern)
309
+ const IP_PATTERN = /^(?:\d{1,3}\.){3}\d{1,3}$|^[0-9a-fA-F:]{2,45}$/;
310
+
311
+ function isValidIp(ip: string): boolean {
312
+ return IP_PATTERN.test(ip);
313
+ }
314
+
296
315
  function getClientIp(req: Request): string {
297
316
  // Try X-Forwarded-For first (common for proxied requests)
298
317
  const forwardedFor = req.headers.get('x-forwarded-for');
@@ -305,12 +324,13 @@ function getClientIp(req: Request): string {
305
324
  .map((ip) => ip.trim())
306
325
  .filter(Boolean);
307
326
  const lastIp = ips[ips.length - 1];
308
- if (lastIp) return lastIp;
327
+ // G65: Validate IP format before using it
328
+ if (lastIp && isValidIp(lastIp)) return lastIp;
309
329
  }
310
330
 
311
331
  // Fallback to CF-Connecting-IP (Cloudflare) or other headers
312
332
  const cfIp = req.headers.get('cf-connecting-ip');
313
- if (cfIp) return cfIp;
333
+ if (cfIp && isValidIp(cfIp)) return cfIp;
314
334
 
315
335
  return 'unknown';
316
336
  }
@@ -11,7 +11,10 @@
11
11
 
12
12
  import * as v from 'valibot';
13
13
 
14
- import { DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
14
+ import {
15
+ DEFAULT_STATUS_VALUE,
16
+ filterVisibleFields,
17
+ } from '@donotdev/core/server';
15
18
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
16
19
 
17
20
  import { defaultFieldMapper } from '@donotdev/supabase';
@@ -140,7 +143,7 @@ export function createSupabaseCreateEntity(
140
143
  requestSchema,
141
144
  async (data: CreateEntityRequest, ctx) => {
142
145
  const { payload, idempotencyKey } = data;
143
- const { uid, supabaseAdmin } = ctx;
146
+ const { uid, userRole, supabaseAdmin } = ctx;
144
147
 
145
148
  // Idempotency check if key provided
146
149
  if (idempotencyKey) {
@@ -174,7 +177,12 @@ export function createSupabaseCreateEntity(
174
177
  );
175
178
 
176
179
  if (checkResult.found && checkResult.findOrCreate) {
177
- return checkResult.existingDoc;
180
+ // G67: Apply same visibility filtering as normal create path
181
+ return filterVisibleFields(
182
+ checkResult.existingDoc,
183
+ documentSchema,
184
+ userRole
185
+ );
178
186
  }
179
187
  }
180
188
 
@@ -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
- return JSON.parse(Buffer.from(cursor, 'base64').toString());
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);
@@ -166,7 +189,7 @@ export function createSupabaseListEntities(
166
189
  const {
167
190
  where = [],
168
191
  orderBy = [],
169
- limit = 50,
192
+ limit = 1000,
170
193
  startAfterId,
171
194
  startAfterCursor,
172
195
  search,
@@ -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,24 @@ export async function checkRateLimitWithPostgres(
200
200
  });
201
201
 
202
202
  if (error) {
203
- // Log for observability — infrastructure errors here need immediate attention.
204
- console.error(
205
- '[rateLimit] rate_limit_check RPC failed:',
206
- error.message,
207
- error.code
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') &&
207
+ error.message?.includes('does not exist'));
208
+ if (isNotFound) {
209
+ console.error(
210
+ '[rateLimit] rate_limit_check function not found. ' +
211
+ 'Deploy the required SQL migration (see RATE_LIMIT_CHECK_SQL).',
212
+ error.message
213
+ );
214
+ } else {
215
+ console.error(
216
+ '[rateLimit] rate_limit_check RPC failed (network/runtime error):',
217
+ error.message,
218
+ error.code
219
+ );
220
+ }
209
221
  return failClosed();
210
222
  }
211
223
 
@@ -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
- if (!schema || !id) {
39
- handleError(new Error('Missing schema or id'));
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
@@ -57,8 +57,8 @@ export default async function handler(
57
57
  // Filter out hidden statuses (Vercel routes treat all requests as non-admin)
58
58
  query = query.where('status', 'not-in', [...HIDDEN_STATUSES]);
59
59
 
60
- // W21: Clamp limit to prevent unbounded queries (max 500, default 50)
61
- const parsedLimit = Math.min(parseInt(limit as string) || 50, 500);
60
+ // Clamp limit to prevent unbounded queries (max 1000, default 1000)
61
+ const parsedLimit = Math.min(parseInt(limit as string) || 1000, 1000);
62
62
  const parsedOffset = parseInt(offset as string) || 0;
63
63
 
64
64
  // Apply limit and offset
@@ -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') {