@donotdev/functions 0.2.2 → 0.2.3

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 (161) hide show
  1. package/README.md +1 -1
  2. package/lib/chunks/chunk-6NXIK35R.js +23 -0
  3. package/lib/chunks/chunk-6NXIK35R.js.map +7 -0
  4. package/lib/chunks/chunk-EZKRLLSQ.js +22 -0
  5. package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-EZKRLLSQ.js.map} +1 -1
  6. package/lib/chunks/chunk-F3PHE627.js +22 -0
  7. package/lib/chunks/chunk-F3PHE627.js.map +7 -0
  8. package/lib/chunks/chunk-F3WBFWPO.js +151 -0
  9. package/lib/chunks/chunk-F3WBFWPO.js.map +7 -0
  10. package/lib/chunks/chunk-G5DRV3DH.js +22 -0
  11. package/lib/chunks/chunk-G5DRV3DH.js.map +7 -0
  12. package/lib/chunks/{chunk-2A4FPYNB.js → chunk-GDIUOJMD.js} +2 -2
  13. package/lib/chunks/chunk-GDIUOJMD.js.map +7 -0
  14. package/lib/chunks/chunk-Q2WLRFOE.js +22 -0
  15. package/lib/chunks/chunk-Q2WLRFOE.js.map +7 -0
  16. package/lib/chunks/chunk-QXIOO2RL.js +22 -0
  17. package/lib/chunks/chunk-QXIOO2RL.js.map +7 -0
  18. package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-UH445BGK.js} +2 -2
  19. package/lib/chunks/chunk-W6W4L44F.js +22 -0
  20. package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
  21. package/lib/chunks/chunk-W74UL7AY.js +22 -0
  22. package/lib/chunks/chunk-W74UL7AY.js.map +7 -0
  23. package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-LXNVBD3G.js} +2 -2
  24. package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-GG5LPWXJ.js} +2 -2
  25. package/lib/chunks/{server-RYGEBS2B.js → server-NODQAE3F.js} +2 -2
  26. package/lib/firebase/crud/aggregate.d.ts +1 -1
  27. package/lib/firebase/index.js +1 -1
  28. package/lib/firebase/index.js.map +3 -3
  29. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  30. package/lib/shared/billing/createCheckout.d.ts +1 -1
  31. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  32. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  33. package/lib/shared/billing/stripePinned.d.ts +43 -0
  34. package/lib/shared/denoEnv.d.ts +25 -0
  35. package/lib/shared/github.d.ts +0 -8
  36. package/lib/shared/index.js +1 -1
  37. package/lib/shared/logger.d.ts +14 -14
  38. package/lib/shared/utils/external/subscription.d.ts +0 -8
  39. package/lib/shared/utils.d.ts +15 -3
  40. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  41. package/lib/supabase/crud/create.d.ts +0 -8
  42. package/lib/supabase/crud/entityStore.d.ts +13 -0
  43. package/lib/supabase/crud/update.d.ts +0 -8
  44. package/lib/supabase/index.d.ts +1 -0
  45. package/lib/supabase/index.js +1 -1
  46. package/lib/supabase/index.js.map +4 -4
  47. package/lib/vercel/api/index.js +1 -1
  48. package/lib/vercel/api/index.js.map +3 -3
  49. package/package.json +9 -9
  50. package/src/firebase/auth/getCustomClaims.ts +2 -0
  51. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  52. package/src/firebase/auth/removeCustomClaims.ts +2 -0
  53. package/src/firebase/auth/setCustomClaims.ts +3 -0
  54. package/src/firebase/baseFunction.ts +5 -2
  55. package/src/firebase/billing/changePlan.ts +6 -5
  56. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  57. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  58. package/src/firebase/billing/webhookHandler.ts +4 -4
  59. package/src/firebase/crud/aggregate.ts +41 -12
  60. package/src/firebase/crud/bulk.ts +7 -0
  61. package/src/firebase/crud/create.ts +21 -8
  62. package/src/firebase/crud/delete.ts +6 -1
  63. package/src/firebase/crud/get.ts +9 -2
  64. package/src/firebase/crud/list.ts +18 -8
  65. package/src/firebase/crud/update.ts +15 -7
  66. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  67. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  68. package/src/firebase/oauth/exchangeToken.ts +4 -0
  69. package/src/firebase/oauth/getConnections.ts +1 -1
  70. package/src/firebase/oauth/githubAccess.ts +3 -0
  71. package/src/firebase/oauth/refreshToken.ts +1 -0
  72. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  73. package/src/shared/ai/classifyAIError.ts +18 -10
  74. package/src/shared/ai/createAIRoute.ts +2 -1
  75. package/src/shared/ai/resolveModelTier.ts +2 -1
  76. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  77. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  78. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  79. package/src/shared/billing/checkoutValidation.ts +19 -2
  80. package/src/shared/billing/createCheckout.ts +56 -11
  81. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  82. package/src/shared/billing/orderWebhook.ts +69 -1
  83. package/src/shared/billing/stripeClient.ts +2 -1
  84. package/src/shared/billing/stripePinned.ts +71 -0
  85. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  86. package/src/shared/billing/webhookHandler.ts +5 -1
  87. package/src/shared/crud/bulkCore.ts +3 -2
  88. package/src/shared/denoEnv.ts +29 -0
  89. package/src/shared/email/createEmailRoute.ts +2 -2
  90. package/src/shared/errorHandling.ts +8 -8
  91. package/src/shared/firebase.ts +26 -9
  92. package/src/shared/github.ts +15 -5
  93. package/src/shared/logger.ts +37 -38
  94. package/src/shared/schema.ts +6 -10
  95. package/src/shared/utils/external/date.ts +4 -4
  96. package/src/shared/utils/external/subscription.ts +2 -89
  97. package/src/shared/utils/firebaseHelpers.ts +2 -0
  98. package/src/shared/utils/internal/idempotency.ts +3 -0
  99. package/src/shared/utils/internal/monitoring.ts +6 -5
  100. package/src/shared/utils/internal/validation.ts +2 -0
  101. package/src/shared/utils/schemaValidation.ts +1 -0
  102. package/src/shared/utils/validation.ts +10 -20
  103. package/src/shared/utils.ts +12 -7
  104. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  105. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  106. package/src/supabase/auth/deleteAccount.ts +72 -5
  107. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  108. package/src/supabase/crud/aggregate.ts +85 -72
  109. package/src/supabase/crud/bulk.ts +3 -0
  110. package/src/supabase/crud/create.ts +13 -9
  111. package/src/supabase/crud/delete.ts +2 -1
  112. package/src/supabase/crud/entityStore.ts +1 -1
  113. package/src/supabase/crud/get.ts +2 -1
  114. package/src/supabase/crud/list.ts +23 -17
  115. package/src/supabase/crud/update.ts +9 -6
  116. package/src/supabase/edgeFunction.ts +2 -1
  117. package/src/supabase/email/createEmailFunction.ts +2 -1
  118. package/src/supabase/index.ts +1 -0
  119. package/src/supabase/oauth/exchangeToken.ts +1 -0
  120. package/src/supabase/oauth/getConnections.ts +1 -1
  121. package/src/supabase/oauth/refreshToken.ts +1 -0
  122. package/src/supabase/utils/idempotency.ts +1 -1
  123. package/src/supabase/utils/monitoring.ts +1 -0
  124. package/src/vercel/api/billing/change-plan.ts +6 -5
  125. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  126. package/src/vercel/api/crud/bulk.ts +7 -2
  127. package/src/vercel/api/crud/create.ts +6 -3
  128. package/src/vercel/api/crud/delete.ts +5 -2
  129. package/src/vercel/api/crud/get.ts +5 -2
  130. package/src/vercel/api/crud/list.ts +6 -3
  131. package/src/vercel/api/crud/update.ts +6 -3
  132. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  133. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  134. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  135. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  136. package/src/vercel/baseFunction.ts +5 -1
  137. package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
  138. package/lib/chunks/chunk-2IFFIUFV.js +0 -23
  139. package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
  140. package/lib/chunks/chunk-FQSQGOBN.js +0 -22
  141. package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
  142. package/lib/chunks/chunk-G4FO76EA.js +0 -22
  143. package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
  144. package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
  145. package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
  146. package/lib/chunks/chunk-M4JV2JCF.js +0 -22
  147. package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
  148. package/lib/chunks/chunk-OZX5ZG44.js +0 -22
  149. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  150. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  151. package/lib/chunks/chunk-UYI56E6Q.js +0 -151
  152. package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
  153. package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
  154. package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
  155. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  156. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  157. package/src/shared/utils/functionWrapper.ts +0 -73
  158. /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-UH445BGK.js.map} +0 -0
  159. /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-LXNVBD3G.js.map} +0 -0
  160. /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
  161. /package/lib/chunks/{server-RYGEBS2B.js.map → server-NODQAE3F.js.map} +0 -0
