@donotdev/functions 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/guidelines/VERCEL.md +24 -15
  2. package/lib/chunks/{chunk-2N73OZFE.js → chunk-4BJP372Z.js} +2 -2
  3. package/lib/chunks/chunk-7T2RZ5A4.js +22 -0
  4. package/lib/chunks/chunk-7T2RZ5A4.js.map +7 -0
  5. package/lib/chunks/chunk-CCEGC2T6.js +22 -0
  6. package/lib/chunks/chunk-CCEGC2T6.js.map +7 -0
  7. package/lib/chunks/{chunk-DGBZDD6D.js → chunk-IO4MUTT6.js} +2 -2
  8. package/lib/chunks/chunk-LJXSA7EP.js +151 -0
  9. package/lib/chunks/chunk-LJXSA7EP.js.map +7 -0
  10. package/lib/chunks/chunk-MJ5VZTLM.js +22 -0
  11. package/lib/chunks/chunk-MJ5VZTLM.js.map +7 -0
  12. package/lib/chunks/chunk-NP4Y2LAO.js +22 -0
  13. package/lib/chunks/chunk-NP4Y2LAO.js.map +7 -0
  14. package/lib/chunks/{chunk-XWMG2FWZ.js → chunk-WJUL2W7Y.js} +2 -2
  15. package/lib/chunks/{chunk-XWMG2FWZ.js.map → chunk-WJUL2W7Y.js.map} +1 -1
  16. package/lib/chunks/{chunk-ZCY6GTIC.js → chunk-Y6BR2QOV.js} +2 -2
  17. package/lib/chunks/{chunk-ZCY6GTIC.js.map → chunk-Y6BR2QOV.js.map} +1 -1
  18. package/lib/chunks/{monitoring-KF7FRUQ6.js → monitoring-B2DYDCYC.js} +2 -2
  19. package/lib/chunks/{rateLimiter-S7TITXOD.js → rateLimiter-JCBEG33M.js} +2 -2
  20. package/lib/chunks/{server-SU4BVPPF.js → server-YXYTPMRF.js} +2 -2
  21. package/lib/firebase/auth/index.d.ts +1 -0
  22. package/lib/firebase/auth/listAuthUsers.d.ts +24 -0
  23. package/lib/firebase/billing/cancelSubscription.d.ts +2 -1
  24. package/lib/firebase/billing/changePlan.d.ts +2 -1
  25. package/lib/firebase/billing/createCheckoutSession.d.ts +2 -1
  26. package/lib/firebase/billing/createCustomerPortal.d.ts +4 -0
  27. package/lib/firebase/billing/healthCheck.d.ts +2 -0
  28. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -1
  29. package/lib/firebase/billing/webhookHandler.d.ts +2 -0
  30. package/lib/firebase/index.js +1 -1
  31. package/lib/firebase/index.js.map +4 -4
  32. package/lib/firebase/oauth/exchangeToken.d.ts +21 -4
  33. package/lib/firebase/oauth/providerSecrets.d.ts +22 -0
  34. package/lib/firebase/oauth/refreshToken.d.ts +34 -4
  35. package/lib/shared/index.js +1 -1
  36. package/lib/shared/utils.d.ts +5 -27
  37. package/lib/supabase/auth/listAuthUsers.d.ts +19 -0
  38. package/lib/supabase/index.d.ts +1 -0
  39. package/lib/supabase/index.js +1 -1
  40. package/lib/supabase/index.js.map +4 -4
  41. package/lib/vercel/api/auth/index.d.ts +3 -3
  42. package/lib/vercel/api/crud/index.d.ts +6 -6
  43. package/lib/vercel/api/index.js +1 -1
  44. package/lib/vercel/api/index.js.map +4 -4
  45. package/lib/vercel/api/oauth/index.d.ts +4 -4
  46. package/package.json +5 -5
  47. package/src/firebase/auth/__tests__/listAuthUsers.test.ts +130 -0
  48. package/src/firebase/auth/index.ts +1 -0
  49. package/src/firebase/auth/listAuthUsers.ts +110 -0
  50. package/src/firebase/billing/__tests__/secretDeclarations.test.ts +55 -0
  51. package/src/firebase/billing/cancelSubscription.ts +9 -2
  52. package/src/firebase/billing/changePlan.ts +6 -2
  53. package/src/firebase/billing/createCheckoutSession.ts +6 -2
  54. package/src/firebase/billing/createCustomerPortal.ts +8 -1
  55. package/src/firebase/billing/healthCheck.ts +13 -1
  56. package/src/firebase/billing/refreshSubscriptionStatus.ts +14 -2
  57. package/src/firebase/billing/webhookHandler.ts +9 -1
  58. package/src/firebase/crud/delete.ts +57 -1
  59. package/src/firebase/oauth/__tests__/tokenFactories.test.ts +99 -0
  60. package/src/firebase/oauth/exchangeToken.ts +53 -8
  61. package/src/firebase/oauth/providerSecrets.ts +65 -0
  62. package/src/firebase/oauth/refreshToken.ts +57 -12
  63. package/src/shared/email/provider.ts +0 -0
  64. package/src/shared/email/resendProvider.ts +0 -0
  65. package/src/shared/utils.ts +5 -75
  66. package/src/supabase/__tests__/firebaseBoundary.test.ts +53 -0
  67. package/src/supabase/auth/__tests__/listAuthUsers.test.ts +156 -0
  68. package/src/supabase/auth/listAuthUsers.ts +98 -0
  69. package/src/supabase/baseFunction.ts +0 -0
  70. package/src/supabase/index.ts +1 -0
  71. package/src/vercel/__tests__/firebaseOptional.test.ts +24 -0
  72. package/src/vercel/api/auth/index.ts +4 -3
  73. package/src/vercel/api/crud/index.ts +7 -6
  74. package/src/vercel/api/oauth/index.ts +5 -4
  75. package/lib/chunks/chunk-472JD6X7.js +0 -22
  76. package/lib/chunks/chunk-472JD6X7.js.map +0 -7
  77. package/lib/chunks/chunk-BTWJEJCV.js +0 -22
  78. package/lib/chunks/chunk-BTWJEJCV.js.map +0 -7
  79. package/lib/chunks/chunk-CN6WXKYF.js +0 -22
  80. package/lib/chunks/chunk-CN6WXKYF.js.map +0 -7
  81. package/lib/chunks/chunk-GBZQPOX4.js +0 -151
  82. package/lib/chunks/chunk-GBZQPOX4.js.map +0 -7
  83. package/lib/chunks/chunk-ORBGTVJI.js +0 -22
  84. package/lib/chunks/chunk-ORBGTVJI.js.map +0 -7
  85. package/lib/chunks/chunk-R3I7U5QT.js +0 -22
  86. package/lib/chunks/chunk-R3I7U5QT.js.map +0 -7
  87. /package/lib/chunks/{chunk-2N73OZFE.js.map → chunk-4BJP372Z.js.map} +0 -0
  88. /package/lib/chunks/{chunk-DGBZDD6D.js.map → chunk-IO4MUTT6.js.map} +0 -0
  89. /package/lib/chunks/{monitoring-KF7FRUQ6.js.map → monitoring-B2DYDCYC.js.map} +0 -0
  90. /package/lib/chunks/{rateLimiter-S7TITXOD.js.map → rateLimiter-JCBEG33M.js.map} +0 -0
  91. /package/lib/chunks/{server-SU4BVPPF.js.map → server-YXYTPMRF.js.map} +0 -0
