@donotdev/functions 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/guidelines/VERCEL.md +25 -16
  2. package/lib/chunks/{chunk-HZM5X5A7.js → chunk-4BJP372Z.js} +2 -2
  3. package/lib/chunks/chunk-CCEGC2T6.js +22 -0
  4. package/lib/chunks/chunk-CCEGC2T6.js.map +7 -0
  5. package/lib/chunks/{chunk-CVYSXC27.js → chunk-IO4MUTT6.js} +2 -2
  6. package/lib/chunks/chunk-LJXSA7EP.js +151 -0
  7. package/lib/chunks/chunk-LJXSA7EP.js.map +7 -0
  8. package/lib/chunks/chunk-MJ5VZTLM.js +22 -0
  9. package/lib/chunks/chunk-MJ5VZTLM.js.map +7 -0
  10. package/lib/chunks/chunk-NP4Y2LAO.js +22 -0
  11. package/lib/chunks/chunk-NP4Y2LAO.js.map +7 -0
  12. package/lib/chunks/chunk-TBHRDSX5.js +22 -0
  13. package/lib/chunks/chunk-TBHRDSX5.js.map +7 -0
  14. package/lib/chunks/{chunk-522YXGDA.js → chunk-WJUL2W7Y.js} +2 -2
  15. package/lib/chunks/{chunk-522YXGDA.js.map → chunk-WJUL2W7Y.js.map} +2 -2
  16. package/lib/chunks/chunk-Y6BR2QOV.js +22 -0
  17. package/lib/chunks/{chunk-ICNQCRLV.js.map → chunk-Y6BR2QOV.js.map} +4 -4
  18. package/lib/chunks/{monitoring-UCBNPPW2.js → monitoring-B2DYDCYC.js} +2 -2
  19. package/lib/chunks/{rateLimiter-XKECWM33.js → rateLimiter-JCBEG33M.js} +2 -2
  20. package/lib/chunks/{server-24XGDDO3.js → server-YXYTPMRF.js} +2 -2
  21. package/lib/firebase/billing/cancelSubscription.d.ts +2 -1
  22. package/lib/firebase/billing/changePlan.d.ts +2 -1
  23. package/lib/firebase/billing/createCheckoutSession.d.ts +2 -1
  24. package/lib/firebase/billing/createCustomerPortal.d.ts +4 -0
  25. package/lib/firebase/billing/healthCheck.d.ts +2 -0
  26. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -1
  27. package/lib/firebase/billing/webhookHandler.d.ts +2 -0
  28. package/lib/firebase/index.js +1 -1
  29. package/lib/firebase/index.js.map +4 -4
  30. package/lib/firebase/oauth/exchangeToken.d.ts +21 -4
  31. package/lib/firebase/oauth/providerSecrets.d.ts +22 -0
  32. package/lib/firebase/oauth/refreshToken.d.ts +34 -4
  33. package/lib/shared/index.js +1 -1
  34. package/lib/supabase/index.js +1 -1
  35. package/lib/supabase/index.js.map +4 -4
  36. package/lib/vercel/api/auth/index.d.ts +3 -3
  37. package/lib/vercel/api/crud/index.d.ts +6 -6
  38. package/lib/vercel/api/index.js +1 -1
  39. package/lib/vercel/api/index.js.map +4 -4
  40. package/lib/vercel/api/oauth/index.d.ts +4 -4
  41. package/package.json +5 -5
  42. package/src/firebase/billing/__tests__/secretDeclarations.test.ts +55 -0
  43. package/src/firebase/billing/cancelSubscription.ts +9 -2
  44. package/src/firebase/billing/changePlan.ts +6 -2
  45. package/src/firebase/billing/createCheckoutSession.ts +6 -2
  46. package/src/firebase/billing/createCustomerPortal.ts +8 -1
  47. package/src/firebase/billing/healthCheck.ts +13 -1
  48. package/src/firebase/billing/refreshSubscriptionStatus.ts +14 -2
  49. package/src/firebase/billing/webhookHandler.ts +9 -1
  50. package/src/firebase/oauth/__tests__/tokenFactories.test.ts +99 -0
  51. package/src/firebase/oauth/exchangeToken.ts +53 -8
  52. package/src/firebase/oauth/providerSecrets.ts +65 -0
  53. package/src/firebase/oauth/refreshToken.ts +57 -12
  54. package/src/vercel/__tests__/firebaseOptional.test.ts +24 -0
  55. package/src/vercel/api/auth/index.ts +4 -3
  56. package/src/vercel/api/crud/index.ts +7 -6
  57. package/src/vercel/api/oauth/index.ts +5 -4
  58. package/lib/chunks/chunk-7ODXXXES.js +0 -151
  59. package/lib/chunks/chunk-7ODXXXES.js.map +0 -7
  60. package/lib/chunks/chunk-CP3NNKO5.js +0 -22
  61. package/lib/chunks/chunk-CP3NNKO5.js.map +0 -7
  62. package/lib/chunks/chunk-ICNQCRLV.js +0 -22
  63. package/lib/chunks/chunk-OAZ2JYSD.js +0 -22
  64. package/lib/chunks/chunk-OAZ2JYSD.js.map +0 -7
  65. package/lib/chunks/chunk-OKRR7ST5.js +0 -22
  66. package/lib/chunks/chunk-OKRR7ST5.js.map +0 -7
  67. package/lib/chunks/chunk-PDBNKSBQ.js +0 -22
  68. package/lib/chunks/chunk-PDBNKSBQ.js.map +0 -7
  69. package/lib/chunks/chunk-TJPJXJEK.js +0 -22
  70. package/lib/chunks/chunk-TJPJXJEK.js.map +0 -7
  71. /package/lib/chunks/{chunk-HZM5X5A7.js.map → chunk-4BJP372Z.js.map} +0 -0
  72. /package/lib/chunks/{chunk-CVYSXC27.js.map → chunk-IO4MUTT6.js.map} +0 -0
  73. /package/lib/chunks/{monitoring-UCBNPPW2.js.map → monitoring-B2DYDCYC.js.map} +0 -0
  74. /package/lib/chunks/{rateLimiter-XKECWM33.js.map → rateLimiter-JCBEG33M.js.map} +0 -0
  75. /package/lib/chunks/{server-24XGDDO3.js.map → server-YXYTPMRF.js.map} +0 -0
