@donotdev/functions 0.2.1 → 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 (184) hide show
  1. package/README.md +2 -2
  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-EZKRLLSQ.js.map +7 -0
  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-5IPULSUX.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-3F4BWKQD.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-E7JBYBHQ.js → monitoring-LXNVBD3G.js} +2 -2
  24. package/lib/chunks/{rateLimiter-SQISLOP5.js → rateLimiter-GG5LPWXJ.js} +2 -2
  25. package/lib/chunks/server-NODQAE3F.js +22 -0
  26. package/lib/firebase/billing/index.d.ts +2 -2
  27. package/lib/firebase/crud/aggregate.d.ts +1 -1
  28. package/lib/firebase/index.d.ts +1 -1
  29. package/lib/firebase/index.js +1 -1
  30. package/lib/firebase/index.js.map +4 -4
  31. package/lib/firebase/registerCrudFunctions.d.ts +0 -5
  32. package/lib/shared/billing/checkoutPrice.d.ts +3 -6
  33. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  34. package/lib/shared/billing/createCheckout.d.ts +4 -4
  35. package/lib/shared/billing/firestoreIdempotency.d.ts +2 -2
  36. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  37. package/lib/shared/billing/idempotency.d.ts +3 -23
  38. package/lib/shared/billing/idempotencyContract.d.ts +0 -20
  39. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  40. package/lib/shared/billing/stripePinned.d.ts +43 -0
  41. package/lib/shared/denoEnv.d.ts +25 -0
  42. package/lib/shared/github.d.ts +0 -8
  43. package/lib/shared/index.js +1 -1
  44. package/lib/shared/logger.d.ts +14 -14
  45. package/lib/shared/utils/external/subscription.d.ts +0 -8
  46. package/lib/shared/utils/internal/auth.d.ts +1 -5
  47. package/lib/shared/utils.d.ts +12 -83
  48. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  49. package/lib/supabase/crud/create.d.ts +0 -8
  50. package/lib/supabase/crud/entityStore.d.ts +13 -0
  51. package/lib/supabase/crud/update.d.ts +0 -8
  52. package/lib/supabase/index.d.ts +1 -0
  53. package/lib/supabase/index.js +1 -1
  54. package/lib/supabase/index.js.map +4 -4
  55. package/lib/vercel/api/index.js +1 -1
  56. package/lib/vercel/api/index.js.map +3 -3
  57. package/package.json +9 -9
  58. package/src/firebase/auth/getCustomClaims.ts +2 -0
  59. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  60. package/src/firebase/auth/removeCustomClaims.ts +2 -0
  61. package/src/firebase/auth/setCustomClaims.ts +3 -0
  62. package/src/firebase/baseFunction.ts +8 -4
  63. package/src/firebase/billing/changePlan.ts +6 -5
  64. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  65. package/src/firebase/billing/index.d.ts +0 -12
  66. package/src/firebase/billing/index.ts +0 -3
  67. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  68. package/src/firebase/billing/webhookHandler.ts +4 -4
  69. package/src/firebase/crud/aggregate.ts +41 -12
  70. package/src/firebase/crud/bulk.ts +7 -0
  71. package/src/firebase/crud/create.ts +21 -8
  72. package/src/firebase/crud/delete.ts +6 -1
  73. package/src/firebase/crud/get.ts +9 -2
  74. package/src/firebase/crud/list.ts +18 -8
  75. package/src/firebase/crud/update.ts +15 -7
  76. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  77. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  78. package/src/firebase/index.ts +0 -1
  79. package/src/firebase/oauth/disconnect.ts +2 -2
  80. package/src/firebase/oauth/exchangeToken.ts +6 -2
  81. package/src/firebase/oauth/getConnections.ts +3 -3
  82. package/src/firebase/oauth/githubAccess.ts +7 -4
  83. package/src/firebase/oauth/refreshToken.ts +3 -2
  84. package/src/firebase/registerCrudFunctions.ts +0 -19
  85. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  86. package/src/shared/__tests__/idempotency.test.ts +0 -32
  87. package/src/shared/__tests__/utils.test.ts +0 -25
  88. package/src/shared/ai/classifyAIError.ts +18 -10
  89. package/src/shared/ai/createAIRoute.ts +2 -1
  90. package/src/shared/ai/resolveModelTier.ts +2 -1
  91. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +4 -110
  92. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  93. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  94. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  95. package/src/shared/billing/checkoutPrice.ts +7 -42
  96. package/src/shared/billing/checkoutValidation.ts +19 -2
  97. package/src/shared/billing/createCheckout.ts +59 -30
  98. package/src/shared/billing/firestoreIdempotency.ts +2 -21
  99. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  100. package/src/shared/billing/idempotency.ts +4 -54
  101. package/src/shared/billing/idempotencyContract.ts +0 -21
  102. package/src/shared/billing/orderWebhook.ts +69 -1
  103. package/src/shared/billing/stripeClient.ts +2 -1
  104. package/src/shared/billing/stripePinned.ts +71 -0
  105. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  106. package/src/shared/billing/webhookHandler.ts +5 -1
  107. package/src/shared/crud/bulkCore.ts +3 -2
  108. package/src/shared/denoEnv.ts +29 -0
  109. package/src/shared/email/createEmailRoute.ts +2 -2
  110. package/src/shared/errorHandling.ts +8 -8
  111. package/src/shared/firebase.ts +26 -9
  112. package/src/shared/github.ts +15 -5
  113. package/src/shared/logger.ts +37 -38
  114. package/src/shared/schema.ts +6 -10
  115. package/src/shared/utils/external/date.ts +4 -4
  116. package/src/shared/utils/external/subscription.ts +2 -89
  117. package/src/shared/utils/firebaseHelpers.ts +2 -0
  118. package/src/shared/utils/internal/auth.ts +1 -6
  119. package/src/shared/utils/internal/idempotency.ts +3 -0
  120. package/src/shared/utils/internal/monitoring.ts +6 -5
  121. package/src/shared/utils/internal/validation.ts +2 -0
  122. package/src/shared/utils/schemaValidation.ts +1 -0
  123. package/src/shared/utils/validation.ts +10 -20
  124. package/src/shared/utils.ts +12 -138
  125. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  126. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  127. package/src/supabase/auth/deleteAccount.ts +72 -5
  128. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  129. package/src/supabase/crud/aggregate.ts +85 -72
  130. package/src/supabase/crud/bulk.ts +3 -0
  131. package/src/supabase/crud/create.ts +13 -9
  132. package/src/supabase/crud/delete.ts +2 -1
  133. package/src/supabase/crud/entityStore.ts +1 -1
  134. package/src/supabase/crud/get.ts +2 -1
  135. package/src/supabase/crud/list.ts +23 -17
  136. package/src/supabase/crud/update.ts +9 -6
  137. package/src/supabase/edgeFunction.ts +2 -1
  138. package/src/supabase/email/createEmailFunction.ts +2 -1
  139. package/src/supabase/index.ts +1 -0
  140. package/src/supabase/oauth/exchangeToken.ts +1 -0
  141. package/src/supabase/oauth/getConnections.ts +1 -1
  142. package/src/supabase/oauth/refreshToken.ts +1 -0
  143. package/src/supabase/utils/idempotency.ts +1 -1
  144. package/src/supabase/utils/monitoring.ts +1 -0
  145. package/src/vercel/api/billing/change-plan.ts +6 -5
  146. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  147. package/src/vercel/api/crud/bulk.ts +7 -2
  148. package/src/vercel/api/crud/create.ts +6 -3
  149. package/src/vercel/api/crud/delete.ts +5 -2
  150. package/src/vercel/api/crud/get.ts +5 -2
  151. package/src/vercel/api/crud/list.ts +6 -3
  152. package/src/vercel/api/crud/update.ts +6 -3
  153. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  154. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  155. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  156. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  157. package/src/vercel/baseFunction.ts +5 -1
  158. package/lib/chunks/chunk-5IPULSUX.js.map +0 -7
  159. package/lib/chunks/chunk-6USHTJED.js +0 -22
  160. package/lib/chunks/chunk-6USHTJED.js.map +0 -7
  161. package/lib/chunks/chunk-CXBSROEW.js +0 -23
  162. package/lib/chunks/chunk-CXBSROEW.js.map +0 -7
  163. package/lib/chunks/chunk-GYTCWMXV.js +0 -22
  164. package/lib/chunks/chunk-GYTCWMXV.js.map +0 -7
  165. package/lib/chunks/chunk-LCDLG4VG.js +0 -151
  166. package/lib/chunks/chunk-LCDLG4VG.js.map +0 -7
  167. package/lib/chunks/chunk-MQANUSY3.js +0 -22
  168. package/lib/chunks/chunk-MQANUSY3.js.map +0 -7
  169. package/lib/chunks/chunk-OFQVO3FD.js +0 -22
  170. package/lib/chunks/chunk-OFQVO3FD.js.map +0 -7
  171. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  172. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  173. package/lib/chunks/chunk-US2VOP4S.js +0 -22
  174. package/lib/chunks/chunk-US2VOP4S.js.map +0 -7
  175. package/lib/chunks/chunk-YTKDNZNW.js +0 -22
  176. package/lib/chunks/chunk-YTKDNZNW.js.map +0 -7
  177. package/lib/chunks/server-IQ5JNJOM.js +0 -22
  178. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  179. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  180. package/src/shared/utils/functionWrapper.ts +0 -73
  181. /package/lib/chunks/{chunk-3F4BWKQD.js.map → chunk-UH445BGK.js.map} +0 -0
  182. /package/lib/chunks/{monitoring-E7JBYBHQ.js.map → monitoring-LXNVBD3G.js.map} +0 -0
  183. /package/lib/chunks/{rateLimiter-SQISLOP5.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
  184. /package/lib/chunks/{server-IQ5JNJOM.js.map → server-NODQAE3F.js.map} +0 -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();
@@ -23,23 +23,20 @@ import type {
23
23
 
24
24
  /** Price resolved for a single-price item (0.1.x rules). */
25
25
  export interface PricePlan {
26
- /** Fixed price charged; undefined for dynamic pricing */
27
- priceId?: string;
28
- /** 0.1.x dynamic pricing (client unitAmount + productName) */
29
- dynamic: boolean;
26
+ /** Price charged */
27
+ priceId: string;
30
28
  mode: CheckoutMode;
31
29
  }
32
30
 
33
31
  /**
34
32
  * 0.1.x pricing for StripePayment/StripeSubscription: a request priceId (must
35
- * match the config priceId when set), else 0.1.x dynamic pricing capped by
36
- * `maxUnitAmount`, else the back-config priceId.
33
+ * match the config priceId when set), else the back-config priceId.
37
34
  */
38
35
  export function resolvePricePlan(
39
36
  item: StripePaymentBackItem | StripeSubscriptionBackItem,
40
37
  request: CreateCheckoutSessionRequest
41
38
  ): PricePlan {
42
- const { billingConfigKey: key, priceId, unitAmount, productName } = request;
39
+ const { billingConfigKey: key, priceId } = request;
43
40
  const [line] = request.lineItems;
44
41
  if (
45
42
  request.lineItems.length !== 1 ||
@@ -52,7 +49,6 @@ export function resolvePricePlan(
52
49
  );
53
50
  }
54
51
 
55
- const dynamic = !priceId && !!unitAmount && !!productName;
56
52
  const mode: CheckoutMode =
57
53
  request.mode ?? (item.type === 'StripeSubscription' ? 'subscription' : 'payment');
58
54
 
@@ -60,29 +56,7 @@ export function resolvePricePlan(
60
56
  if (item.priceId && item.priceId !== priceId) {
61
57
  throw new Error('Price ID mismatch with configuration');
62
58
  }
63
- return { priceId, dynamic, mode };
64
- }
65
-
66
- if (dynamic) {
67
- if (mode === 'subscription') {
68
- throw new Error(
69
- 'Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.'
70
- );
71
- }
72
- if (!item.maxUnitAmount) {
73
- throw new Error(
74
- 'Dynamic pricing requires maxUnitAmount in billing config for security'
75
- );
76
- }
77
- if (unitAmount! > item.maxUnitAmount) {
78
- throw new Error(
79
- `Unit amount ${unitAmount} exceeds maximum allowed: ${item.maxUnitAmount}`
80
- );
81
- }
82
- if (unitAmount! < 100) {
83
- throw new Error('Unit amount must be at least 100 cents (1.00)');
84
- }
85
- return { dynamic, mode };
59
+ return { priceId, mode };
86
60
  }
87
61
 
88
62
  if (!item.priceId) {
@@ -90,7 +64,7 @@ export function resolvePricePlan(
90
64
  `'${key}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`
91
65
  );
92
66
  }
93
- return { priceId: item.priceId, dynamic, mode };
67
+ return { priceId: item.priceId, mode };
94
68
  }
95
69
 
96
70
  /** 0.1.x params → Stripe params (what the 0.1.x Firebase/Supabase providers sent). */
@@ -101,16 +75,7 @@ export function toStripeSessionParams(
101
75
  return {
102
76
  mode,
103
77
  line_items: [
104
- params.priceId
105
- ? { price: params.priceId, quantity: 1 }
106
- : {
107
- price_data: {
108
- currency: params.currency || 'eur',
109
- unit_amount: params.unitAmount!,
110
- product_data: { name: params.productName! },
111
- },
112
- quantity: 1,
113
- },
78
+ { price: params.priceId, quantity: 1 },
114
79
  ],
115
80
  allow_promotion_codes: params.allowPromotionCodes,
116
81
  success_url: params.successUrl,
@@ -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`
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Create Checkout Session Algorithm
5
5
  * @description Platform-agnostic algorithm for creating Stripe checkout sessions.
6
6
  * StripePayment/StripeSubscription items keep the 0.1.x behaviour (request or
7
- * back-config priceId, 0.1.x dynamic pricing). StripeOrder items are priced on
7
+ * back-config priceId). StripeOrder items are priced on
8
8
  * the server (`resolveLineItems`) and need a {@link StripeSessionProvider}.
9
9
  *
10
10
  * @version 0.2.0
@@ -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
  };
@@ -206,11 +243,11 @@ type CheckoutArgs =
206
243
  * Create checkout session algorithm
207
244
  *
208
245
  * 1. Resolve the billing config item and verify the user
209
- * 2. Single-price items: 0.1.x pricing (request/back-config priceId, dynamic pricing)
210
- * 3. `beforeCheckout` hook (block/allow; 0.1.x dynamic-pricing overrides)
246
+ * 2. Single-price items: 0.1.x pricing (request/back-config priceId)
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
@@ -301,8 +338,6 @@ export async function createCheckoutAlgorithm(
301
338
  );
302
339
 
303
340
  const allowPromotionCodes = request.allowPromotionCodes ?? true;
304
- let unitAmount = request.unitAmount;
305
- let productName = request.productName;
306
341
 
307
342
  if (billingItem.beforeCheckout) {
308
343
  const options: BeforeCheckoutOptions = {
@@ -323,11 +358,6 @@ export async function createCheckoutAlgorithm(
323
358
  hookResult.reason || 'Checkout blocked by beforeCheckout hook'
324
359
  );
325
360
  }
326
- // 0.1.x: overrides apply to dynamic pricing only
327
- if (plan?.dynamic && hookResult.overrides) {
328
- unitAmount = hookResult.overrides.unitAmount ?? unitAmount;
329
- productName = hookResult.overrides.productName ?? productName;
330
- }
331
361
  }
332
362
 
333
363
  const successUrl = resolveRedirectUrl(request.successUrl, 'success');
@@ -368,6 +398,14 @@ export async function createCheckoutAlgorithm(
368
398
  billingConfigKey
369
399
  );
370
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
+ }
371
409
  if (sessionOptions?.invoiceFooter && !billingItem.invoiceCreation) {
372
410
  throw new Error(
373
411
  `resolveLineItems for '${billingConfigKey}': session.invoiceFooter needs invoiceCreation`
@@ -382,17 +420,8 @@ export async function createCheckoutAlgorithm(
382
420
  assertCheckoutSessionMetadata(params);
383
421
  session = await stripeProvider.createStripeSession(params);
384
422
  } else {
385
- const dynamic = !!plan?.dynamic && !!unitAmount && !!productName;
386
- // 0.1.x: an overridden amount still respects the security cap
387
- if (dynamic && billingItem.maxUnitAmount && unitAmount! > billingItem.maxUnitAmount) {
388
- throw new Error(
389
- `Hook-overridden unit amount ${unitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
390
- );
391
- }
392
423
  const params: CheckoutSessionParams = {
393
424
  priceId: plan?.priceId,
394
- unitAmount: dynamic ? unitAmount : undefined,
395
- productName: dynamic ? productName : undefined,
396
425
  currency: request.currency || billingItem.currency || 'eur',
397
426
  customerEmail: request.customerEmail,
398
427
  metadata,
@@ -22,7 +22,7 @@ import {
22
22
  newOwnerToken,
23
23
  } from './idempotencyContract.js';
24
24
  import type {
25
- LegacyIdempotencyStore,
25
+ IdempotencyStore,
26
26
  ReservationResult,
27
27
  } from './idempotencyContract.js';
28
28
 
@@ -75,7 +75,7 @@ function parseEventDoc(eventId: string, data: unknown) {
75
75
  * @since 0.2.0
76
76
  * @author AMBROISE PARK Consulting
77
77
  */
78
- export function createFirestoreIdempotencyStore(): LegacyIdempotencyStore {
78
+ export function createFirestoreIdempotencyStore(): IdempotencyStore {
79
79
  let firebase: typeof import('@donotdev/firebase/server') | null = null;
80
80
  const load = async () => {
81
81
  if (!firebase) firebase = await import('@donotdev/firebase/server');
@@ -122,9 +122,6 @@ export function createFirestoreIdempotencyStore(): LegacyIdempotencyStore {
122
122
 
123
123
  return {
124
124
  reserve,
125
- async checkAndReserve(eventId) {
126
- return (await reserve(eventId)).state !== 'reserved';
127
- },
128
125
  async markProcessed(eventId, ownerToken) {
129
126
  const { firestore, Timestamp, refOf } = await load();
130
127
  const ref = refOf(eventId);
@@ -136,11 +133,6 @@ export function createFirestoreIdempotencyStore(): LegacyIdempotencyStore {
136
133
  expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),
137
134
  };
138
135
  try {
139
- if (ownerToken === undefined) {
140
- // 0.1.x call: unconditional write
141
- await ref.set(processed);
142
- return;
143
- }
144
136
  await firestore.runTransaction(async (tx) => {
145
137
  const snapshot = await tx.get(ref);
146
138
  const data = snapshot.exists
@@ -174,16 +166,5 @@ export function createFirestoreIdempotencyStore(): LegacyIdempotencyStore {
174
166
  throw handleError(error);
175
167
  }
176
168
  },
177
- async isProcessed(eventId) {
178
- const { refOf } = await load();
179
- try {
180
- const snapshot = await refOf(eventId).get();
181
- if (!snapshot.exists) return false;
182
- const data = parseEventDoc(eventId, snapshot.data());
183
- return data.status !== 'processing' && (data.expiresAt ?? 0) >= Date.now();
184
- } catch (error) {
185
- throw handleError(error);
186
- }
187
- },
188
169
  };
189
170
  }
@@ -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
  },
@@ -18,15 +18,13 @@
18
18
  * @author AMBROISE PARK Consulting
19
19
  */
20
20
 
21
- import { isFirestoreConfigured } from '../utils/detectFirestore.js';
22
- import { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
23
21
  import {
24
22
  RESERVATION_LEASE_MS,
25
23
  ReservationLostError,
26
24
  newOwnerToken,
27
25
  } from './idempotencyContract.js';
28
26
  import type {
29
- LegacyIdempotencyStore,
27
+ IdempotencyStore,
30
28
  ReservationResult,
31
29
  } from './idempotencyContract.js';
32
30
 
@@ -37,7 +35,6 @@ export {
37
35
  } from './idempotencyContract.js';
38
36
  export type {
39
37
  IdempotencyStore,
40
- LegacyIdempotencyStore,
41
38
  ReservationResult,
42
39
  } from './idempotencyContract.js';
43
40
  export { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
@@ -53,7 +50,7 @@ export { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
53
50
  * @since 0.2.0
54
51
  * @author AMBROISE PARK Consulting
55
52
  */
56
- export function createInMemoryIdempotencyStore(): LegacyIdempotencyStore {
53
+ export function createInMemoryIdempotencyStore(): IdempotencyStore {
57
54
  const events = new Map<
58
55
  string,
59
56
  { status: 'processing' | 'processed'; ownerToken: string; at: number }
@@ -71,17 +68,14 @@ export function createInMemoryIdempotencyStore(): LegacyIdempotencyStore {
71
68
  };
72
69
  return {
73
70
  reserve,
74
- async checkAndReserve(eventId) {
75
- return (await reserve(eventId)).state !== 'reserved';
76
- },
77
71
  async markProcessed(eventId, ownerToken) {
78
72
  const entry = events.get(eventId);
79
- if (ownerToken !== undefined && entry?.ownerToken !== ownerToken) {
73
+ if (entry?.ownerToken !== ownerToken) {
80
74
  throw new ReservationLostError(eventId);
81
75
  }
82
76
  events.set(eventId, {
83
77
  status: 'processed',
84
- ownerToken: ownerToken ?? entry?.ownerToken ?? newOwnerToken(),
78
+ ownerToken,
85
79
  at: Date.now(),
86
80
  });
87
81
  },
@@ -93,53 +87,9 @@ export function createInMemoryIdempotencyStore(): LegacyIdempotencyStore {
93
87
  events.delete(eventId);
94
88
  return true;
95
89
  },
96
- async isProcessed(eventId) {
97
- return events.get(eventId)?.status === 'processed';
98
- },
99
90
  };
100
91
  }
101
92
 
102
- // =============================================================================
103
- // 0.1.x auto-detection (deprecated)
104
- // =============================================================================
105
-
106
- let cachedStore: LegacyIdempotencyStore | null = null;
107
-
108
- /**
109
- * 0.1.x store auto-detection: Firestore when configured, else in-memory.
110
- *
111
- * @deprecated In-memory is not durable across instances. Pass an explicit store:
112
- * {@link createFirestoreIdempotencyStore} or `createSupabaseIdempotencyStore`.
113
- * Framework webhook entry points already do.
114
- * @version 0.2.0
115
- * @since 0.0.1
116
- * @author AMBROISE PARK Consulting
117
- */
118
- export function createIdempotencyStore(): LegacyIdempotencyStore {
119
- if (cachedStore) return cachedStore;
120
- if (isFirestoreConfigured()) {
121
- cachedStore = createFirestoreIdempotencyStore();
122
- } else {
123
- console.warn(
124
- '[Idempotency] Firestore not configured, using in-memory (not durable). Pass an explicit store.'
125
- );
126
- cachedStore = createInMemoryIdempotencyStore();
127
- }
128
- return cachedStore;
129
- }
130
-
131
- /**
132
- * Reset the store cached by {@link createIdempotencyStore} (tests).
133
- *
134
- * @deprecated See {@link createIdempotencyStore}.
135
- * @version 0.1.0
136
- * @since 0.0.1
137
- * @author AMBROISE PARK Consulting
138
- */
139
- export function resetIdempotencyStore() {
140
- cachedStore = null;
141
- }
142
-
143
93
  export {
144
94
  WEBHOOK_EVENTS_SQL,
145
95
  createSupabaseIdempotencyStore,