@@ -0,0 +1,130 @@
1
+ /**
2
+ * @fileoverview Unit tests for `listAuthUsers` (Firebase).
3
+ * @description Runs the real `createBaseFunction`: a non-admin is refused and
4
+ * nothing is listed; an admin gets every page of Admin SDK
5
+ * `listUsers`, mapped to `AuthUserSummary`.
6
+ */
7
+
8
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
9
+
10
+ vi.mock('firebase-functions/v2', () => ({
11
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), log: vi.fn() },
12
+ }));
13
+
14
+ vi.mock('firebase-functions/v2/https', () => {
15
+ class HttpsError extends Error {
16
+ constructor(
17
+ public code: string,
18
+ message: string,
19
+ public details?: unknown
20
+ ) {
21
+ super(message);
22
+ }
23
+ }
24
+ // onCall returns the raw handler so the test calls it with a request
25
+ return {
26
+ onCall: (_config: unknown, handler: unknown) => handler,
27
+ HttpsError,
28
+ };
29
+ });
30
+
31
+ const listUsers = vi.fn();
32
+ vi.mock('@donotdev/firebase/server', () => ({
33
+ getFirebaseAdminAuth: () => ({ listUsers }),
34
+ }));
35
+
36
+ import { listAuthUsers } from '../listAuthUsers.js';
37
+
38
+ type Callable = (request: unknown) => Promise<unknown>;
39
+
40
+ function call(role?: string) {
41
+ const handler = listAuthUsers() as unknown as Callable;
42
+ return handler({
43
+ auth: { uid: 'caller', token: role ? { role } : {} },
44
+ data: {},
45
+ app: {},
46
+ rawRequest: { headers: {} },
47
+ });
48
+ }
49
+
50
+ /** A Firebase UserRecord; `n` makes uids unique. */
51
+ function record(n: number, extra: Record<string, unknown> = {}) {
52
+ return {
53
+ uid: `u${n}`,
54
+ email: `u${n}@example.com`,
55
+ emailVerified: false,
56
+ metadata: {
57
+ creationTime: 'Thu, 01 Jan 2026 00:00:00 GMT',
58
+ lastSignInTime: null,
59
+ },
60
+ ...extra,
61
+ };
62
+ }
63
+
64
+ describe('listAuthUsers (Firebase)', () => {
65
+ beforeEach(() => {
66
+ listUsers.mockReset();
67
+ process.env.DISABLE_RATE_LIMITING = 'true';
68
+ });
69
+ afterEach(() => {
70
+ delete process.env.DISABLE_RATE_LIMITING;
71
+ });
72
+
73
+ it.each([undefined, 'user'])(
74
+ 'refuses a non-admin caller (role %s)',
75
+ async (role) => {
76
+ // createBaseFunction's role refusal (plain "Access denied" Error) reaches the
77
+ // client through handleError, which classifies it as `internal` today.
78
+ await expect(call(role)).rejects.toThrow();
79
+ expect(listUsers).not.toHaveBeenCalled();
80
+ }
81
+ );
82
+
83
+ it('pages with the page token (1000 per page) until there is none', async () => {
84
+ listUsers
85
+ .mockResolvedValueOnce({ users: [record(1)], pageToken: 'next' })
86
+ .mockResolvedValueOnce({ users: [record(2)] });
87
+ const result = (await call('admin')) as { users: { id: string }[] };
88
+ expect(result.users.map((u) => u.id)).toEqual(['u1', 'u2']);
89
+ expect(listUsers.mock.calls).toEqual([
90
+ [1000, undefined],
91
+ [1000, 'next'],
92
+ ]);
93
+ });
94
+
95
+ it('maps the record (ISO dates; verified address carries the creation time)', async () => {
96
+ listUsers.mockResolvedValueOnce({
97
+ users: [
98
+ record(1, {
99
+ emailVerified: true,
100
+ displayName: 'Ana',
101
+ metadata: {
102
+ creationTime: 'Thu, 01 Jan 2026 00:00:00 GMT',
103
+ lastSignInTime: 'Sat, 03 Jan 2026 00:00:00 GMT',
104
+ },
105
+ }),
106
+ record(2, { email: undefined }),
107
+ ],
108
+ });
109
+ expect(await call('super')).toEqual({
110
+ users: [
111
+ {
112
+ id: 'u1',
113
+ email: 'u1@example.com',
114
+ emailConfirmedAt: '2026-01-01T00:00:00.000Z',
115
+ createdAt: '2026-01-01T00:00:00.000Z',
116
+ lastSignInAt: '2026-01-03T00:00:00.000Z',
117
+ displayName: 'Ana',
118
+ },
119
+ {
120
+ id: 'u2',
121
+ email: null,
122
+ emailConfirmedAt: null,
123
+ createdAt: '2026-01-01T00:00:00.000Z',
124
+ lastSignInAt: null,
125
+ displayName: null,
126
+ },
127
+ ],
128
+ });
129
+ });
130
+ });
@@ -11,5 +11,6 @@
11
11
 
