@donotdev/functions 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/guidelines/FUNCTIONS.md +9 -0
  2. package/guidelines/VERCEL.md +260 -0
  3. package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
  4. package/lib/firebase/index.js +3 -3
  5. package/lib/firebase/index.js.map +4 -4
  6. package/lib/shared/ai/classifyAIError.d.ts +35 -0
  7. package/lib/shared/ai/costTracker.d.ts +20 -0
  8. package/lib/shared/ai/createAIRoute.d.ts +20 -0
  9. package/lib/shared/ai/index.d.ts +6 -0
  10. package/lib/shared/ai/resolveModelTier.d.ts +14 -0
  11. package/lib/shared/billing/createCheckout.d.ts +8 -2
  12. package/lib/shared/email/createEmailRoute.d.ts +30 -0
  13. package/lib/shared/email/index.d.ts +3 -0
  14. package/lib/shared/email/provider.d.ts +30 -0
  15. package/lib/shared/email/resendProvider.d.ts +22 -0
  16. package/lib/shared/github.d.ts +5 -0
  17. package/lib/shared/index.d.ts +2 -0
  18. package/lib/shared/index.js +4 -3
  19. package/lib/shared/index.js.map +4 -4
  20. package/lib/shared/logger.d.ts +2 -0
  21. package/lib/shared/oauth/exchangeToken.d.ts +1 -0
  22. package/lib/shared/oauth/grantAccess.d.ts +1 -0
  23. package/lib/shared/utils/internal/idempotency.d.ts +1 -0
  24. package/lib/supabase/ai/createAIFunction.d.ts +30 -0
  25. package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
  26. package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
  27. package/lib/supabase/billing/changePlan.d.ts +1 -1
  28. package/lib/supabase/crud/aggregate.d.ts +1 -0
  29. package/lib/supabase/crud/create.d.ts +1 -0
  30. package/lib/supabase/crud/delete.d.ts +1 -0
  31. package/lib/supabase/crud/get.d.ts +1 -0
  32. package/lib/supabase/crud/list.d.ts +1 -0
  33. package/lib/supabase/crud/update.d.ts +1 -0
  34. package/lib/supabase/edgeFunction.d.ts +56 -0
  35. package/lib/supabase/email/createEmailFunction.d.ts +31 -0
  36. package/lib/supabase/index.d.ts +8 -0
  37. package/lib/supabase/index.js +3 -2
  38. package/lib/supabase/index.js.map +4 -4
  39. package/lib/vercel/api/ai/chat.d.ts +29 -0
  40. package/lib/vercel/api/ai/index.d.ts +1 -0
  41. package/lib/vercel/api/index.d.ts +1 -0
  42. package/lib/vercel/api/index.js +3 -2
  43. package/lib/vercel/api/index.js.map +4 -4
  44. package/package.json +38 -5
  45. package/src/firebase/billing/createCheckoutSession.ts +79 -187
  46. package/src/firebase/oauth/exchangeToken.ts +4 -4
  47. package/src/firebase/oauth/refreshToken.ts +4 -4
  48. package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
  49. package/src/shared/ai/classifyAIError.ts +163 -0
  50. package/src/shared/ai/costTracker.ts +51 -0
  51. package/src/shared/ai/createAIRoute.ts +397 -0
  52. package/src/shared/ai/index.ts +8 -0
  53. package/src/shared/ai/resolveModelTier.ts +58 -0
  54. package/src/shared/billing/createCheckout.ts +153 -8
  55. package/src/shared/billing/helpers/subscriptionManagement.ts +9 -0
  56. package/src/shared/billing/idempotency.ts +5 -0
  57. package/src/shared/email/createEmailRoute.ts +81 -0
  58. package/src/shared/email/index.ts +5 -0
  59. package/src/shared/email/provider.ts +31 -0
  60. package/src/shared/email/resendProvider.ts +56 -0
  61. package/src/shared/errorHandling.ts +10 -4
  62. package/src/shared/github.ts +38 -0
  63. package/src/shared/index.ts +2 -0
  64. package/src/shared/logger.ts +2 -0
  65. package/src/shared/oauth/exchangeToken.ts +1 -0
  66. package/src/shared/oauth/grantAccess.ts +1 -0
  67. package/src/shared/utils/internal/idempotency.ts +1 -0
  68. package/src/shared/utils/internal/rateLimiter.ts +6 -3
  69. package/src/shared/validation.ts +1 -1
  70. package/src/supabase/ai/createAIFunction.ts +75 -0
  71. package/src/supabase/auth/removeCustomClaims.ts +38 -2
  72. package/src/supabase/auth/setCustomClaims.ts +66 -5
  73. package/src/supabase/baseFunction.ts +26 -2
  74. package/src/supabase/billing/changePlan.ts +6 -1
  75. package/src/supabase/billing/createCheckoutSession.ts +16 -2
  76. package/src/supabase/crud/aggregate.ts +1 -0
  77. package/src/supabase/crud/create.ts +1 -0
  78. package/src/supabase/crud/delete.ts +1 -0
  79. package/src/supabase/crud/get.ts +1 -0
  80. package/src/supabase/crud/list.ts +1 -0
  81. package/src/supabase/crud/update.ts +1 -0
  82. package/src/supabase/edgeFunction.ts +195 -0
  83. package/src/supabase/email/createEmailFunction.ts +75 -0
  84. package/src/supabase/index.ts +12 -0
  85. package/src/supabase/oauth/exchangeToken.ts +38 -7
  86. package/src/supabase/oauth/refreshToken.ts +4 -5
  87. package/src/supabase/registerCrudFunctions.ts +29 -41
  88. package/src/supabase/utils/idempotency.ts +6 -2
  89. package/src/vercel/api/ai/chat.ts +77 -0
  90. package/src/vercel/api/ai/index.ts +1 -0
  91. package/src/vercel/api/billing/create-checkout-session.ts +27 -4
  92. package/src/vercel/api/billing/webhook-handler.ts +8 -1
  93. package/src/vercel/api/index.ts +1 -0
  94. package/src/vercel/api/oauth/exchange-token.ts +24 -1
  95. package/src/vercel/api/utils/cors.ts +6 -0
