@donotdev/functions 0.0.18 → 0.0.20

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 (149) hide show
  1. package/lib/firebase/auth/getCustomClaims.d.ts +25 -0
  2. package/lib/firebase/auth/getUserAuthStatus.d.ts +29 -0
  3. package/lib/firebase/auth/index.d.ts +12 -0
  4. package/lib/firebase/auth/removeCustomClaims.d.ts +28 -0
  5. package/lib/firebase/auth/setCustomClaims.d.ts +34 -0
  6. package/lib/firebase/baseFunction.d.ts +26 -0
  7. package/lib/firebase/billing/cancelSubscription.d.ts +10 -0
  8. package/lib/firebase/billing/changePlan.d.ts +13 -0
  9. package/lib/firebase/billing/createCheckoutSession.d.ts +21 -0
  10. package/lib/firebase/billing/createCustomerPortal.d.ts +19 -0
  11. package/lib/firebase/billing/healthCheck.d.ts +5 -0
  12. package/lib/firebase/billing/index.d.ts +18 -0
  13. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +19 -0
  14. package/lib/firebase/billing/webhookHandler.d.ts +6 -0
  15. package/lib/firebase/config/constants.d.ts +89 -0
  16. package/lib/firebase/config/index.d.ts +9 -0
  17. package/lib/firebase/config/secrets.d.ts +15 -0
  18. package/lib/firebase/crud/aggregate.d.ts +98 -0
  19. package/lib/firebase/crud/create.d.ts +16 -0
  20. package/lib/firebase/crud/delete.d.ts +20 -0
  21. package/lib/firebase/crud/get.d.ts +24 -0
  22. package/lib/firebase/crud/index.d.ts +14 -0
  23. package/lib/firebase/crud/list.d.ts +25 -0
  24. package/lib/firebase/crud/update.d.ts +25 -0
  25. package/lib/firebase/helpers/githubAccessHelper.d.ts +30 -0
  26. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +36 -0
  27. package/lib/firebase/helpers/index.d.ts +10 -0
  28. package/lib/firebase/index.d.ts +17 -0
  29. package/lib/firebase/index.js +25 -9110
  30. package/lib/firebase/index.js.map +4 -4
  31. package/lib/firebase/oauth/disconnect.d.ts +12 -0
  32. package/lib/firebase/oauth/exchangeToken.d.ts +9 -0
  33. package/lib/firebase/oauth/getConnections.d.ts +11 -0
  34. package/lib/firebase/oauth/githubAccess.d.ts +83 -0
  35. package/lib/firebase/oauth/index.d.ts +13 -0
  36. package/lib/firebase/oauth/refreshToken.d.ts +9 -0
  37. package/lib/firebase/registerCrudFunctions.d.ts +32 -0
  38. package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +14 -0
  39. package/lib/firebase/scheduled/index.d.ts +9 -0
  40. package/lib/shared/billing/createCheckout.d.ts +50 -0
  41. package/lib/shared/billing/helpers/index.d.ts +10 -0
  42. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +34 -0
  43. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +45 -0
  44. package/lib/shared/billing/idempotency.d.ts +22 -0
  45. package/lib/shared/billing/index.d.ts +11 -0
  46. package/lib/shared/billing/webhookHandler.d.ts +37 -0
  47. package/lib/shared/errorHandling.d.ts +14 -0
  48. package/lib/shared/firebase.d.ts +73 -0
  49. package/lib/shared/github.d.ts +128 -0
  50. package/lib/shared/index.d.ts +16 -0
  51. package/lib/shared/index.js +25 -6927
  52. package/lib/shared/index.js.map +4 -4
  53. package/lib/shared/logger.d.ts +133 -0
  54. package/lib/shared/metadata.d.ts +36 -0
  55. package/lib/shared/oauth/exchangeToken.d.ts +24 -0
  56. package/lib/shared/oauth/grantAccess.d.ts +30 -0
  57. package/lib/shared/oauth/index.d.ts +10 -0
  58. package/lib/shared/schema.d.ts +56 -0
  59. package/lib/shared/utils/detectFirestore.d.ts +31 -0
  60. package/lib/shared/utils/external/date.d.ts +36 -0
  61. package/lib/shared/utils/external/index.d.ts +11 -0
  62. package/lib/shared/utils/external/references.d.ts +12 -0
  63. package/lib/shared/utils/external/subscription.d.ts +41 -0
  64. package/lib/shared/utils/firebaseHelpers.d.ts +23 -0
  65. package/lib/shared/utils/functionWrapper.d.ts +36 -0
  66. package/lib/shared/utils/index.d.ts +14 -0
  67. package/lib/shared/utils/internal/auth.d.ts +57 -0
  68. package/lib/shared/utils/internal/firebase.d.ts +5 -0
  69. package/lib/shared/utils/internal/idempotency.d.ts +21 -0
  70. package/lib/shared/utils/internal/index.d.ts +14 -0
  71. package/lib/shared/utils/internal/monitoring.d.ts +80 -0
  72. package/lib/shared/utils/internal/rateLimiter.d.ts +82 -0
  73. package/lib/shared/utils/internal/validation.d.ts +43 -0
  74. package/lib/shared/utils/schemaValidation.d.ts +60 -0
  75. package/lib/shared/utils/validation.d.ts +98 -0
  76. package/lib/shared/utils/vercelHelpers.d.ts +18 -0
  77. package/lib/shared/utils.d.ts +234 -0
  78. package/lib/shared/validation.d.ts +16 -0
  79. package/lib/supabase/auth/deleteAccount.d.ts +16 -0
  80. package/lib/supabase/auth/getCustomClaims.d.ts +16 -0
  81. package/lib/supabase/auth/getUserAuthStatus.d.ts +18 -0
  82. package/lib/supabase/auth/removeCustomClaims.d.ts +16 -0
  83. package/lib/supabase/auth/setCustomClaims.d.ts +18 -0
  84. package/lib/supabase/baseFunction.d.ts +43 -0
  85. package/lib/supabase/billing/cancelSubscription.d.ts +9 -0
  86. package/lib/supabase/billing/changePlan.d.ts +11 -0
  87. package/lib/supabase/billing/createCheckoutSession.d.ts +11 -0
  88. package/lib/supabase/billing/createCustomerPortal.d.ts +9 -0
  89. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +9 -0
  90. package/lib/supabase/crud/aggregate.d.ts +27 -0
  91. package/lib/supabase/crud/create.d.ts +23 -0
  92. package/lib/supabase/crud/delete.d.ts +30 -0
  93. package/lib/supabase/crud/get.d.ts +23 -0
  94. package/lib/supabase/crud/index.d.ts +20 -0
  95. package/lib/supabase/crud/list.d.ts +33 -0
  96. package/lib/supabase/crud/update.d.ts +24 -0
  97. package/lib/supabase/helpers/authProvider.d.ts +22 -0
  98. package/lib/supabase/index.d.ts +29 -0
  99. package/lib/supabase/index.js +23 -0
  100. package/lib/supabase/index.js.map +7 -0
  101. package/lib/supabase/registerCrudFunctions.d.ts +24 -0
  102. package/lib/supabase/utils/idempotency.d.ts +36 -0
  103. package/lib/supabase/utils/monitoring.d.ts +59 -0
  104. package/lib/supabase/utils/rateLimiter.d.ts +56 -0
  105. package/lib/vercel/api/auth/get-custom-claims.d.ts +2 -0
  106. package/lib/vercel/api/auth/get-user-auth-status.d.ts +2 -0
  107. package/lib/vercel/api/auth/index.d.ts +12 -0
  108. package/lib/vercel/api/auth/remove-custom-claims.d.ts +2 -0
  109. package/lib/vercel/api/auth/set-custom-claims.d.ts +10 -0
  110. package/lib/vercel/api/billing/cancel.d.ts +10 -0
  111. package/lib/vercel/api/billing/change-plan.d.ts +11 -0
  112. package/lib/vercel/api/billing/create-checkout-session.d.ts +13 -0
  113. package/lib/vercel/api/billing/customer-portal.d.ts +3 -0
  114. package/lib/vercel/api/billing/index.d.ts +14 -0
  115. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +31 -0
  116. package/lib/vercel/api/billing/webhook-handler.d.ts +22 -0
  117. package/lib/vercel/api/config/constants.d.ts +103 -0
  118. package/lib/vercel/api/config/firebase-admin.d.ts +19 -0
  119. package/lib/vercel/api/config/index.d.ts +10 -0
  120. package/lib/vercel/api/crud/create.d.ts +2 -0
  121. package/lib/vercel/api/crud/delete.d.ts +2 -0
  122. package/lib/vercel/api/crud/get.d.ts +2 -0
  123. package/lib/vercel/api/crud/index.d.ts +13 -0
  124. package/lib/vercel/api/crud/list.d.ts +2 -0
  125. package/lib/vercel/api/crud/update.d.ts +2 -0
  126. package/lib/vercel/api/index.d.ts +13 -0
  127. package/lib/vercel/api/index.js +22 -4790
  128. package/lib/vercel/api/index.js.map +4 -4
  129. package/lib/vercel/api/oauth/check-github-access.d.ts +12 -0
  130. package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
  131. package/lib/vercel/api/oauth/grant-github-access.d.ts +12 -0
  132. package/lib/vercel/api/oauth/index.d.ts +12 -0
  133. package/lib/vercel/api/oauth/revoke-github-access.d.ts +11 -0
  134. package/lib/vercel/api/utils/cors.d.ts +49 -0
  135. package/lib/vercel/baseFunction.d.ts +25 -0
  136. package/package.json +4 -4
  137. package/src/firebase/auth/setCustomClaims.ts +61 -16
  138. package/src/firebase/billing/healthCheck.ts +7 -23
  139. package/src/firebase/billing/webhookHandler.ts +0 -1
  140. package/src/firebase/crud/create.ts +17 -2
  141. package/src/firebase/oauth/exchangeToken.ts +5 -5
  142. package/src/shared/billing/createCheckout.ts +6 -1
  143. package/src/shared/utils/internal/validation.ts +1 -1
  144. package/src/supabase/crud/aggregate.ts +10 -7
  145. package/src/supabase/crud/create.ts +1 -1
  146. package/src/supabase/crud/get.ts +1 -1
  147. package/src/supabase/crud/list.ts +1 -1
  148. package/src/supabase/crud/update.ts +1 -1
  149. package/src/vercel/api/auth/set-custom-claims.ts +70 -23