12
12
  export * from './getCustomClaims.js';
13
13
  export * from './getUserAuthStatus.js';
14
+ export * from './listAuthUsers.js';
14
15
  export * from './removeCustomClaims.js';
15
16
  export * from './setCustomClaims.js';
@@ -0,0 +1,110 @@
1
+ // packages/functions/src/firebase/auth/listAuthUsers.ts
2
+
3
+ /**
4
+ * @fileoverview List auth users Firebase function
5
+ * @description Admin-only Firebase callable listing every auth account (email,
6
+ * verification, sign-in dates) straight from Firebase Auth (Admin SDK `listUsers`).
7
+ *
8
+ * @version 0.1.0
9
+ * @since 0.3.3
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import type { UserRecord } from 'firebase-admin/auth';
14
+ import type {
15
+ CallableFunction,
16
+ CallableRequest,
17
+ } from 'firebase-functions/v2/https';
18
+ import * as v from 'valibot';
19
+
20
+ import type {
21
+ AuthUserSummary,
22
+ ListAuthUsersResponse,
23
+ } from '@donotdev/core/server';
24
+ import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
25
+
26
+ import { createBaseFunction } from '../baseFunction.js';
27
+ import { AUTH_CONFIG } from '../config/constants.js';
28
+
29
+ const listAuthUsersSchema = v.object({});
30
+
31
+ export type ListAuthUsersRequest = v.InferOutput<typeof listAuthUsersSchema>;
32
+
33
+ /** Page size of Admin SDK `listUsers` (its maximum). */
34
+ const PER_PAGE = 1000;
35
+
36
+ /** Firebase metadata time (UTC string) as ISO 8601; null when absent. */
37
+ function toIso(time: string | null | undefined): string | null {
38
+ return time ? new Date(time).toISOString() : null;
39
+ }
40
+
41
+ /**
42
+ * Map a Firebase user record to an {@link AuthUserSummary}.
43
+ * Firebase records no confirmation time: a verified address carries the account
44
+ * creation time as `emailConfirmedAt`; an unverified one, null.
45
+ */
46
+ function toAuthUserSummary(user: UserRecord): AuthUserSummary {
47
+ const createdAt = toIso(user.metadata.creationTime)!;
48
+ return {
49
+ id: user.uid,
50
+ email: user.email ?? null,
51
+ emailConfirmedAt: user.emailVerified ? createdAt : null,
52
+ createdAt,
53
+ lastSignInAt: toIso(user.metadata.lastSignInTime),
54
+ displayName: user.displayName ?? null,
55
+ };
56
+ }
57
+
58
+ /**
59
+ * Business logic: pages through Admin SDK `listUsers` (1000 per page) until the last page.
60
+ * Base function handles: validation, auth, admin role check, rate limiting, monitoring
61
+ *
62
+ * @version 0.1.0
63
+ * @since 0.3.3
64
+ * @author AMBROISE PARK Consulting
65
+ */
66
+ async function listAuthUsersLogic(
67
+ _data: ListAuthUsersRequest,
68
+ _context: { uid: string; request: CallableRequest<ListAuthUsersRequest> }
69
+ ): Promise<ListAuthUsersResponse> {
70
+ const auth = getFirebaseAdminAuth();
71
+ const users: AuthUserSummary[] = [];
72
+ let pageToken: string | undefined;
73
+ do {
74
+ const page = await auth.listUsers(PER_PAGE, pageToken);
75
+ users.push(...page.users.map(toAuthUserSummary));
76
+ pageToken = page.pageToken;
77
+ } while (pageToken);
78
+ return { users };
79
+ }
80
+
81
+ /**
82
+ * Lists every auth user. Admin only: callers without the `admin` (or `super`) role
83
+ * claim are refused (the base function rejects them before the listing runs).
84
+ * Client side: `useAuthUsers()` / `useAuth('listUsers')` from `@donotdev/auth`
85
+ * (the Firebase auth provider calls the callable named `listAuthUsers`).
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * // functions/src/index.ts
90
+ * import { listAuthUsers as frameworkListAuthUsers } from '@donotdev/functions/firebase';
91
+ * export const listAuthUsers = frameworkListAuthUsers();
92
+ * ```
93
+ *
94
+ * @version 0.1.0
95
+ * @since 0.3.3
96
+ * @author AMBROISE PARK Consulting
97
+ */
98
+ export const listAuthUsers = (
99
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: same signature as the sibling auth factories (accepts schemas of any output type)
100
+ customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
101
+ ): CallableFunction<ListAuthUsersRequest, Promise<ListAuthUsersResponse>> => {
102
+ const schema = customSchema || listAuthUsersSchema;
103
+ return createBaseFunction(
104
+ AUTH_CONFIG,
105
+ schema,
106
+ 'list_auth_users',
107
+ listAuthUsersLogic,
108
+ 'admin'
109
+ );
110
+ };
@@ -0,0 +1,55 @@
1
+ // packages/functions/src/firebase/billing/__tests__/secretDeclarations.test.ts
2
+
3
+ /**
4
+ * @fileoverview Billing functions declare the Stripe secrets they read
5
+ * @description The deploy binds a secret to a function only when the function
6
+ * declares it (`secrets` option → `__endpoint.secretEnvironmentVariables`).
7
+ */
8
+
9
+ import { describe, expect, it, vi } from 'vitest';
10
+
11
+ vi.mock('@donotdev/firebase/server', () => ({
12
+ getFirebaseAdminAuth: vi.fn(),
13
+ getFirebaseAdminFirestore: vi.fn(),
14
+ FieldValue: {},
15
+ }));
16
+
17
+ import { billingHealth } from '../healthCheck';
18
+ import { cancelSubscription } from '../cancelSubscription';
19
+ import { changePlan } from '../changePlan';
20
+ import { createCheckoutSession } from '../createCheckoutSession';
21
+ import { createCustomerPortal } from '../createCustomerPortal';
22
+ import { refreshSubscriptionStatus } from '../refreshSubscriptionStatus';
23
+ import { createStripeWebhook } from '../webhookHandler';
24
+
25
+ /** Secret names a built function declares. */
26
+ function declared(fn: {
27
+ __endpoint: { secretEnvironmentVariables?: Array<{ key: string }> };
28
+ }): string[] {
29
+ return (fn.__endpoint.secretEnvironmentVariables ?? []).map((s) => s.key);
30
+ }
31
+
32
+ describe('billing functions declare their Stripe secrets', () => {
33
+ it.each([
34
+ ['createCheckoutSession', () => createCheckoutSession({})],
35
+ ['createCustomerPortal', () => createCustomerPortal()],
36
+ ['cancelSubscription', () => cancelSubscription()],
37
+ ['changePlan', () => changePlan({})],
38
+ ['refreshSubscriptionStatus', () => refreshSubscriptionStatus()],
39
+ ])('%s declares STRIPE_SECRET_KEY', (_name, create) => {
40
+ expect(declared(create())).toEqual(['STRIPE_SECRET_KEY']);
41
+ });
42
+
43
+ it.each([
44
+ ['createStripeWebhook', () => createStripeWebhook({})],
45
+ ['billingHealth', () => billingHealth],
46
+ ])(
47
+ '%s declares STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET',
48
+ (_name, create) => {
49
+ expect(declared(create())).toEqual([
50
+ 'STRIPE_SECRET_KEY',
51
+ 'STRIPE_WEBHOOK_SECRET',
52
+ ]);
53
+ }
54
+ );
55
+ });
@@ -20,6 +20,12 @@ import { createBaseFunction } from '../baseFunction.js';
20
20
  import { STRIPE_CONFIG } from '../config/constants.js';