@@ -139,12 +139,18 @@ export function mapClassifiedToHTTP(code: AIErrorCode): number {
139
139
  function extractStatus(err: unknown): number | undefined {
140
140
  if (err && typeof err === 'object') {
141
141
  // Anthropic SDK errors have .status
142
- if ('status' in err && typeof (err as any).status === 'number') {
143
- return (err as any).status;
142
+ if ('status' in err && typeof err.status === 'number') {
143
+ return err.status;
144
144
  }
145
145
  // Some errors nest status in .error
146
- if ('error' in err && typeof (err as any).error?.status === 'number') {
147
- return (err as any).error.status;
146
+ if (
147
+ 'error' in err &&
148
+ typeof err.error === 'object' &&
149
+ err.error !== null &&
150
+ 'status' in err.error &&
151
+ typeof err.error.status === 'number'
152
+ ) {
153
+ return err.error.status;
148
154
  }
149
155
  }
150
156
  return undefined;
@@ -154,7 +160,7 @@ function extractMessage(err: unknown): string {
154
160
  if (err instanceof Error) return err.message.toLowerCase();
155
161
  if (typeof err === 'string') return err.toLowerCase();
156
162
  if (err && typeof err === 'object' && 'message' in err) {
157
- return String((err as any).message).toLowerCase();
163
+ return String(err.message).toLowerCase();
158
164
  }
159
165
  return '';
160
166
  }
@@ -162,12 +168,14 @@ function extractMessage(err: unknown): string {
162
168
  function extractRetryAfter(err: unknown): number | undefined {
163
169
  if (err && typeof err === 'object') {
164
170
  // Anthropic SDK puts headers on the error
165
- const headers = (err as any).headers;
166
- if (headers) {
167
- const retryAfter =
168
- typeof headers.get === 'function'
171
+ const headers: unknown = 'headers' in err ? err.headers : undefined;
172
+ if (headers && typeof headers === 'object') {
173
+ const retryAfter: unknown =
174
+ 'get' in headers && typeof headers.get === 'function'
169
175
  ? headers.get('retry-after')
170
- : headers['retry-after'];
176
+ : 'retry-after' in headers
177
+ ? headers['retry-after']
178
+ : undefined;
171
179
  if (retryAfter) {
172
180
  const seconds = Number(retryAfter);
173
181
  if (!Number.isNaN(seconds)) return seconds * 1000;
@@ -28,6 +28,7 @@ import type {
28
28
  import { AI_MODELS, validateAIChatRequest } from '@donotdev/core/server';
29
29
 
30
30
  import { calculateCost } from './costTracker.js';
31
+ import { getDenoEnv } from '../denoEnv.js';
31
32
 
32
33
  // =============================================================================
33
34
  // Types
@@ -395,7 +396,7 @@ function jsonError(message: string, status: number): Response {
395
396
 
396
397
  function getEnv(name: string): string | undefined {
397
398
  if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
398
- return (globalThis as any).Deno?.env?.get(name);
399
+ return getDenoEnv()?.get(name);
399
400
  }
400
401
  return typeof process !== 'undefined' ? process.env[name] : undefined;
401
402
  }
@@ -13,6 +13,7 @@
13
13
 
14
14
  import { AI_TIERS } from '@donotdev/core/server';
15
15
  import type { AITierId } from '@donotdev/core/server';
16
+ import { getDenoEnv } from '../denoEnv.js';
16
17
 
17
18
  // =============================================================================
18
19
  // Env helper (Deno + Node cross-runtime)
@@ -20,7 +21,7 @@ import type { AITierId } from '@donotdev/core/server';
20
21
 
21
22
  function getEnv(name: string): string | undefined {
22
23
  if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
23
- return (globalThis as any).Deno?.env?.get(name);
24
+ return getDenoEnv()?.get(name);
24
25
  }
25
26
  return typeof process !== 'undefined' ? process.env[name] : undefined;
26
27
  }
@@ -415,6 +415,100 @@ describe('createCheckoutAlgorithm — StripeOrder session options', () => {
415
415
  run(ORDER_REQUEST, makeConfig(withSession({ invoiceFooter: 'x' }, { invoiceCreation: false })))
416
416
  ).rejects.toThrow(/invoiceCreation/);
417
417
  });
418
+
419
+ it('existing customer under automatic tax: customer + customer_update, no customer_email / customer_creation', async () => {
420
+ const { params } = await run(
421
+ { ...ORDER_REQUEST, customerEmail: 'pro@example.com' },
422
+ makeConfig(
423
+ withSession(
424
+ { customerId: 'cus_Pro123' },
425
+ {
426
+ tax: { mode: 'automatic' },
427
+ taxIdCollection: 'disabled',
428
+ shipping: { allowedCountries: ['FR', 'DE'] },
429
+ }
430
+ )
431
+ )
432
+ );
433
+ expect(params!.customer).toBe('cus_Pro123');
434
+ expect(params!.customer_update).toEqual({ address: 'auto', shipping: 'auto' });
435
+ expect(params).not.toHaveProperty('customer_email');
436
+ expect(params).not.toHaveProperty('customer_creation');
437
+ expect(params!.tax_id_collection).toEqual({ enabled: false });
438
+ expect(params!.automatic_tax).toEqual({ enabled: true });
439
+ });
440
+
441
+ it('existing customer with tax ID collection: customer_update.name auto (Stripe requirement)', async () => {
442
+ const { params } = await run(
443
+ ORDER_REQUEST,
444
+ makeConfig(withSession({ customerId: 'cus_Pro123' }, { taxIdCollection: 'optional' }))
445
+ );
446
+ // manual tax, no shipping: only the name is written back
447
+ expect(params!.customer_update).toEqual({ name: 'auto' });
448
+ });
449
+
450
+ it('existing customer with manual tax, no shipping, no tax ID collection: no customer_update', async () => {
451
+ const { params } = await run(
452
+ ORDER_REQUEST,
453
+ makeConfig(withSession({ customerId: 'cus_Pro123' }, { taxIdCollection: 'disabled' }))
454
+ );
455
+ expect(params!.customer).toBe('cus_Pro123');
456
+ expect(params).not.toHaveProperty('customer_update');
457
+ });
458
+
459
+ it('without customerId keeps customer_email + customer_creation', async () => {
460
+ const { params } = await run(
461
+ { ...ORDER_REQUEST, customerEmail: 'pro@example.com' },
462
+ makeConfig(withSession({}))
463
+ );
464
+ expect(params!.customer_email).toBe('pro@example.com');
465
+ expect(params!.customer_creation).toBe('always');
466
+ expect(params).not.toHaveProperty('customer');
467
+ expect(params).not.toHaveProperty('customer_update');
468
+ });
469
+
470
+ it('rejects a customerId that is not a Stripe Customer ID', async () => {
471
+ await expect(
472
+ run(ORDER_REQUEST, makeConfig(withSession({ customerId: 'user_42' })))
473
+ ).rejects.toThrow(/customerId/);
474
+ });
475
+
476
+ it('line taxCode becomes product_data.tax_code under automatic tax', async () => {
477
+ const shippingLine = { productId: 'shipping', name: 'Colissimo', unitAmount: 1009, quantity: 1, taxCode: 'txcd_92010001' };
478
+ const order = makeOrderItem({
479
+ tax: { mode: 'automatic' },
480
+ resolveLineItems: vi.fn(async () => ({ orderId: 'ord_1', lineItems: [line, shippingLine] })),
481
+ });
482
+ const { params } = await run(ORDER_REQUEST, makeConfig(order));
483
+ expect(params!.line_items![0]!.price_data!.product_data).not.toHaveProperty('tax_code');
484
+ expect(params!.line_items![1]!.price_data!.product_data!.tax_code).toBe('txcd_92010001');
485
+ });
486
+
487
+ it('rejects a malformed taxCode and a taxCode under manual tax', async () => {
488
+ const bad = { ...line, taxCode: 'shipping' };
489
+ await expect(
490
+ run(
491
+ ORDER_REQUEST,
492
+ makeConfig(
493
+ makeOrderItem({
494
+ tax: { mode: 'automatic' },
495
+ resolveLineItems: vi.fn(async () => ({ orderId: 'ord_1', lineItems: [bad] })),
496
+ })
497
+ )
498
+ )
499
+ ).rejects.toThrow(/taxCode/);
500
+ const manual = { ...line, taxCode: 'txcd_92010001' };
501
+ await expect(
502
+ run(
503
+ ORDER_REQUEST,
504
+ makeConfig(
505
+ makeOrderItem({
506
+ resolveLineItems: vi.fn(async () => ({ orderId: 'ord_1', lineItems: [manual] })),
507
+ })
508
+ )
509
+ )
510
+ ).rejects.toThrow(/tax.mode 'automatic'/);
511
+ });
418
512
  });
419
513
 
420
514
  // ---------------------------------------------------------------------------
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Firestore idempotency store against the Firestore emulator
5
5
  * @description Runs only when FIRESTORE_EMULATOR_HOST is set, e.g.
6
6
  * `bunx firebase-tools emulators:exec --only firestore --project demo-dndev
7
- * "bun test src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts"`.
7
+ * "bunx vitest run src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts"`.
8
8
  *
9
9
  * @version 0.2.0
10
10
  * @since 0.2.0
@@ -1052,6 +1052,114 @@ describe('event routing — invoice.payment_failed', () => {
1052
1052
 
1053
1053
  // ---------------------------------------------------------------------------
1054
1054
 
1055
+ describe('event routing — customer.tax_id.updated', () => {
1056
+ beforeEach(() => {
1057
+ resetIdempotencyStore();
1058
+ vi.spyOn(console, 'error').mockImplementation(() => {});
1059
+ });
1060
+
1061
+ const taxIdObject = (status: string | null) => ({
1062
+ id: 'txi_123',
1063
+ object: 'tax_id',
1064
+ customer: 'cus_pro_1',
1065
+ type: 'eu_vat',
1066
+ value: 'DE123456789',
1067
+ country: 'DE',
1068
+ verification: status
1069
+ ? { status, verified_name: 'Salon GmbH', verified_address: null }
1070
+ : null,
1071
+ });
1072
+
1073
+ const orderItem = (onTaxIdUpdated?: (...args: any[]) => Promise<void>) => ({
1074
+ type: 'StripeOrder' as const,
1075
+ name: 'Order',
1076
+ currency: 'eur',
1077
+ tax: { mode: 'automatic' },
1078
+ taxIdCollection: 'disabled',
1079
+ billingAddressCollection: 'required',
1080
+ customerCreation: 'always',
1081
+ invoiceCreation: true,
1082
+ resolveLineItems: vi.fn(),
1083
+ onOrderPaid: vi.fn(),
1084
+ ...(onTaxIdUpdated && { onTaxIdUpdated }),
1085
+ });
1086
+
1087
+ it('calls onTaxIdUpdated with the tax ID snapshot and event context', async () => {
1088
+ const onTaxIdUpdated = vi.fn(async () => {});
1089
+ const event = makeEvent('customer.tax_id.updated', taxIdObject('unverified'));
1090
+
1091
+ const result = await callProcessWebhook({
1092
+ stripe: makeStripe(event),
1093
+ config: { ...makeConfig(), shop_order: orderItem(onTaxIdUpdated) },
1094
+ });
1095
+
1096
+ expect(result).toEqual({ success: true, message: 'Webhook processed' });
1097
+ expect(onTaxIdUpdated).toHaveBeenCalledTimes(1);
1098
+ expect(onTaxIdUpdated).toHaveBeenCalledWith(
1099
+ {
1100
+ id: 'txi_123',
1101
+ customerId: 'cus_pro_1',
1102
+ type: 'eu_vat',
1103
+ value: 'DE123456789',
1104
+ country: 'DE',
1105
+ verification: {
1106
+ status: 'unverified',
1107
+ verifiedName: 'Salon GmbH',
1108
+ verifiedAddress: null,
1109
+ },
1110
+ },
1111
+ { billingConfigKey: 'shop_order', eventId: event.id }
1112
+ );
1113
+ });
1114
+
1115
+ it('runs a hook shared by several StripeOrder items once; skips items without it', async () => {
1116
+ const onTaxIdUpdated = vi.fn(async () => {});
1117
+ const event = makeEvent('customer.tax_id.updated', taxIdObject(null));
1118
+
1119
+ await callProcessWebhook({
1120
+ stripe: makeStripe(event),
1121
+ config: {
1122
+ ...makeConfig(),
1123
+ order_a: orderItem(onTaxIdUpdated),
1124
+ order_b: orderItem(onTaxIdUpdated),
1125
+ order_c: orderItem(),
1126
+ },
1127
+ });
1128
+
1129
+ expect(onTaxIdUpdated).toHaveBeenCalledTimes(1);
1130
+ expect((onTaxIdUpdated.mock.calls[0] as any[])[0].verification).toBeNull();
1131
+ });
1132
+
1133
+ it('succeeds without any onTaxIdUpdated hook', async () => {
1134
+ const event = makeEvent('customer.tax_id.updated', taxIdObject('verified'));
1135
+ const result = await callProcessWebhook({
1136
+ stripe: makeStripe(event),
1137
+ config: { ...makeConfig(), shop_order: orderItem() },
1138
+ });
1139
+ expect(result).toEqual({ success: true, message: 'Webhook processed' });
1140
+ });
1141
+
1142
+ it('a throwing hook fails the webhook and the retry is processed (reservation released)', async () => {
1143
+ const onTaxIdUpdated = vi
1144
+ .fn<(...args: any[]) => Promise<void>>()
1145
+ .mockRejectedValueOnce(new Error('db down'))
1146
+ .mockResolvedValueOnce(undefined);
1147
+ const event = makeEvent('customer.tax_id.updated', taxIdObject('unverified'));
1148
+ const config = { ...makeConfig(), shop_order: orderItem(onTaxIdUpdated) };
1149
+
1150
+ await expect(
1151
+ callProcessWebhook({ stripe: makeStripe(event), config })
1152
+ ).rejects.toThrow();
1153
+ const retry = await callProcessWebhook({ stripe: makeStripe(event), config });
1154
+
1155
+ expect(retry).toEqual({ success: true, message: 'Webhook processed' });
1156
+ expect(onTaxIdUpdated).toHaveBeenCalledTimes(2);
1157
+ const replay = await callProcessWebhook({ stripe: makeStripe(event), config });
1158
+ expect(replay).toEqual({ success: true, message: 'Event already processed' });
1159
+ expect(onTaxIdUpdated).toHaveBeenCalledTimes(2);
1160
+ });
1161
+ });
1162
+
1055
1163
  describe('event routing — unknown event types', () => {
1056
1164
  beforeEach(() => {
1057
1165
  resetIdempotencyStore();
@@ -54,7 +54,7 @@ export function validateCheckoutUrl(url: string, name: string): void {
54
54
  * Length limits are checked on the final metadata ({@link assertStripeMetadata}).
55
55
  */
56
56
  export function sanitizeMetadata(
57
- metadata: Record<string, any>
57
+ metadata: Record<string, unknown>
58
58
  ): Record<string, string> {
59
59
  const sanitized: Record<string, string> = {};
60
60
 
@@ -184,6 +184,11 @@ export function assertResolvedOrder(
184
184
  `Line '${line.productId}': quantity must be a positive integer, got ${line.quantity}`
185
185
  );
186
186
  }
187
+ if (line.taxCode !== undefined && !STRIPE_TAX_CODE.test(line.taxCode)) {
188
+ throw new Error(
189
+ `Line '${line.productId}': taxCode must be a Stripe tax code (txcd_ + 8 digits), got '${line.taxCode}'`
190
+ );
191
+ }
187
192
  }
188
193
  }
189
194
 
@@ -195,6 +200,12 @@ const MAX_INVOICE_FOOTER_LENGTH = 5000;
195
200
 
196
201
  const ORDER_PAYMENT_METHOD_TYPES = ['card', 'sepa_debit'] as const;
197
202
 
203
+ /** Stripe Customer ID shape. */
204
+ const STRIPE_CUSTOMER_ID = /^cus_[A-Za-z0-9]+$/;
205
+
206
+ /** Stripe tax code shape (https://docs.stripe.com/tax/tax-codes), e.g. `txcd_92010001`. */
207
+ const STRIPE_TAX_CODE = /^txcd_\d{8}$/;
208
+
198
209
  /**
199
210
  * Validate per-order session options returned by `resolveLineItems`.
200
211
  * Item-dependent checks (manual tax, invoice creation) run in `createCheckoutAlgorithm`.
@@ -212,7 +223,13 @@ export function assertResolvedOrderSession(
212
223
  configKey: string,
213
224
  nowSeconds: number = Math.floor(Date.now() / 1000)
214
225
  ): void {
215
- const { taxRateIds, paymentMethodTypes, expiresAt, invoiceFooter } = session;
226
+ const { taxRateIds, paymentMethodTypes, expiresAt, invoiceFooter, customerId } =
227
+ session;
228
+ if (customerId !== undefined && !STRIPE_CUSTOMER_ID.test(customerId)) {
229
+ throw new Error(
230
+ `resolveLineItems for '${configKey}': session.customerId must be a Stripe Customer ID (cus_...), got '${customerId}'`
231
+ );
232
+ }
216
233
  if (taxRateIds && taxRateIds.some((id) => typeof id !== 'string' || id.length === 0)) {
217
234
  throw new Error(
218
235
  `resolveLineItems for '${configKey}': session.taxRateIds must be non-empty strings`
@@ -88,6 +88,7 @@ export type CheckoutProvider = StripeCheckoutProvider | StripeSessionProvider;
88
88
  */
89
89
  export interface AuthCheckoutProvider {
90
90
  getUser(userId: string): Promise<{
91
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
91
92
  customClaims?: Record<string, any>;
92
93
  }>;
93
94
  }
@@ -116,6 +117,26 @@ interface BaseSessionParams {
116
117
  metadata: Record<string, string>;
117
118
  }
118
119
 
120
+ /**
121
+ * What Checkout writes back to an existing Customer (`customer_update`):
122
+ * - `address` under automatic tax: Stripe Tax needs an address on the Customer, the
123
+ * billing address entered at checkout replaces the saved one;
124
+ * - `shipping` when shipping is collected (Stripe: needs shipping_address_collection);
125
+ * - `name` when tax ID collection is enabled (Stripe: required for existing customers).
126
+ * Undefined when nothing applies (manual tax, no shipping, no tax ID collection).
127
+ */
128
+ function customerUpdate(
129
+ item: StripeOrderBackItem,
130
+ taxIdCollectionEnabled: boolean
131
+ ): Stripe.Checkout.SessionCreateParams.CustomerUpdate | undefined {
132
+ const update: Stripe.Checkout.SessionCreateParams.CustomerUpdate = {
133
+ ...(item.tax.mode === 'automatic' && { address: 'auto' }),
134
+ ...(item.shipping && { shipping: 'auto' }),
135
+ ...(taxIdCollectionEnabled && { name: 'auto' }),
136
+ };
137
+ return Object.keys(update).length > 0 ? update : undefined;
138
+ }
139
+
119
140
  /**
120
141
  * Session params for a StripeOrder: server-priced lines (excl. VAT) and the
121
142
  * item's B2B options.
@@ -131,6 +152,23 @@ function buildOrderSessionParams(
131
152
  ? (options.taxRateIds ?? item.tax.taxRateIds)
132
153
  : undefined;
133
154
  const metadata = { ...base.metadata, [ORDER_ID_METADATA_KEY]: order.orderId };
155
+ const taxIdCollectionEnabled = item.taxIdCollection !== 'disabled';
156
+ const update = customerUpdate(item, taxIdCollectionEnabled);
157
+
158
+ // Existing Customer: Stripe applies customer_email / customer_creation only when it
159
+ // creates a Customer, so they are replaced by customer + customer_update.
160
+ const customerParams: Pick<
161
+ Stripe.Checkout.SessionCreateParams,
162
+ 'customer' | 'customer_update' | 'customer_email' | 'customer_creation'
163
+ > = options.customerId
164
+ ? {
165
+ customer: options.customerId,
166
+ ...(update && { customer_update: update }),
167
+ }
168
+ : {
169
+ customer_creation: item.customerCreation,
170
+ customer_email: base.customerEmail,
171
+ };
134
172
 
135
173
  return {
136
174
  mode: 'payment',
@@ -143,6 +181,7 @@ function buildOrderSessionParams(
143
181
  product_data: {
144
182
  name: line.name,
145
183
  ...(line.description && { description: line.description }),
184
+ ...(line.taxCode && { tax_code: line.taxCode }),
146
185
  metadata: { [PRODUCT_ID_METADATA_KEY]: line.productId },
147
186
  },
148
187
  },
@@ -150,14 +189,13 @@ function buildOrderSessionParams(
150
189
  ...(taxRates && taxRates.length > 0 && { tax_rates: taxRates }),
151
190
  })),
152
191
  automatic_tax: { enabled: item.tax.mode === 'automatic' },
153
- tax_id_collection:
154
- item.taxIdCollection === 'disabled'
155
- ? { enabled: false }
156
- : {
157
- enabled: true,
158
- required:
159
- item.taxIdCollection === 'required' ? 'if_supported' : 'never',
160
- },
192
+ tax_id_collection: taxIdCollectionEnabled
193
+ ? {
194
+ enabled: true,
195
+ required:
196
+ item.taxIdCollection === 'required' ? 'if_supported' : 'never',
197
+ }
198
+ : { enabled: false },
161
199
  billing_address_collection: item.billingAddressCollection,
162
200
  ...(item.shipping && {
163
201
  shipping_address_collection: {
@@ -171,7 +209,7 @@ function buildOrderSessionParams(
171
209
  })),
172
210
  }),
173
211
  }),
174
- customer_creation: item.customerCreation,
212
+ ...customerParams,
175
213
  invoice_creation: {
176
214
  enabled: item.invoiceCreation,
177
215
  ...(item.invoiceCreation && {
@@ -192,7 +230,6 @@ function buildOrderSessionParams(
192
230
  allow_promotion_codes: item.allowPromotionCodes === true,
193
231
  success_url: base.successUrl,
194
232
  cancel_url: base.cancelUrl,
195
- customer_email: base.customerEmail,
196
233
  metadata,
197
234
  payment_intent_data: { metadata },
198
235
  };
@@ -210,7 +247,7 @@ type CheckoutArgs =
210
247
  * 3. `beforeCheckout` hook (block/allow)
211
248
  * 4. StripeOrder: reject inclusive manual Tax Rates, `resolveLineItems` prices every line
212
249
  * and may set per-order session options (`ResolvedOrder.session`: tax rates,
213
- * payment methods, expiry, invoice footer)
250
+ * payment methods, expiry, invoice footer, existing Stripe customer)
214
251
  * 5. Validate metadata against Stripe limits, create the session through the provider
215
252
  *
216
253
  * Server-owned metadata (`userId`, `billingConfigKey`, `orderId`) is written after
@@ -361,6 +398,14 @@ export async function createCheckoutAlgorithm(
361
398
  billingConfigKey
362
399
  );
363
400
  }
401
+ if (
402
+ billingItem.tax.mode !== 'automatic' &&
403
+ order.lineItems.some((line) => line.taxCode !== undefined)
404
+ ) {
405
+ throw new Error(
406
+ `resolveLineItems for '${billingConfigKey}': line taxCode needs tax.mode 'automatic'`
407
+ );
408
+ }
364
409
  if (sessionOptions?.invoiceFooter && !billingItem.invoiceCreation) {
365
410
  throw new Error(
366
411
  `resolveLineItems for '${billingConfigKey}': session.invoiceFooter needs invoiceCreation`
@@ -12,11 +12,15 @@
12
12
  import type Stripe from 'stripe';
13
13
 
14
14
  import { SUBSCRIPTION_STATUS } from '@donotdev/core/server';
15
- import type { BillingAuthProvider } from '@donotdev/core/server';
15
+ import type {
16
+ BillingAuthProvider,
17
+ StripeBackConfig,
18
+ } from '@donotdev/core/server';
16
19
 
17
20
  import { updateUserSubscription } from './updateUserSubscription.js';
18
21
  import { handleError } from '../../errorHandling.js';
19
22
  import { stripe, validateStripeEnvironment } from '../stripeClient.js';
23
+ import { isOneOf, pinnedSubscriptionPeriod } from '../stripePinned.js';
20
24
 
21
25
  /**
22
26
  * Cancel user subscription at period end
@@ -59,8 +63,8 @@ export async function cancelUserSubscription(
59
63
  'trialing',
60
64
  'incomplete',
61
65
  ] as const;
62
- const status = validStatuses.includes(updatedSubscription.status as any)
63
- ? (updatedSubscription.status as (typeof validStatuses)[number])
66
+ const status = isOneOf(validStatuses, updatedSubscription.status)
67
+ ? updatedSubscription.status
64
68
  : 'incomplete';
65
69
 
66
70
  // Update Firebase Auth claims
@@ -70,7 +74,7 @@ export async function cancelUserSubscription(
70
74
  tier: subscription?.tier || 'free',
71
75
  status,
72
76
  subscriptionEnd: new Date(
73
- (updatedSubscription as any).current_period_end * 1000
77
+ pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000
74
78
  ).toISOString(),
75
79
  cancelAtPeriodEnd: true,
76
80
  subscriptionId: updatedSubscription.id,
@@ -82,7 +86,7 @@ export async function cancelUserSubscription(
82
86
  return {
83
87
  success: true,
84
88
  endsAt: new Date(
85
- (updatedSubscription as any).current_period_end * 1000
89
+ pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000
86
90
  ).toISOString(),
87
91
  };
88
92
  }
@@ -98,7 +102,7 @@ export async function changeUserPlan(
98
102
  userId: string,
99
103
  newPriceId: string,
100
104
  billingConfigKey: string,
101
- billingConfig: Record<string, any>,
105
+ billingConfig: StripeBackConfig,
102
106
  authProvider: BillingAuthProvider
103
107
  ): Promise<{ success: boolean; newTier: string; newPrice: number }> {
104
108
  validateStripeEnvironment();
@@ -153,8 +157,8 @@ export async function changeUserPlan(
153
157
  'trialing',
154
158
  'incomplete',
155
159
  ] as const;
156
- const status = validStatuses.includes(updatedSubscription.status as any)
157
- ? (updatedSubscription.status as (typeof validStatuses)[number])
160
+ const status = isOneOf(validStatuses, updatedSubscription.status)
161
+ ? updatedSubscription.status
158
162
  : 'incomplete';
159
163
 
160
164
  // Update Firebase Auth claims
@@ -164,9 +168,9 @@ export async function changeUserPlan(
164
168
  tier: billingItem.tier,
165
169
  status,
166
170
  subscriptionEnd: new Date(
167
- (updatedSubscription as any).current_period_end * 1000
171
+ pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000
168
172
  ).toISOString(),
169
- cancelAtPeriodEnd: (updatedSubscription as any).cancel_at_period_end,
173
+ cancelAtPeriodEnd: updatedSubscription.cancel_at_period_end,
170
174
  subscriptionId: updatedSubscription.id,
171
175
  customerId: updatedSubscription.customer as string,
172
176
  },
@@ -3,7 +3,8 @@
3
3
  /**
4
4
  * @fileoverview StripeOrder webhook handling
5
5
  * @description Maps Checkout Session events of one-time, multi-line orders to the
6
- * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`).
6
+ * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`), and
7
+ * `customer.tax_id.updated` to `onTaxIdUpdated`.
7
8
  * Hook errors propagate: the webhook answers non-2xx and Stripe retries.
8
9
  *
9
10
  * @version 0.2.0
@@ -18,7 +19,9 @@ import type {
18
19
  CheckoutSessionSnapshot,
19
20
  OrderHookContext,
20
21
  PaidLineItem,
22
+ StripeBackConfig,
21
23
  StripeOrderBackItem,
24
+ TaxIdSnapshot,
22
25
  } from '@donotdev/core/server';
23
26
 
24
27
  import { logger } from '../logger.js';
@@ -267,3 +270,68 @@ export async function handleOrderSessionEvent(
267
270
  return;
268
271
  }
269
272
  }
273
+
274
+ /**
275
+ * Map a Stripe TaxId to the provider-neutral snapshot given to `onTaxIdUpdated`.
276
+ *
277
+ * @param taxId - TaxId from a `customer.tax_id.updated` event
278
+ * @returns Snapshot
279
+ *
280
+ * @version 0.2.0
281
+ * @since 0.2.3
282
+ * @author AMBROISE PARK Consulting
283
+ */
284
+ export function toTaxIdSnapshot(taxId: Stripe.TaxId): TaxIdSnapshot {
285
+ return {
286
+ id: taxId.id,
287
+ customerId: idOf(taxId.customer),
288
+ type: taxId.type,
289
+ value: taxId.value,
290
+ country: taxId.country,
291
+ verification: taxId.verification && {
292
+ status: taxId.verification.status,
293
+ verifiedName: taxId.verification.verified_name,
294
+ verifiedAddress: taxId.verification.verified_address,
295
+ },
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Handle `customer.tax_id.updated`: run `onTaxIdUpdated` of every StripeOrder item
301
+ * that defines it, once per distinct function. Called by `processWebhook` after
302
+ * signature verification and idempotency reservation (same path as order events).
303
+ *
304
+ * @param eventId - Stripe event ID
305
+ * @param taxId - TaxId from the event
306
+ * @param config - App back config
307
+ * @throws When a hook throws (the webhook answers non-2xx and Stripe retries)
308
+ *
309
+ * @version 0.2.0
310
+ * @since 0.2.3
311
+ * @author AMBROISE PARK Consulting
312
+ */
313
+ export async function handleTaxIdUpdated(
314
+ eventId: string,
315
+ taxId: Stripe.TaxId,
316
+ config: StripeBackConfig
317
+ ): Promise<void> {
318
+ const snapshot = toTaxIdSnapshot(taxId);
319
+ const ran = new Set<StripeOrderBackItem['onTaxIdUpdated']>();
320
+ for (const [billingConfigKey, item] of Object.entries(config)) {
321
+ if (item.type !== 'StripeOrder' || !item.onTaxIdUpdated) continue;
322
+ if (ran.has(item.onTaxIdUpdated)) continue;
323
+ ran.add(item.onTaxIdUpdated);
324
+ await item.onTaxIdUpdated(snapshot, { billingConfigKey, eventId });
325
+ logger.info('[Webhook] Tax ID updated', {
326
+ taxIdId: snapshot.id,
327
+ status: snapshot.verification?.status ?? null,
328
+ billingConfigKey,
329
+ operation: 'tax_id_updated',
330
+ });
331
+ }
332
+ if (ran.size === 0) {
333
+ logger.debug('[Webhook] customer.tax_id.updated without onTaxIdUpdated hook', {
334
+ eventId,
335
+ });
336
+ }
337
+ }
@@ -34,7 +34,8 @@ export function initStripe(apiKey: string) {
34
34
  const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;
35
35
 
36
36
  _stripe = new Stripe(apiKey, {
37
- apiVersion: apiVersion as any,
37
+ // why: SDK types accept only the latest API version; the pinned/env version is older by design
38
+ apiVersion: apiVersion as Stripe.LatestApiVersion,
38
39
  });
39
40
  return _stripe;
40
41
  }