@donotdev/functions 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/lib/chunks/chunk-6NXIK35R.js +23 -0
- package/lib/chunks/chunk-6NXIK35R.js.map +7 -0
- package/lib/chunks/chunk-EZKRLLSQ.js +22 -0
- package/lib/chunks/chunk-EZKRLLSQ.js.map +7 -0
- package/lib/chunks/chunk-F3PHE627.js +22 -0
- package/lib/chunks/chunk-F3PHE627.js.map +7 -0
- package/lib/chunks/chunk-F3WBFWPO.js +151 -0
- package/lib/chunks/chunk-F3WBFWPO.js.map +7 -0
- package/lib/chunks/chunk-G5DRV3DH.js +22 -0
- package/lib/chunks/chunk-G5DRV3DH.js.map +7 -0
- package/lib/chunks/{chunk-5IPULSUX.js → chunk-GDIUOJMD.js} +2 -2
- package/lib/chunks/chunk-GDIUOJMD.js.map +7 -0
- package/lib/chunks/chunk-Q2WLRFOE.js +22 -0
- package/lib/chunks/chunk-Q2WLRFOE.js.map +7 -0
- package/lib/chunks/chunk-QXIOO2RL.js +22 -0
- package/lib/chunks/chunk-QXIOO2RL.js.map +7 -0
- package/lib/chunks/{chunk-3F4BWKQD.js → chunk-UH445BGK.js} +2 -2
- package/lib/chunks/chunk-W6W4L44F.js +22 -0
- package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
- package/lib/chunks/chunk-W74UL7AY.js +22 -0
- package/lib/chunks/chunk-W74UL7AY.js.map +7 -0
- package/lib/chunks/{monitoring-E7JBYBHQ.js → monitoring-LXNVBD3G.js} +2 -2
- package/lib/chunks/{rateLimiter-SQISLOP5.js → rateLimiter-GG5LPWXJ.js} +2 -2
- package/lib/chunks/server-NODQAE3F.js +22 -0
- package/lib/firebase/billing/index.d.ts +2 -2
- package/lib/firebase/crud/aggregate.d.ts +1 -1
- 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/checkoutValidation.d.ts +1 -1
- package/lib/shared/billing/createCheckout.d.ts +4 -4
- package/lib/shared/billing/firestoreIdempotency.d.ts +2 -2
- package/lib/shared/billing/helpers/subscriptionManagement.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/billing/orderWebhook.d.ts +29 -2
- package/lib/shared/billing/stripePinned.d.ts +43 -0
- package/lib/shared/denoEnv.d.ts +25 -0
- package/lib/shared/github.d.ts +0 -8
- 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/internal/auth.d.ts +1 -5
- package/lib/shared/utils.d.ts +12 -83
- package/lib/supabase/auth/deleteAccount.d.ts +34 -2
- package/lib/supabase/crud/create.d.ts +0 -8
- package/lib/supabase/crud/entityStore.d.ts +13 -0
- package/lib/supabase/crud/update.d.ts +0 -8
- package/lib/supabase/index.d.ts +1 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- 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 +2 -0
- package/src/firebase/auth/setCustomClaims.ts +3 -0
- package/src/firebase/baseFunction.ts +8 -4
- package/src/firebase/billing/changePlan.ts +6 -5
- package/src/firebase/billing/createCustomerPortal.ts +6 -4
- package/src/firebase/billing/index.d.ts +0 -12
- package/src/firebase/billing/index.ts +0 -3
- package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
- package/src/firebase/billing/webhookHandler.ts +4 -4
- package/src/firebase/crud/aggregate.ts +41 -12
- package/src/firebase/crud/bulk.ts +7 -0
- package/src/firebase/crud/create.ts +21 -8
- package/src/firebase/crud/delete.ts +6 -1
- package/src/firebase/crud/get.ts +9 -2
- package/src/firebase/crud/list.ts +18 -8
- package/src/firebase/crud/update.ts +15 -7
- package/src/firebase/helpers/githubAccessHelper.ts +3 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
- package/src/firebase/index.ts +0 -1
- package/src/firebase/oauth/disconnect.ts +2 -2
- package/src/firebase/oauth/exchangeToken.ts +6 -2
- package/src/firebase/oauth/getConnections.ts +3 -3
- package/src/firebase/oauth/githubAccess.ts +7 -4
- package/src/firebase/oauth/refreshToken.ts +3 -2
- package/src/firebase/registerCrudFunctions.ts +0 -19
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
- package/src/shared/__tests__/idempotency.test.ts +0 -32
- package/src/shared/__tests__/utils.test.ts +0 -25
- 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.compat.test.ts +4 -110
- 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__/webhookHandler.test.ts +108 -0
- package/src/shared/billing/checkoutPrice.ts +7 -42
- package/src/shared/billing/checkoutValidation.ts +19 -2
- package/src/shared/billing/createCheckout.ts +59 -30
- package/src/shared/billing/firestoreIdempotency.ts +2 -21
- package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
- package/src/shared/billing/idempotency.ts +4 -54
- package/src/shared/billing/idempotencyContract.ts +0 -21
- 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/webhookHandler.ts +5 -1
- package/src/shared/crud/bulkCore.ts +3 -2
- 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/logger.ts +37 -38
- package/src/shared/schema.ts +6 -10
- 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/auth.ts +1 -6
- 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 +12 -138
- package/src/supabase/__tests__/aggregate.test.ts +132 -0
- package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
- package/src/supabase/auth/deleteAccount.ts +72 -5
- package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
- package/src/supabase/crud/aggregate.ts +85 -72
- package/src/supabase/crud/bulk.ts +3 -0
- package/src/supabase/crud/create.ts +13 -9
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/entityStore.ts +1 -1
- package/src/supabase/crud/get.ts +2 -1
- package/src/supabase/crud/list.ts +23 -17
- package/src/supabase/crud/update.ts +9 -6
- package/src/supabase/edgeFunction.ts +2 -1
- package/src/supabase/email/createEmailFunction.ts +2 -1
- package/src/supabase/index.ts +1 -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/utils/idempotency.ts +1 -1
- package/src/supabase/utils/monitoring.ts +1 -0
- 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 +7 -2
- package/src/vercel/api/crud/create.ts +6 -3
- package/src/vercel/api/crud/delete.ts +5 -2
- package/src/vercel/api/crud/get.ts +5 -2
- package/src/vercel/api/crud/list.ts +6 -3
- package/src/vercel/api/crud/update.ts +6 -3
- 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-5IPULSUX.js.map +0 -7
- 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-CXBSROEW.js.map +0 -7
- package/lib/chunks/chunk-GYTCWMXV.js +0 -22
- package/lib/chunks/chunk-GYTCWMXV.js.map +0 -7
- package/lib/chunks/chunk-LCDLG4VG.js +0 -151
- package/lib/chunks/chunk-LCDLG4VG.js.map +0 -7
- package/lib/chunks/chunk-MQANUSY3.js +0 -22
- package/lib/chunks/chunk-MQANUSY3.js.map +0 -7
- package/lib/chunks/chunk-OFQVO3FD.js +0 -22
- package/lib/chunks/chunk-OFQVO3FD.js.map +0 -7
- package/lib/chunks/chunk-PWAGW4R6.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
- package/lib/chunks/chunk-US2VOP4S.js +0 -22
- package/lib/chunks/chunk-US2VOP4S.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/shared/utils/functionWrapper.d.ts +0 -36
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
- package/src/shared/utils/functionWrapper.ts +0 -73
- /package/lib/chunks/{chunk-3F4BWKQD.js.map → chunk-UH445BGK.js.map} +0 -0
- /package/lib/chunks/{monitoring-E7JBYBHQ.js.map → monitoring-LXNVBD3G.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-SQISLOP5.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
- /package/lib/chunks/{server-IQ5JNJOM.js.map → server-NODQAE3F.js.map} +0 -0
|
@@ -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
|
|
|
@@ -44,7 +44,7 @@ export const getConnections = onCall<{ purpose?: OAuthPurpose }>(
|
|
|
44
44
|
const snapshot = await query.get();
|
|
45
45
|
|
|
46
46
|
// Format connections
|
|
47
|
-
const connections = snapshot.docs.map((doc
|
|
47
|
+
const connections = snapshot.docs.map((doc) => {
|
|
48
48
|
const data = doc.data();
|
|
49
49
|
|
|
50
50
|
// Check if the token is expired
|
|
@@ -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;
|
|
@@ -151,6 +151,7 @@ async function grantGitHubAccessInternal(
|
|
|
151
151
|
*/
|
|
152
152
|
export const grantGitHubAccess: CallableFunction<
|
|
153
153
|
GrantGitHubAccessRequest,
|
|
154
|
+
// 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)
|
|
154
155
|
Promise<any>
|
|
155
156
|
> = onCall<GrantGitHubAccessRequest>(
|
|
156
157
|
OAUTH_CONFIG,
|
|
@@ -193,7 +194,7 @@ async function revokeGitHubAccessInternal(
|
|
|
193
194
|
>
|
|
194
195
|
) {
|
|
195
196
|
try {
|
|
196
|
-
const uid = assertAuthenticated(request.auth);
|
|
197
|
+
const uid = assertAuthenticated(request.auth?.uid);
|
|
197
198
|
|
|
198
199
|
// Use provided schema or default to framework schema
|
|
199
200
|
const schema = customSchema || revokeGitHubAccessSchema;
|
|
@@ -282,6 +283,7 @@ async function revokeGitHubAccessInternal(
|
|
|
282
283
|
*/
|
|
283
284
|
export const revokeGitHubAccess: CallableFunction<
|
|
284
285
|
RevokeGitHubAccessRequest,
|
|
286
|
+
// 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)
|
|
285
287
|
Promise<any>
|
|
286
288
|
> = onCall<RevokeGitHubAccessRequest>(
|
|
287
289
|
OAUTH_CONFIG,
|
|
@@ -324,7 +326,7 @@ async function checkGitHubAccessInternal(
|
|
|
324
326
|
>
|
|
325
327
|
) {
|
|
326
328
|
try {
|
|
327
|
-
const uid = assertAuthenticated(request.auth);
|
|
329
|
+
const uid = assertAuthenticated(request.auth?.uid);
|
|
328
330
|
|
|
329
331
|
// Use provided schema or default to framework schema
|
|
330
332
|
const schema = customSchema || checkGitHubAccessSchema;
|
|
@@ -393,6 +395,7 @@ async function checkGitHubAccessInternal(
|
|
|
393
395
|
*/
|
|
394
396
|
export const checkGitHubAccess: CallableFunction<
|
|
395
397
|
CheckGitHubAccessRequest,
|
|
398
|
+
// 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)
|
|
396
399
|
Promise<any>
|
|
397
400
|
> = onCall<CheckGitHubAccessRequest>(
|
|
398
401
|
OAUTH_CONFIG,
|
|
@@ -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,
|
|
@@ -85,6 +85,7 @@ export const refreshToken = onCall<OAuthRefreshRequest>(async (request) => {
|
|
|
85
85
|
);
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: untrusted OAuth token response; needs a valibot schema (strict vs loose expires_in is an open owner decision)
|
|
88
89
|
const tokenData = (await response.json()) as any;
|
|
89
90
|
|
|
90
91
|
// Update the connection in Firestore
|
|
@@ -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
|
*/
|
|
@@ -108,7 +108,10 @@ export const checkExpiredSubscriptions = onSchedule(
|
|
|
108
108
|
/**
|
|
109
109
|
* Revoke expired subscription access and clean up claims
|
|
110
110
|
*/
|
|
111
|
-
async function revokeExpiredSubscription(
|
|
111
|
+
async function revokeExpiredSubscription(
|
|
112
|
+
userId: string,
|
|
113
|
+
subscription: Record<string, unknown>
|
|
114
|
+
) {
|
|
112
115
|
try {
|
|
113
116
|
const auth = getFirebaseAdminAuth();
|
|
114
117
|
const user = await auth.getUser(userId);
|
|
@@ -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
|
// ---------------------------------------------------------------------------
|
|
@@ -139,12 +139,18 @@ export function mapClassifiedToHTTP(code: AIErrorCode): number {
|
|
|
139
139
|
function extractStatus(err: unknown): number | undefined {
|
|
140
140
|
if (err && typeof err === 'object') {
|
|
141
141
|
// Anthropic SDK errors have .status
|
|
142
|
-
if ('status' in err && typeof
|
|
143
|
-
return
|
|
142
|
+
if ('status' in err && typeof err.status === 'number') {
|
|
143
|
+
return err.status;
|
|
144
144
|
}
|
|
145
145
|
// Some errors nest status in .error
|
|
146
|
-
if (
|
|
147
|
-
|
|
146
|
+
if (
|
|
147
|
+
'error' in err &&
|
|
148
|
+
typeof err.error === 'object' &&
|
|
149
|
+
err.error !== null &&
|
|
150
|
+
'status' in err.error &&
|
|
151
|
+
typeof err.error.status === 'number'
|
|
152
|
+
) {
|
|
153
|
+
return err.error.status;
|
|
148
154
|
}
|
|
149
155
|
}
|
|
150
156
|
return undefined;
|
|
@@ -154,7 +160,7 @@ function extractMessage(err: unknown): string {
|
|
|
154
160
|
if (err instanceof Error) return err.message.toLowerCase();
|
|
155
161
|
if (typeof err === 'string') return err.toLowerCase();
|
|
156
162
|
if (err && typeof err === 'object' && 'message' in err) {
|
|
157
|
-
return String(
|
|
163
|
+
return String(err.message).toLowerCase();
|
|
158
164
|
}
|
|
159
165
|
return '';
|
|
160
166
|
}
|
|
@@ -162,12 +168,14 @@ function extractMessage(err: unknown): string {
|
|
|
162
168
|
function extractRetryAfter(err: unknown): number | undefined {
|
|
163
169
|
if (err && typeof err === 'object') {
|
|
164
170
|
// Anthropic SDK puts headers on the error
|
|
165
|
-
const headers =
|
|
166
|
-
if (headers) {
|
|
167
|
-
const retryAfter =
|
|
168
|
-
typeof headers.get === 'function'
|
|
171
|
+
const headers: unknown = 'headers' in err ? err.headers : undefined;
|
|
172
|
+
if (headers && typeof headers === 'object') {
|
|
173
|
+
const retryAfter: unknown =
|
|
174
|
+
'get' in headers && typeof headers.get === 'function'
|
|
169
175
|
? headers.get('retry-after')
|
|
170
|
-
:
|
|
176
|
+
: 'retry-after' in headers
|
|
177
|
+
? headers['retry-after']
|
|
178
|
+
: undefined;
|
|
171
179
|
if (retryAfter) {
|
|
172
180
|
const seconds = Number(retryAfter);
|
|
173
181
|
if (!Number.isNaN(seconds)) return seconds * 1000;
|
|
@@ -28,6 +28,7 @@ import type {
|
|
|
28
28
|
import { AI_MODELS, validateAIChatRequest } from '@donotdev/core/server';
|
|
29
29
|
|
|
30
30
|
import { calculateCost } from './costTracker.js';
|
|
31
|
+
import { getDenoEnv } from '../denoEnv.js';
|
|
31
32
|
|
|
32
33
|
// =============================================================================
|
|
33
34
|
// Types
|
|
@@ -395,7 +396,7 @@ function jsonError(message: string, status: number): Response {
|
|
|
395
396
|
|
|
396
397
|
function getEnv(name: string): string | undefined {
|
|
397
398
|
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
398
|
-
return (
|
|
399
|
+
return getDenoEnv()?.get(name);
|
|
399
400
|
}
|
|
400
401
|
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
401
402
|
}
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
import { AI_TIERS } from '@donotdev/core/server';
|
|
15
15
|
import type { AITierId } from '@donotdev/core/server';
|
|
16
|
+
import { getDenoEnv } from '../denoEnv.js';
|
|
16
17
|
|
|
17
18
|
// =============================================================================
|
|
18
19
|
// Env helper (Deno + Node cross-runtime)
|
|
@@ -20,7 +21,7 @@ import type { AITierId } from '@donotdev/core/server';
|
|
|
20
21
|
|
|
21
22
|
function getEnv(name: string): string | undefined {
|
|
22
23
|
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
23
|
-
return (
|
|
24
|
+
return getDenoEnv()?.get(name);
|
|
24
25
|
}
|
|
25
26
|
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
26
27
|
}
|
|
@@ -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(
|
|
@@ -415,6 +415,100 @@ describe('createCheckoutAlgorithm — StripeOrder session options', () => {
|
|
|
415
415
|
run(ORDER_REQUEST, makeConfig(withSession({ invoiceFooter: 'x' }, { invoiceCreation: false })))
|
|
416
416
|
).rejects.toThrow(/invoiceCreation/);
|
|
417
417
|
});
|
|
418
|
+
|
|
419
|
+
it('existing customer under automatic tax: customer + customer_update, no customer_email / customer_creation', async () => {
|
|
420
|
+
const { params } = await run(
|
|
421
|
+
{ ...ORDER_REQUEST, customerEmail: 'pro@example.com' },
|
|
422
|
+
makeConfig(
|
|
423
|
+
withSession(
|
|
424
|
+
{ customerId: 'cus_Pro123' },
|
|
425
|
+
{
|
|
426
|
+
tax: { mode: 'automatic' },
|
|
427
|
+
taxIdCollection: 'disabled',
|
|
428
|
+
shipping: { allowedCountries: ['FR', 'DE'] },
|
|
429
|
+
}
|
|
430
|
+
)
|
|
431
|
+
)
|
|
432
|
+
);
|
|
433
|
+
expect(params!.customer).toBe('cus_Pro123');
|
|
434
|
+
expect(params!.customer_update).toEqual({ address: 'auto', shipping: 'auto' });
|
|
435
|
+
expect(params).not.toHaveProperty('customer_email');
|
|
436
|
+
expect(params).not.toHaveProperty('customer_creation');
|
|
437
|
+
expect(params!.tax_id_collection).toEqual({ enabled: false });
|
|
438
|
+
expect(params!.automatic_tax).toEqual({ enabled: true });
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
it('existing customer with tax ID collection: customer_update.name auto (Stripe requirement)', async () => {
|
|
442
|
+
const { params } = await run(
|
|
443
|
+
ORDER_REQUEST,
|
|
444
|
+
makeConfig(withSession({ customerId: 'cus_Pro123' }, { taxIdCollection: 'optional' }))
|
|
445
|
+
);
|
|
446
|
+
// manual tax, no shipping: only the name is written back
|
|
447
|
+
expect(params!.customer_update).toEqual({ name: 'auto' });
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
it('existing customer with manual tax, no shipping, no tax ID collection: no customer_update', async () => {
|
|
451
|
+
const { params } = await run(
|
|
452
|
+
ORDER_REQUEST,
|
|
453
|
+
makeConfig(withSession({ customerId: 'cus_Pro123' }, { taxIdCollection: 'disabled' }))
|
|
454
|
+
);
|
|
455
|
+
expect(params!.customer).toBe('cus_Pro123');
|
|
456
|
+
expect(params).not.toHaveProperty('customer_update');
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
it('without customerId keeps customer_email + customer_creation', async () => {
|
|
460
|
+
const { params } = await run(
|
|
461
|
+
{ ...ORDER_REQUEST, customerEmail: 'pro@example.com' },
|
|
462
|
+
makeConfig(withSession({}))
|
|
463
|
+
);
|
|
464
|
+
expect(params!.customer_email).toBe('pro@example.com');
|
|
465
|
+
expect(params!.customer_creation).toBe('always');
|
|
466
|
+
expect(params).not.toHaveProperty('customer');
|
|
467
|
+
expect(params).not.toHaveProperty('customer_update');
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
it('rejects a customerId that is not a Stripe Customer ID', async () => {
|
|
471
|
+
await expect(
|
|
472
|
+
run(ORDER_REQUEST, makeConfig(withSession({ customerId: 'user_42' })))
|
|
473
|
+
).rejects.toThrow(/customerId/);
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
it('line taxCode becomes product_data.tax_code under automatic tax', async () => {
|
|
477
|
+
const shippingLine = { productId: 'shipping', name: 'Colissimo', unitAmount: 1009, quantity: 1, taxCode: 'txcd_92010001' };
|
|
478
|
+
const order = makeOrderItem({
|
|
479
|
+
tax: { mode: 'automatic' },
|
|
480
|
+
resolveLineItems: vi.fn(async () => ({ orderId: 'ord_1', lineItems: [line, shippingLine] })),
|
|
481
|
+
});
|
|
482
|
+
const { params } = await run(ORDER_REQUEST, makeConfig(order));
|
|
483
|
+
expect(params!.line_items![0]!.price_data!.product_data).not.toHaveProperty('tax_code');
|
|
484
|
+
expect(params!.line_items![1]!.price_data!.product_data!.tax_code).toBe('txcd_92010001');
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
it('rejects a malformed taxCode and a taxCode under manual tax', async () => {
|
|
488
|
+
const bad = { ...line, taxCode: 'shipping' };
|
|
489
|
+
await expect(
|
|
490
|
+
run(
|
|
491
|
+
ORDER_REQUEST,
|
|
492
|
+
makeConfig(
|
|
493
|
+
makeOrderItem({
|
|
494
|
+
tax: { mode: 'automatic' },
|
|
495
|
+
resolveLineItems: vi.fn(async () => ({ orderId: 'ord_1', lineItems: [bad] })),
|
|
496
|
+
})
|
|
497
|
+
)
|
|
498
|
+
)
|
|
499
|
+
).rejects.toThrow(/taxCode/);
|
|
500
|
+
const manual = { ...line, taxCode: 'txcd_92010001' };
|
|
501
|
+
await expect(
|
|
502
|
+
run(
|
|
503
|
+
ORDER_REQUEST,
|
|
504
|
+
makeConfig(
|
|
505
|
+
makeOrderItem({
|
|
506
|
+
resolveLineItems: vi.fn(async () => ({ orderId: 'ord_1', lineItems: [manual] })),
|
|
507
|
+
})
|
|
508
|
+
)
|
|
509
|
+
)
|
|
510
|
+
).rejects.toThrow(/tax.mode 'automatic'/);
|
|
511
|
+
});
|
|
418
512
|
});
|
|
419
513
|
|
|
420
514
|
// ---------------------------------------------------------------------------
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @fileoverview Firestore idempotency store against the Firestore emulator
|
|
5
5
|
* @description Runs only when FIRESTORE_EMULATOR_HOST is set, e.g.
|
|
6
6
|
* `bunx firebase-tools emulators:exec --only firestore --project demo-dndev
|
|
7
|
-
* "
|
|
7
|
+
* "bunx vitest run src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts"`.
|
|
8
8
|
*
|
|
9
9
|
* @version 0.2.0
|
|
10
10
|
* @since 0.2.0
|