@@ -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
 
@@ -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
+ });
@@ -2,14 +2,16 @@
2
2
 
3
3
  /**
4
4
  * @fileoverview OAuth token exchange Firebase function
5
- * @description Firebase callable function for exchanging OAuth codes for tokens
5
+ * @description Factory for the Firebase callable that exchanges OAuth codes for
6
+ * tokens, for the providers the app enables.
6
7
  *
7
- * @version 0.1.0
8
+ * @version 0.2.0
8
9
  * @since 0.0.1
9
10
  * @author AMBROISE PARK Consulting
10
11
  */
11
12
 
12
13
  import { onCall, HttpsError } from 'firebase-functions/v2/https';
14
+ import type { CallableFunction } from 'firebase-functions/v2/https';
13
15
 
14
16
  import {
15
17
  OAUTH_PARTNERS,
@@ -22,20 +24,56 @@ import {
22
24
  } from '@donotdev/firebase/server';
23
25
 
24
26
  import { assertAuthenticated } from '../../shared/utils/internal/auth.js';
27
+ import { defineOAuthProviderSecrets } from './providerSecrets.js';
25
28
 
26
29
  /**
27
- * Exchange OAuth authorization code for access token
30
+ * Create the callable that exchanges an OAuth authorization code for tokens.
28
31
  *
29
- * @version 0.1.0
32
+ * Serves only `providers`: it declares `${PROVIDER}_CLIENT_SECRET` for each one
33
+ * (bound at deploy) and rejects a request for any other provider with
34
+ * `invalid-argument`. `${PROVIDER}_CLIENT_ID` stays plain config in functions/.env.
35
+ *
36
+ * @param providers - OAuth partner ids from `OAUTH_PARTNERS` (at least one)
37
+ * @returns The `exchangeToken` callable
38
+ * @throws Error when `providers` is empty or lists an unknown provider
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * // functions/src/index.ts
43
+ * import { createExchangeToken } from '@donotdev/functions/firebase';
44
+ *
45
+ * export const exchangeToken = createExchangeToken(['github', 'google']);
46
+ * ```
47
+ *
48
+ * @version 0.2.0
30
49
  * @since 0.0.1
31
50
  * @author AMBROISE PARK Consulting
32
51
  */
33
- export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
52
+ export function createExchangeToken(
53
+ providers: readonly OAuthPartnerId[]
54
+ ): CallableFunction<ExchangeTokenRequest, Promise<unknown>> {
55
+ const { allowed, secrets } = defineOAuthProviderSecrets(
56
+ providers,
57
+ 'createExchangeToken'
58
+ );
59
+ return onCall<ExchangeTokenRequest>({ secrets }, (request) =>
60
+ exchangeTokenHandler(request.auth?.uid, request.data, allowed)
61
+ );
62
+ }
63
+
64
+ /**
65
+ * Exchange OAuth authorization code for access token (enabled providers only).
66
+ */
67
+ async function exchangeTokenHandler(
68
+ authUid: string | undefined,
69
+ data: ExchangeTokenRequest,
70
+ allowed: ReadonlySet<string>
71
+ ): Promise<unknown> {
34
72
  // Verify authentication
35
- const uid = assertAuthenticated(request.auth?.uid);
73
+ const uid = assertAuthenticated(authUid);
36
74
 
37
75
  const { provider, purpose, code, redirectUri, codeVerifier, idempotencyKey } =
38
- request.data;
76
+ data;
39
77
 
40
78
  // W17: Validate idempotency key length and content.
41
79
  if (idempotencyKey !== undefined) {
@@ -62,6 +100,13 @@ export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
62
100
  throw new HttpsError('invalid-argument', 'Missing required parameters');
63
101
  }
64
102
 
103
+ if (!allowed.has(provider)) {
104
+ throw new HttpsError(
105
+ 'invalid-argument',
106
+ `Provider ${provider} is not enabled`
107
+ );
108
+ }
109
+
65
110
  // C9: Atomic idempotency check using Firestore transaction to prevent TOCTOU race.
66
111
  // A concurrent request with the same key would see the 'pending' sentinel and wait
67
112
  // or return early instead of executing duplicate business logic.
@@ -203,7 +248,7 @@ export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
203
248
  : 'Failed to exchange code for token'
204
249
  );
205
250
  }
