@donotdev/functions 0.0.16 → 0.0.18

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.
Files changed (56) hide show
  1. package/lib/firebase/index.js +558 -1515
  2. package/lib/firebase/index.js.map +4 -4
  3. package/lib/shared/index.js +163 -333
  4. package/lib/shared/index.js.map +4 -4
  5. package/lib/vercel/api/index.js +190 -325
  6. package/lib/vercel/api/index.js.map +4 -4
  7. package/package.json +4 -4
  8. package/src/firebase/baseFunction.ts +4 -5
  9. package/src/firebase/billing/changePlan.ts +1 -1
  10. package/src/firebase/billing/createCheckoutSession.ts +4 -4
  11. package/src/firebase/billing/refreshSubscriptionStatus.ts +1 -1
  12. package/src/firebase/crud/create.ts +16 -6
  13. package/src/firebase/crud/delete.ts +0 -6
  14. package/src/firebase/crud/list.ts +12 -8
  15. package/src/firebase/crud/update.ts +1 -1
  16. package/src/firebase/oauth/exchangeToken.ts +7 -2
  17. package/src/firebase/oauth/getConnections.ts +2 -1
  18. package/src/shared/billing/__tests__/createCheckout.test.ts +7 -5
  19. package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -0
  20. package/src/shared/billing/createCheckout.ts +2 -2
  21. package/src/shared/billing/helpers/subscriptionManagement.ts +2 -2
  22. package/src/shared/billing/idempotency.ts +39 -0
  23. package/src/shared/billing/webhookHandler.ts +19 -17
  24. package/src/shared/errorHandling.ts +2 -1
  25. package/src/shared/oauth/__tests__/exchangeToken.test.ts +2 -1
  26. package/src/shared/schema.ts +1 -1
  27. package/src/shared/utils/__tests__/functionWrapper.test.ts +1 -1
  28. package/src/shared/utils/firebaseHelpers.ts +1 -1
  29. package/src/shared/utils/internal/auth.ts +1 -1
  30. package/src/shared/utils/internal/idempotency.ts +4 -72
  31. package/src/shared/utils/internal/rateLimiter.ts +1 -1
  32. package/src/shared/utils/internal/validation.ts +4 -1
  33. package/src/shared/utils/vercelHelpers.ts +1 -2
  34. package/src/shared/validation.ts +1 -1
  35. package/src/supabase/baseFunction.ts +7 -5
  36. package/src/supabase/billing/createCheckoutSession.ts +2 -3
  37. package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -1
  38. package/src/supabase/crud/aggregate.ts +0 -1
  39. package/src/supabase/crud/create.ts +4 -2
  40. package/src/supabase/crud/get.ts +0 -1
  41. package/src/supabase/crud/list.ts +1 -2
  42. package/src/supabase/crud/update.ts +0 -1
  43. package/src/supabase/helpers/authProvider.ts +0 -1
  44. package/src/supabase/utils/rateLimiter.ts +4 -2
  45. package/src/vercel/api/billing/change-plan.ts +1 -1
  46. package/src/vercel/api/billing/create-checkout-session.ts +1 -2
  47. package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
  48. package/src/vercel/api/crud/create.ts +1 -1
  49. package/src/vercel/api/crud/delete.ts +1 -1
  50. package/src/vercel/api/crud/get.ts +1 -1
  51. package/src/vercel/api/crud/list.ts +3 -3
  52. package/src/vercel/api/crud/update.ts +1 -1
  53. package/src/vercel/api/oauth/check-github-access.ts +1 -2
  54. package/src/vercel/api/oauth/exchange-token.ts +1 -2
  55. package/src/vercel/api/oauth/grant-github-access.ts +1 -2
  56. package/src/vercel/baseFunction.ts +3 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@donotdev/functions",
3
- "version": "0.0.16",
3
+ "version": "0.0.18",
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.35",
51
+ "@donotdev/firebase": "^0.0.18",
52
+ "@donotdev/supabase": "^0.0.7"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "@sentry/node": "^10.39.0",
@@ -13,9 +13,9 @@ import { logger } from 'firebase-functions/v2';
13
13
  import { onCall } from 'firebase-functions/v2/https';
14
14
  import * as v from 'valibot';
15
15
 
