@donotdev/functions 0.0.16 → 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.16",
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.29",
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",
@@ -266,10 +266,9 @@ export function createBaseFunction<TRequest, TResponse>(
266
266
  : `uid_${uid}`;
267
267
  const rateLimitKey = `${operation}_${rateLimitIdentifier}`;
268
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;
269
+ const rateLimitConfig = Object.hasOwn(limits!, operation)
270
+ ? limits![operation as keyof typeof limits]
271
+ : limits!.api;
273
272
  const rateLimitResult = await checkLimit!(
274
273
  rateLimitKey,
275
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
  }),
@@ -230,10 +230,13 @@ function createEntityLogicFactory(
230
230
 
231
231
  if (checkResult.found && checkResult.findOrCreate) {
232
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
- });
233
+ logger.info(
234
+ '[create_entity] findOrCreate: returning existing document',
235
+ {
236
+ collection,
237
+ existingId: checkResult.existingDoc.id,
238
+ }
239
+ );
237
240
  return checkResult.existingDoc;
238
241
  }
239
242
  // If found but not findOrCreate, checkUniqueKeys already threw an error
@@ -246,9 +249,16 @@ function createEntityLogicFactory(
246
249
  : payload;
247
250
 
248
251
  // Validate the document against the schema
249
- // Skip validation for drafts - required fields can be incomplete
252
+ // Drafts get structural validation (type checking) but skip required-field enforcement
250
253
  if (!isDraft) {
251
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
+ }
252
262
  }
253
263
 
254
264
  // Prepare the document for Firestore and add metadata
@@ -41,12 +41,6 @@ function deleteEntityLogicFactory(collection: string) {
41
41
  ) {
42
42
  const { id } = data;
43
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
-
50
44
  // Check for references to this document
51
45
  const references = await findReferences(collection, id);
52
46
 
@@ -179,18 +179,21 @@ function listEntitiesLogicFactory(
179
179
  }
180
180
 
181
181
  // W13: Cap at MAX_LIST_LIMIT to prevent unbounded reads (DoS via cost amplification).
182
- const MAX_LIST_LIMIT = 500;
182
+ const MAX_LIST_LIMIT = 1000;
183
183
  const effectiveLimit =
184
184
  limit !== undefined && limit > 0
185
185
  ? Math.min(limit, MAX_LIST_LIMIT)
186
186
  : MAX_LIST_LIMIT;
187
187
  // G56: Warn when the requested limit exceeds MAX_LIST_LIMIT
188
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
- });
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
+ );
194
197
  }
195
198
  query = query.limit(effectiveLimit);
196
199
 
@@ -300,7 +303,7 @@ export const listEntities = (
300
303
  orderBy: v.optional(
301
304
  v.array(v.tuple([v.string(), v.picklist(['asc', 'desc'])]))
302
305
  ),
303
- 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))),
304
307
  startAfterId: v.optional(v.string()),
305
308
  search: v.optional(
306
309
  v.object({
@@ -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`,
@@ -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
  /**
@@ -54,6 +56,12 @@ class InMemoryIdempotency implements IdempotencyStore {
54
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,26 +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
111
  // G59: Warn when authProvider is null — subscription update events will fail
112
112
  if (!authProvider) {
113
- logger.warn('[Webhook] authProvider is null — subscription-related events will fail', {
114
- eventType: event.type,
115
- eventId: event.id,
116
- });
113
+ logger.warn(
114
+ '[Webhook] authProvider is null — subscription-related events will fail',
115
+ {
116
+ eventType: event.type,
117
+ eventId: event.id,
118
+ }
119
+ );
117
120
  }
118
121
 
119
122
  // Route to handler
120
123
  await routeEvent(event, config, updateSubscription, stripe, authProvider);
121
124
 
122
- // ✅ MARK: Event as processed
123
- await getIdempotencyStore().markProcessed(event.id);
124
-
125
125
  return { success: true, message: 'Webhook processed' };
126
126
  } catch (error) {
127
127
  throw handleError(error);
@@ -317,12 +317,15 @@ async function handleInvoicePaymentSucceeded(
317
317
  const { userId, billingConfigKey } = subscription.metadata || {};
318
318
  if (!userId || !billingConfigKey) {
319
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
- });
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
+ );
326
329
  return;
327
330
  }
328
331
 
@@ -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
- }
@@ -89,7 +89,10 @@ export function validateDocument(data: any, schema?: any): void {
89
89
  }
90
90
 
91
91
  if (Array.isArray(data)) {
92
- throw new DoNotDevError('Document data cannot be an array', 'invalid-argument');
92
+ throw new DoNotDevError(
93
+ 'Document data cannot be an array',
94
+ 'invalid-argument'
95
+ );
93
96
  }
94
97
 
95
98
  // W1: Perform schema validation when a Valibot schema is supplied.
@@ -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
 
@@ -206,7 +206,9 @@ export function createSupabaseHandler<TReq, TRes>(
206
206
  const MAX_BODY_SIZE = 1_048_576; // 1MB
207
207
  if (contentLength && parseInt(contentLength, 10) > MAX_BODY_SIZE) {
208
208
  return respond(
209
- { error: `Request body too large. Maximum size: ${MAX_BODY_SIZE} bytes` },
209
+ {
210
+ error: `Request body too large. Maximum size: ${MAX_BODY_SIZE} bytes`,
211
+ },
210
212
  413
211
213
  );
212
214
  }
@@ -304,8 +306,7 @@ function getEnv(key: string, defaultValue: string = ''): string {
304
306
  }
305
307
 
306
308
  // 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
+ const IP_PATTERN = /^(?:\d{1,3}\.){3}\d{1,3}$|^[0-9a-fA-F:]{2,45}$/;
309
310
 
310
311
  function isValidIp(ip: string): boolean {
311
312
  return IP_PATTERN.test(ip);
@@ -11,7 +11,10 @@
11
11
 
12
12
  import * as v from 'valibot';
13
13
 
14
- import { DEFAULT_STATUS_VALUE, filterVisibleFields } 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';
@@ -189,7 +189,7 @@ export function createSupabaseListEntities(
189
189
  const {
190
190
  where = [],
191
191
  orderBy = [],
192
- limit = 50,
192
+ limit = 1000,
193
193
  startAfterId,
194
194
  startAfterCursor,
195
195
  search,
@@ -203,7 +203,8 @@ export async function checkRateLimitWithPostgres(
203
203
  // G70: Distinguish missing function from network/other errors for clearer diagnostics
204
204
  const isNotFound =
205
205
  error.code === '42883' ||
206
- error.message?.includes('function') && error.message?.includes('does not exist');
206
+ (error.message?.includes('function') &&
207
+ error.message?.includes('does not exist'));
207
208
  if (isNotFound) {
208
209
  console.error(
209
210
  '[rateLimit] rate_limit_check function not found. ' +
@@ -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