206
- });
251
+ }
207
252
 
208
253
  /**
209
254
  * Fetch user profile from OAuth provider
@@ -0,0 +1,65 @@
1
+ // packages/functions/src/firebase/oauth/providerSecrets.ts
2
+
3
+ /**
4
+ * @fileoverview OAuth provider secrets for the token callables
5
+ * @description Validates the providers an app enables and declares one
6
+ * `${PROVIDER}_CLIENT_SECRET` secret per provider, so the deploy binds exactly
7
+ * those to the function. `${PROVIDER}_CLIENT_ID` is not a secret: it stays
8
+ * plain config in functions/.env.
9
+ *
10
+ * @version 0.1.0
11
+ * @since 0.3.2
12
+ * @author AMBROISE PARK Consulting
13
+ */
14
+
15
+ import { defineSecret } from 'firebase-functions/params';
16
+ import type { SecretParam } from 'firebase-functions/params';
17
+
18
+ import { OAUTH_PARTNERS, type OAuthPartnerId } from '@donotdev/core/server';
19
+
20
+ /** Providers a token callable serves and the secrets it declares for them. */
21
+ export interface OAuthProviderSecrets {
22
+ /** Enabled providers; a request for any other provider is rejected. */
23
+ allowed: ReadonlySet<string>;
24
+ /** One `${PROVIDER}_CLIENT_SECRET` per enabled provider. */
25
+ secrets: SecretParam[];
26
+ }
27
+
28
+ /**
29
+ * Validate the providers a token callable serves and declare their client secrets.
30
+ *
31
+ * @param providers - OAuth partner ids from `OAUTH_PARTNERS` (at least one)
32
+ * @param factory - Factory name, used in error messages
33
+ * @returns Enabled providers and their declared secrets
34
+ * @throws Error when `providers` is empty or lists an id `OAUTH_PARTNERS` does not have
35
+ *
36
+ * @version 0.1.0
37
+ * @since 0.3.2
38
+ * @author AMBROISE PARK Consulting
39
+ */
40
+ export function defineOAuthProviderSecrets(
41
+ providers: readonly OAuthPartnerId[],
42
+ factory: string
43
+ ): OAuthProviderSecrets {
44
+ if (!Array.isArray(providers) || providers.length === 0) {
45
+ throw new Error(
46
+ `${factory}: providers is required and must list at least one OAuth provider (${Object.keys(OAUTH_PARTNERS).join(', ')}).`
47
+ );
48
+ }
49
+ const allowed = new Set<string>();
50
+ for (const provider of providers) {
51
+ if (
52
+ typeof provider !== 'string' ||
53
+ !Object.hasOwn(OAUTH_PARTNERS, provider)
54
+ ) {
55
+ throw new Error(
56
+ `${factory}: unknown OAuth provider "${String(provider)}". Known providers: ${Object.keys(OAUTH_PARTNERS).join(', ')}.`
57
+ );
58
+ }
59
+ allowed.add(provider);
60
+ }
61
+ const secrets = [...allowed].map((provider) =>
62
+ defineSecret(`${provider.toUpperCase()}_CLIENT_SECRET`)
63
+ );
64
+ return { allowed, secrets };
65
+ }
@@ -2,17 +2,20 @@
2
2
 