21
21
  import { stripeSecretKey } from '../config/secrets.js';
22
22
 
23
+ /** Stripe options plus the secrets this function reads (bound at deploy). */
24
+ const CANCEL_SUBSCRIPTION_CONFIG = {
25
+ ...STRIPE_CONFIG,
26
+ secrets: [stripeSecretKey],
27
+ };
28
+
23
29
  const cancelSubscriptionSchema = v.object({
24
30
  userId: v.string(),
25
31
  });
@@ -57,7 +63,8 @@ async function cancelSubscriptionLogic(
57
63
  }
58
64
 
59
65
  /**
60
- * Cancel subscription function
66
+ * Cancel subscription function.
67
+ * Declares the `STRIPE_SECRET_KEY` secret, so the deploy binds it to this function.
61
68
  *
62
69
  * @version 0.1.0
63
70
  * @since 0.0.1
@@ -65,7 +72,7 @@ async function cancelSubscriptionLogic(
65
72
  */
66
73
  export function cancelSubscription() {
67
74
  return createBaseFunction(
68
- STRIPE_CONFIG,
75
+ CANCEL_SUBSCRIPTION_CONFIG,
69
76
  cancelSubscriptionSchema,
70
77
  'cancel_subscription',
71
78
  cancelSubscriptionLogic
@@ -24,6 +24,9 @@ import { STRIPE_CONFIG } from '../config/constants.js';
24
24
  import { stripeSecretKey } from '../config/secrets.js';
25
25
  import { isOneOf, pinnedSubscriptionPeriod } from '../../shared/billing/stripePinned.js';
26
26
 
27
+ /** Stripe options plus the secrets this function reads (bound at deploy). */
28
+ const CHANGE_PLAN_CONFIG = { ...STRIPE_CONFIG, secrets: [stripeSecretKey] };
29
+
27
30
  const changePlanSchema = v.object({
28
31
  userId: v.string(),
29
32
  newPriceId: v.string(),
@@ -134,7 +137,8 @@ async function changePlanLogic(
134
137
  }
135
138
 
136
139
  /**
137
- * Change subscription plan function
140
+ * Change subscription plan function.
141
+ * Declares the `STRIPE_SECRET_KEY` secret, so the deploy binds it to this function.
138
142
  *
139
143
  * @version 0.1.0
140
144
  * @since 0.0.1
@@ -144,7 +148,7 @@ export function changePlan(billingConfig: StripeBackConfig) {
144
148
  return createBaseFunction<
145
149
  v.InferOutput<typeof changePlanSchema>,
146
150
  { success: boolean; newTier: string; newPrice: number }
147
- >(STRIPE_CONFIG, changePlanSchema, 'change_plan', (data, context) =>
151
+ >(CHANGE_PLAN_CONFIG, changePlanSchema, 'change_plan', (data, context) =>
148
152
  changePlanLogic(data, context, billingConfig)
149
153
  );
150
154
  }
@@ -31,6 +31,9 @@ import { createBaseFunction } from '../baseFunction.js';
31
31
  import { STRIPE_CONFIG } from '../config/constants.js';
32
32
  import { stripeSecretKey } from '../config/secrets.js';
33
33
 
34
+ /** Stripe options plus the secrets this function reads (bound at deploy). */
35
+ const CHECKOUT_CONFIG = { ...STRIPE_CONFIG, secrets: [stripeSecretKey] };
36
+
34
37
  /**
35
38
  * Business logic for creating Stripe checkout session.
36
39
  * Uses shared algorithm - same as Supabase and Vercel handlers.
@@ -91,7 +94,8 @@ async function createCheckoutSessionLogic(
91
94
  }
92
95
 
93
96
  /**
94
- * Create Firebase function for checkout session creation
97
+ * Create Firebase function for checkout session creation.
98
+ * Declares the `STRIPE_SECRET_KEY` secret, so the deploy binds it to this function.
95
99
  */
96
100
  export function createCheckoutSession(
97
101
  billingConfig: StripeBackConfig
@@ -103,7 +107,7 @@ export function createCheckoutSession(
103
107
  CreateCheckoutSessionRequest,
104
108
  { sessionId: string; sessionUrl: string | null }
105
109
  >(
106
- STRIPE_CONFIG,
110
+ CHECKOUT_CONFIG,
107
111
  CreateCheckoutSessionRequestSchema,
108
112
  'create_checkout_session',
109
113
  (data, context) => createCheckoutSessionLogic(data, context, billingConfig)
@@ -27,6 +27,9 @@ import { createBaseFunction } from '../baseFunction.js';
27
27
  import { STRIPE_CONFIG } from '../config/constants.js';
28
28
  import { stripeSecretKey } from '../config/secrets.js'; // ✅ IMPORT SECRET
29
29
 
30
+ /** Stripe options plus the secrets this function reads (bound at deploy). */
31
+ const CUSTOMER_PORTAL_CONFIG = { ...STRIPE_CONFIG, secrets: [stripeSecretKey] };
32
+
30
33
  const customerPortalSchema = v.object({
31
34
  userId: v.string(),
32
35
  returnUrl: v.optional(v.pipe(v.string(), v.url())),
@@ -92,12 +95,16 @@ async function createCustomerPortalLogic(
92
95
  };
93
96
  }
94
97
 
98
+ /**
99
+ * Create the Stripe Customer Portal callable.
100
+ * Declares the `STRIPE_SECRET_KEY` secret, so the deploy binds it to this function.
101
+ */
95
102
  export function createCustomerPortal(): CallableFunction<
96
103
  CustomerPortalRequest,
97
104
  Promise<{ url: string }>
98
105
  > {
99
106
  return createBaseFunction<CustomerPortalRequest, { url: string }>(
100
- STRIPE_CONFIG,
107
+ CUSTOMER_PORTAL_CONFIG,
101
108
  customerPortalSchema,
102
109
  'create_customer_portal',
103
110
  createCustomerPortalLogic
@@ -14,12 +14,24 @@ import { onRequest } from 'firebase-functions/v2/https';
14
14
  import { isFirestoreConfigured } from '../../shared/utils/detectFirestore.js';
15
15
  import { stripe } from '../../shared/billing/stripeClient.js';
16
16
  import { STRIPE_CONFIG } from '../config/constants.js';
17
+ import { stripeSecretKey, stripeWebhookSecret } from '../config/secrets.js';
18
+
19
+ /**
20
+ * Stripe options plus the secrets the check reads (bound at deploy): it reads
21
+ * them from `process.env`, which Cloud Run sets only for declared secrets.
22
+ */
23
+ const HEALTH_CONFIG = {
24
+ ...STRIPE_CONFIG,
25
+ secrets: [stripeSecretKey, stripeWebhookSecret],
26
+ };
17
27
 
18
28
  /**
19
29
  * Comprehensive health check for billing system
20
30
  * GET /billingHealth
31
+ * Declares the `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` secrets, so the
32
+ * deploy binds them to this function.
21
33
  */
22
- export const billingHealth = onRequest(STRIPE_CONFIG, async (req, res) => {
34
+ export const billingHealth = onRequest(HEALTH_CONFIG, async (req, res) => {
23
35
  let overallStatus: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
24
36
 
25
37
  // Check Stripe connection
@@ -19,8 +19,19 @@ import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
19
19
  import { stripe, validateStripeEnvironment } from '../../shared/billing/stripeClient.js';
20
20
  import { createBaseFunction } from '../baseFunction.js';
21
21
  import { STRIPE_CONFIG } from '../config/constants.js';
22
+ import { stripeSecretKey } from '../config/secrets.js';
22
23
  import { pinnedSubscriptionPeriod } from '../../shared/billing/stripePinned.js';
23
24
 
25
+ /**
26
+ * Stripe options plus the secrets this function reads (bound at deploy):
27
+ * `stripe` and `validateStripeEnvironment` read `process.env.STRIPE_SECRET_KEY`,
28
+ * which Cloud Run sets only for a declared secret.
29
+ */
30
+ const REFRESH_SUBSCRIPTION_CONFIG = {
31
+ ...STRIPE_CONFIG,
32
+ secrets: [stripeSecretKey],
33
+ };
34
+
24
35
  /**
25
36
  * Schema for refreshing subscription status
26
37
  */
@@ -95,7 +106,8 @@ async function refreshSubscriptionStatusLogic(
95
106
 
96
107
  /**
97
108
  * Refreshes user's subscription status from Stripe
98
- * Base function handles all common concerns automatically
109
+ * Base function handles all common concerns automatically.
110
+ * Declares the `STRIPE_SECRET_KEY` secret, so the deploy binds it to this function.
99
111
  *
100
112
  * @version 0.1.0
101
113
  * @since 0.0.1
@@ -107,7 +119,7 @@ export const refreshSubscriptionStatus = (
107
119
  ) => {
108
120
  const schema = customSchema || refreshSubscriptionStatusSchema;
109
121
  return createBaseFunction(
110
- STRIPE_CONFIG,
122
+ REFRESH_SUBSCRIPTION_CONFIG,
111
123
  schema,
112
124
  'refresh_subscription_status',
113
125
  refreshSubscriptionStatusLogic
@@ -28,6 +28,12 @@ import {
28
28
  import { STRIPE_CONFIG } from '../config/constants.js';
29
29
  import { stripeSecretKey, stripeWebhookSecret } from '../config/secrets.js'; // ✅ IMPORT SECRETS
30
30
 
31
+ /** Stripe options plus the secrets the webhook reads (bound at deploy). */
32
+ const WEBHOOK_CONFIG = {
33
+ ...STRIPE_CONFIG,
34
+ secrets: [stripeSecretKey, stripeWebhookSecret],
35
+ };
36
+
31
37
  /**
32
38
  * Read raw body from request stream
33
39
  */
@@ -51,6 +57,8 @@ async function getRawBody(req: Request): Promise<Buffer> {
51
57
  * Create the Firebase Stripe webhook (HTTPS function) from the app's back config.
52
58
  * Events are stored in Firestore `webhook_idempotency`; any failure answers
53
59
  * non-2xx so Stripe retries the event.
60
+ * Declares the `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` secrets, so the
61
+ * deploy binds them to this function.
54
62
  *
55
63
  * @example
56
64
  * ```typescript
@@ -68,7 +76,7 @@ async function getRawBody(req: Request): Promise<Buffer> {
68
76
  export function createStripeWebhook(
69
77
  billingConfig: StripeBackConfig
70
78
  ): HttpsFunction {
71
- return onRequest(STRIPE_CONFIG, async (req, res) => {
79
+ return onRequest(WEBHOOK_CONFIG, async (req, res) => {
72
80
  // ✅ LATEST BEST PRACTICE: Init with secret value
73
81
  initStripe(stripeSecretKey.value());
74
82
 
@@ -19,12 +19,68 @@ import * as v from 'valibot';
19
19
  import type { UserRole } from '@donotdev/core/server';
20
20
  import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
21
21
 
22
- import { DoNotDevError, findReferences } from '../../shared/utils.js';
22
+ import { DoNotDevError } from '../../shared/utils.js';
23
23
  import { createBaseFunction } from '../baseFunction.js';
24
24
  import { CRUD_CONFIG } from '../config/constants.js';
25
25
 
26
26
  export type DeleteEntityRequest = { id: string };
27
27
 
28
+ /**
29
+ * Finds Firestore documents that reference a document.
30
+ *
31
+ * Firebase-only: lives here, not in `shared/utils.ts`, which Supabase Edge
32
+ * Functions import (the edge bundler resolves every import of that module).
33
+ *
34
+ * @param collection - Collection of the document to delete
35
+ * @param docId - Id of the document to delete
36
+ * @param referenceMetadata - Incoming references to check (none: no check)
37
+ * @returns One entry per referencing collection field
38
+ *
39
+ * @version 0.2.0
40
+ * @since 0.0.1
41
+ * @author AMBROISE PARK Consulting
42
+ */
43
+ async function findReferences(
44
+ collection: string,
45
+ docId: string,
46
+ referenceMetadata?: {
47
+ incoming?: Array<{
48
+ sourceCollection: string;
49
+ sourceField: string;
50
+ }>;
51
+ }
52
+ ): Promise<Array<{ collection: string; field: string; count: number }>> {
53
+ const references: Array<{
54
+ collection: string;
55
+ field: string;
56
+ count: number;
57
+ }> = [];
58
+
59
+ if (!referenceMetadata?.incoming?.length) {
60
+ return references;
61
+ }
62
+
63
+ const db = getFirebaseAdminFirestore();
64
+
65
+ for (const ref of referenceMetadata.incoming) {
66
+ const snapshot = await db
67
+ .collection(ref.sourceCollection)
68
+ .where(ref.sourceField, '==', docId)
69
+ .limit(1)
70
+ .get();
71
+
72
+ if (!snapshot.empty) {
73
+ references.push({
74
+ collection: ref.sourceCollection,
75
+ field: ref.sourceField,
76
+ count: snapshot.size,
77
+ });
78
+ }
79
+ }
80
+
81
+ return references;
82
+ }
83
+
28
84
  /**
29
85
  * Generic business logic for deleting entities
30
86
  * Base function handles: validation, auth, rate limiting, monitoring
@@ -0,0 +1,99 @@
1
+ // packages/functions/src/firebase/oauth/__tests__/tokenFactories.test.ts
2
+
3
+ /**
4
+ * @fileoverview OAuth token callables are built per enabled provider list
5
+ * @description `createExchangeToken` / `createRefreshToken` declare
6
+ * `${PROVIDER}_CLIENT_SECRET` for exactly the listed providers, fail at
7
+ * creation on an unknown or empty list, and reject requests for any other
8
+ * provider with `invalid-argument`.
9
+ */
10
+
11
+ import { describe, expect, it, vi } from 'vitest';
12
+
13
+ vi.mock('@donotdev/firebase/server', () => ({
14
+ getFirebaseAdminFirestore: vi.fn(() => {
15
+ throw new Error('Firestore must not be reached for a rejected provider');
16
+ }),
17
+ FieldValue: {},
18
+ }));
19
+
20
+ import type { OAuthPartnerId } from '@donotdev/core/server';
21
+
22
+ import { createExchangeToken } from '../exchangeToken';
23
+ import { createRefreshToken } from '../refreshToken';
24
+
25
+ /** Secret names a built function declares. */
26
+ function declared(fn: {
27
+ __endpoint: { secretEnvironmentVariables?: Array<{ key: string }> };
28
+ }): string[] {
29
+ return (fn.__endpoint.secretEnvironmentVariables ?? []).map((s) => s.key);
30
+ }
31
+
32
+ const auth = { uid: 'user-1', token: {}, rawToken: 'raw' };
33
+
34
+ describe.each([
35
+ ['createExchangeToken', createExchangeToken],
36
+ ['createRefreshToken', createRefreshToken],
37
+ ] as const)('%s', (name, factory) => {
38
+ it('declares the client secret of exactly the listed providers', () => {
39
+ const fn = factory(['github', 'google', 'github']);
40
+ expect(declared(fn)).toEqual([
41
+ 'GITHUB_CLIENT_SECRET',
42
+ 'GOOGLE_CLIENT_SECRET',
43
+ ]);
44
+ expect(declared(fn)).not.toContain('GITHUB_CLIENT_ID');
45
+ });
46
+
47
+ it('fails at creation on an unknown provider', () => {
48
+ expect(() => factory(['github', 'nope' as OAuthPartnerId])).toThrow(
49
+ `${name}: unknown OAuth provider "nope"`
50
+ );
51
+ });
52
+
53
+ it('fails at creation on an empty provider list', () => {
54
+ expect(() => factory([])).toThrow(
55
+ `${name}: providers is required and must list at least one OAuth provider`
56
+ );
57
+ });
58
+ });
59
+
60
+ describe('requests for a provider that is not listed', () => {
61
+ it('exchangeToken rejects them with invalid-argument', async () => {
62
+ const fn = createExchangeToken(['github']);
63
+ await expect(
64
+ fn.run({
65
+ auth,
66
+ data: {
67
+ provider: 'google',
68
+ purpose: 'signin',
69
+ code: 'code',
70
+ redirectUri: 'https://app.example/callback',
71
+ },
72
+ rawRequest: {},
73
+ acceptsStreaming: false,
74
+ } as unknown as Parameters<typeof fn.run>[0])
75
+ ).rejects.toMatchObject({
76
+ code: 'invalid-argument',
77
+ message: 'Provider google is not enabled',
78
+ });
79
+ });
80
+
81
+ it('refreshToken rejects them with invalid-argument', async () => {
82
+ const fn = createRefreshToken(['github']);
83
+ await expect(
84
+ fn.run({
85
+ auth,
86
+ data: {
87
+ provider: 'google',
88
+ refreshToken: 'refresh',
89
+ redirectUri: 'https://app.example/callback',
90
+ },
91
+ rawRequest: {},
92
+ acceptsStreaming: false,
93
+ } as unknown as Parameters<typeof fn.run>[0])
94
+ ).rejects.toMatchObject({
95
+ code: 'invalid-argument',
96
+ message: 'Provider google is not enabled',
97
+ });
98
+ });
99
+ });