@donotdev/functions 0.2.1 → 0.2.2
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-5IPULSUX.js → chunk-2A4FPYNB.js} +2 -2
- package/lib/chunks/chunk-2IFFIUFV.js +23 -0
- package/lib/chunks/{chunk-CXBSROEW.js.map → chunk-2IFFIUFV.js.map} +3 -3
- package/lib/chunks/chunk-FQSQGOBN.js +22 -0
- package/lib/chunks/chunk-FQSQGOBN.js.map +7 -0
- package/lib/chunks/chunk-G4FO76EA.js +22 -0
- package/lib/chunks/{chunk-GYTCWMXV.js.map → chunk-G4FO76EA.js.map} +3 -3
- package/lib/chunks/{chunk-US2VOP4S.js → chunk-LSM5Y2E5.js} +2 -2
- package/lib/chunks/{chunk-MQANUSY3.js → chunk-M4JV2JCF.js} +2 -2
- package/lib/chunks/chunk-OZX5ZG44.js +22 -0
- package/lib/chunks/chunk-OZX5ZG44.js.map +7 -0
- package/lib/chunks/{chunk-3F4BWKQD.js → chunk-PJCJ5H2O.js} +2 -2
- package/lib/chunks/chunk-UYI56E6Q.js +151 -0
- package/lib/chunks/chunk-UYI56E6Q.js.map +7 -0
- package/lib/chunks/{chunk-OFQVO3FD.js → chunk-ZVHC2CAV.js} +2 -2
- package/lib/chunks/{monitoring-E7JBYBHQ.js → monitoring-UIDJS2KA.js} +2 -2
- package/lib/chunks/{rateLimiter-SQISLOP5.js → rateLimiter-WNWHI3B4.js} +2 -2
- package/lib/chunks/server-RYGEBS2B.js +22 -0
- package/lib/firebase/billing/index.d.ts +2 -2
- package/lib/firebase/index.d.ts +1 -1
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/registerCrudFunctions.d.ts +0 -5
- package/lib/shared/billing/checkoutPrice.d.ts +3 -6
- package/lib/shared/billing/createCheckout.d.ts +3 -3
- package/lib/shared/billing/firestoreIdempotency.d.ts +2 -2
- package/lib/shared/billing/idempotency.d.ts +3 -23
- package/lib/shared/billing/idempotencyContract.d.ts +0 -20
- package/lib/shared/index.js +1 -1
- package/lib/shared/utils/internal/auth.d.ts +1 -5
- package/lib/shared/utils.d.ts +0 -83
- package/lib/supabase/index.js +1 -1
- package/lib/vercel/api/index.js +1 -1
- package/package.json +2 -2
- package/src/firebase/baseFunction.ts +3 -2
- package/src/firebase/billing/index.d.ts +0 -12
- package/src/firebase/billing/index.ts +0 -3
- package/src/firebase/index.ts +0 -1
- package/src/firebase/oauth/disconnect.ts +2 -2
- package/src/firebase/oauth/exchangeToken.ts +2 -2
- package/src/firebase/oauth/getConnections.ts +2 -2
- package/src/firebase/oauth/githubAccess.ts +4 -4
- package/src/firebase/oauth/refreshToken.ts +2 -2
- package/src/firebase/registerCrudFunctions.ts +0 -19
- package/src/shared/__tests__/idempotency.test.ts +0 -32
- package/src/shared/__tests__/utils.test.ts +0 -25
- package/src/shared/billing/__tests__/createCheckout.compat.test.ts +4 -110
- package/src/shared/billing/checkoutPrice.ts +7 -42
- package/src/shared/billing/createCheckout.ts +3 -19
- package/src/shared/billing/firestoreIdempotency.ts +2 -21
- package/src/shared/billing/idempotency.ts +4 -54
- package/src/shared/billing/idempotencyContract.ts +0 -21
- package/src/shared/utils/internal/auth.ts +1 -6
- package/src/shared/utils.ts +0 -131
- package/lib/chunks/chunk-6USHTJED.js +0 -22
- package/lib/chunks/chunk-6USHTJED.js.map +0 -7
- package/lib/chunks/chunk-CXBSROEW.js +0 -23
- package/lib/chunks/chunk-GYTCWMXV.js +0 -22
- package/lib/chunks/chunk-LCDLG4VG.js +0 -151
- package/lib/chunks/chunk-LCDLG4VG.js.map +0 -7
- package/lib/chunks/chunk-YTKDNZNW.js +0 -22
- package/lib/chunks/chunk-YTKDNZNW.js.map +0 -7
- package/lib/chunks/server-IQ5JNJOM.js +0 -22
- /package/lib/chunks/{chunk-5IPULSUX.js.map → chunk-2A4FPYNB.js.map} +0 -0
- /package/lib/chunks/{chunk-US2VOP4S.js.map → chunk-LSM5Y2E5.js.map} +0 -0
- /package/lib/chunks/{chunk-MQANUSY3.js.map → chunk-M4JV2JCF.js.map} +0 -0
- /package/lib/chunks/{chunk-3F4BWKQD.js.map → chunk-PJCJ5H2O.js.map} +0 -0
- /package/lib/chunks/{chunk-OFQVO3FD.js.map → chunk-ZVHC2CAV.js.map} +0 -0
- /package/lib/chunks/{monitoring-E7JBYBHQ.js.map → monitoring-UIDJS2KA.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-SQISLOP5.js.map → rateLimiter-WNWHI3B4.js.map} +0 -0
- /package/lib/chunks/{server-IQ5JNJOM.js.map → server-RYGEBS2B.js.map} +0 -0
|
@@ -24,13 +24,10 @@ export * from '../../shared/billing/helpers/index.js';
|
|
|
24
24
|
// Webhook idempotency stores
|
|
25
25
|
export {
|
|
26
26
|
createFirestoreIdempotencyStore,
|
|
27
|
-
createIdempotencyStore,
|
|
28
|
-
resetIdempotencyStore,
|
|
29
27
|
ReservationLostError,
|
|
30
28
|
} from '../../shared/billing/idempotency.js';
|
|
31
29
|
export type {
|
|
32
30
|
IdempotencyStore,
|
|
33
|
-
LegacyIdempotencyStore,
|
|
34
31
|
ReservationResult,
|
|
35
32
|
} from '../../shared/billing/idempotency.js';
|
|
36
33
|
|
package/src/firebase/index.ts
CHANGED
|
@@ -15,7 +15,7 @@ import { OAUTH_PARTNERS } from '@donotdev/core/server';
|
|
|
15
15
|
import type { OAuthPartnerId, OAuthPurpose } from '@donotdev/core/server';
|
|
16
16
|
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
|
|
17
17
|
|
|
18
|
-
import { assertAuthenticated } from '../../shared/utils.js';
|
|
18
|
+
import { assertAuthenticated } from '../../shared/utils/internal/auth.js';
|
|
19
19
|
|
|
20
20
|
/**
|
|
21
21
|
* Disconnect a provider
|
|
@@ -29,7 +29,7 @@ export const disconnect = onCall<{
|
|
|
29
29
|
purpose: OAuthPurpose;
|
|
30
30
|
}>(async (request) => {
|
|
31
31
|
// Verify authentication
|
|
32
|
-
const uid = assertAuthenticated(request.auth);
|
|
32
|
+
const uid = assertAuthenticated(request.auth?.uid);
|
|
33
33
|
|
|
34
34
|
const { provider, purpose } = request.data;
|
|
35
35
|
|
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
FieldValue,
|
|
22
22
|
} from '@donotdev/firebase/server';
|
|
23
23
|
|
|
24
|
-
import { assertAuthenticated } from '../../shared/utils.js';
|
|
24
|
+
import { assertAuthenticated } from '../../shared/utils/internal/auth.js';
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
27
|
* Exchange OAuth authorization code for access token
|
|
@@ -32,7 +32,7 @@ import { assertAuthenticated } from '../../shared/utils.js';
|
|
|
32
32
|
*/
|
|
33
33
|
export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
|
|
34
34
|
// Verify authentication
|
|
35
|
-
const uid = assertAuthenticated(request.auth);
|
|
35
|
+
const uid = assertAuthenticated(request.auth?.uid);
|
|
36
36
|
|
|
37
37
|
const { provider, purpose, code, redirectUri, codeVerifier, idempotencyKey } =
|
|
38
38
|
request.data;
|
|
@@ -14,7 +14,7 @@ import { onCall, HttpsError } from 'firebase-functions/v2/https';
|
|
|
14
14
|
import type { OAuthPurpose } from '@donotdev/core/server';
|
|
15
15
|
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
|
|
16
16
|
|
|
17
|
-
import { assertAuthenticated } from '../../shared/utils.js';
|
|
17
|
+
import { assertAuthenticated } from '../../shared/utils/internal/auth.js';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Get a user's OAuth connections
|
|
@@ -26,7 +26,7 @@ import { assertAuthenticated } from '../../shared/utils.js';
|
|
|
26
26
|
export const getConnections = onCall<{ purpose?: OAuthPurpose }>(
|
|
27
27
|
async (request) => {
|
|
28
28
|
// Verify authentication
|
|
29
|
-
const uid = assertAuthenticated(request.auth);
|
|
29
|
+
const uid = assertAuthenticated(request.auth?.uid);
|
|
30
30
|
|
|
31
31
|
const { purpose } = request.data || {};
|
|
32
32
|
|
|
@@ -27,7 +27,7 @@ import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
|
|
|
27
27
|
|
|
28
28
|
import { handleError } from '../../shared/errorHandling.js';
|
|
29
29
|
import { GitHubApiService } from '../../shared/index.js';
|
|
30
|
-
import { assertAuthenticated } from '../../shared/utils.js';
|
|
30
|
+
import { assertAuthenticated } from '../../shared/utils/internal/auth.js';
|
|
31
31
|
import { AUTH_CONFIG } from '../config/constants.js';
|
|
32
32
|
import { githubPersonalAccessToken } from '../config/secrets.js';
|
|
33
33
|
|
|
@@ -52,7 +52,7 @@ async function grantGitHubAccessInternal(
|
|
|
52
52
|
>
|
|
53
53
|
) {
|
|
54
54
|
try {
|
|
55
|
-
const uid = assertAuthenticated(request.auth);
|
|
55
|
+
const uid = assertAuthenticated(request.auth?.uid);
|
|
56
56
|
|
|
57
57
|
// Use provided schema or default to framework schema
|
|
58
58
|
const schema = customSchema || grantGitHubAccessSchema;
|
|
@@ -193,7 +193,7 @@ async function revokeGitHubAccessInternal(
|
|
|
193
193
|
>
|
|
194
194
|
) {
|
|
195
195
|
try {
|
|
196
|
-
const uid = assertAuthenticated(request.auth);
|
|
196
|
+
const uid = assertAuthenticated(request.auth?.uid);
|
|
197
197
|
|
|
198
198
|
// Use provided schema or default to framework schema
|
|
199
199
|
const schema = customSchema || revokeGitHubAccessSchema;
|
|
@@ -324,7 +324,7 @@ async function checkGitHubAccessInternal(
|
|
|
324
324
|
>
|
|
325
325
|
) {
|
|
326
326
|
try {
|
|
327
|
-
const uid = assertAuthenticated(request.auth);
|
|
327
|
+
const uid = assertAuthenticated(request.auth?.uid);
|
|
328
328
|
|
|
329
329
|
// Use provided schema or default to framework schema
|
|
330
330
|
const schema = customSchema || checkGitHubAccessSchema;
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
FieldValue,
|
|
21
21
|
} from '@donotdev/firebase/server';
|
|
22
22
|
|
|
23
|
-
import { assertAuthenticated } from '../../shared/utils.js';
|
|
23
|
+
import { assertAuthenticated } from '../../shared/utils/internal/auth.js';
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
26
|
* Refresh an OAuth token
|
|
@@ -31,7 +31,7 @@ import { assertAuthenticated } from '../../shared/utils.js';
|
|
|
31
31
|
*/
|
|
32
32
|
export const refreshToken = onCall<OAuthRefreshRequest>(async (request) => {
|
|
33
33
|
// Verify authentication
|
|
34
|
-
const uid = assertAuthenticated(request.auth);
|
|
34
|
+
const uid = assertAuthenticated(request.auth?.uid);
|
|
35
35
|
|
|
36
36
|
const {
|
|
37
37
|
provider,
|
|
@@ -119,25 +119,6 @@ export function createCrudFunctions(
|
|
|
119
119
|
return functions;
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
-
/**
|
|
123
|
-
* @deprecated Use createCrudFunctions() for ESM. This mutates target which doesn't work in ESM.
|
|
124
|
-
* Auto-register CRUD functions for all entities (CJS pattern)
|
|
125
|
-
*/
|
|
126
|
-
export function registerCrudFunctions(
|
|
127
|
-
entities: Record<string, Entity | unknown>,
|
|
128
|
-
target?: Record<string, any>,
|
|
129
|
-
options: RegisterOptions = {}
|
|
130
|
-
): CrudFunctions {
|
|
131
|
-
const functions = createCrudFunctions(entities, options);
|
|
132
|
-
|
|
133
|
-
// If target provided, mutate it (CJS compat)
|
|
134
|
-
if (target) {
|
|
135
|
-
Object.assign(target, functions);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
return functions;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
122
|
/**
|
|
142
123
|
* Type guard to check if a value is an Entity
|
|
143
124
|
*/
|
|
@@ -69,10 +69,8 @@ import {
|
|
|
69
69
|
WEBHOOK_EVENT_RETENTION_MS,
|
|
70
70
|
WEBHOOK_EVENTS_SQL,
|
|
71
71
|
createFirestoreIdempotencyStore,
|
|
72
|
-
createIdempotencyStore,
|
|
73
72
|
createInMemoryIdempotencyStore,
|
|
74
73
|
createSupabaseIdempotencyStore,
|
|
75
|
-
resetIdempotencyStore,
|
|
76
74
|
} from '../billing/idempotency';
|
|
77
75
|
import type { IdempotencyStore } from '../billing/idempotency';
|
|
78
76
|
|
|
@@ -290,33 +288,3 @@ describe('supabase idempotency store', () => {
|
|
|
290
288
|
expect(body).toContain("cron.schedule(\n 'cleanup-webhook-events'");
|
|
291
289
|
});
|
|
292
290
|
});
|
|
293
|
-
|
|
294
|
-
describe('0.1.x API (deprecated)', () => {
|
|
295
|
-
afterEach(() => {
|
|
296
|
-
resetIdempotencyStore();
|
|
297
|
-
vi.restoreAllMocks();
|
|
298
|
-
});
|
|
299
|
-
|
|
300
|
-
it('auto-detects in-memory without Firestore and caches the instance', () => {
|
|
301
|
-
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
302
|
-
const store = createIdempotencyStore();
|
|
303
|
-
expect(createIdempotencyStore()).toBe(store);
|
|
304
|
-
});
|
|
305
|
-
|
|
306
|
-
it('keeps checkAndReserve / isProcessed / tokenless markProcessed working', async () => {
|
|
307
|
-
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
308
|
-
const store = createIdempotencyStore();
|
|
309
|
-
expect(await store.checkAndReserve('evt_l1')).toBe(false);
|
|
310
|
-
expect(await store.checkAndReserve('evt_l1')).toBe(true);
|
|
311
|
-
expect(await store.isProcessed('evt_l1')).toBe(false);
|
|
312
|
-
await store.markProcessed('evt_l1');
|
|
313
|
-
expect(await store.isProcessed('evt_l1')).toBe(true);
|
|
314
|
-
});
|
|
315
|
-
|
|
316
|
-
it('firestore: tokenless markProcessed writes unconditionally', async () => {
|
|
317
|
-
const store = createFirestoreIdempotencyStore();
|
|
318
|
-
await store.markProcessed('evt_l2');
|
|
319
|
-
expect(await store.isProcessed('evt_l2')).toBe(true);
|
|
320
|
-
expect(await store.checkAndReserve('evt_l2')).toBe(true);
|
|
321
|
-
});
|
|
322
|
-
});
|
|
@@ -46,7 +46,6 @@ import {
|
|
|
46
46
|
createErrorResponse,
|
|
47
47
|
validateDocument,
|
|
48
48
|
validateCollectionName,
|
|
49
|
-
assertAuthenticated,
|
|
50
49
|
} from '../utils';
|
|
51
50
|
import { validateStripeEnvironment } from '../billing/stripeClient';
|
|
52
51
|
|
|
@@ -235,30 +234,6 @@ describe('validateCollectionName', () => {
|
|
|
235
234
|
// assertAuthenticated
|
|
236
235
|
// ---------------------------------------------------------------------------
|
|
237
236
|
|
|
238
|
-
describe('assertAuthenticated', () => {
|
|
239
|
-
it('returns uid when auth has uid', () => {
|
|
240
|
-
const result = assertAuthenticated({ uid: 'user-123' });
|
|
241
|
-
|
|
242
|
-
expect(result).toBe('user-123');
|
|
243
|
-
});
|
|
244
|
-
|
|
245
|
-
it('throws when auth is null', () => {
|
|
246
|
-
expect(() => assertAuthenticated(null)).toThrow(
|
|
247
|
-
'User must be authenticated'
|
|
248
|
-
);
|
|
249
|
-
});
|
|
250
|
-
|
|
251
|
-
it('throws when auth has no uid', () => {
|
|
252
|
-
expect(() => assertAuthenticated({})).toThrow('User must be authenticated');
|
|
253
|
-
});
|
|
254
|
-
|
|
255
|
-
it('throws when auth.uid is empty string', () => {
|
|
256
|
-
expect(() => assertAuthenticated({ uid: '' })).toThrow(
|
|
257
|
-
'User must be authenticated'
|
|
258
|
-
);
|
|
259
|
-
});
|
|
260
|
-
});
|
|
261
|
-
|
|
262
237
|
// ---------------------------------------------------------------------------
|
|
263
238
|
// validateStripeEnvironment
|
|
264
239
|
// ---------------------------------------------------------------------------
|
|
@@ -32,7 +32,7 @@ const URLS = {
|
|
|
32
32
|
cancelUrl: 'https://app.example.com/billing/cancel',
|
|
33
33
|
};
|
|
34
34
|
|
|
35
|
-
/** 0.1.x back config: no priceId, client-supplied price
|
|
35
|
+
/** 0.1.x back config: no priceId, client-supplied price. */
|
|
36
36
|
function makeLegacyConfig(
|
|
37
37
|
beforeCheckout?: BeforeCheckoutHook
|
|
38
38
|
): StripeBackConfig {
|
|
@@ -42,7 +42,6 @@ function makeLegacyConfig(
|
|
|
42
42
|
name: 'Credits',
|
|
43
43
|
price: 0,
|
|
44
44
|
currency: 'eur',
|
|
45
|
-
maxUnitAmount: 50000,
|
|
46
45
|
tier: 'credits',
|
|
47
46
|
duration: 'lifetime',
|
|
48
47
|
beforeCheckout,
|
|
@@ -109,84 +108,6 @@ describe('0.1.x (a): back-config item without priceId', () => {
|
|
|
109
108
|
});
|
|
110
109
|
});
|
|
111
110
|
|
|
112
|
-
it('dynamic pricing: unitAmount + productName within maxUnitAmount', async () => {
|
|
113
|
-
const stripe = makeSessionProvider();
|
|
114
|
-
const request = legacyRequest({
|
|
115
|
-
unitAmount: 2500,
|
|
116
|
-
productName: '25 credits',
|
|
117
|
-
mode: 'payment',
|
|
118
|
-
metadata: { billingConfigKey: 'credits' },
|
|
119
|
-
});
|
|
120
|
-
await createCheckoutAlgorithm(request, USER_ID, stripe, auth, makeLegacyConfig());
|
|
121
|
-
expect(stripe.createStripeSession.mock.calls[0]?.[0]).toMatchObject({
|
|
122
|
-
mode: 'payment',
|
|
123
|
-
line_items: [
|
|
124
|
-
{
|
|
125
|
-
price_data: {
|
|
126
|
-
currency: 'eur',
|
|
127
|
-
unit_amount: 2500,
|
|
128
|
-
product_data: { name: '25 credits' },
|
|
129
|
-
},
|
|
130
|
-
quantity: 1,
|
|
131
|
-
},
|
|
132
|
-
],
|
|
133
|
-
});
|
|
134
|
-
});
|
|
135
|
-
|
|
136
|
-
it.each([
|
|
137
|
-
['above maxUnitAmount', { unitAmount: 60000 }, /exceeds maximum allowed: 50000/],
|
|
138
|
-
['below 1.00', { unitAmount: 50 }, /at least 100 cents/],
|
|
139
|
-
['subscription mode', { mode: 'subscription' }, /not supported for subscriptions/],
|
|
140
|
-
])('dynamic pricing keeps the 0.1.x guards (%s)', async (_label, patch, error) => {
|
|
141
|
-
const request = legacyRequest({
|
|
142
|
-
unitAmount: 2500,
|
|
143
|
-
productName: '25 credits',
|
|
144
|
-
metadata: { billingConfigKey: 'credits' },
|
|
145
|
-
...patch,
|
|
146
|
-
});
|
|
147
|
-
await expect(
|
|
148
|
-
createCheckoutAlgorithm(request, USER_ID, makeSessionProvider(), auth, makeLegacyConfig())
|
|
149
|
-
).rejects.toThrow(error);
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
it('dynamic pricing without maxUnitAmount fails as in 0.1.x', async () => {
|
|
153
|
-
const config = makeLegacyConfig();
|
|
154
|
-
const { maxUnitAmount: _omit, ...noCap } = config.credits as any;
|
|
155
|
-
config.credits = noCap;
|
|
156
|
-
const request = legacyRequest({
|
|
157
|
-
unitAmount: 2500,
|
|
158
|
-
productName: '25 credits',
|
|
159
|
-
metadata: { billingConfigKey: 'credits' },
|
|
160
|
-
});
|
|
161
|
-
await expect(
|
|
162
|
-
createCheckoutAlgorithm(request, USER_ID, makeSessionProvider(), auth, config)
|
|
163
|
-
).rejects.toThrow(/requires maxUnitAmount/);
|
|
164
|
-
});
|
|
165
|
-
|
|
166
|
-
it('beforeCheckout overrides apply to dynamic pricing, still capped', async () => {
|
|
167
|
-
const stripe = makeSessionProvider();
|
|
168
|
-
const config = makeLegacyConfig(async () => ({
|
|
169
|
-
allowed: true,
|
|
170
|
-
overrides: { unitAmount: 4000, productName: 'Server-priced credits' },
|
|
171
|
-
}));
|
|
172
|
-
const request = legacyRequest({
|
|
173
|
-
unitAmount: 100,
|
|
174
|
-
productName: 'client',
|
|
175
|
-
metadata: { billingConfigKey: 'credits' },
|
|
176
|
-
});
|
|
177
|
-
await createCheckoutAlgorithm(request, USER_ID, stripe, auth, config);
|
|
178
|
-
expect(stripe.createStripeSession.mock.calls[0]?.[0].line_items?.[0]).toMatchObject({
|
|
179
|
-
price_data: { unit_amount: 4000, product_data: { name: 'Server-priced credits' } },
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
const capped = makeLegacyConfig(async () => ({
|
|
183
|
-
allowed: true,
|
|
184
|
-
overrides: { unitAmount: 99999 },
|
|
185
|
-
}));
|
|
186
|
-
await expect(
|
|
187
|
-
createCheckoutAlgorithm(request, USER_ID, makeSessionProvider(), auth, capped)
|
|
188
|
-
).rejects.toThrow(/Hook-overridden unit amount 99999/);
|
|
189
|
-
});
|
|
190
111
|
});
|
|
191
112
|
|
|
192
113
|
// ---------------------------------------------------------------------------
|
|
@@ -194,20 +115,18 @@ describe('0.1.x (a): back-config item without priceId', () => {
|
|
|
194
115
|
// ---------------------------------------------------------------------------
|
|
195
116
|
|
|
196
117
|
describe('0.1.x (b): beforeCheckout options', () => {
|
|
197
|
-
it('receives priceId / mode /
|
|
118
|
+
it('receives priceId / mode / currency, plus the new fields', async () => {
|
|
198
119
|
const hook = vi.fn<BeforeCheckoutHook>(async () => ({ allowed: true }));
|
|
199
120
|
const request = legacyRequest({
|
|
200
|
-
|
|
201
|
-
productName: '25 credits',
|
|
121
|
+
priceId: 'price_client',
|
|
202
122
|
currency: 'usd',
|
|
203
123
|
mode: 'payment',
|
|
204
124
|
metadata: { billingConfigKey: 'credits' },
|
|
205
125
|
});
|
|
206
126
|
await createCheckoutAlgorithm(request, USER_ID, makeSessionProvider(), auth, makeLegacyConfig(hook));
|
|
207
127
|
expect(hook.mock.calls[0]?.[1]).toMatchObject({
|
|
128
|
+
priceId: 'price_client',
|
|
208
129
|
mode: 'payment',
|
|
209
|
-
unitAmount: 2500,
|
|
210
|
-
productName: '25 credits',
|
|
211
130
|
currency: 'usd',
|
|
212
131
|
allowPromotionCodes: true,
|
|
213
132
|
metadata: { billingConfigKey: 'credits' },
|
|
@@ -276,8 +195,6 @@ describe('0.1.x (c): createCheckoutAlgorithm(request, provider, auth, config)',
|
|
|
276
195
|
});
|
|
277
196
|
expect(stripe.createCheckoutSession).toHaveBeenCalledWith({
|
|
278
197
|
priceId: 'price_client',
|
|
279
|
-
unitAmount: undefined,
|
|
280
|
-
productName: undefined,
|
|
281
198
|
currency: 'eur',
|
|
282
199
|
customerEmail: 'a@b.co',
|
|
283
200
|
metadata: { billingConfigKey: 'pro_monthly', ref: 'x', userId: USER_ID },
|
|
@@ -288,29 +205,6 @@ describe('0.1.x (c): createCheckoutAlgorithm(request, provider, auth, config)',
|
|
|
288
205
|
});
|
|
289
206
|
});
|
|
290
207
|
|
|
291
|
-
it('dynamic pricing through a 0.1.x provider', async () => {
|
|
292
|
-
const stripe = makeLegacyProvider();
|
|
293
|
-
await createCheckoutAlgorithm(
|
|
294
|
-
{
|
|
295
|
-
unitAmount: 2500,
|
|
296
|
-
productName: '25 credits',
|
|
297
|
-
userId: USER_ID,
|
|
298
|
-
metadata: { billingConfigKey: 'credits' },
|
|
299
|
-
...URLS,
|
|
300
|
-
},
|
|
301
|
-
stripe,
|
|
302
|
-
auth,
|
|
303
|
-
makeLegacyConfig()
|
|
304
|
-
);
|
|
305
|
-
expect(stripe.createCheckoutSession.mock.calls[0]?.[0]).toMatchObject({
|
|
306
|
-
priceId: undefined,
|
|
307
|
-
unitAmount: 2500,
|
|
308
|
-
productName: '25 credits',
|
|
309
|
-
currency: 'eur',
|
|
310
|
-
mode: 'payment',
|
|
311
|
-
});
|
|
312
|
-
});
|
|
313
|
-
|
|
314
208
|
it('0.1.x call shape requires request.userId', async () => {
|
|
315
209
|
await expect(
|
|
316
210
|
createCheckoutAlgorithm(
|
|
@@ -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
|
-
/**
|
|
27
|
-
priceId
|
|
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
|
|
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
|
|
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,
|
|
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,
|
|
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,
|
|
@@ -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
|
|
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
|
|
@@ -206,8 +206,8 @@ type CheckoutArgs =
|
|
|
206
206
|
* Create checkout session algorithm
|
|
207
207
|
*
|
|
208
208
|
* 1. Resolve the billing config item and verify the user
|
|
209
|
-
* 2. Single-price items: 0.1.x pricing (request/back-config priceId
|
|
210
|
-
* 3. `beforeCheckout` hook (block/allow
|
|
209
|
+
* 2. Single-price items: 0.1.x pricing (request/back-config priceId)
|
|
210
|
+
* 3. `beforeCheckout` hook (block/allow)
|
|
211
211
|
* 4. StripeOrder: reject inclusive manual Tax Rates, `resolveLineItems` prices every line
|
|
212
212
|
* and may set per-order session options (`ResolvedOrder.session`: tax rates,
|
|
213
213
|
* payment methods, expiry, invoice footer)
|
|
@@ -301,8 +301,6 @@ export async function createCheckoutAlgorithm(
|
|
|
301
301
|
);
|
|
302
302
|
|
|
303
303
|
const allowPromotionCodes = request.allowPromotionCodes ?? true;
|
|
304
|
-
let unitAmount = request.unitAmount;
|
|
305
|
-
let productName = request.productName;
|
|
306
304
|
|
|
307
305
|
if (billingItem.beforeCheckout) {
|
|
308
306
|
const options: BeforeCheckoutOptions = {
|
|
@@ -323,11 +321,6 @@ export async function createCheckoutAlgorithm(
|
|
|
323
321
|
hookResult.reason || 'Checkout blocked by beforeCheckout hook'
|
|
324
322
|
);
|
|
325
323
|
}
|
|
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
324
|
}
|
|
332
325
|
|
|
333
326
|
const successUrl = resolveRedirectUrl(request.successUrl, 'success');
|
|
@@ -382,17 +375,8 @@ export async function createCheckoutAlgorithm(
|
|
|
382
375
|
assertCheckoutSessionMetadata(params);
|
|
383
376
|
session = await stripeProvider.createStripeSession(params);
|
|
384
377
|
} 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
378
|
const params: CheckoutSessionParams = {
|
|
393
379
|
priceId: plan?.priceId,
|
|
394
|
-
unitAmount: dynamic ? unitAmount : undefined,
|
|
395
|
-
productName: dynamic ? productName : undefined,
|
|
396
380
|
currency: request.currency || billingItem.currency || 'eur',
|
|
397
381
|
customerEmail: request.customerEmail,
|
|
398
382
|
metadata,
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
newOwnerToken,
|
|
23
23
|
} from './idempotencyContract.js';
|
|
24
24
|
import type {
|
|
25
|
-
|
|
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():
|
|
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
|
}
|