@donotdev/functions 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/chunks/chunk-522YXGDA.js +23 -0
- package/lib/chunks/chunk-522YXGDA.js.map +7 -0
- package/lib/chunks/chunk-7ODXXXES.js +151 -0
- package/lib/chunks/chunk-7ODXXXES.js.map +7 -0
- package/lib/chunks/chunk-CP3NNKO5.js +22 -0
- package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
- package/lib/chunks/{chunk-2A4FPYNB.js → chunk-CVYSXC27.js} +2 -2
- package/lib/chunks/chunk-CVYSXC27.js.map +7 -0
- package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-HZM5X5A7.js} +2 -2
- package/lib/chunks/chunk-ICNQCRLV.js +22 -0
- package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
- package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
- package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
- package/lib/chunks/chunk-OKRR7ST5.js +22 -0
- package/lib/chunks/chunk-OKRR7ST5.js.map +7 -0
- package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
- package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
- package/lib/chunks/chunk-TJPJXJEK.js +22 -0
- package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-TJPJXJEK.js.map} +1 -1
- package/lib/chunks/chunk-W6W4L44F.js +22 -0
- package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
- package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-UCBNPPW2.js} +2 -2
- package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-XKECWM33.js} +2 -2
- package/lib/chunks/{server-RYGEBS2B.js → server-24XGDDO3.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/crud/aggregate.d.ts +1 -1
- package/lib/firebase/crud/create.d.ts +22 -1
- package/lib/firebase/crud/update.d.ts +27 -3
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +3 -3
- package/lib/shared/billing/checkoutValidation.d.ts +1 -1
- package/lib/shared/billing/createCheckout.d.ts +1 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +29 -2
- package/lib/shared/billing/stripePinned.d.ts +43 -0
- package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
- package/lib/shared/crud/bulkCore.d.ts +38 -10
- package/lib/shared/crud/index.d.ts +1 -0
- package/lib/shared/crud/written.d.ts +21 -0
- package/lib/shared/denoEnv.d.ts +25 -0
- package/lib/shared/github.d.ts +0 -8
- package/lib/shared/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/logger.d.ts +14 -14
- package/lib/shared/utils/external/subscription.d.ts +0 -8
- package/lib/shared/utils.d.ts +13 -10
- package/lib/supabase/auth/deleteAccount.d.ts +34 -2
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -9
- package/lib/supabase/crud/entityStore.d.ts +67 -14
- package/lib/supabase/crud/update.d.ts +7 -10
- package/lib/supabase/index.d.ts +5 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/crud/create.d.ts +6 -1
- package/lib/vercel/api/crud/update.d.ts +8 -1
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +3 -3
- package/package.json +9 -9
- package/src/firebase/auth/getCustomClaims.ts +2 -0
- package/src/firebase/auth/getUserAuthStatus.ts +2 -0
- package/src/firebase/auth/removeCustomClaims.ts +33 -1
- package/src/firebase/auth/setCustomClaims.ts +6 -0
- package/src/firebase/baseFunction.ts +5 -2
- package/src/firebase/billing/changePlan.ts +6 -5
- package/src/firebase/billing/createCustomerPortal.ts +6 -4
- package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
- package/src/firebase/billing/webhookHandler.ts +4 -4
- package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
- package/src/firebase/crud/__tests__/create.test.ts +64 -0
- package/src/firebase/crud/__tests__/update.test.ts +97 -0
- package/src/firebase/crud/aggregate.ts +37 -19
- package/src/firebase/crud/bulk.ts +30 -10
- package/src/firebase/crud/create.ts +40 -26
- package/src/firebase/crud/delete.ts +6 -1
- package/src/firebase/crud/get.ts +12 -14
- package/src/firebase/crud/list.ts +23 -12
- package/src/firebase/crud/update.ts +49 -25
- package/src/firebase/helpers/githubAccessHelper.ts +3 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
- package/src/firebase/oauth/exchangeToken.ts +4 -0
- package/src/firebase/oauth/getConnections.ts +1 -1
- package/src/firebase/oauth/githubAccess.ts +3 -0
- package/src/firebase/oauth/refreshToken.ts +1 -0
- package/src/firebase/registerCrudFunctions.ts +1 -0
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
- package/src/shared/__tests__/bulkCore.test.ts +191 -0
- package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
- package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
- package/src/shared/__tests__/utils.test.ts +0 -30
- package/src/shared/ai/classifyAIError.ts +18 -10
- package/src/shared/ai/createAIRoute.ts +2 -1
- package/src/shared/ai/resolveModelTier.ts +2 -1
- package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
- package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
- package/src/shared/billing/checkoutValidation.ts +19 -2
- package/src/shared/billing/createCheckout.ts +56 -11
- package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
- package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +69 -1
- package/src/shared/billing/stripeClient.ts +2 -1
- package/src/shared/billing/stripePinned.ts +71 -0
- package/src/shared/billing/tierWebhookEvents.ts +3 -2
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/billing/webhookHandler.ts +5 -1
- package/src/shared/crud/bulkCore.ts +112 -82
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/denoEnv.ts +29 -0
- package/src/shared/email/createEmailRoute.ts +2 -2
- package/src/shared/errorHandling.ts +8 -8
- package/src/shared/firebase.ts +26 -9
- package/src/shared/github.ts +15 -5
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/logger.ts +37 -38
- package/src/shared/utils/external/date.ts +4 -4
- package/src/shared/utils/external/subscription.ts +2 -89
- package/src/shared/utils/firebaseHelpers.ts +2 -0
- package/src/shared/utils/internal/idempotency.ts +3 -0
- package/src/shared/utils/internal/monitoring.ts +6 -5
- package/src/shared/utils/internal/validation.ts +2 -0
- package/src/shared/utils/schemaValidation.ts +1 -0
- package/src/shared/utils/validation.ts +10 -20
- package/src/shared/utils.ts +4 -42
- package/src/supabase/__tests__/aggregate.test.ts +132 -0
- package/src/supabase/__tests__/bulk.test.ts +60 -2
- package/src/supabase/__tests__/create.test.ts +86 -0
- package/src/supabase/__tests__/entityStore.test.ts +91 -25
- package/src/supabase/__tests__/update.test.ts +107 -0
- package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
- package/src/supabase/auth/deleteAccount.ts +72 -5
- package/src/supabase/auth/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
- package/src/supabase/crud/aggregate.ts +85 -72
- package/src/supabase/crud/bulk.ts +50 -0
- package/src/supabase/crud/create.ts +27 -33
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/entityStore.ts +107 -18
- package/src/supabase/crud/get.ts +5 -13
- package/src/supabase/crud/list.ts +28 -21
- package/src/supabase/crud/update.ts +29 -24
- package/src/supabase/edgeFunction.ts +2 -1
- package/src/supabase/email/createEmailFunction.ts +2 -1
- package/src/supabase/index.ts +8 -0
- package/src/supabase/oauth/exchangeToken.ts +1 -0
- package/src/supabase/oauth/getConnections.ts +1 -1
- package/src/supabase/oauth/refreshToken.ts +1 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/supabase/utils/idempotency.ts +1 -1
- package/src/supabase/utils/monitoring.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/billing/change-plan.ts +6 -5
- package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
- package/src/vercel/api/crud/bulk.ts +34 -6
- package/src/vercel/api/crud/create.ts +22 -21
- package/src/vercel/api/crud/delete.ts +5 -2
- package/src/vercel/api/crud/get.ts +10 -8
- package/src/vercel/api/crud/list.ts +10 -8
- package/src/vercel/api/crud/update.ts +25 -20
- package/src/vercel/api/oauth/check-github-access.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +5 -2
- package/src/vercel/api/oauth/grant-github-access.ts +1 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
- package/src/vercel/baseFunction.ts +5 -1
- package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
- package/lib/chunks/chunk-2IFFIUFV.js +0 -23
- package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
- package/lib/chunks/chunk-FQSQGOBN.js +0 -22
- package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
- package/lib/chunks/chunk-G4FO76EA.js +0 -22
- package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
- package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
- package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
- package/lib/chunks/chunk-M4JV2JCF.js +0 -22
- package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
- package/lib/chunks/chunk-OZX5ZG44.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
- package/lib/chunks/chunk-UYI56E6Q.js +0 -151
- package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
- package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
- package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/lib/shared/utils/functionWrapper.d.ts +0 -36
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -192
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
- package/src/shared/utils/functionWrapper.ts +0 -73
- /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-HZM5X5A7.js.map} +0 -0
- /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-UCBNPPW2.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-XKECWM33.js.map} +0 -0
- /package/lib/chunks/{server-RYGEBS2B.js.map → server-24XGDDO3.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();
|
|
@@ -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,
|
|
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 } =
|
|
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
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
-
|
|
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 {
|
|
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
|
|
63
|
-
?
|
|
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
|
|
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
|
|
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:
|
|
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
|
|
157
|
-
?
|
|
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
|
|
171
|
+
pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000
|
|
168
172
|
).toISOString(),
|
|
169
|
-
cancelAtPeriodEnd:
|
|
173
|
+
cancelAtPeriodEnd: updatedSubscription.cancel_at_period_end,
|
|
170
174
|
subscriptionId: updatedSubscription.id,
|
|
171
175
|
customerId: updatedSubscription.customer as string,
|
|
172
176
|
},
|
|
@@ -9,11 +9,16 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import * as v from 'valibot';
|
|
13
|
+
|
|
14
|
+
import { SubscriptionClaimsSchema } from '@donotdev/core/server';
|
|
12
15
|
import type { BillingAuthProvider, SubscriptionUpdate } from '@donotdev/core/server';
|
|
13
16
|
|
|
14
17
|
/**
|
|
15
18
|
* Platform-agnostic subscription update using dependency injection
|
|
16
19
|
* Works on Firebase Functions, Vercel, AWS Lambda, etc.
|
|
20
|
+
* Validates canonical auth claims; one-time payments may have no billing customer.
|
|
21
|
+
* Billing identifiers are preserved when supplied, never fabricated from a user ID.
|
|
17
22
|
*
|
|
18
23
|
* @version 0.1.0
|
|
19
24
|
* @since 0.0.1
|
|
@@ -31,26 +36,17 @@ export async function updateUserSubscription(
|
|
|
31
36
|
throw new Error('Invalid subscription data: missing tier or status');
|
|
32
37
|
}
|
|
33
38
|
|
|
34
|
-
|
|
35
|
-
// Stripe customer ID, which makes future Stripe API calls unreliable.
|
|
36
|
-
if (!subscriptionData.customerId) {
|
|
37
|
-
console.warn(
|
|
38
|
-
`[updateUserSubscription] customerId is undefined for user ${userId}. ` +
|
|
39
|
-
`Falling back to userId. This may cause issues with Stripe API calls.`
|
|
40
|
-
);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const subscriptionClaims = {
|
|
39
|
+
const subscriptionClaims = v.parse(SubscriptionClaimsSchema, {
|
|
44
40
|
tier: subscriptionData.tier,
|
|
45
|
-
subscriptionId: subscriptionData.subscriptionId
|
|
46
|
-
customerId: subscriptionData.customerId
|
|
41
|
+
subscriptionId: subscriptionData.subscriptionId ?? null,
|
|
42
|
+
customerId: subscriptionData.customerId ?? null,
|
|
47
43
|
status: subscriptionData.status,
|
|
48
44
|
// Keep as ISO string - no conversion needed
|
|
49
45
|
subscriptionEnd: subscriptionData.subscriptionEnd,
|
|
50
|
-
cancelAtPeriodEnd: subscriptionData.cancelAtPeriodEnd
|
|
46
|
+
cancelAtPeriodEnd: subscriptionData.cancelAtPeriodEnd ?? false,
|
|
51
47
|
updatedAt: new Date().toISOString(),
|
|
52
48
|
isDefault: false,
|
|
53
|
-
};
|
|
49
|
+
});
|
|
54
50
|
|
|
55
51
|
const updatedClaims = {
|
|
56
52
|
...currentClaims,
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
export * from './createCheckout.js';
|
|
13
|
+
/** Read-only order verification and its separate retrieval/binding dependencies. */
|
|
14
|
+
export * from './verifyOrderCheckout.js';
|
|
13
15
|
export * from './helpers/index.js';
|
|
14
16
|
export * from './webhookHandler.js';
|
|
15
17
|
export * from './idempotency.js';
|
|
@@ -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
|
-
|
|
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
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/stripePinned.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Typed access to Stripe fields of the pinned API version
|
|
5
|
+
* @description The Stripe SDK types follow the latest API version only, while
|
|
6
|
+
* requests run at `STRIPE_API_VERSION_PIN` (pre-basil). Fields that basil
|
|
7
|
+
* moved (subscription period, invoice subscription) are read here, through one
|
|
8
|
+
* documented cast, instead of `as any` at every call site. Internal: not
|
|
9
|
+
* re-exported from any package entry.
|
|
10
|
+
*
|
|
11
|
+
* @version 0.1.0
|
|
12
|
+
* @since 0.2.2
|
|
13
|
+
* @author AMBROISE PARK Consulting
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type Stripe from 'stripe';
|
|
17
|
+
|
|
18
|
+
/** Subscription fields present at `STRIPE_API_VERSION_PIN`, dropped from the latest SDK types. */
|
|
19
|
+
interface PinnedSubscriptionFields {
|
|
20
|
+
current_period_start: number;
|
|
21
|
+
current_period_end: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Invoice fields present at `STRIPE_API_VERSION_PIN`, dropped from the latest SDK types. */
|
|
25
|
+
interface PinnedInvoiceFields {
|
|
26
|
+
/** Not expanded in webhook payloads: the subscription id, or null for one-off invoices. */
|
|
27
|
+
subscription: string | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Period fields of a subscription at the pinned API version.
|
|
32
|
+
*
|
|
33
|
+
* @version 0.1.0
|
|
34
|
+
* @since 0.2.2
|
|
35
|
+
* @author AMBROISE PARK Consulting
|
|
36
|
+
*/
|
|
37
|
+
export function pinnedSubscriptionPeriod(
|
|
38
|
+
subscription: Stripe.Subscription
|
|
39
|
+
): PinnedSubscriptionFields {
|
|
40
|
+
// why: SDK v20 types track the latest API (period moved to items); runtime is pinned pre-basil
|
|
41
|
+
return subscription as unknown as PinnedSubscriptionFields;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Subscription id of an invoice at the pinned API version.
|
|
46
|
+
*
|
|
47
|
+
* @version 0.1.0
|
|
48
|
+
* @since 0.2.2
|
|
49
|
+
* @author AMBROISE PARK Consulting
|
|
50
|
+
*/
|
|
51
|
+
export function pinnedInvoiceSubscriptionId(
|
|
52
|
+
invoice: Stripe.Invoice
|
|
53
|
+
): string | null {
|
|
54
|
+
// why: SDK v20 types track the latest API (moved to invoice.parent); runtime is pinned pre-basil
|
|
55
|
+
return (invoice as unknown as PinnedInvoiceFields).subscription;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Narrows a value to one of a readonly list of literals.
|
|
60
|
+
*
|
|
61
|
+
* @version 0.1.0
|
|
62
|
+
* @since 0.2.2
|
|
63
|
+
* @author AMBROISE PARK Consulting
|
|
64
|
+
*/
|
|
65
|
+
export function isOneOf<T extends string>(
|
|
66
|
+
values: readonly T[],
|
|
67
|
+
value: string
|
|
68
|
+
): value is T {
|
|
69
|
+
const list: readonly string[] = values;
|
|
70
|
+
return list.includes(value);
|
|
71
|
+
}
|
|
@@ -23,6 +23,7 @@ import type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from
|
|
|
23
23
|
import { handleError } from '../errorHandling.js';
|
|
24
24
|
import { logger } from '../logger.js';
|
|
25
25
|
import type { OrderSessionEventType } from './orderWebhook.js';
|
|
26
|
+
import { pinnedInvoiceSubscriptionId, pinnedSubscriptionPeriod } from './stripePinned.js';
|
|
26
27
|
|
|
27
28
|
/**
|
|
28
29
|
* Checkout Session event of a StripePayment / StripeSubscription item.
|
|
@@ -224,7 +225,7 @@ export async function handleInvoicePaymentSucceeded(
|
|
|
224
225
|
stripe: Stripe,
|
|
225
226
|
authProvider: BillingAuthProvider | null
|
|
226
227
|
): Promise<void> {
|
|
227
|
-
const subscriptionId = (invoice
|
|
228
|
+
const subscriptionId = pinnedInvoiceSubscriptionId(invoice);
|
|
228
229
|
if (!subscriptionId) return;
|
|
229
230
|
|
|
230
231
|
// ✅ FIX: Fetch subscription to get metadata
|
|
@@ -322,7 +323,7 @@ export async function handleSubscriptionDeleted(
|
|
|
322
323
|
tier: SUBSCRIPTION_TIERS.FREE,
|
|
323
324
|
status: SUBSCRIPTION_STATUS.CANCELED,
|
|
324
325
|
subscriptionEnd: new Date(
|
|
325
|
-
(subscription
|
|
326
|
+
pinnedSubscriptionPeriod(subscription).current_period_end * 1000
|
|
326
327
|
).toISOString(),
|
|
327
328
|
subscriptionId: subscription.id,
|
|
328
329
|
customerId: subscription.customer as string,
|