@@ -24,7 +24,13 @@ import type {
24
24
  */
25
25
  export interface StripeCheckoutProvider {
26
26
  createCheckoutSession(params: {
27
- priceId: string;
27
+ priceId?: string;
28
+ /** Amount in cents (dynamic pricing mode) */
29
+ unitAmount?: number;
30
+ /** Product name for Stripe checkout (dynamic pricing mode) */
31
+ productName?: string;
32
+ /** Currency code, defaults to 'eur' */
33
+ currency?: string;
28
34
  customerEmail?: string;
29
35
  metadata: Record<string, string>;
30
36
  allowPromotionCodes: boolean;
@@ -50,10 +56,64 @@ export interface AuthCheckoutProvider {
50
56
  }>;
51
57
  }
52
58
 
59
+ /**
60
+ * Validate URL has http/https protocol.
61
+ * Platform-agnostic (no firebase logger dependency).
62
+ */
63
+ function validateCheckoutUrl(url: string, name: string): void {
64
+ try {
65
+ const parsed = new URL(url);
66
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
67
+ throw new Error(`Invalid protocol: ${parsed.protocol}`);
68
+ }
69
+ } catch (error) {
70
+ throw new Error(
71
+ `Invalid ${name} URL: ${url}. ${error instanceof Error ? error.message : 'Invalid URL format'}`
72
+ );
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Sanitize metadata: enforce string values, strip script injection, cap lengths.
78
+ * Platform-agnostic (no firebase logger dependency).
79
+ */
80
+ function sanitizeMetadata(
81
+ metadata: Record<string, any>
82
+ ): Record<string, string> {
83
+ const sanitized: Record<string, string> = {};
84
+
85
+ for (const [key, value] of Object.entries(metadata)) {
86
+ if (typeof value !== 'string') {
87
+ throw new Error(
88
+ `Metadata value for key '${key}' must be a string, got ${typeof value}`
89
+ );
90
+ }
91
+
92
+ const sanitizedValue = value
93
+ .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
94
+ .replace(/javascript:/gi, '')
95
+ .replace(/on\w+\s*=/gi, '');
96
+
97
+ if (sanitizedValue.length > 1000) {
98
+ throw new Error(
99
+ `Metadata value for key '${key}' is too long (max 1000 characters)`
100
+ );
101
+ }
102
+
103
+ if (key.length > 100) {
104
+ throw new Error(`Metadata key '${key}' is too long (max 100 characters)`);
105
+ }
106
+
107
+ sanitized[key] = sanitizedValue;
108
+ }
109
+
110
+ return sanitized;
111
+ }
112
+
53
113
  /**
54
114
  * Create checkout session algorithm
55
115
  *
56
- * @version 0.1.0
116
+ * @version 0.2.0
57
117
  * @since 0.0.1
58
118
  * @author AMBROISE PARK Consulting
59
119
  */
@@ -63,8 +123,15 @@ export async function createCheckoutAlgorithm(
63
123
  authProvider: AuthCheckoutProvider,
64
124
  billingConfig: StripeBackConfig
65
125
  ): Promise<CreateCheckoutSessionResponse> {
126
+ if (!process.env.FRONTEND_URL) {
127
+ throw new Error('FRONTEND_URL environment variable is required');
128
+ }
129
+
66
130
  const {
67
131
  priceId,
132
+ unitAmount,
133
+ productName,
134
+ currency,
68
135
  userId,
69
136
  customerEmail,
70
137
  metadata = {},
@@ -86,9 +153,41 @@ export async function createCheckoutAlgorithm(
86
153
  throw new Error(`Invalid billing config key: ${configKey}`);
87
154
  }
88
155
 
89
- // ✅ VALIDATE: priceId matches config
90
- if (billingItem.priceId !== priceId) {
91
- throw new Error('Price ID mismatch with configuration');
156
+ // ✅ VALIDATE: either priceId or (unitAmount + productName)
157
+ const useDynamicPricing = !priceId && unitAmount && productName;
158
+ if (!priceId && !useDynamicPricing) {
159
+ throw new Error(
160
+ 'Either priceId or (unitAmount + productName) is required'
161
+ );
162
+ }
163
+
164
+ // ✅ VALIDATE: price_data not supported for subscriptions
165
+ if (useDynamicPricing && mode === 'subscription') {
166
+ throw new Error(
167
+ 'Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.'
168
+ );
169
+ }
170
+
171
+ if (priceId) {
172
+ // Fixed pricing: validate priceId matches config (if config has one)
173
+ if (billingItem.priceId && billingItem.priceId !== priceId) {
174
+ throw new Error('Price ID mismatch with configuration');
175
+ }
176
+ } else {
177
+ // Dynamic pricing: maxUnitAmount is required as a security cap
178
+ if (!billingItem.maxUnitAmount) {
179
+ throw new Error(
180
+ 'Dynamic pricing requires maxUnitAmount in billing config for security'
181
+ );
182
+ }
183
+ if (unitAmount! > billingItem.maxUnitAmount) {
184
+ throw new Error(
185
+ `Unit amount ${unitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
186
+ );
187
+ }
188
+ if (unitAmount! < 100) {
189
+ throw new Error('Unit amount must be at least 100 cents (1.00)');
190
+ }
92
191
  }
93
192
 
94
193
  // ✅ VALIDATE: userId exists
@@ -99,18 +198,64 @@ export async function createCheckoutAlgorithm(
99
198
  // Verify user exists
100
199
  await authProvider.getUser(userId);
101
200
 
201
+ // ✅ HOOK: beforeCheckout (ownership check, status validation, server-resolved pricing)
202
+ let finalUnitAmount = unitAmount;
203
+ let finalProductName = productName;
204
+
205
+ if (billingItem.beforeCheckout) {
206
+ const hookResult = await billingItem.beforeCheckout(
207
+ userId,
208
+ { priceId, unitAmount, productName, currency, mode, metadata, allowPromotionCodes },
209
+ sanitizeMetadata(metadata)
210
+ );
211
+
212
+ if (!hookResult.allowed) {
213
+ throw new Error(hookResult.reason || 'Checkout blocked by beforeCheckout hook');
214
+ }
215
+
216
+ if (hookResult.overrides) {
217
+ if (hookResult.overrides.unitAmount !== undefined) {
218
+ finalUnitAmount = hookResult.overrides.unitAmount;
219
+ }
220
+ if (hookResult.overrides.productName !== undefined) {
221
+ finalProductName = hookResult.overrides.productName;
222
+ }
223
+ }
224
+ }
225
+
226
+ const finalUseDynamicPricing = !priceId && finalUnitAmount && finalProductName;
227
+
228
+ // ✅ VALIDATE: overridden amount still respects security cap
229
+ if (finalUseDynamicPricing && billingItem.maxUnitAmount && finalUnitAmount! > billingItem.maxUnitAmount) {
230
+ throw new Error(
231
+ `Hook-overridden unit amount ${finalUnitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
232
+ );
233
+ }
234
+
235
+ // ✅ VALIDATE: URLs are valid http/https
236
+ const resolvedSuccessUrl = successUrl || `${process.env.FRONTEND_URL}/billing/success`;
237
+ const resolvedCancelUrl = cancelUrl || `${process.env.FRONTEND_URL}/billing/cancel`;
238
+ validateCheckoutUrl(resolvedSuccessUrl, 'success');
239
+ validateCheckoutUrl(resolvedCancelUrl, 'cancel');
240
+
241
+ // ✅ SANITIZE: metadata values (strip scripts, cap lengths)
242
+ const sanitizedMetadata = sanitizeMetadata(metadata);
243
+
102
244
  // Create checkout session
103
245
  const session = await stripeProvider.createCheckoutSession({
104
246
  priceId,
247
+ unitAmount: finalUseDynamicPricing ? finalUnitAmount : undefined,
248
+ productName: finalUseDynamicPricing ? finalProductName : undefined,
249
+ currency: currency || billingItem.currency || 'eur',
105
250
  customerEmail,
106
251
  metadata: {
107
- ...metadata,
252
+ ...sanitizedMetadata,
108
253
  userId,
109
254
  billingConfigKey: configKey as string, // ✅ Server values AFTER spread — cannot be overwritten by client
110
255
  },
111
256
  allowPromotionCodes,
112
- successUrl: successUrl || `${process.env.FRONTEND_URL}/billing/success`,
113
- cancelUrl: cancelUrl || `${process.env.FRONTEND_URL}/billing/cancel`,
257
+ successUrl: resolvedSuccessUrl,
258
+ cancelUrl: resolvedCancelUrl,
114
259
  mode,
115
260
  });
116
261
 
@@ -208,6 +208,15 @@ export async function createCustomerPortalSession(
208
208
  throw handleError(new Error('No customer found'));
209
209
  }
210
210
 
211
+ // Validate returnUrl domain
212
+ if (returnUrl) {
213
+ const parsed = new URL(returnUrl);
214
+ const frontendUrl = new URL(process.env.FRONTEND_URL || '');
215
+ if (parsed.origin !== frontendUrl.origin) {
216
+ throw new Error('Invalid return URL: must match frontend domain');
217
+ }
218
+ }
219
+
211
220
  // Create portal session
212
221
  const session = await stripe.billingPortal.sessions.create({
213
222
  customer: customerId,
@@ -57,6 +57,11 @@ class InMemoryIdempotency implements IdempotencyStore {
57
57
  }
58
58
  }
59
59
 
60
+ /**
61
+ * @limitation Not truly atomic for concurrent async operations within the same event loop tick.
62
+ * Two webhook retries arriving simultaneously could both pass the check.
63
+ * For production billing, use the Firestore/Supabase implementations which provide true atomicity.
64
+ */
60
65
  async checkAndReserve(eventId: string): Promise<boolean> {
61
66
  if (this.store.has(eventId)) return true;
62
67
  this.store.add(eventId);
@@ -0,0 +1,81 @@
1
+ // packages/functions/src/shared/email/createEmailRoute.ts
2
+
3
+ /**
4
+ * @fileoverview Email Route Handler
5
+ * @description Platform-agnostic handler for email send requests.
6
+ * Validates request, resolves template, renders with locale, sends via provider.
7
+ *
8
+ * @version 0.1.0
9
+ * @since 0.1.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import type {
14
+ EmailRouteConfig,
15
+ SendEmailRequest,
16
+ SendEmailResponse,
17
+ } from '@donotdev/core/server';
18
+ import { validateSendEmailRequest } from '@donotdev/core/server';
19
+
20
+ import type { EmailProviderAdapter } from './provider.js';
21
+
22
+ /**
23
+ * Handle an email send request.
24
+ * Validates input, resolves the template from the registry, renders with locale, and sends.
25
+ *
26
+ * @param request - Email send request (templateId, to, data, locale)
27
+ * @param config - Email route configuration (provider, templates, defaultFrom)
28
+ * @param provider - Email provider adapter (Resend, etc.)
29
+ * @returns Send result with success status and messageId
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * const result = await handleEmailRequest(
34
+ * { templateId: 'order-confirmation', to: 'user@example.com', data: { orderId: '123' }, locale: 'fr' },
35
+ * emailConfig,
36
+ * resendProvider
37
+ * );
38
+ * ```
39
+ */
40
+ export async function handleEmailRequest(
41
+ request: SendEmailRequest,
42
+ config: EmailRouteConfig,
43
+ provider: EmailProviderAdapter
44
+ ): Promise<SendEmailResponse> {
45
+ // Validate request
46
+ const validation = validateSendEmailRequest(request);
47
+ if (!validation.success) {
48
+ return {
49
+ success: false,
50
+ error: `Invalid email request: ${validation.issues?.map((i) => i.message).join(', ')}`,
51
+ };
52
+ }
53
+
54
+ // Resolve template
55
+ const template = config.templates[request.templateId];
56
+ if (!template) {
57
+ return {
58
+ success: false,
59
+ error: `Template not found: ${request.templateId}`,
60
+ };
61
+ }
62
+
63
+ // Render template with locale
64
+ const locale = request.locale || 'fr';
65
+ const subject = template.subject(request.data as any, locale);
66
+ const html = template.html(request.data as any, locale);
67
+
68
+ // Send via provider
69
+ const result = await provider.send({
70
+ from: request.from || config.defaultFrom,
71
+ to: request.to,
72
+ subject,
73
+ html,
74
+ replyTo: request.replyTo || config.replyTo,
75
+ });
76
+
77
+ return {
78
+ success: true,
79
+ messageId: result.messageId,
80
+ };
81
+ }
@@ -0,0 +1,5 @@
1
+ // packages/functions/src/shared/email/index.ts
2
+
3
+ export { handleEmailRequest } from './createEmailRoute.js';
4
+ export type { EmailProviderAdapter } from './provider.js';
5
+ export { createResendProvider } from './resendProvider.js';
@@ -0,0 +1,31 @@
1
+ // packages/functions/src/shared/email/provider.ts
2
+
3
+ /**
4
+ * @fileoverview Email Provider Adapter Interface
5
+ * @description Abstract interface for email sending. Providers implement this.
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.1.0
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+
12
+ /**
13
+ * Email provider adapter interface.
14
+ * Each provider (Resend, SES, etc.) implements this single method.
15
+ */
16
+ export interface EmailProviderAdapter {
17
+ /**
18
+ * Send an email via the provider.
19
+ *
20
+ * @param params - Email parameters
21
+ * @returns Provider message ID for tracking
22
+ * @throws On provider error (network, auth, etc.)
23
+ */
24
+ send(params: {
25
+ from: string;
26
+ to: string;
27
+ subject: string;
28
+ html: string;
29
+ replyTo?: string;
30
+ }): Promise<{ messageId: string }>;
31
+ }
@@ -0,0 +1,56 @@
1
+ // packages/functions/src/shared/email/resendProvider.ts
2
+
3
+ /**
4
+ * @fileoverview Resend Email Provider
5
+ * @description Zero-dependency Resend implementation using raw fetch.
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.1.0
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+
12
+ import type { EmailProviderAdapter } from './provider.js';
13
+
14
+ const RESEND_API_URL = 'https://api.resend.com/emails';
15
+
16
+ /**
17
+ * Create a Resend email provider adapter.
18
+ *
19
+ * @param apiKey - Resend API key
20
+ * @returns EmailProviderAdapter implementation
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * const provider = createResendProvider(Deno.env.get('RESEND_API_KEY')!);
25
+ * await provider.send({ from: 'noreply@app.com', to: 'user@example.com', subject: 'Hello', html: '<p>Hi</p>' });
26
+ * ```
27
+ */
28
+ export function createResendProvider(apiKey: string): EmailProviderAdapter {
29
+ if (!apiKey) {
30
+ throw new Error('Resend API key is required');
31
+ }
32
+
33
+ return {
34
+ async send({ from, to, subject, html, replyTo }) {
35
+ const body: Record<string, string> = { from, to, subject, html };
36
+ if (replyTo) body.reply_to = replyTo;
37
+
38
+ const response = await fetch(RESEND_API_URL, {
39
+ method: 'POST',
40
+ headers: {
41
+ 'Authorization': `Bearer ${apiKey}`,
42
+ 'Content-Type': 'application/json',
43
+ },
44
+ body: JSON.stringify(body),
45
+ });
46
+
47
+ if (!response.ok) {
48
+ const errorText = await response.text().catch(() => 'Unknown error');
49
+ throw new Error(`Resend API error (${response.status}): ${errorText}`);
50
+ }
51
+
52
+ const result = await response.json();
53
+ return { messageId: result.id };
54
+ },
55
+ };
56
+ }
@@ -89,13 +89,19 @@ export function handleError(error: unknown): never {
89
89
  details = undefined;
90
90
  } else {
91
91
  code = 'internal';
92
- // W10: Never expose error.stack in details — it leaks internal file paths
93
- // and implementation details to clients. Log server-side only.
94
- message =
95
- error instanceof Error ? error.message : 'An unexpected error occurred';
92
+ // W10: Never expose error.message for internal errors — it may leak
93
+ // internal file paths, SQL queries, or implementation details to clients.
94
+ // Log server-side only; clients always get the generic message.
95
+ message = 'An unexpected error occurred';
96
96
  details = undefined;
97
97
  }
98
98
 
99
+ // For internal errors, always use the generic message regardless of source.
100
+ // Other error codes may carry safe, developer-authored messages.
101
+ if (code === 'internal') {
102
+ message = 'An unexpected error occurred';
103
+ }
104
+
99
105
  throw new DoNotDevError(
100
106
  message,
101
107
  code as any,
@@ -9,11 +9,13 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ /** Configuration for authenticating with the GitHub API. */
12
13
  export interface GitHubApiConfig {
13
14
  accessToken: string;
14
15
  baseUrl?: string;
15
16
  }
16
17
 
18
+ /** GitHub user profile returned by the API. */
17
19
  export interface GitHubUser {
18
20
  id: number;
19
21
  login: string;
@@ -22,6 +24,7 @@ export interface GitHubUser {
22
24
  avatar_url: string;
23
25
  }
24
26
 
27
+ /** GitHub repository metadata returned by the API. */
25
28
  export interface GitHubRepository {
26
29
  id: number;
27
30
  name: string;
@@ -33,6 +36,7 @@ export interface GitHubRepository {
33
36
  };
34
37
  }
35
38
 
39
+ /** Request payload for adding a collaborator to a GitHub repository. */
36
40
  export interface AddCollaboratorRequest {
37
41
  owner: string;
38
42
  repo: string;
@@ -40,12 +44,25 @@ export interface AddCollaboratorRequest {
40
44
  permission?: 'pull' | 'triage' | 'push' | 'maintain' | 'admin';
41
45
  }
42
46
 
47
+ /** Error response structure from the GitHub API. */
43
48
  export interface GitHubApiError {
44
49
  message: string;
45
50
  documentation_url?: string;
46
51
  status?: number;
47
52
  }
48
53
 
54
+ /** Pattern for valid GitHub usernames, org names, repo names, and team slugs */
55
+ const SAFE_GITHUB_NAME = /^[a-zA-Z0-9_.-]+$/;
56
+
57
+ /** Validate a GitHub name (username, owner, repo, team slug) against path injection */
58
+ function validateGitHubName(name: string, label: string): void {
59
+ if (!SAFE_GITHUB_NAME.test(name)) {
60
+ throw new Error(
61
+ `Invalid ${label}: must contain only alphanumeric, hyphens, underscores, and dots`
62
+ );
63
+ }
64
+ }
65
+
49
66
  /**
50
67
  * GitHub API Service for server-side operations
51
68
  *
@@ -83,6 +100,9 @@ export class GitHubApiService {
83
100
  * @author AMBROISE PARK Consulting
84
101
  */
85
102
  async getUserRepositories(username?: string): Promise<GitHubRepository[]> {
103
+ if (username) {
104
+ validateGitHubName(username, 'username');
105
+ }
86
106
  const endpoint = username ? `/users/${username}/repos` : '/user/repos';
87
107
  const response = await this.request<GitHubRepository[]>(endpoint);
88
108
  return response;
@@ -96,6 +116,9 @@ export class GitHubApiService {
96
116
  * @author AMBROISE PARK Consulting
97
117
  */
98
118
  async addCollaborator(request: AddCollaboratorRequest): Promise<boolean> {
119
+ validateGitHubName(request.owner, 'owner');
120
+ validateGitHubName(request.repo, 'repo');
121
+ validateGitHubName(request.username, 'username');
99
122
  try {
100
123
  await this.request(
101
124
  `/repos/${request.owner}/${request.repo}/collaborators/${request.username}`,
@@ -126,6 +149,9 @@ export class GitHubApiService {
126
149
  repo: string,
127
150
  username: string
128
151
  ): Promise<boolean> {
152
+ validateGitHubName(owner, 'owner');
153
+ validateGitHubName(repo, 'repo');
154
+ validateGitHubName(username, 'username');
129
155
  try {
130
156
  // GitHub returns 204 if user is collaborator, 404 if not
131
157
  await this.request(`/repos/${owner}/${repo}/collaborators/${username}`, {
@@ -153,6 +179,9 @@ export class GitHubApiService {
153
179
  repo: string,
154
180
  username: string
155
181
  ): Promise<boolean> {
182
+ validateGitHubName(owner, 'owner');
183
+ validateGitHubName(repo, 'repo');
184
+ validateGitHubName(username, 'username');
156
185
  try {
157
186
  await this.request(`/repos/${owner}/${repo}/collaborators/${username}`, {
158
187
  method: 'DELETE',
@@ -177,6 +206,9 @@ export class GitHubApiService {
177
206
  username: string,
178
207
  role: 'member' | 'maintainer' = 'member'
179
208
  ): Promise<boolean> {
209
+ validateGitHubName(org, 'org');
210
+ validateGitHubName(teamSlug, 'teamSlug');
211
+ validateGitHubName(username, 'username');
180
212
  try {
181
213
  await this.request(
182
214
  `/orgs/${org}/teams/${teamSlug}/memberships/${username}`,
@@ -204,6 +236,9 @@ export class GitHubApiService {
204
236
  teamSlug: string,
205
237
  username: string
206
238
  ): Promise<boolean> {
239
+ validateGitHubName(org, 'org');
240
+ validateGitHubName(teamSlug, 'teamSlug');
241
+ validateGitHubName(username, 'username');
207
242
  try {
208
243
  await this.request(
209
244
  `/orgs/${org}/teams/${teamSlug}/memberships/${username}`,
@@ -230,6 +265,9 @@ export class GitHubApiService {
230
265
  teamSlug: string,
231
266
  username: string
232
267
  ): Promise<boolean> {
268
+ validateGitHubName(org, 'org');
269
+ validateGitHubName(teamSlug, 'teamSlug');
270
+ validateGitHubName(username, 'username');
233
271
  try {
234
272
  await this.request(
235
273
  `/orgs/${org}/teams/${teamSlug}/memberships/${username}`,
@@ -14,7 +14,9 @@ export * from './github.js';
14
14
  export * from './metadata.js';
15
15
  export * from './schema.js';
16
16
  export * from './utils/index.js';
17
+ export * from './ai/index.js';
17
18
  export * from './billing/index.js';
19
+ export * from './email/index.js';
18
20
  export * from './oauth/index.js';
19
21
  export {
20
22
  createTimestamp,
@@ -232,6 +232,8 @@ export const logger = {
232
232
  * @param message - Log message
233
233
  * @param context - Additional context data
234
234
  *
235
+ * @security Callers MUST NOT pass secrets (tokens, passwords, API keys) in context. Context is logged in plaintext.
236
+ *
235
237
  * @version 0.1.0
236
238
  * @since 0.0.1
237
239
  * @author AMBROISE PARK Consulting
@@ -14,6 +14,7 @@ import type {
14
14
  TokenResponse,
15
15
  } from '@donotdev/core/server';
16
16
 
17
+ /** Platform-agnostic provider for exchanging OAuth authorization codes for tokens. */
17
18
  export interface OAuthProvider {
18
19
  exchangeCodeForToken(params: {
19
20
  code: string;
@@ -9,6 +9,7 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ /** Platform-agnostic provider for granting OAuth access to a user. */
12
13
  export interface OAuthGrantProvider {
13
14
  grantAccess(params: {
14
15
  userId: string;
@@ -13,6 +13,7 @@ import { logger } from 'firebase-functions/v2';
13
13
 
14
14
  import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
15
15
 
16
+ /** Stored result of a previously processed idempotent operation. */
16
17
  export interface IdempotencyResult<T = any> {
17
18
  result: T;
18
19
  processedAt: string;
@@ -225,10 +225,13 @@ export async function checkRateLimitWithFirestore(
225
225
  key,
226
226
  error: error instanceof Error ? error.message : String(error),
227
227
  });
228
- // Fail open - allow the request if rate limiting fails
228
+ // Fail closed — deny the request if rate limiting infrastructure fails.
229
+ // Aligns with the Supabase implementation's fail-closed policy.
230
+ // Availability trade-off: legitimate requests may be blocked during
231
+ // Firestore outages, but this prevents abuse when enforcement is down.
229
232
  return {
230
- allowed: true,
231
- remaining: config.maxAttempts,
233
+ allowed: false,
234
+ remaining: 0,
232
235
  resetAt: null,
233
236
  blockRemainingSeconds: null,
234
237
  };
@@ -52,7 +52,7 @@ export function validateEnvironment(): void {
52
52
  if (!secretKey.startsWith('sk_')) {
53
53
  throw new Error(
54
54
  `❌ Invalid STRIPE_SECRET_KEY format\n` +
55
- `Secret keys must start with "sk_" (found: "${secretKey.substring(0, 3)}...")`
55
+ `Secret keys must start with "sk_" (found: "[redacted]")`
56
56
  );
57
57
  }
58
58