16
+ import type { SecurityContext } from '@donotdev/core';
16
17
  import { hasRoleAccess } from '@donotdev/core/server';
17
18
  import type { UserRole } from '@donotdev/core/server';
18
- import type { SecurityContext } from '@donotdev/core';
19
19
 
20
20
  import { FUNCTION_CONFIG } from './config/constants.js';
21
21
  import { handleError, DoNotDevError } from '../shared/errorHandling.js';
@@ -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
@@ -9,7 +9,6 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import Stripe from 'stripe';
13
12
  import * as v from 'valibot';
14
13
 
15
14
  import type { StripeBackConfig } from '@donotdev/core/server';
@@ -27,6 +26,7 @@ import { STRIPE_CONFIG } from '../config/constants.js';
27
26
  import { stripeSecretKey } from '../config/secrets.js';
28
27
 
29
28
  import type { CallableRequest } from 'firebase-functions/v2/https';
29
+ import type Stripe from 'stripe';
30
30
 
31
31
  const changePlanSchema = v.object({
32
32
  userId: v.string(),
@@ -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,7 +9,6 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import Stripe from 'stripe';
13
12
  import * as v from 'valibot';
14
13
 
15
14
  import type { RefreshSubscriptionRequest } from '@donotdev/core/server';
@@ -20,6 +19,7 @@ import { createBaseFunction } from '../baseFunction.js';
20
19
  import { STRIPE_CONFIG } from '../config/constants.js';
21
20
 
22
21
  import type { CallableRequest } from 'firebase-functions/v2/https';
22
+ import type Stripe from 'stripe';
23
23
 
24
24
  /**
25
25
  * Schema for refreshing subscription status
@@ -25,11 +25,11 @@ import { DoNotDevError, validateDocument } from '../../shared/utils.js';
25
25
  import { createBaseFunction } from '../baseFunction.js';
26
26
  import { CRUD_CONFIG } from '../config/constants.js';
27
27
 
28
+ import type { Query, DocumentData } from 'firebase-admin/firestore';
28
29
  import type {
29
30
  CallableFunction,
30
31
  CallableRequest,
31
32
  } from 'firebase-functions/v2/https';
32
- import type { Query, DocumentData } from 'firebase-admin/firestore';
33
33
 
34
34
  export type CreateEntityRequest = {
35
35
  payload: Record<string, any>;
@@ -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
 
@@ -22,7 +22,8 @@ import type {
22
22
  EntityOwnershipPublicCondition,
23
23
  UserRole,
24
24
  } from '@donotdev/core/server';
25
- import { getFirebaseAdminFirestore, Query } from '@donotdev/firebase/server';
25
+ import type { Query } from '@donotdev/firebase/server';
26
+ import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
26
27
 
27
28
  import { transformFirestoreData } from '../../shared/index.js';
28
29
  import { DoNotDevError } from '../../shared/utils.js';
@@ -179,18 +180,21 @@ function listEntitiesLogicFactory(
179
180
  }
180
181
 
181
182
  // W13: Cap at MAX_LIST_LIMIT to prevent unbounded reads (DoS via cost amplification).
182
- const MAX_LIST_LIMIT = 500;
183
+ const MAX_LIST_LIMIT = 1000;
183
184
  const effectiveLimit =
184
185
  limit !== undefined && limit > 0
185
186
  ? Math.min(limit, MAX_LIST_LIMIT)
186
187
  : MAX_LIST_LIMIT;
187
188
  // G56: Warn when the requested limit exceeds MAX_LIST_LIMIT
188
189
  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
- });
190
+ logger.warn(
191
+ `[list_entities] Requested limit ${limit} exceeds MAX_LIST_LIMIT (${MAX_LIST_LIMIT}), capping`,
192
+ {
193
+ requestedLimit: limit,
194
+ effectiveLimit,
195
+ collection,
196
+ }
197
+ );
194
198
  }
195
199
  query = query.limit(effectiveLimit);
196
200
 
@@ -300,7 +304,7 @@ export const listEntities = (
300
304
  orderBy: v.optional(
301
305
  v.array(v.tuple([v.string(), v.picklist(['asc', 'desc'])]))
302
306
  ),
303
- limit: v.optional(v.pipe(v.number(), v.minValue(1), v.maxValue(500))),
307
+ limit: v.optional(v.pipe(v.number(), v.minValue(1), v.maxValue(1000))),
304
308
  startAfterId: v.optional(v.string()),
305
309
  search: v.optional(
306
310
  v.object({
@@ -24,11 +24,11 @@ import { DoNotDevError, validateDocument } from '../../shared/utils.js';
24
24
  import { createBaseFunction } from '../baseFunction.js';
25
25
  import { CRUD_CONFIG } from '../config/constants.js';
26
26
 
27
+ import type { Query, DocumentData } from 'firebase-admin/firestore';
27
28
  import type {
28
29
  CallableFunction,
29
30
  CallableRequest,
30
31
  } from 'firebase-functions/v2/https';
31
- import type { Query, DocumentData } from 'firebase-admin/firestore';
32
32
 
33
33
  export type UpdateEntityRequest = {
34
34
  id: string;
@@ -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
  });
@@ -11,16 +11,18 @@
11
11
 
12
12
  import { describe, it, expect, vi, beforeEach } from 'vitest';
13
13
 
14
- import type {
15
- StripeCheckoutProvider,
16
- AuthCheckoutProvider,
17
- } from '../createCheckout.js';
18
- import { createCheckoutAlgorithm } from '../createCheckout.js';
19
14
  import type {
20
15
  CreateCheckoutSessionRequest,
21
16
  StripeBackConfig,
22
17
  } from '@donotdev/core/server';
23
18
 
19
+ import { createCheckoutAlgorithm } from '../createCheckout.js';
20
+
21
+ import type {
22
+ StripeCheckoutProvider,
23
+ AuthCheckoutProvider,
24
+ } from '../createCheckout.js';
25
+
24
26
  // ---------------------------------------------------------------------------
25
27
  // Fixtures
26
28
  // ---------------------------------------------------------------------------
@@ -80,6 +80,7 @@ vi.mock('../../logger.js', () => ({
80
80
  // Reset idempotency store between tests so events are never pre-marked
81
81
  import { resetIdempotencyStore } from '../idempotency.js';
82
82
  import { processWebhook } from '../webhookHandler.js';
83
+
83
84
  import type {
84
85
  UpdateSubscriptionFn,
85
86
  WebhookAuthProvider,
@@ -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`,
@@ -9,8 +9,6 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import Stripe from 'stripe';
13
-
14
12
  import { SUBSCRIPTION_STATUS } from '@donotdev/core/server';
15
13
 
16
14
  import {
@@ -20,6 +18,8 @@ import {
20
18
  import { handleError } from '../../errorHandling.js';
21
19
  import { stripe, validateStripeEnvironment } from '../../utils.js';
22
20
 
21
+ import type Stripe from 'stripe';
22
+
23
23
  /**
24
24
  * Cancel user subscription at period end
25
25
  *
@@ -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
  /**
@@ -9,8 +9,6 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import Stripe from 'stripe';
13
-
14
12
  import {
15
13
  validateStripeBackConfig,
16
14
  SUBSCRIPTION_STATUS,
@@ -27,6 +25,7 @@ import type {
27
25
  SubscriptionData,
28
26
  AuthProvider,
29
27
  } from './helpers/updateUserSubscription.js';
28
+ import type Stripe from 'stripe';
30
29
 
31
30
  // W7: Lazy singleton — resolving at import time reads env vars / Firebase Admin
32
31
  // before they are fully injected (e.g., defineSecret values on Firebase Functions v2).
@@ -102,26 +101,26 @@ export async function processWebhook(
102
101
  operation: 'webhook_processing',
103
102
  });
104
103
 
105
- // ✅ CHECK: Idempotency (auto-detects storage, lazy init per W7)
106
- if (await getIdempotencyStore().isProcessed(event.id)) {
104
+ // ✅ CHECK+RESERVE: Atomic idempotency (eliminates TOCTOU race between check and mark)
105
+ if (await getIdempotencyStore().checkAndReserve(event.id)) {
107
106
  logger.info('[Webhook] Already processed', { eventId: event.id });
108
107
  return { success: true, message: 'Event already processed' };
109
108
  }
110
109
 
111
110
  // G59: Warn when authProvider is null — subscription update events will fail
112
111
  if (!authProvider) {
113
- logger.warn('[Webhook] authProvider is null — subscription-related events will fail', {
114
- eventType: event.type,
115
- eventId: event.id,
116
- });
112
+ logger.warn(
113
+ '[Webhook] authProvider is null — subscription-related events will fail',
114
+ {
115
+ eventType: event.type,
116
+ eventId: event.id,
117
+ }
118
+ );
117
119
  }
118
120
 
119
121
  // Route to handler
120
122
  await routeEvent(event, config, updateSubscription, stripe, authProvider);
121
123
 
122
- // ✅ MARK: Event as processed
123
- await getIdempotencyStore().markProcessed(event.id);
124
-
125
124
  return { success: true, message: 'Webhook processed' };
126
125
  } catch (error) {
127
126
  throw handleError(error);
@@ -317,12 +316,15 @@ async function handleInvoicePaymentSucceeded(
317
316
  const { userId, billingConfigKey } = subscription.metadata || {};
318
317
  if (!userId || !billingConfigKey) {
319
318
  // 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
- });
319
+ logger.error(
320
+ '[Webhook] Subscription metadata missing userId or billingConfigKey',
321
+ {
322
+ subscriptionId,
323
+ hasUserId: !!userId,
324
+ hasBillingConfigKey: !!billingConfigKey,
325
+ operation: 'invoice_payment_succeeded_metadata_missing',
326
+ }
327
+ );
326
328
  return;
327
329
  }
328
330
 
@@ -10,7 +10,8 @@
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
12
12
 
13
- import { DoNotDevError, EntityHookError } from '@donotdev/core/server';
13
+ import type { EntityHookError } from '@donotdev/core/server';
14
+ import { DoNotDevError } from '@donotdev/core/server';
14
15
 
15
16
  // Re-export DoNotDevError so existing imports from this module continue to work
16
17
  export { DoNotDevError };
@@ -11,12 +11,13 @@
11
11
 
12
12
  import { describe, it, expect, vi } from 'vitest';
13
13
 
14
- import { exchangeTokenAlgorithm, type OAuthProvider } from '../exchangeToken';
15
14
  import type {
16
15
  ExchangeTokenRequest,
17
16
  TokenResponse,
18
17
  } from '@donotdev/core/server';
19
18
 
19
+ import { exchangeTokenAlgorithm, type OAuthProvider } from '../exchangeToken';
20
+
20
21
  // ---------------------------------------------------------------------------
21
22
  // Helpers
22
23
  // ---------------------------------------------------------------------------
@@ -9,7 +9,7 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import * as v from 'valibot';
12
+ import type * as v from 'valibot';
13
13
 
14
14
  /** Visibility levels matching @donotdev/core */
15
15
  type Visibility = 'guest' | 'user' | 'admin' | 'technical' | 'hidden' | 'owner';
@@ -9,8 +9,8 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import { describe, it, expect, vi, beforeEach } from 'vitest';
13
12
  import * as v from 'valibot';
13
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
14
14
 
15
15
  import {
16
16
  withValidation,
@@ -10,11 +10,11 @@
10
10
  */
11
11
 
12
12
  import { onCall } from 'firebase-functions/v2/https';
13
- import * as v from 'valibot';
14
13
 
15
14
  import { withSchemaValidation } from './schemaValidation.js';
16
15
 
17
16
  import type { CallableRequest } from 'firebase-functions/v2/https';
17
+ import type * as v from 'valibot';
18
18
 
19
19
  /**
20
20
  * Creates a Firebase onCall function with schema validation
@@ -10,8 +10,8 @@
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
12
12
 
13
- import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
14
13
  import { hasProvider, getProvider } from '@donotdev/core/server';
14
+ import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
15
15
 
16
16
  import type { NextApiRequest } from 'next';
17
17
 
@@ -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,11 +11,11 @@
11
11
 
12
12
  import { logger } from 'firebase-functions/v2';
13
13
 
14
- import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
15
14
  import type {
16
15
  ServerRateLimitConfig as RateLimitConfig,
17
16
  ServerRateLimitResult as RateLimitResult,
18
17
  } from '@donotdev/core';
18
+ import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
19
19
 
20
20
  export type { RateLimitConfig, RateLimitResult };
21
21
 
@@ -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.