3
3
  /**
4
4
  * @fileoverview OAuth token refresh Firebase function
5
- * @description Firebase callable function for refreshing OAuth tokens
5
+ * @description Factory for the Firebase callable that refreshes OAuth tokens,
6
+ * for the providers the app enables.
6
7
  *
7
- * @version 0.1.0
8
+ * @version 0.2.0
8
9
  * @since 0.0.1
9
10
  * @author AMBROISE PARK Consulting
10
11
  */
11
12
 
12
13
  import { onCall, HttpsError } from 'firebase-functions/v2/https';
14
+ import type { CallableFunction } from 'firebase-functions/v2/https';
13
15
 
14
16
  import {
15
17
  OAUTH_PARTNERS,
18
+ type OAuthPartnerId,
16
19
  type OAuthRefreshRequest,
17
20
  } from '@donotdev/core/server';
18
21
  import {
@@ -21,23 +24,65 @@ import {
21
24
  } from '@donotdev/firebase/server';
22
25
 
23
26
  import { assertAuthenticated } from '../../shared/utils/internal/auth.js';
27
+ import { defineOAuthProviderSecrets } from './providerSecrets.js';
24
28
 
25
29
  /**
26
- * Refresh an OAuth token
30
+ * Create the callable that refreshes an OAuth token.
27
31
  *
28
- * @version 0.1.0
32
+ * Serves only `providers`: it declares `${PROVIDER}_CLIENT_SECRET` for each one
33
+ * (bound at deploy) and rejects a request for any other provider with
34
+ * `invalid-argument`. `${PROVIDER}_CLIENT_ID` stays plain config in functions/.env.
35
+ *
36
+ * @param providers - OAuth partner ids from `OAUTH_PARTNERS` (at least one)
37
+ * @returns The `refreshToken` callable
38
+ * @throws Error when `providers` is empty or lists an unknown provider
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * // functions/src/index.ts
43
+ * import { createRefreshToken } from '@donotdev/functions/firebase';
44
+ *
45
+ * export const refreshToken = createRefreshToken(['github', 'google']);
46
+ * ```
47
+ *
48
+ * @version 0.2.0
29
49
  * @since 0.0.1
30
50
  * @author AMBROISE PARK Consulting
31
51
  */
32
- export const refreshToken = onCall<OAuthRefreshRequest>(async (request) => {
52
+ export function createRefreshToken(
53
+ providers: readonly OAuthPartnerId[]
54
+ ): CallableFunction<
55
+ OAuthRefreshRequest,
56
+ ReturnType<typeof refreshTokenHandler>
57
+ > {
58
+ const { allowed, secrets } = defineOAuthProviderSecrets(
59
+ providers,
60
+ 'createRefreshToken'
61
+ );
62
+ return onCall<OAuthRefreshRequest>({ secrets }, (request) =>
63
+ refreshTokenHandler(request.auth?.uid, request.data, allowed)
64
+ );
65
+ }
66
+
67
+ /**
68
+ * Refresh an OAuth token (enabled providers only).
69
+ */
70
+ async function refreshTokenHandler(
71
+ authUid: string | undefined,
72
+ data: OAuthRefreshRequest,
73
+ allowed: ReadonlySet<string>
74
+ ) {
33
75
  // Verify authentication
34
- const uid = assertAuthenticated(request.auth?.uid);
76
+ const uid = assertAuthenticated(authUid);
77
+
78
+ const { provider, refreshToken: refreshTokenValue, redirectUri } = data;
35
79
 
36
- const {
37
- provider,
38
- refreshToken: refreshTokenValue,
39
- redirectUri,
40
- } = request.data;
80
+ if (!allowed.has(provider)) {
81
+ throw new HttpsError(
82
+ 'invalid-argument',
83
+ `Provider ${provider} is not enabled`
84
+ );
85
+ }
41
86
 
42
87
  try {
43
88
  // Get provider endpoints
@@ -146,4 +191,4 @@ export const refreshToken = onCall<OAuthRefreshRequest>(async (request) => {
146
191
  error instanceof Error ? error.message : 'Failed to refresh token'
147
192
  );
148
193
  }
149
- });
194
+ }
@@ -48,6 +48,30 @@ describe('vercel entry without firebase', () => {
48
48
  expect(typeof entry.refreshSubscriptionStatus).toBe('function');
49
49
  });
50
50
 
51
+ // Route handlers are default exports of their modules; the barrels name them
52
+ // (scaffolded functions/src/api/** files import these names)
53
+ it('exports every route handler by name', async () => {
54
+ const entry = await import('../api/index.js');
55
+ for (const name of [
56
+ 'getCustomClaims',
57
+ 'getUserAuthStatus',
58
+ 'removeCustomClaims',
59
+ 'createSetCustomClaimsHandler',
60
+ 'bulk',
61
+ 'createEntity',
62
+ 'deleteEntity',
63
+ 'getEntity',
64
+ 'listEntities',
65
+ 'updateEntity',
66
+ 'checkGitHubAccess',
67
+ 'exchangeToken',
68
+ 'grantGitHubAccess',
69
+ 'revokeGitHubAccess',
70
+ ] as const) {
71
+ expect(typeof entry[name], name).toBe('function');
72
+ }
73
+ });
74
+
51
75
  it('builds Supabase billing handlers and resolves the supabase backend', async () => {
52
76
  process.env.SUPABASE_URL = 'https://example.supabase.co';
53
77
  process.env.SUPABASE_SECRET_KEY = 'sb_secret_test';
@@ -9,7 +9,8 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- export * from './get-custom-claims.js';
13
- export * from './get-user-auth-status.js';
14
- export * from './remove-custom-claims.js';
12
+ // Route handlers are default exports: `export *` would drop them
13
+ export { default as getCustomClaims } from './get-custom-claims.js';
14
+ export { default as getUserAuthStatus } from './get-user-auth-status.js';
15
+ export { default as removeCustomClaims } from './remove-custom-claims.js';
15
16
  export * from './set-custom-claims.js';
@@ -9,9 +9,10 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- export * from './bulk.js';
13
- export * from './create.js';
14
- export * from './delete.js';
15
- export * from './get.js';
16
- export * from './list.js';
17
- export * from './update.js';
12
+ // Route handlers are default exports: `export *` would drop them
13
+ export { default as bulk } from './bulk.js';
14
+ export { default as createEntity } from './create.js';
15
+ export { default as deleteEntity } from './delete.js';
16
+ export { default as getEntity } from './get.js';
17
+ export { default as listEntities } from './list.js';
18
+ export { default as updateEntity } from './update.js';
@@ -9,7 +9,8 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- export * from './check-github-access.js';
13
- export * from './exchange-token.js';
14
- export * from './grant-github-access.js';
15
- export * from './revoke-github-access.js';
12
+ // Route handlers and factories are default exports: `export *` would drop them
13
+ export { default as checkGitHubAccess } from './check-github-access.js';
14
+ export { default as exchangeToken } from './exchange-token.js';
15
+ export { default as grantGitHubAccess } from './grant-github-access.js';
16
+ export { default as revokeGitHubAccess } from './revoke-github-access.js';