@@ -0,0 +1,12 @@
1
+ import type { NextApiRequest, NextApiResponse } from 'next';
2
+ import type * as v from 'valibot';
3
+ /**
4
+ * Vercel API handler for checking GitHub access
5
+ * Base function handles all common concerns automatically
6
+ *
7
+ * @version 0.0.1
8
+ * @since 0.0.1
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+ declare const checkGitHubAccess: (customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>) => (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
12
+ export default checkGitHubAccess;
@@ -0,0 +1,8 @@
1
+ import type { NextApiRequest, NextApiResponse } from 'next';
2
+ import type * as v from 'valibot';
3
+ /**
4
+ * Vercel API handler for exchanging OAuth tokens
5
+ * Base function handles all common concerns automatically
6
+ */
7
+ declare const exchangeToken: (customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>) => (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
8
+ export default exchangeToken;
@@ -0,0 +1,12 @@
1
+ import type { NextApiRequest, NextApiResponse } from 'next';
2
+ import type * as v from 'valibot';
3
+ /**
4
+ * Vercel API handler for granting GitHub access
5
+ * Base function handles all common concerns automatically
6
+ *
7
+ * @version 0.0.1
8
+ * @since 0.0.1
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+ declare const grantGitHubAccess: (customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>) => (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
12
+ export default grantGitHubAccess;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @fileoverview Vercel API OAuth barrel exports
3
+ * @description Centralized exports for Vercel API OAuth functions
4
+ *
5
+ * @version 0.0.1
6
+ * @since 0.0.1
7
+ * @author AMBROISE PARK Consulting
8
+ */
9
+ export * from './check-github-access.js';
10
+ export * from './exchange-token.js';
11
+ export * from './grant-github-access.js';
12
+ export * from './revoke-github-access.js';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @fileoverview Revoke GitHub access API handler
3
+ * @description Vercel API route for revoking GitHub access
4
+ *
5
+ * @version 0.0.1
6
+ * @since 0.0.1
7
+ * @author AMBROISE PARK Consulting
8
+ */
9
+ import * as v from 'valibot';
10
+ import type { NextApiRequest, NextApiResponse } from 'next';
11
+ export default function handler(req: NextApiRequest, res: NextApiResponse, customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>): Promise<void>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @fileoverview CORS utilities for Vercel API
3
+ * @description CORS configuration and handling for Vercel functions
4
+ *
5
+ * @version 0.0.1
6
+ * @since 0.0.1
7
+ * @author AMBROISE PARK Consulting
8
+ */
9
+ import type { NextApiRequest, NextApiResponse } from 'next';
10
+ /**
11
+ * CORS configuration for Vercel functions.
12
+ *
13
+ * **Architecture decision — CORS wildcard (`*`) as framework default:**
14
+ * The wildcard origin is an intentional development-convenience default, not a
15
+ * security oversight. Consumer apps MUST override `allowedOrigins` in their
16
+ * deployment configuration for production environments. The framework provides
17
+ * `configureCors({ allowedOrigins: ['https://myapp.example'] })` for this purpose.
18
+ *
19
+ * C2: Allow-Credentials:true is incompatible with wildcard origin per the Fetch spec.
20
+ * Credentialed requests require an explicit origin. Removed Allow-Credentials header so
21
+ * the wildcard origin remains valid. Consumers that need credentialed cross-origin requests
22
+ * must replace '*' with their specific origin and re-add Allow-Credentials:true.
23
+ *
24
+ * @version 0.0.1
25
+ * @since 0.0.1
26
+ * @author AMBROISE PARK Consulting
27
+ */
28
+ export declare const corsHeaders: {
29
+ 'Access-Control-Allow-Origin': string;
30
+ 'Access-Control-Allow-Methods': string;
31
+ 'Access-Control-Allow-Headers': string;
32
+ 'Access-Control-Max-Age': string;
33
+ };
34
+ /**
35
+ * Handle CORS preflight requests
36
+ *
37
+ * @version 0.0.1
38
+ * @since 0.0.1
39
+ * @author AMBROISE PARK Consulting
40
+ */
41
+ export declare function handleCors(req: NextApiRequest, res: NextApiResponse): boolean;
42
+ /**
43
+ * Wrapper for Vercel API functions to automatically handle CORS
44
+ *
45
+ * @version 0.0.1
46
+ * @since 0.0.1
47
+ * @author AMBROISE PARK Consulting
48
+ */
49
+ export declare function withCors(handler: (req: NextApiRequest, res: NextApiResponse) => Promise<void>): (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @fileoverview Base Vercel function that handles all common concerns
3
+ * @description Rate limiting, monitoring, authentication, validation - all in one place
4
+ *
5
+ * @version 0.0.1
6
+ * @since 0.0.1
7
+ * @author AMBROISE PARK Consulting
8
+ */
9
+ import * as v from 'valibot';
10
+ import type { SecurityContext } from '@donotdev/core';
11
+ import type { AuthProvider } from '../shared/utils/internal/auth.js';
12
+ import type { NextApiRequest, NextApiResponse } from 'next';
13
+ /**
14
+ * Base Vercel function that handles all common concerns
15
+ * Users just provide their business logic
16
+ *
17
+ * @version 0.0.1
18
+ * @since 0.0.1
19
+ * @author AMBROISE PARK Consulting
20
+ */
21
+ export declare function createVercelBaseFunction<TRequest, TResponse>(method: string, schema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>, operation: string, businessLogic: (req: NextApiRequest, res: NextApiResponse, data: TRequest, context: {
22
+ uid: string;
23
+ }) => Promise<TResponse>, security?: SecurityContext,
24
+ /** Auth provider for token verification. Auto-detects via provider registry if omitted. */
25
+ provider?: AuthProvider): (req: NextApiRequest, res: NextApiResponse) => Promise<TResponse>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@donotdev/functions",
3
- "version": "0.0.18",
3
+ "version": "0.0.20",
4
4
  "private": false,
5
5
  "description": "Backend functions for DoNotDev Framework - Firebase, Vercel, and platform-agnostic implementations for auth, billing, CRUD, and OAuth",
6
6
  "main": "./lib/firebase/index.js",
@@ -47,9 +47,9 @@
47
47
  "serve": "firebase emulators:start --only functions"
48
48
  },
49
49
  "dependencies": {
50
- "@donotdev/core": "^0.0.35",
51
- "@donotdev/firebase": "^0.0.18",
52
- "@donotdev/supabase": "^0.0.7"
50
+ "@donotdev/core": "^0.0.38",
51
+ "@donotdev/firebase": "^0.0.22",
52
+ "@donotdev/supabase": "^0.0.12"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "@sentry/node": "^10.39.0",
@@ -24,6 +24,23 @@ import type {
24
24
  CallableRequest,
25
25
  } from 'firebase-functions/v2/https';
26
26
 
27
+ /**
28
+ * Claim keys that must NEVER be self-assignable — privilege escalation vectors.
29
+ */
30
+ const BLOCKED_CLAIM_KEYS = new Set([
31
+ 'admin',
32
+ 'isAdmin',
33
+ 'isSuper',
34
+ 'isSuperAdmin',
35
+ 'role',
36
+ 'roles',
37
+ 'permissions',
38
+ 'superuser',
39
+ 'moderator',
40
+ 'staff',
41
+ 'elevated',
42
+ ]);
43
+
27
44
  const setCustomClaimsSchema = v.object({
28
45
  customClaims: v.record(v.string(), v.any()),
29
46
  idempotencyKey: v.optional(v.string()),
@@ -37,6 +54,12 @@ export type SetCustomClaimsResponse = {
37
54
  customClaims: Record<string, any>;
38
55
  };
39
56
 
57
+ export interface SetCustomClaimsOptions {
58
+ /** Explicit allowlist of claim keys users may set on themselves. Required. */
59
+ allowedClaimKeys: string[];
60
+ customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;
61
+ }
62
+
40
63
  /**
41
64
  * Business logic for setting custom claims
42
65
  * Base function handles: validation, auth, rate limiting, monitoring
@@ -45,18 +68,28 @@ export type SetCustomClaimsResponse = {
45
68
  * @since 0.0.1
46
69
  * @author AMBROISE PARK Consulting
47
70
  */
48
- async function setCustomClaimsLogic(
49
- data: SetCustomClaimsRequest,
50
- context: {
51
- uid: string;
52
- request: CallableRequest<SetCustomClaimsRequest>;
53
- }
54
- ) {
55
- const { customClaims, idempotencyKey } = data;
71
+ function createSetCustomClaimsLogic(allowedKeys: Set<string>) {
72
+ return async function setCustomClaimsLogic(
73
+ data: SetCustomClaimsRequest,
74
+ context: {
75
+ uid: string;
76
+ request: CallableRequest<SetCustomClaimsRequest>;
77
+ }
78
+ ) {
79
+ const { customClaims, idempotencyKey } = data;
56
80
 
57
- if (!customClaims || typeof customClaims !== 'object') {
58
- throw new Error('customClaims must be an object');
59
- }
81
+ if (!customClaims || typeof customClaims !== 'object') {
82
+ throw new Error('customClaims must be an object');
83
+ }
84
+
85
+ const disallowedKeys = Object.keys(customClaims).filter(
86
+ (k) => !allowedKeys.has(k)
87
+ );
88
+ if (disallowedKeys.length > 0) {
89
+ throw new Error(
90
+ `Claim keys not allowed: ${disallowedKeys.join(', ')}`
91
+ );
92
+ }
60
93
 
61
94
  // W17: Validate idempotency key to prevent oversized or malformed inputs.
62
95
  if (idempotencyKey !== undefined) {
@@ -131,27 +164,39 @@ async function setCustomClaimsLogic(
131
164
  }
132
165
 
133
166
  return result;
167
+ };
134
168
  }
135
169
 
136
170
  /**
137
- * Sets custom claims for a user
138
- * Base function handles all common concerns automatically
171
+ * Sets custom claims for a user, restricted to allowed keys.
172
+ * Consumers MUST specify which claim keys are self-assignable.
139
173
  *
140
174
  * @version 0.0.1
141
175
  * @since 0.0.1
142
176
  * @author AMBROISE PARK Consulting
143
177
  */
144
178
  export const setCustomClaims = (
145
- customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
179
+ options: SetCustomClaimsOptions
146
180
  ): CallableFunction<
147
181
  SetCustomClaimsRequest,
148
182
  Promise<SetCustomClaimsResponse>
149
183
  > => {
150
- const schema = customSchema || setCustomClaimsSchema;
184
+ const allowedKeys = new Set(options.allowedClaimKeys);
185
+
186
+ // Fail fast if consumer accidentally allows a privilege key
187
+ for (const key of allowedKeys) {
188
+ if (BLOCKED_CLAIM_KEYS.has(key)) {
189
+ throw new Error(
190
+ `Claim key "${key}" is blocked — it is a privilege-escalation vector and cannot be self-assigned.`
191
+ );
192
+ }
193
+ }
194
+
195
+ const schema = options.customSchema || setCustomClaimsSchema;
151
196
  return createBaseFunction(
152
197
  AUTH_CONFIG,
153
198
  schema,
154
199
  'set_custom_claims',
155
- setCustomClaimsLogic
200
+ createSetCustomClaimsLogic(allowedKeys)
156
201
  );
157
202
  };
@@ -20,49 +20,33 @@ import { STRIPE_CONFIG } from '../config/constants.js';
20
20
  * GET /billingHealth
21
21
  */
22
22
  export const billingHealth = onRequest(STRIPE_CONFIG, async (req, res) => {
23
- const checks: Record<string, string> = {};
24
23
  let overallStatus: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
25
24
 
26
25
  // Check Stripe connection
27
26
  try {
28
27
  await stripe.products.list({ limit: 1 });
29
- checks.stripe = 'connected';
30
- } catch (error) {
31
- checks.stripe = 'error';
28
+ } catch {
32
29
  overallStatus = 'unhealthy';
33
30
  }
34
31
 
35
32
  // Check idempotency storage
36
- checks.idempotency = isFirestoreConfigured() ? 'firestore' : 'in-memory';
37
- if (checks.idempotency === 'in-memory') {
33
+ if (!isFirestoreConfigured()) {
38
34
  overallStatus = overallStatus === 'healthy' ? 'degraded' : overallStatus;
39
35
  }
40
36
 
41
- // Check environment variables
37
+ // Check environment variables (don't expose which ones)
42
38
  const requiredEnvVars = [
43
39
  'STRIPE_SECRET_KEY',
44
40
  'STRIPE_WEBHOOK_SECRET',
45
41
  'STRIPE_API_VERSION',
46
42
  ];
47
- const missingEnvVars = requiredEnvVars.filter((v) => !process.env[v]);
48
- checks.environment = missingEnvVars.length === 0 ? 'configured' : 'missing';
49
- if (missingEnvVars.length > 0) {
50
- checks.missingEnvVars = missingEnvVars.join(', ');
43
+ if (requiredEnvVars.some((v) => !process.env[v])) {
51
44
  overallStatus = 'unhealthy';
52
45
  }
53
46
 
54
- const health = {
47
+ const statusCode = overallStatus === 'unhealthy' ? 503 : 200;
48
+ res.status(statusCode).json({
55
49
  status: overallStatus,
56
50
  timestamp: Date.now(),
57
- checks,
58
- version: process.env.STRIPE_API_VERSION || 'unknown',
59
- };
60
-
61
- const statusCode =
62
- overallStatus === 'healthy'
63
- ? 200
64
- : overallStatus === 'degraded'
65
- ? 200
66
- : 503;
67
- res.status(statusCode).json(health);
51
+ });
68
52
  });
@@ -65,7 +65,6 @@ export function createStripeWebhook(
65
65
  const error = new Error('No Stripe signature found');
66
66
  logger.error('[Webhook] Missing signature', {
67
67
  error,
68
- headers: req.headers,
69
68
  operation: 'webhook_signature_validation',
70
69
  });
71
70
  throw handleError(error);
@@ -256,8 +256,23 @@ function createEntityLogicFactory(
256
256
  // For drafts: validate field types that ARE present, but allow missing required fields
257
257
  try {
258
258
  validateDocument(normalizedPayload, documentSchema);
259
- } catch {
260
- // Swallow required-field errors for drafts — type errors would still throw from Valibot
259
+ } catch (error: any) {
260
+ // Only swallow required-field errors; re-throw type mismatches
261
+ const issues = error?.issues ?? error?.cause?.issues;
262
+ if (issues && Array.isArray(issues)) {
263
+ const nonRequiredIssues = issues.filter(
264
+ (issue: any) =>
265
+ issue.type !== 'non_optional' &&
266
+ issue.type !== 'non_nullish' &&
267
+ issue.type !== 'non_nullable'
268
+ );
269
+ if (nonRequiredIssues.length > 0) {
270
+ throw error;
271
+ }
272
+ } else {
273
+ // Not a Valibot error — re-throw
274
+ throw error;
275
+ }
261
276
  }
262
277
  }
263
278
 
@@ -57,6 +57,11 @@ export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
57
57
  }
58
58
  }
59
59
 
60
+ // Validate required parameters BEFORE reserving idempotency key
61
+ if (!provider || !purpose || !code || !redirectUri) {
62
+ throw new HttpsError('invalid-argument', 'Missing required parameters');
63
+ }
64
+
60
65
  // C9: Atomic idempotency check using Firestore transaction to prevent TOCTOU race.
61
66
  // A concurrent request with the same key would see the 'pending' sentinel and wait
62
67
  // or return early instead of executing duplicate business logic.
@@ -88,11 +93,6 @@ export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
88
93
  }
89
94
  }
90
95
 
91
- // Validate required parameters
92
- if (!provider || !purpose || !code || !redirectUri) {
93
- throw new HttpsError('invalid-argument', 'Missing required parameters');
94
- }
95
-
96
96
  try {
97
97
  // Get provider endpoints
98
98
  const endpoints = OAUTH_PARTNERS[provider];
@@ -91,6 +91,11 @@ export async function createCheckoutAlgorithm(
91
91
  throw new Error('Price ID mismatch with configuration');
92
92
  }
93
93
 
94
+ // ✅ VALIDATE: userId exists
95
+ if (!userId) {
96
+ throw new Error('Missing userId in request');
97
+ }
98
+
94
99
  // Verify user exists
95
100
  await authProvider.getUser(userId);
96
101
 
@@ -101,7 +106,7 @@ export async function createCheckoutAlgorithm(
101
106
  metadata: {
102
107
  ...metadata,
103
108
  userId,
104
- billingConfigKey: configKey, // ✅ Server values AFTER spread — cannot be overwritten by client
109
+ billingConfigKey: configKey as string, // ✅ Server values AFTER spread — cannot be overwritten by client
105
110
  },
106
111
  allowPromotionCodes,
107
112
  successUrl: successUrl || `${process.env.FRONTEND_URL}/billing/success`,
@@ -102,7 +102,7 @@ export function validateDocument(data: any, schema?: any): void {
102
102
  const messages = result.issues
103
103
  .map(
104
104
  (issue) =>
105
- `${issue.path?.map((p) => (p as any).key).join('.') || 'root'}: ${issue.message}`
105
+ `${issue.path?.map((p: { key: string }) => p.key).join('.') || 'root'}: ${issue.message}`
106
106
  )
107
107
  .join('; ');
108
108
  throw new DoNotDevError(
@@ -12,7 +12,7 @@
12
12
  import * as v from 'valibot';
13
13
 
14
14
  import type { UserRole } from '@donotdev/core/server';
15
- import { defaultFieldMapper } from '@donotdev/supabase';
15
+ import { defaultFieldMapper } from '@donotdev/supabase/server';
16
16
 
17
17
  import { DoNotDevError } from '../../shared/utils.js';
18
18
  import { createSupabaseHandler } from '../baseFunction.js';
@@ -88,7 +88,8 @@ export function createSupabaseAggregateEntities(
88
88
  const { supabaseAdmin } = ctx;
89
89
 
90
90
  const aggregateColumn = mapper.toBackendField(aggregate.field);
91
- let query = supabaseAdmin.from(collection);
91
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Dynamic aggregate builder; Supabase types change across chained calls
92
+ let query: any = supabaseAdmin.from(collection);
92
93
 
93
94
  for (const [field, operator, value] of where) {
94
95
  query = applyOperator(
@@ -143,9 +144,9 @@ export function createSupabaseAggregateEntities(
143
144
  } else {
144
145
  // Calculate aggregate from rows
145
146
  const values = (rows || ([] as any[]))
146
- .map((row) => row[aggregateColumn])
147
- .filter((v) => v != null && !isNaN(Number(v)))
148
- .map((v) => Number(v));
147
+ .map((row: any) => row[aggregateColumn])
148
+ .filter((v: any) => v != null && !isNaN(Number(v)))
149
+ .map((v: any) => Number(v));
149
150
 
150
151
  if (values.length === 0) {
151
152
  return { value: 0 };
@@ -154,10 +155,12 @@ export function createSupabaseAggregateEntities(
154
155
  let result: number;
155
156
  switch (aggregate.operation) {
156
157
  case 'sum':
157
- result = values.reduce((a, b) => a + b, 0);
158
+ result = values.reduce((a: number, b: number) => a + b, 0);
158
159
  break;
159
160
  case 'avg':
160
- result = values.reduce((a, b) => a + b, 0) / values.length;
161
+ result =
162
+ values.reduce((a: number, b: number) => a + b, 0) /
163
+ values.length;
161
164
  break;
162
165
  case 'min':
163
166
  result = Math.min(...values);
@@ -16,7 +16,7 @@ import {
16
16
  filterVisibleFields,
17
17
  } from '@donotdev/core/server';
18
18
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
19
- import { defaultFieldMapper } from '@donotdev/supabase';
19
+ import { defaultFieldMapper } from '@donotdev/supabase/server';
20
20
 
21
21
  import { createMetadata } from '../../shared/index.js';
22
22
  import { DoNotDevError, validateDocument } from '../../shared/utils.js';
@@ -21,7 +21,7 @@ import {
21
21
  createEntityAwareMapper,
22
22
  defaultFieldMapper,
23
23
  getEntityFieldNames,
24
- } from '@donotdev/supabase';
24
+ } from '@donotdev/supabase/server';
25
25
 
26
26
  import { DoNotDevError } from '../../shared/utils.js';
27
27
  import { createSupabaseHandler } from '../baseFunction.js';
@@ -25,7 +25,7 @@ import {
25
25
  createEntityAwareMapper,
26
26
  defaultFieldMapper,
27
27
  getEntityFieldNames,
28
- } from '@donotdev/supabase';
28
+ } from '@donotdev/supabase/server';
29
29
 
30
30
  import { DoNotDevError } from '../../shared/utils.js';
31
31
  import { createSupabaseHandler } from '../baseFunction.js';
@@ -12,7 +12,7 @@
12
12
  import * as v from 'valibot';
13
13
 
14
14
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
15
- import { defaultFieldMapper } from '@donotdev/supabase';
15
+ import { defaultFieldMapper } from '@donotdev/supabase/server';
16
16
 
17
17
  import { updateMetadata } from '../../shared/index.js';
18
18
  import { DoNotDevError, validateDocument } from '../../shared/utils.js';
@@ -16,35 +16,82 @@ import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
16
16
 
17
17
  import type { NextApiRequest, NextApiResponse } from 'next';
18
18
 
19
- export default async function handler(
20
- req: NextApiRequest,
21
- res: NextApiResponse
19
+ /**
20
+ * Claim keys that must NEVER be self-assignable — privilege escalation vectors.
21
+ */
22
+ const BLOCKED_CLAIM_KEYS = new Set([
23
+ 'admin',
24
+ 'isAdmin',
25
+ 'isSuper',
26
+ 'isSuperAdmin',
27
+ 'role',
28
+ 'roles',
29
+ 'permissions',
30
+ 'superuser',
31
+ 'moderator',
32
+ 'staff',
33
+ 'elevated',
34
+ ]);
35
+
36
+ export interface SetCustomClaimsHandlerOptions {
37
+ /** Explicit allowlist of claim keys users may set on themselves. Required. */
38
+ allowedClaimKeys: string[];
39
+ }
40
+
41
+ /**
42
+ * Factory that returns a set-custom-claims handler scoped to allowed keys.
43
+ * Consumers MUST specify which claim keys are self-assignable.
44
+ */
45
+ export function createSetCustomClaimsHandler(
46
+ options: SetCustomClaimsHandlerOptions
22
47
  ) {
23
- if (req.method !== 'POST') {
24
- return res.status(405).json({ error: 'Method not allowed' });
25
- }
48
+ const allowedKeys = new Set(options.allowedClaimKeys);
26
49
 
27
- try {
28
- // C1: verifyAuthToken extracts the Bearer token and verifies the JWT.
29
- // The previous assertAuthenticated(req.headers.authorization) only checked
30
- // that the header was non-empty — it never verified the signature.
31
- const uid = await verifyAuthToken(req);
32
- const { customClaims } = req.body;
50
+ // Fail fast if consumer accidentally allows a privilege key
51
+ for (const key of allowedKeys) {
52
+ if (BLOCKED_CLAIM_KEYS.has(key)) {
53
+ throw new Error(
54
+ `Claim key "${key}" is blocked — it is a privilege-escalation vector and cannot be self-assigned.`
55
+ );
56
+ }
57
+ }
33
58
 
34
- if (!customClaims || typeof customClaims !== 'object') {
35
- throw handleError(new Error('customClaims must be an object'));
59
+ return async function handler(req: NextApiRequest, res: NextApiResponse) {
60
+ if (req.method !== 'POST') {
61
+ return res.status(405).json({ error: 'Method not allowed' });
36
62
  }
37
63
 
38
- const user = await getFirebaseAdminAuth().getUser(uid);
39
- const currentClaims = user.customClaims || {};
64
+ try {
65
+ const uid = await verifyAuthToken(req);
66
+ const { customClaims } = req.body;
40
67
 
41
- // Merge with existing claims
42
- const updatedClaims = { ...currentClaims, ...customClaims };
68
+ if (!customClaims || typeof customClaims !== 'object') {
69
+ throw handleError(new Error('customClaims must be an object'));
70
+ }
43
71
 
44
- await getFirebaseAdminAuth().setCustomUserClaims(uid, updatedClaims);
72
+ const disallowedKeys = Object.keys(customClaims).filter(
73
+ (k) => !allowedKeys.has(k)
74
+ );
75
+ if (disallowedKeys.length > 0) {
76
+ throw handleError(
77
+ new Error(
78
+ `Claim keys not allowed: ${disallowedKeys.join(', ')}`
79
+ )
80
+ );
81
+ }
45
82
 
46
- return res.status(200).json({ success: true, customClaims: updatedClaims });
47
- } catch (error) {
48
- throw handleError(error);
49
- }
83
+ const user = await getFirebaseAdminAuth().getUser(uid);
84
+ const currentClaims = user.customClaims || {};
85
+
86
+ const updatedClaims = { ...currentClaims, ...customClaims };
87
+
88
+ await getFirebaseAdminAuth().setCustomUserClaims(uid, updatedClaims);
89
+
90
+ return res
91
+ .status(200)
92
+ .json({ success: true, customClaims: updatedClaims });
93
+ } catch (error) {
94
+ throw handleError(error);
95
+ }
96
+ };
50
97
  }