@donotdev/functions 0.2.3 → 0.3.1
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/guidelines/VERCEL.md +2 -2
- package/lib/chunks/{chunk-UH445BGK.js → chunk-2N73OZFE.js} +2 -2
- package/lib/chunks/chunk-472JD6X7.js +22 -0
- package/lib/chunks/chunk-472JD6X7.js.map +7 -0
- package/lib/chunks/{chunk-QXIOO2RL.js → chunk-BTWJEJCV.js} +2 -2
- package/lib/chunks/chunk-CN6WXKYF.js +22 -0
- package/lib/chunks/chunk-CN6WXKYF.js.map +7 -0
- package/lib/chunks/{chunk-GDIUOJMD.js → chunk-DGBZDD6D.js} +2 -2
- package/lib/chunks/chunk-GBZQPOX4.js +151 -0
- package/lib/chunks/{chunk-F3WBFWPO.js.map → chunk-GBZQPOX4.js.map} +3 -3
- package/lib/chunks/chunk-ORBGTVJI.js +22 -0
- package/lib/chunks/{chunk-EZKRLLSQ.js.map → chunk-ORBGTVJI.js.map} +1 -1
- package/lib/chunks/chunk-R3I7U5QT.js +22 -0
- package/lib/chunks/chunk-R3I7U5QT.js.map +7 -0
- package/lib/chunks/{chunk-6NXIK35R.js → chunk-XWMG2FWZ.js} +2 -2
- package/lib/chunks/{chunk-6NXIK35R.js.map → chunk-XWMG2FWZ.js.map} +1 -1
- package/lib/chunks/chunk-ZCY6GTIC.js +22 -0
- package/lib/chunks/chunk-ZCY6GTIC.js.map +7 -0
- package/lib/chunks/{monitoring-LXNVBD3G.js → monitoring-KF7FRUQ6.js} +2 -2
- package/lib/chunks/{rateLimiter-GG5LPWXJ.js → rateLimiter-S7TITXOD.js} +2 -2
- package/lib/chunks/{server-NODQAE3F.js → server-SU4BVPPF.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.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/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -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/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/utils.d.ts +0 -9
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -1
- package/lib/supabase/crud/entityStore.d.ts +54 -14
- package/lib/supabase/crud/update.d.ts +7 -2
- package/lib/supabase/index.d.ts +4 -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/package.json +3 -3
- package/src/firebase/auth/removeCustomClaims.ts +31 -1
- package/src/firebase/auth/setCustomClaims.ts +3 -0
- 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 +10 -21
- package/src/firebase/crud/bulk.ts +23 -10
- package/src/firebase/crud/create.ts +19 -18
- package/src/firebase/crud/get.ts +3 -12
- package/src/firebase/crud/list.ts +5 -4
- package/src/firebase/crud/update.ts +35 -19
- package/src/firebase/registerCrudFunctions.ts +1 -0
- 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/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/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/crud/bulkCore.ts +110 -81
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/utils.ts +0 -43
- 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/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/crud/bulk.ts +47 -0
- package/src/supabase/crud/create.ts +14 -24
- package/src/supabase/crud/entityStore.ts +106 -17
- package/src/supabase/crud/get.ts +3 -12
- package/src/supabase/crud/list.ts +5 -4
- package/src/supabase/crud/update.ts +20 -18
- package/src/supabase/index.ts +7 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/crud/bulk.ts +27 -4
- package/src/vercel/api/crud/create.ts +17 -19
- package/src/vercel/api/crud/get.ts +5 -6
- package/src/vercel/api/crud/list.ts +4 -5
- package/src/vercel/api/crud/update.ts +20 -18
- package/lib/chunks/chunk-EZKRLLSQ.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js.map +0 -7
- package/lib/chunks/chunk-F3WBFWPO.js +0 -151
- package/lib/chunks/chunk-G5DRV3DH.js +0 -22
- package/lib/chunks/chunk-G5DRV3DH.js.map +0 -7
- package/lib/chunks/chunk-Q2WLRFOE.js +0 -22
- package/lib/chunks/chunk-Q2WLRFOE.js.map +0 -7
- package/lib/chunks/chunk-W74UL7AY.js +0 -22
- package/lib/chunks/chunk-W74UL7AY.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -188
- /package/lib/chunks/{chunk-UH445BGK.js.map → chunk-2N73OZFE.js.map} +0 -0
- /package/lib/chunks/{chunk-QXIOO2RL.js.map → chunk-BTWJEJCV.js.map} +0 -0
- /package/lib/chunks/{chunk-GDIUOJMD.js.map → chunk-DGBZDD6D.js.map} +0 -0
- /package/lib/chunks/{monitoring-LXNVBD3G.js.map → monitoring-KF7FRUQ6.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-GG5LPWXJ.js.map → rateLimiter-S7TITXOD.js.map} +0 -0
- /package/lib/chunks/{server-NODQAE3F.js.map → server-SU4BVPPF.js.map} +0 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const { getUser, setCustomUserClaims, getUserById, updateUserById } = vi.hoisted(() => ({
|
|
4
|
+
getUser: vi.fn(),
|
|
5
|
+
setCustomUserClaims: vi.fn(),
|
|
6
|
+
getUserById: vi.fn(),
|
|
7
|
+
updateUserById: vi.fn(),
|
|
8
|
+
}));
|
|
9
|
+
|
|
10
|
+
vi.mock('@donotdev/firebase/server', () => ({
|
|
11
|
+
getFirebaseAdminAuth: () => ({ getUser, setCustomUserClaims }),
|
|
12
|
+
getFirebaseAdminFirestore: vi.fn(),
|
|
13
|
+
}));
|
|
14
|
+
vi.mock('../../firebase/baseFunction.js', () => ({
|
|
15
|
+
createBaseFunction: (_config: unknown, _schema: unknown, _name: string, handler: unknown) => handler,
|
|
16
|
+
}));
|
|
17
|
+
vi.mock('../../supabase/baseFunction.js', () => ({
|
|
18
|
+
createSupabaseHandler: (_name: string, _schema: unknown, handler: unknown) => handler,
|
|
19
|
+
}));
|
|
20
|
+
|
|
21
|
+
import { setCustomClaims } from '../../firebase/auth/setCustomClaims.js';
|
|
22
|
+
import { createSetCustomClaims } from '../../supabase/auth/setCustomClaims.js';
|
|
23
|
+
|
|
24
|
+
// Base wrappers are mocked above to expose only the authenticated business logic.
|
|
25
|
+
type Handler = (data: { customClaims: Record<string, unknown> }, context: unknown) => Promise<unknown>;
|
|
26
|
+
|
|
27
|
+
const subscription = {
|
|
28
|
+
tier: 'member',
|
|
29
|
+
status: 'active',
|
|
30
|
+
subscriptionEnd: null,
|
|
31
|
+
updatedAt: '2026-06-01T00:00:00.000Z',
|
|
32
|
+
};
|
|
33
|
+
const existingClaims = { subscription, role: 'user', locale: 'en' };
|
|
34
|
+
|
|
35
|
+
beforeEach(() => {
|
|
36
|
+
vi.clearAllMocks();
|
|
37
|
+
getUser.mockResolvedValue({ customClaims: existingClaims });
|
|
38
|
+
setCustomUserClaims.mockResolvedValue(undefined);
|
|
39
|
+
getUserById.mockResolvedValue({ data: { user: { app_metadata: existingClaims } }, error: null });
|
|
40
|
+
updateUserById.mockResolvedValue({ error: null });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
for (const provider of ['firebase', 'supabase'] as const) {
|
|
44
|
+
describe(`${provider} self-service custom claims`, () => {
|
|
45
|
+
const create = (allowedClaimKeys: string[]) => provider === 'firebase'
|
|
46
|
+
? setCustomClaims({ allowedClaimKeys })
|
|
47
|
+
: createSetCustomClaims({ allowedClaimKeys });
|
|
48
|
+
const context = {
|
|
49
|
+
uid: 'user-1',
|
|
50
|
+
supabaseAdmin: { auth: { admin: { getUserById, updateUserById } } },
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
it.each(['subscription', 'role', 'tier', 'plan'])(
|
|
54
|
+
'rejects mistakenly allowlisted %s at factory creation',
|
|
55
|
+
(key) => {
|
|
56
|
+
expect(() => create(['locale', key])).toThrow(`Claim key "${key}" is blocked`);
|
|
57
|
+
expect(getUser).not.toHaveBeenCalled();
|
|
58
|
+
expect(getUserById).not.toHaveBeenCalled();
|
|
59
|
+
expect(setCustomUserClaims).not.toHaveBeenCalled();
|
|
60
|
+
expect(updateUserById).not.toHaveBeenCalled();
|
|
61
|
+
}
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
it.each([subscription, { ...subscription, tier: 'premium', subscriptionId: 'sub_paid', customerId: 'cus_paid', cancelAtPeriodEnd: false }, null])(
|
|
65
|
+
'rejects subscription assignment or replacement through the request',
|
|
66
|
+
async (value) => {
|
|
67
|
+
const handler = create(['locale']) as unknown as Handler;
|
|
68
|
+
await expect(handler({ customClaims: { subscription: value } }, context))
|
|
69
|
+
.rejects.toThrow('Claim keys not allowed: subscription');
|
|
70
|
+
expect(getUser).not.toHaveBeenCalled();
|
|
71
|
+
expect(getUserById).not.toHaveBeenCalled();
|
|
72
|
+
expect(setCustomUserClaims).not.toHaveBeenCalled();
|
|
73
|
+
expect(updateUserById).not.toHaveBeenCalled();
|
|
74
|
+
}
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
it.runIf(provider === 'supabase')('does not replay stale access claims over a concurrent trusted revoke', async () => {
|
|
78
|
+
const handler = create(['locale']) as unknown as Handler;
|
|
79
|
+
const revoked = { ...subscription, tier: 'free', status: 'canceled' };
|
|
80
|
+
const stored = { ...existingClaims, subscription: revoked };
|
|
81
|
+
// getUserById returns the earlier snapshot; the server has since revoked access.
|
|
82
|
+
updateUserById.mockImplementation(async (_uid, { app_metadata }) => {
|
|
83
|
+
Object.assign(stored, app_metadata);
|
|
84
|
+
return { error: null };
|
|
85
|
+
});
|
|
86
|
+
await handler({ customClaims: { locale: 'fr' } }, context);
|
|
87
|
+
expect(stored).toEqual({ ...existingClaims, subscription: revoked, locale: 'fr' });
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('preserves canonical subscription and unrelated claims when updating an allowed key', async () => {
|
|
91
|
+
const handler = create(['locale']) as unknown as Handler;
|
|
92
|
+
const updatedClaims = { ...existingClaims, locale: 'fr' };
|
|
93
|
+
await expect(handler({ customClaims: { locale: 'fr' } }, context))
|
|
94
|
+
.resolves.toEqual({ success: true, customClaims: updatedClaims });
|
|
95
|
+
if (provider === 'firebase') {
|
|
96
|
+
expect(setCustomUserClaims).toHaveBeenCalledWith('user-1', updatedClaims);
|
|
97
|
+
} else {
|
|
98
|
+
expect(updateUserById).toHaveBeenCalledWith('user-1', { app_metadata: { locale: 'fr' } });
|
|
99
|
+
}
|
|
100
|
+
expect(existingClaims.subscription).toEqual(subscription);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
}
|
|
@@ -44,7 +44,6 @@ import {
|
|
|
44
44
|
getUserRole,
|
|
45
45
|
createSuccessResponse,
|
|
46
46
|
createErrorResponse,
|
|
47
|
-
validateDocument,
|
|
48
47
|
validateCollectionName,
|
|
49
48
|
} from '../utils';
|
|
50
49
|
import { validateStripeEnvironment } from '../billing/stripeClient';
|
|
@@ -166,35 +165,6 @@ describe('createErrorResponse', () => {
|
|
|
166
165
|
});
|
|
167
166
|
});
|
|
168
167
|
|
|
169
|
-
// ---------------------------------------------------------------------------
|
|
170
|
-
// validateDocument
|
|
171
|
-
// ---------------------------------------------------------------------------
|
|
172
|
-
|
|
173
|
-
describe('validateDocument', () => {
|
|
174
|
-
it('accepts valid object data', () => {
|
|
175
|
-
expect(() => validateDocument({ name: 'test' })).not.toThrow();
|
|
176
|
-
});
|
|
177
|
-
|
|
178
|
-
it('rejects null', () => {
|
|
179
|
-
expect(() => validateDocument(null)).toThrow('Invalid document data');
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
it('rejects undefined', () => {
|
|
183
|
-
expect(() => validateDocument(undefined)).toThrow('Invalid document data');
|
|
184
|
-
});
|
|
185
|
-
|
|
186
|
-
it('rejects non-object', () => {
|
|
187
|
-
expect(() => validateDocument('string')).toThrow('Invalid document data');
|
|
188
|
-
expect(() => validateDocument(123)).toThrow('Invalid document data');
|
|
189
|
-
});
|
|
190
|
-
|
|
191
|
-
it('rejects arrays', () => {
|
|
192
|
-
expect(() => validateDocument([1, 2])).toThrow(
|
|
193
|
-
'Document data cannot be an array'
|
|
194
|
-
);
|
|
195
|
-
});
|
|
196
|
-
});
|
|
197
|
-
|
|
198
168
|
// ---------------------------------------------------------------------------
|
|
199
169
|
// validateCollectionName
|
|
200
170
|
// ---------------------------------------------------------------------------
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import * as v from 'valibot';
|
|
3
|
+
|
|
4
|
+
import type { SubscriptionUpdate } from '@donotdev/core/server';
|
|
5
|
+
import { SubscriptionClaimsSchema } from '../../../../../core/types/src/auth/schemas';
|
|
6
|
+
import { updateUserSubscription } from '../helpers/updateUserSubscription';
|
|
7
|
+
|
|
8
|
+
// Keep the real canonical schema while isolating unrelated server integrations.
|
|
9
|
+
vi.mock('@donotdev/core/server', async () => {
|
|
10
|
+
const { SubscriptionClaimsSchema } = await import('../../../../../core/types/src/auth/schemas');
|
|
11
|
+
return { SubscriptionClaimsSchema };
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
function paidUpdate(): SubscriptionUpdate {
|
|
15
|
+
return {
|
|
16
|
+
tier: 'pro',
|
|
17
|
+
status: 'active',
|
|
18
|
+
subscriptionEnd: '2026-07-01T00:00:00.000Z',
|
|
19
|
+
subscriptionId: 'sub_paid',
|
|
20
|
+
customerId: 'cus_paid',
|
|
21
|
+
cancelAtPeriodEnd: false,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function provider() {
|
|
26
|
+
const customClaims = {
|
|
27
|
+
role: 'admin',
|
|
28
|
+
permissions: ['manage-team'],
|
|
29
|
+
unrelated: { preserved: true },
|
|
30
|
+
subscription: { tier: 'old', features: ['old-feature'] },
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
customClaims,
|
|
34
|
+
getUser: vi.fn(async () => ({ customClaims })),
|
|
35
|
+
setCustomUserClaims: vi.fn(async (_userId: string, _claims: Record<string, unknown>) => {}),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe('updateUserSubscription', () => {
|
|
40
|
+
afterEach(() => vi.useRealTimers());
|
|
41
|
+
|
|
42
|
+
it.each(['active', 'canceled', 'past_due', 'trialing', 'incomplete'] as const)(
|
|
43
|
+
'writes canonical paid %s claims and preserves unrelated metadata',
|
|
44
|
+
async (status) => {
|
|
45
|
+
vi.useFakeTimers();
|
|
46
|
+
vi.setSystemTime(new Date('2026-06-02T12:34:56.789Z'));
|
|
47
|
+
const auth = provider();
|
|
48
|
+
const update = { ...paidUpdate(), status };
|
|
49
|
+
await updateUserSubscription('user-a', update, auth);
|
|
50
|
+
const subscription = {
|
|
51
|
+
...update,
|
|
52
|
+
updatedAt: new Date().toISOString(),
|
|
53
|
+
isDefault: false,
|
|
54
|
+
};
|
|
55
|
+
expect(v.parse(SubscriptionClaimsSchema, subscription)).toEqual(subscription);
|
|
56
|
+
expect(auth.setCustomUserClaims).toHaveBeenCalledExactlyOnceWith('user-a', {
|
|
57
|
+
...auth.customClaims,
|
|
58
|
+
subscription,
|
|
59
|
+
});
|
|
60
|
+
expect(auth.customClaims.subscription).toEqual({ tier: 'old', features: ['old-feature'] });
|
|
61
|
+
}
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
it.each([
|
|
65
|
+
{ tier: 'member', status: 'active' },
|
|
66
|
+
{ tier: 'free', status: 'canceled' },
|
|
67
|
+
] as const)('writes complete $tier access without payment identifiers', async ({ tier, status }) => {
|
|
68
|
+
const auth = provider();
|
|
69
|
+
await updateUserSubscription('user-a', { tier, status, subscriptionEnd: null }, auth);
|
|
70
|
+
expect(auth.setCustomUserClaims).toHaveBeenCalledExactlyOnceWith('user-a', {
|
|
71
|
+
...auth.customClaims,
|
|
72
|
+
subscription: {
|
|
73
|
+
tier,
|
|
74
|
+
status,
|
|
75
|
+
subscriptionEnd: null,
|
|
76
|
+
subscriptionId: null,
|
|
77
|
+
customerId: null,
|
|
78
|
+
cancelAtPeriodEnd: false,
|
|
79
|
+
updatedAt: expect.any(String),
|
|
80
|
+
isDefault: false,
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
const claims = auth.setCustomUserClaims.mock.calls[0]?.[1];
|
|
84
|
+
expect(v.safeParse(SubscriptionClaimsSchema, claims?.subscription).success).toBe(true);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('supports one-time paid access without a recurring subscription ID', async () => {
|
|
88
|
+
const auth = provider();
|
|
89
|
+
const update = paidUpdate();
|
|
90
|
+
delete update.subscriptionId;
|
|
91
|
+
delete update.cancelAtPeriodEnd;
|
|
92
|
+
update.subscriptionEnd = null;
|
|
93
|
+
await updateUserSubscription('user-a', update, auth);
|
|
94
|
+
expect(auth.setCustomUserClaims).toHaveBeenCalledWith('user-a', expect.objectContaining({
|
|
95
|
+
subscription: expect.objectContaining({
|
|
96
|
+
customerId: 'cus_paid', subscriptionId: null, subscriptionEnd: null,
|
|
97
|
+
cancelAtPeriodEnd: false,
|
|
98
|
+
}),
|
|
99
|
+
}));
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it.each(['tier', 'status'] as const)('retains the missing %s error', async (field) => {
|
|
103
|
+
const auth = provider();
|
|
104
|
+
const update = paidUpdate();
|
|
105
|
+
Reflect.set(update, field, '');
|
|
106
|
+
await expect(updateUserSubscription('user-a', update, auth))
|
|
107
|
+
.rejects.toThrow('Invalid subscription data: missing tier or status');
|
|
108
|
+
expect(auth.setCustomUserClaims).not.toHaveBeenCalled();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it.each([undefined, null])('preserves customer-less one-time checkout without fabricating an ID: %s', async (customerId) => {
|
|
112
|
+
const auth = provider();
|
|
113
|
+
const update = paidUpdate();
|
|
114
|
+
delete update.subscriptionId;
|
|
115
|
+
Reflect.set(update, 'customerId', customerId);
|
|
116
|
+
await updateUserSubscription('user-a', update, auth);
|
|
117
|
+
expect(auth.setCustomUserClaims).toHaveBeenCalledWith('user-a', expect.objectContaining({
|
|
118
|
+
subscription: expect.objectContaining({ customerId: null, subscriptionId: null }),
|
|
119
|
+
}));
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it.each([
|
|
123
|
+
['tier', 42],
|
|
124
|
+
['status', true],
|
|
125
|
+
['subscriptionEnd', 'not-a-timestamp'],
|
|
126
|
+
['subscriptionEnd', undefined],
|
|
127
|
+
['subscriptionId', { id: 'sub_expanded' }],
|
|
128
|
+
['customerId', { id: 'cus_expanded' }],
|
|
129
|
+
['cancelAtPeriodEnd', 'false'],
|
|
130
|
+
])('rejects invalid %s before persisting claims', async (field, value) => {
|
|
131
|
+
const auth = provider();
|
|
132
|
+
const update = paidUpdate();
|
|
133
|
+
// Exercise untrusted runtime input without changing the typed producer API.
|
|
134
|
+
Reflect.set(update, field, value);
|
|
135
|
+
await expect(updateUserSubscription('user-a', update, auth)).rejects.toThrow();
|
|
136
|
+
expect(auth.setCustomUserClaims).not.toHaveBeenCalled();
|
|
137
|
+
expect(auth.customClaims.unrelated).toEqual({ preserved: true });
|
|
138
|
+
});
|
|
139
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { describe, expect, expectTypeOf, it } from 'vitest';
|
|
2
|
+
import type Stripe from 'stripe';
|
|
3
|
+
|
|
4
|
+
import * as shared from '../../index.js';
|
|
5
|
+
import * as supabase from '../../../supabase/index.js';
|
|
6
|
+
import type { StripeSessionProvider } from '../createCheckout.js';
|
|
7
|
+
import type { VerifyOrderCheckoutDependencies } from '../verifyOrderCheckout.js';
|
|
8
|
+
import { verifyOrderCheckoutAlgorithm } from '../verifyOrderCheckout.js';
|
|
9
|
+
import { createCheckoutAlgorithm } from '../createCheckout.js';
|
|
10
|
+
import { handleOrderSessionEvent } from '../orderWebhook.js';
|
|
11
|
+
import { createCheckoutSession } from '../../../supabase/billing/createCheckoutSession.js';
|
|
12
|
+
import { createStripeWebhook } from '../../../supabase/billing/stripeWebhook.js';
|
|
13
|
+
import type {
|
|
14
|
+
ProcessPaymentSuccessRequest,
|
|
15
|
+
ProcessPaymentSuccessResponse,
|
|
16
|
+
} from '@donotdev/core/server';
|
|
17
|
+
|
|
18
|
+
describe('checkout verification additive public exports', () => {
|
|
19
|
+
it('exposes the same algorithm through shared and Supabase entry points', () => {
|
|
20
|
+
expect(shared.verifyOrderCheckoutAlgorithm).toBe(verifyOrderCheckoutAlgorithm);
|
|
21
|
+
expect(supabase.verifyOrderCheckoutAlgorithm).toBe(verifyOrderCheckoutAlgorithm);
|
|
22
|
+
expectTypeOf<supabase.VerifyOrderCheckoutDependencies>().toEqualTypeOf<VerifyOrderCheckoutDependencies>();
|
|
23
|
+
expectTypeOf<shared.OrderCheckoutBinding>().toEqualTypeOf<supabase.OrderCheckoutBinding>();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('preserves existing checkout and webhook exports', () => {
|
|
27
|
+
expect(shared.createCheckoutAlgorithm).toBe(createCheckoutAlgorithm);
|
|
28
|
+
expect(supabase.createCheckoutAlgorithm).toBe(createCheckoutAlgorithm);
|
|
29
|
+
expect(shared.handleOrderSessionEvent).toBe(handleOrderSessionEvent);
|
|
30
|
+
expect(supabase.createCheckoutSession).toBe(createCheckoutSession);
|
|
31
|
+
expect(supabase.createStripeWebhook).toBe(createStripeWebhook);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('keeps retrieval separate from existing creation providers and legacy success declarations', () => {
|
|
35
|
+
const provider: StripeSessionProvider = {
|
|
36
|
+
createStripeSession: async () => ({ id: 'cs_created', url: null }),
|
|
37
|
+
retrieveTaxRate: async (id) => ({ id, inclusive: false }),
|
|
38
|
+
};
|
|
39
|
+
expect(Object.keys(provider)).toEqual(['createStripeSession', 'retrieveTaxRate']);
|
|
40
|
+
expectTypeOf<StripeSessionProvider>().toEqualTypeOf<supabase.StripeSessionProvider>();
|
|
41
|
+
expectTypeOf<VerifyOrderCheckoutDependencies['retrieveStripeSession']>().toEqualTypeOf<
|
|
42
|
+
(id: string) => Promise<Pick<Stripe.Checkout.Session, 'id' | 'mode' | 'status' | 'payment_status' | 'metadata'>>
|
|
43
|
+
>();
|
|
44
|
+
expectTypeOf<ProcessPaymentSuccessRequest>().toEqualTypeOf<{ sessionId: string }>();
|
|
45
|
+
expectTypeOf<ProcessPaymentSuccessResponse>().toEqualTypeOf<{ success: boolean; sessionId: string }>();
|
|
46
|
+
});
|
|
47
|
+
});
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import * as v from 'valibot';
|
|
3
|
+
|
|
4
|
+
import { VerifyOrderCheckoutRequestSchema } from '@donotdev/core/server';
|
|
5
|
+
import type { StripeOrderBackItem } from '@donotdev/core/server';
|
|
6
|
+
|
|
7
|
+
import { createSupabaseHandler } from '../../../supabase/baseFunction.js';
|
|
8
|
+
import { logger } from '../../logger.js';
|
|
9
|
+
import { verifyOrderCheckoutAlgorithm } from '../verifyOrderCheckout.js';
|
|
10
|
+
import type { VerifyOrderCheckoutDependencies } from '../verifyOrderCheckout.js';
|
|
11
|
+
|
|
12
|
+
vi.mock('@supabase/supabase-js', () => ({
|
|
13
|
+
createClient: () => ({
|
|
14
|
+
auth: { getUser: async (token: string) => ({
|
|
15
|
+
data: { user: token === 'valid' ? { id: 'owner', app_metadata: {} } : null },
|
|
16
|
+
error: null,
|
|
17
|
+
}) },
|
|
18
|
+
}),
|
|
19
|
+
}));
|
|
20
|
+
vi.mock('../../logger.js', () => ({ logger: { warn: vi.fn() } }));
|
|
21
|
+
|
|
22
|
+
const request = { sessionId: 'cs_private', billingConfigKey: 'shop' };
|
|
23
|
+
const binding = { ...request, userId: 'owner', orderId: 'order_private' };
|
|
24
|
+
|
|
25
|
+
function fixture() {
|
|
26
|
+
const order: StripeOrderBackItem = {
|
|
27
|
+
type: 'StripeOrder', name: 'Shop', currency: 'eur',
|
|
28
|
+
tax: { mode: 'automatic' }, taxIdCollection: 'disabled',
|
|
29
|
+
billingAddressCollection: 'auto', customerCreation: 'if_required', invoiceCreation: false,
|
|
30
|
+
resolveLineItems: vi.fn(), beforeCheckout: vi.fn(), onOrderPaid: vi.fn(),
|
|
31
|
+
onOrderExpired: vi.fn(), onOrderPaymentFailed: vi.fn(), onTaxIdUpdated: vi.fn(),
|
|
32
|
+
};
|
|
33
|
+
const deps = {
|
|
34
|
+
billingConfig: { shop: order },
|
|
35
|
+
resolveOrderBinding: vi.fn<VerifyOrderCheckoutDependencies['resolveOrderBinding']>(async () => binding),
|
|
36
|
+
retrieveStripeSession: vi.fn<VerifyOrderCheckoutDependencies['retrieveStripeSession']>(async () => ({
|
|
37
|
+
id: request.sessionId, mode: 'payment', status: 'complete', payment_status: 'paid',
|
|
38
|
+
metadata: { userId: 'owner', billingConfigKey: 'shop', orderId: binding.orderId },
|
|
39
|
+
})),
|
|
40
|
+
};
|
|
41
|
+
const handler = createSupabaseHandler('verify-order-checkout', v.unknown(), (input, ctx) =>
|
|
42
|
+
verifyOrderCheckoutAlgorithm(input, { ...deps, userId: ctx.uid })
|
|
43
|
+
);
|
|
44
|
+
return { deps, handler, order };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function post(body: string, token = 'valid') {
|
|
48
|
+
return new Request('https://example.test/verify', {
|
|
49
|
+
method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
beforeEach(() => {
|
|
54
|
+
vi.stubEnv('SUPABASE_URL', 'https://example.test');
|
|
55
|
+
vi.stubEnv('SUPABASE_SECRET_KEY', 'synthetic');
|
|
56
|
+
vi.stubEnv('DISABLE_RATE_LIMITING', 'true');
|
|
57
|
+
vi.stubEnv('ENABLE_METRICS', 'false');
|
|
58
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
59
|
+
vi.mocked(logger.warn).mockReset();
|
|
60
|
+
});
|
|
61
|
+
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); });
|
|
62
|
+
|
|
63
|
+
describe('checkout verification through the real Supabase handler', () => {
|
|
64
|
+
it('returns only verified state using the authenticated identity without invoking fulfillment', async () => {
|
|
65
|
+
const { handler, deps, order } = fixture();
|
|
66
|
+
const response = await handler(post(JSON.stringify({ ...request, userId: 'attacker' })));
|
|
67
|
+
expect(response.status).toBe(200);
|
|
68
|
+
expect(await response.json()).toEqual({ ...request, orderId: binding.orderId, sessionStatus: 'complete', paymentStatus: 'paid' });
|
|
69
|
+
expect(deps.resolveOrderBinding).toHaveBeenCalledExactlyOnceWith({ ...request, userId: 'owner' });
|
|
70
|
+
expect(order.onOrderPaid).not.toHaveBeenCalled();
|
|
71
|
+
expect(order.beforeCheckout).not.toHaveBeenCalled();
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it.each(['malformed', 'foreign', 'missing', 'mismatch', 'provider'] as const)(
|
|
75
|
+
'maps %s to the same safe response', async (scenario) => {
|
|
76
|
+
const { handler, deps } = fixture();
|
|
77
|
+
if (scenario === 'foreign') deps.resolveOrderBinding.mockResolvedValue({ ...binding, userId: 'foreign_secret' });
|
|
78
|
+
if (scenario === 'missing') deps.resolveOrderBinding.mockResolvedValue(null);
|
|
79
|
+
if (scenario === 'mismatch') deps.resolveOrderBinding.mockResolvedValue({ ...binding, sessionId: 'cs_other_secret' });
|
|
80
|
+
if (scenario === 'provider') deps.retrieveStripeSession.mockRejectedValue(new Error('sk_secret private@example.com'));
|
|
81
|
+
const input = scenario === 'malformed' ? { sessionId: '', billingConfigKey: 'shop' } : request;
|
|
82
|
+
const response = await handler(post(JSON.stringify(input)));
|
|
83
|
+
expect(response.status).toBe(403);
|
|
84
|
+
expect(await response.json()).toEqual({ error: 'Checkout verification denied' });
|
|
85
|
+
if (scenario === 'malformed') expect(deps.resolveOrderBinding).not.toHaveBeenCalled();
|
|
86
|
+
if (scenario !== 'provider') expect(deps.retrieveStripeSession).not.toHaveBeenCalled();
|
|
87
|
+
expect(logger.warn).toHaveBeenCalledExactlyOnceWith('[Checkout verification] Failed', {
|
|
88
|
+
stage: scenario === 'malformed' ? 'validation' : scenario === 'provider' ? 'provider' : 'binding',
|
|
89
|
+
category: scenario === 'malformed' ? 'invalid' : scenario === 'provider' ? 'unavailable' : 'rejected',
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
it('demonstrates direct schema validation differs, while auth and parsing retain base-handler behavior', async () => {
|
|
95
|
+
const { handler } = fixture();
|
|
96
|
+
const strict = createSupabaseHandler('strict-example', VerifyOrderCheckoutRequestSchema, async () => ({}));
|
|
97
|
+
const invalid = await strict(post(JSON.stringify({ sessionId: '' })));
|
|
98
|
+
expect(invalid.status).toBe(400);
|
|
99
|
+
expect((await invalid.json()).error).toMatch(/^Validation failed:/);
|
|
100
|
+
const unauthorized = await handler(post('{}', 'invalid'));
|
|
101
|
+
expect(unauthorized.status).toBe(401);
|
|
102
|
+
expect(await unauthorized.json()).toEqual({ error: 'Invalid or expired token' });
|
|
103
|
+
const badJson = await handler(post('{'));
|
|
104
|
+
expect(badJson.status).toBe(403);
|
|
105
|
+
expect(await badJson.json()).toEqual({ error: 'Checkout verification denied' });
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import type { StripeOrderBackItem } from '@donotdev/core/server';
|
|
4
|
+
|
|
5
|
+
import { logger } from '../../logger.js';
|
|
6
|
+
import { verifyOrderCheckoutAlgorithm } from '../verifyOrderCheckout.js';
|
|
7
|
+
import type {
|
|
8
|
+
OrderCheckoutBinding,
|
|
9
|
+
VerifyOrderCheckoutDependencies,
|
|
10
|
+
} from '../verifyOrderCheckout.js';
|
|
11
|
+
|
|
12
|
+
vi.mock('../../logger.js', () => ({ logger: { warn: vi.fn() } }));
|
|
13
|
+
|
|
14
|
+
beforeEach(() => {
|
|
15
|
+
vi.mocked(logger.warn).mockReset();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const request = { sessionId: 'cs_owner', billingConfigKey: 'shop' };
|
|
19
|
+
const binding: OrderCheckoutBinding = {
|
|
20
|
+
...request, userId: 'owner', orderId: 'order_1',
|
|
21
|
+
};
|
|
22
|
+
type Session = Awaited<ReturnType<VerifyOrderCheckoutDependencies['retrieveStripeSession']>>;
|
|
23
|
+
|
|
24
|
+
function fixture() {
|
|
25
|
+
const session: Session = {
|
|
26
|
+
id: request.sessionId, mode: 'payment', status: 'complete', payment_status: 'paid',
|
|
27
|
+
metadata: { userId: 'owner', billingConfigKey: 'shop', orderId: 'order_1', secret: 'private' },
|
|
28
|
+
};
|
|
29
|
+
const order: StripeOrderBackItem = {
|
|
30
|
+
type: 'StripeOrder', name: 'Shop', currency: 'eur',
|
|
31
|
+
tax: { mode: 'automatic' }, taxIdCollection: 'disabled',
|
|
32
|
+
billingAddressCollection: 'auto', customerCreation: 'if_required', invoiceCreation: false,
|
|
33
|
+
resolveLineItems: vi.fn(), beforeCheckout: vi.fn(), onOrderPaid: vi.fn(),
|
|
34
|
+
onOrderExpired: vi.fn(), onOrderPaymentFailed: vi.fn(), onTaxIdUpdated: vi.fn(),
|
|
35
|
+
};
|
|
36
|
+
const deps = {
|
|
37
|
+
userId: 'owner', billingConfig: { shop: order },
|
|
38
|
+
retrieveStripeSession: vi.fn<VerifyOrderCheckoutDependencies['retrieveStripeSession']>(async () => session),
|
|
39
|
+
resolveOrderBinding: vi.fn<VerifyOrderCheckoutDependencies['resolveOrderBinding']>(async () => ({ ...binding })),
|
|
40
|
+
};
|
|
41
|
+
return { session, order, deps };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function denied(deps: VerifyOrderCheckoutDependencies, input = request) {
|
|
45
|
+
await expect(verifyOrderCheckoutAlgorithm(input, deps)).rejects.toEqual(
|
|
46
|
+
new Error('Checkout verification denied')
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe('verifyOrderCheckoutAlgorithm', () => {
|
|
51
|
+
it('verifies the authenticated owner, uses read dependencies, and returns only allowlisted state', async () => {
|
|
52
|
+
const { deps, session } = fixture();
|
|
53
|
+
Object.assign(session, { customer_details: { email: 'private@example.com' }, customer: 'cus_secret' });
|
|
54
|
+
const result = await verifyOrderCheckoutAlgorithm({ ...request, ...{ userId: 'attacker' } }, deps);
|
|
55
|
+
expect(result).toEqual({
|
|
56
|
+
...request, orderId: 'order_1', sessionStatus: 'complete', paymentStatus: 'paid',
|
|
57
|
+
});
|
|
58
|
+
expect(deps.resolveOrderBinding).toHaveBeenCalledExactlyOnceWith({ ...request, userId: 'owner' });
|
|
59
|
+
expect(deps.retrieveStripeSession).toHaveBeenCalledExactlyOnceWith('cs_owner');
|
|
60
|
+
expect(logger.warn).not.toHaveBeenCalled();
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it.each([
|
|
64
|
+
['complete', 'paid'], ['complete', 'unpaid'], ['complete', 'no_payment_required'],
|
|
65
|
+
['open', 'unpaid'], ['expired', 'unpaid'],
|
|
66
|
+
] as const)('represents %s/%s without asserting fulfillment or invoking hooks', async (status, paymentStatus) => {
|
|
67
|
+
const { deps, session, order } = fixture();
|
|
68
|
+
session.status = status;
|
|
69
|
+
session.payment_status = paymentStatus;
|
|
70
|
+
const writes = vi.fn();
|
|
71
|
+
Object.assign(deps, { writeOrder: writes, clearCart: writes, fulfillOrder: writes });
|
|
72
|
+
const original = JSON.stringify({ session, order });
|
|
73
|
+
await expect(verifyOrderCheckoutAlgorithm(request, deps)).resolves.toEqual({
|
|
74
|
+
...request, orderId: 'order_1', sessionStatus: status, paymentStatus,
|
|
75
|
+
});
|
|
76
|
+
for (const hook of [order.resolveLineItems, order.beforeCheckout, order.onOrderPaid,
|
|
77
|
+
order.onOrderExpired, order.onOrderPaymentFailed, order.onTaxIdUpdated]) {
|
|
78
|
+
expect(hook).not.toHaveBeenCalled();
|
|
79
|
+
}
|
|
80
|
+
expect(writes).not.toHaveBeenCalled();
|
|
81
|
+
expect(JSON.stringify({ session, order })).toBe(original);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it.each(['orderId', 'userId', 'sessionId', 'billingConfigKey'] as const)(
|
|
85
|
+
'rejects a mismatched persisted binding %s with the same public error', async (key) => {
|
|
86
|
+
const { deps } = fixture();
|
|
87
|
+
deps.resolveOrderBinding.mockResolvedValue({ ...binding, [key]: 'foreign' });
|
|
88
|
+
await denied(deps);
|
|
89
|
+
}
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
it.each([null, undefined])('fails closed without persisted binding (%s), even with valid Stripe metadata', async (value) => {
|
|
93
|
+
const { deps } = fixture();
|
|
94
|
+
deps.resolveOrderBinding.mockResolvedValue(value);
|
|
95
|
+
await denied(deps);
|
|
96
|
+
expect(deps.retrieveStripeSession).not.toHaveBeenCalled();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it.each(['', ' '])('rejects empty persisted order IDs (%j)', async (orderId) => {
|
|
100
|
+
const { deps } = fixture();
|
|
101
|
+
deps.resolveOrderBinding.mockResolvedValue({ ...binding, orderId });
|
|
102
|
+
await denied(deps);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it.each(['userId', 'billingConfigKey', 'orderId'] as const)('requires matching server metadata %s', async (key) => {
|
|
106
|
+
for (const value of [undefined, '', 'foreign']) {
|
|
107
|
+
const { deps, session } = fixture();
|
|
108
|
+
session.metadata = { userId: 'owner', billingConfigKey: 'shop', orderId: 'order_1' };
|
|
109
|
+
if (value === undefined) delete session.metadata[key];
|
|
110
|
+
else session.metadata[key] = value;
|
|
111
|
+
await denied(deps);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('rejects absent metadata and foreign authenticated owners', async () => {
|
|
116
|
+
const { deps, session } = fixture();
|
|
117
|
+
session.metadata = null;
|
|
118
|
+
await denied(deps);
|
|
119
|
+
const foreign = fixture();
|
|
120
|
+
foreign.deps.userId = 'attacker';
|
|
121
|
+
await denied(foreign.deps);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it.each(['subscription', 'setup'] as const)('rejects mode %s', async (mode) => {
|
|
125
|
+
const { deps, session } = fixture();
|
|
126
|
+
session.mode = mode;
|
|
127
|
+
await denied(deps);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('rejects a retrieved session ID mismatch', async () => {
|
|
131
|
+
const { deps, session } = fixture();
|
|
132
|
+
session.id = 'cs_other';
|
|
133
|
+
await denied(deps);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it.each([null, undefined, 'unknown'])('rejects invalid session status %s', async (status) => {
|
|
137
|
+
const { deps, session } = fixture();
|
|
138
|
+
Object.assign(session, { status });
|
|
139
|
+
await denied(deps);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it.each([null, undefined, 'unknown'])('rejects invalid payment status %s', async (payment_status) => {
|
|
143
|
+
const { deps, session } = fixture();
|
|
144
|
+
Object.assign(session, { payment_status });
|
|
145
|
+
await denied(deps);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it('rejects missing/wrong server configs before reading dependencies', async () => {
|
|
149
|
+
const { deps } = fixture();
|
|
150
|
+
await denied(deps, { ...request, billingConfigKey: 'missing' });
|
|
151
|
+
await denied(deps, { ...request, billingConfigKey: '__proto__' });
|
|
152
|
+
for (const type of ['StripePayment', 'StripeSubscription']) {
|
|
153
|
+
Object.assign(deps.billingConfig.shop, { type });
|
|
154
|
+
await denied(deps);
|
|
155
|
+
}
|
|
156
|
+
expect(deps.resolveOrderBinding).not.toHaveBeenCalled();
|
|
157
|
+
expect(deps.retrieveStripeSession).not.toHaveBeenCalled();
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it('validates input and authenticated identity even when invoked without a schema handler', async () => {
|
|
161
|
+
const { deps } = fixture();
|
|
162
|
+
await denied(deps, { ...request, sessionId: '' });
|
|
163
|
+
await denied(deps, { ...request, billingConfigKey: ' ' });
|
|
164
|
+
deps.userId = '';
|
|
165
|
+
await denied(deps);
|
|
166
|
+
expect(deps.resolveOrderBinding).not.toHaveBeenCalled();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it.each([
|
|
170
|
+
['retrieveStripeSession', 'provider'],
|
|
171
|
+
['resolveOrderBinding', 'binding'],
|
|
172
|
+
] as const)('diagnoses unavailable %s without leaking dependency errors', async (key, stage) => {
|
|
173
|
+
const { deps } = fixture();
|
|
174
|
+
deps[key].mockRejectedValue(new Error(
|
|
175
|
+
'owner order_1 cs_owner sk_test_secret Cookie: session=private private@example.com'
|
|
176
|
+
));
|
|
177
|
+
await denied(deps);
|
|
178
|
+
expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
|
|
179
|
+
'[Checkout verification] Failed', { stage, category: 'unavailable' }
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('distinguishes rejected owner from unavailable storage without logging identities', async () => {
|
|
184
|
+
const { deps } = fixture();
|
|
185
|
+
deps.resolveOrderBinding.mockResolvedValue({ ...binding, userId: 'foreign_owner_secret' });
|
|
186
|
+
await denied(deps);
|
|
187
|
+
expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
|
|
188
|
+
'[Checkout verification] Failed', { stage: 'binding', category: 'rejected' }
|
|
189
|
+
);
|
|
190
|
+
expect(deps.retrieveStripeSession).not.toHaveBeenCalled();
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it.each(['validation', 'auth', 'config', 'response'] as const)(
|
|
194
|
+
'records sanitized %s diagnostics', async (stage) => {
|
|
195
|
+
const { deps, session } = fixture();
|
|
196
|
+
let input = request;
|
|
197
|
+
if (stage === 'validation') input = { ...request, sessionId: '' };
|
|
198
|
+
if (stage === 'auth') deps.userId = '';
|
|
199
|
+
if (stage === 'config') deps.billingConfig = {};
|
|
200
|
+
if (stage === 'response') Object.assign(session, { status: 'secret_invalid_status' });
|
|
201
|
+
await denied(deps, input);
|
|
202
|
+
expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
|
|
203
|
+
'[Checkout verification] Failed',
|
|
204
|
+
{ stage, category: stage === 'auth' ? 'rejected' : 'invalid' }
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
it('diagnoses rejected provider metadata without logging provider/customer data', async () => {
|
|
210
|
+
const { deps, session } = fixture();
|
|
211
|
+
session.metadata = { userId: 'foreign_owner_secret', token: 'sk_test_secret' };
|
|
212
|
+
Object.assign(session, { customer_details: { email: 'private@example.com' } });
|
|
213
|
+
await denied(deps);
|
|
214
|
+
expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
|
|
215
|
+
'[Checkout verification] Failed', { stage: 'response', category: 'rejected' }
|
|
216
|
+
);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it.each(['throw', 'reject'] as const)('preserves safe public error when logger fails (%s)', async (mode) => {
|
|
220
|
+
const { deps } = fixture();
|
|
221
|
+
deps.retrieveStripeSession.mockRejectedValue(new Error('provider credential secret'));
|
|
222
|
+
vi.mocked(logger.warn).mockImplementation(() => {
|
|
223
|
+
if (mode === 'throw') throw new Error('logger credential secret');
|
|
224
|
+
return Promise.reject(new Error('logger credential secret'));
|
|
225
|
+
});
|
|
226
|
+
const error = await verifyOrderCheckoutAlgorithm(request, deps).catch((cause: unknown) => cause);
|
|
227
|
+
expect(error).toEqual(new Error('Checkout verification denied'));
|
|
228
|
+
expect(error).not.toHaveProperty('cause');
|
|
229
|
+
expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
|
|
230
|
+
'[Checkout verification] Failed', { stage: 'provider', category: 'unavailable' }
|
|
231
|
+
);
|
|
232
|
+
});
|
|
233
|
+
});
|