@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.
- package/guidelines/FUNCTIONS.md +9 -0
- package/guidelines/VERCEL.md +260 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
- package/lib/firebase/index.js +3 -3
- package/lib/firebase/index.js.map +4 -4
- package/lib/shared/ai/classifyAIError.d.ts +35 -0
- package/lib/shared/ai/costTracker.d.ts +20 -0
- package/lib/shared/ai/createAIRoute.d.ts +20 -0
- package/lib/shared/ai/index.d.ts +6 -0
- package/lib/shared/ai/resolveModelTier.d.ts +14 -0
- package/lib/shared/billing/createCheckout.d.ts +8 -2
- package/lib/shared/email/createEmailRoute.d.ts +30 -0
- package/lib/shared/email/index.d.ts +3 -0
- package/lib/shared/email/provider.d.ts +30 -0
- package/lib/shared/email/resendProvider.d.ts +22 -0
- package/lib/shared/github.d.ts +5 -0
- package/lib/shared/index.d.ts +2 -0
- package/lib/shared/index.js +4 -3
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +2 -0
- package/lib/shared/oauth/exchangeToken.d.ts +1 -0
- package/lib/shared/oauth/grantAccess.d.ts +1 -0
- package/lib/shared/utils/internal/idempotency.d.ts +1 -0
- package/lib/supabase/ai/createAIFunction.d.ts +30 -0
- package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
- package/lib/supabase/billing/changePlan.d.ts +1 -1
- package/lib/supabase/crud/aggregate.d.ts +1 -0
- package/lib/supabase/crud/create.d.ts +1 -0
- package/lib/supabase/crud/delete.d.ts +1 -0
- package/lib/supabase/crud/get.d.ts +1 -0
- package/lib/supabase/crud/list.d.ts +1 -0
- package/lib/supabase/crud/update.d.ts +1 -0
- package/lib/supabase/edgeFunction.d.ts +56 -0
- package/lib/supabase/email/createEmailFunction.d.ts +31 -0
- package/lib/supabase/index.d.ts +8 -0
- package/lib/supabase/index.js +3 -2
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/ai/chat.d.ts +29 -0
- package/lib/vercel/api/ai/index.d.ts +1 -0
- package/lib/vercel/api/index.d.ts +1 -0
- package/lib/vercel/api/index.js +3 -2
- package/lib/vercel/api/index.js.map +4 -4
- package/package.json +38 -5
- package/src/firebase/billing/createCheckoutSession.ts +79 -187
- package/src/firebase/oauth/exchangeToken.ts +4 -4
- package/src/firebase/oauth/refreshToken.ts +4 -4
- package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
- package/src/shared/ai/classifyAIError.ts +163 -0
- package/src/shared/ai/costTracker.ts +51 -0
- package/src/shared/ai/createAIRoute.ts +397 -0
- package/src/shared/ai/index.ts +8 -0
- package/src/shared/ai/resolveModelTier.ts +58 -0
- package/src/shared/billing/createCheckout.ts +153 -8
- package/src/shared/billing/helpers/subscriptionManagement.ts +9 -0
- package/src/shared/billing/idempotency.ts +5 -0
- package/src/shared/email/createEmailRoute.ts +81 -0
- package/src/shared/email/index.ts +5 -0
- package/src/shared/email/provider.ts +31 -0
- package/src/shared/email/resendProvider.ts +56 -0
- package/src/shared/errorHandling.ts +10 -4
- package/src/shared/github.ts +38 -0
- package/src/shared/index.ts +2 -0
- package/src/shared/logger.ts +2 -0
- package/src/shared/oauth/exchangeToken.ts +1 -0
- package/src/shared/oauth/grantAccess.ts +1 -0
- package/src/shared/utils/internal/idempotency.ts +1 -0
- package/src/shared/utils/internal/rateLimiter.ts +6 -3
- package/src/shared/validation.ts +1 -1
- package/src/supabase/ai/createAIFunction.ts +75 -0
- package/src/supabase/auth/removeCustomClaims.ts +38 -2
- package/src/supabase/auth/setCustomClaims.ts +66 -5
- package/src/supabase/baseFunction.ts +26 -2
- package/src/supabase/billing/changePlan.ts +6 -1
- package/src/supabase/billing/createCheckoutSession.ts +16 -2
- package/src/supabase/crud/aggregate.ts +1 -0
- package/src/supabase/crud/create.ts +1 -0
- package/src/supabase/crud/delete.ts +1 -0
- package/src/supabase/crud/get.ts +1 -0
- package/src/supabase/crud/list.ts +1 -0
- package/src/supabase/crud/update.ts +1 -0
- package/src/supabase/edgeFunction.ts +195 -0
- package/src/supabase/email/createEmailFunction.ts +75 -0
- package/src/supabase/index.ts +12 -0
- package/src/supabase/oauth/exchangeToken.ts +38 -7
- package/src/supabase/oauth/refreshToken.ts +4 -5
- package/src/supabase/registerCrudFunctions.ts +29 -41
- package/src/supabase/utils/idempotency.ts +6 -2
- package/src/vercel/api/ai/chat.ts +77 -0
- package/src/vercel/api/ai/index.ts +1 -0
- package/src/vercel/api/billing/create-checkout-session.ts +27 -4
- package/src/vercel/api/billing/webhook-handler.ts +8 -1
- package/src/vercel/api/index.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +24 -1
- package/src/vercel/api/utils/cors.ts +6 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// packages/functions/src/supabase/ai/createAIFunction.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview AI Chat - Supabase Edge Function Factory
|
|
5
|
+
* @description Wraps the shared AI route handler for Supabase Edge Functions.
|
|
6
|
+
* Uses Vercel AI SDK via createAIRoute for streaming and non-streaming.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.1.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type {
|
|
14
|
+
AIChatRequest,
|
|
15
|
+
AICostRecord,
|
|
16
|
+
AIRouteConfig,
|
|
17
|
+
} from '@donotdev/core/server';
|
|
18
|
+
import { AIChatRequestSchema } from '@donotdev/core/server';
|
|
19
|
+
|
|
20
|
+
import { handleAIRequest } from '../../shared/ai/index.js';
|
|
21
|
+
import { createSupabaseHandler } from '../baseFunction.js';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Create a Supabase Edge Function handler for AI chat.
|
|
25
|
+
*
|
|
26
|
+
* @param config - AI route configuration
|
|
27
|
+
* @returns `(req: Request) => Promise<Response>` handler
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* // supabase/functions/ai-chat/index.ts
|
|
32
|
+
* import { createAIFunction } from '@donotdev/functions/supabase';
|
|
33
|
+
*
|
|
34
|
+
* const handler = createAIFunction({
|
|
35
|
+
* provider: 'anthropic',
|
|
36
|
+
* model: 'claude-sonnet-4-20250514',
|
|
37
|
+
* cost: { markup: 4.0, monthlyBudgetTokens: 500_000, showCostToUsers: false, displayCurrency: 'eur' },
|
|
38
|
+
* });
|
|
39
|
+
* Deno.serve(handler);
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export function createAIFunction(config: AIRouteConfig) {
|
|
43
|
+
return createSupabaseHandler(
|
|
44
|
+
'ai-chat',
|
|
45
|
+
AIChatRequestSchema,
|
|
46
|
+
async (data: AIChatRequest, ctx) => {
|
|
47
|
+
return handleAIRequest(data, config, {
|
|
48
|
+
userId: ctx.uid,
|
|
49
|
+
requestId: crypto.randomUUID(),
|
|
50
|
+
onCostRecord: async (record: AICostRecord) => {
|
|
51
|
+
// Write cost record to Supabase
|
|
52
|
+
const { error } = await ctx.supabaseAdmin
|
|
53
|
+
.from('ai_usage')
|
|
54
|
+
.insert({
|
|
55
|
+
user_id: record.userId,
|
|
56
|
+
model: record.model,
|
|
57
|
+
provider: record.provider,
|
|
58
|
+
prompt_tokens: record.usage.promptTokens,
|
|
59
|
+
completion_tokens: record.usage.completionTokens,
|
|
60
|
+
total_tokens: record.usage.totalTokens,
|
|
61
|
+
provider_cost: record.providerCost,
|
|
62
|
+
billed_cost: record.billedCost,
|
|
63
|
+
markup: record.markup,
|
|
64
|
+
request_id: record.requestId,
|
|
65
|
+
created_at: record.timestamp,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
if (error) {
|
|
69
|
+
console.error('[AI] Failed to record cost to Supabase:', error.message);
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
);
|
|
75
|
+
}
|
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* @fileoverview Remove Custom Claims Supabase Edge Function
|
|
5
5
|
* @description Removes specific keys from the user's app_metadata.
|
|
6
|
+
* Blocklist prevents removal of security-critical claims.
|
|
6
7
|
*
|
|
7
|
-
* @version 0.
|
|
8
|
+
* @version 0.2.0
|
|
8
9
|
* @since 0.6.0
|
|
9
10
|
* @author AMBROISE PARK Consulting
|
|
10
11
|
*/
|
|
@@ -24,6 +25,31 @@ const removeCustomClaimsSchema = v.object({
|
|
|
24
25
|
),
|
|
25
26
|
});
|
|
26
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Claim keys that must NEVER be removed by users - privilege/integrity vectors.
|
|
30
|
+
* Matches BLOCKED_CLAIM_KEYS in setCustomClaims.ts.
|
|
31
|
+
*/
|
|
32
|
+
const BLOCKED_CLAIM_KEYS = new Set([
|
|
33
|
+
'admin',
|
|
34
|
+
'isAdmin',
|
|
35
|
+
'isSuper',
|
|
36
|
+
'isSuperAdmin',
|
|
37
|
+
'role',
|
|
38
|
+
'roles',
|
|
39
|
+
'permissions',
|
|
40
|
+
'superuser',
|
|
41
|
+
'moderator',
|
|
42
|
+
'staff',
|
|
43
|
+
'elevated',
|
|
44
|
+
'plan',
|
|
45
|
+
'tier',
|
|
46
|
+
'provider',
|
|
47
|
+
'providers',
|
|
48
|
+
'sub',
|
|
49
|
+
'iss',
|
|
50
|
+
'aud',
|
|
51
|
+
]);
|
|
52
|
+
|
|
27
53
|
// =============================================================================
|
|
28
54
|
// Handler
|
|
29
55
|
// =============================================================================
|
|
@@ -40,7 +66,7 @@ const removeCustomClaimsSchema = v.object({
|
|
|
40
66
|
* Deno.serve(createRemoveCustomClaims());
|
|
41
67
|
* ```
|
|
42
68
|
*
|
|
43
|
-
* @version 0.
|
|
69
|
+
* @version 0.2.0
|
|
44
70
|
* @since 0.6.0
|
|
45
71
|
*/
|
|
46
72
|
export function createRemoveCustomClaims() {
|
|
@@ -48,6 +74,16 @@ export function createRemoveCustomClaims() {
|
|
|
48
74
|
'remove-custom-claims',
|
|
49
75
|
removeCustomClaimsSchema,
|
|
50
76
|
async (data, ctx) => {
|
|
77
|
+
// Block removal of security-critical claims
|
|
78
|
+
const blocked = data.claimsToRemove.filter((k) =>
|
|
79
|
+
BLOCKED_CLAIM_KEYS.has(k)
|
|
80
|
+
);
|
|
81
|
+
if (blocked.length > 0) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`Protected claims cannot be removed: ${blocked.join(', ')}`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
51
87
|
// Get current app_metadata
|
|
52
88
|
const {
|
|
53
89
|
data: { user },
|
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* @fileoverview Set Custom Claims Supabase Edge Function
|
|
5
5
|
* @description Merges custom claims into the user's app_metadata.
|
|
6
|
+
* Mirrors the Firebase pattern: consumer provides an explicit allowlist,
|
|
7
|
+
* framework enforces a blocklist as safety net.
|
|
6
8
|
*
|
|
7
|
-
* @version 0.
|
|
9
|
+
* @version 0.2.0
|
|
8
10
|
* @since 0.6.0
|
|
9
11
|
* @author AMBROISE PARK Consulting
|
|
10
12
|
*/
|
|
@@ -22,6 +24,41 @@ const setCustomClaimsSchema = v.object({
|
|
|
22
24
|
idempotencyKey: v.optional(v.string()),
|
|
23
25
|
});
|
|
24
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Claim keys that must NEVER be self-assignable - privilege escalation vectors.
|
|
29
|
+
* Matches Firebase `BLOCKED_CLAIM_KEYS`.
|
|
30
|
+
*/
|
|
31
|
+
const BLOCKED_CLAIM_KEYS = new Set([
|
|
32
|
+
'admin',
|
|
33
|
+
'isAdmin',
|
|
34
|
+
'isSuper',
|
|
35
|
+
'isSuperAdmin',
|
|
36
|
+
'role',
|
|
37
|
+
'roles',
|
|
38
|
+
'permissions',
|
|
39
|
+
'superuser',
|
|
40
|
+
'moderator',
|
|
41
|
+
'staff',
|
|
42
|
+
'elevated',
|
|
43
|
+
'plan',
|
|
44
|
+
'tier',
|
|
45
|
+
'provider',
|
|
46
|
+
'providers',
|
|
47
|
+
'sub',
|
|
48
|
+
'iss',
|
|
49
|
+
'aud',
|
|
50
|
+
]);
|
|
51
|
+
|
|
52
|
+
// =============================================================================
|
|
53
|
+
// Types
|
|
54
|
+
// =============================================================================
|
|
55
|
+
|
|
56
|
+
/** Options for the set-custom-claims edge function factory. */
|
|
57
|
+
export interface SetCustomClaimsOptions {
|
|
58
|
+
/** Explicit allowlist of claim keys users may set on themselves. Required. */
|
|
59
|
+
allowedClaimKeys: string[];
|
|
60
|
+
}
|
|
61
|
+
|
|
25
62
|
// =============================================================================
|
|
26
63
|
// Handler
|
|
27
64
|
// =============================================================================
|
|
@@ -29,25 +66,49 @@ const setCustomClaimsSchema = v.object({
|
|
|
29
66
|
/**
|
|
30
67
|
* Create a Supabase Edge Function handler for setting custom claims (app_metadata).
|
|
31
68
|
*
|
|
32
|
-
*
|
|
69
|
+
* Consumers MUST specify which claim keys are self-assignable.
|
|
70
|
+
* The framework enforces a blocklist as a safety net even if the consumer
|
|
71
|
+
* accidentally includes a privilege key.
|
|
33
72
|
*
|
|
73
|
+
* @param options - Configuration with allowedClaimKeys
|
|
34
74
|
* @returns `(req: Request) => Promise<Response>` handler
|
|
35
75
|
*
|
|
36
76
|
* @example
|
|
37
77
|
* ```typescript
|
|
38
78
|
* // supabase/functions/set-custom-claims/index.ts
|
|
39
79
|
* import { createSetCustomClaims } from '@donotdev/functions/supabase';
|
|
40
|
-
* Deno.serve(createSetCustomClaims());
|
|
80
|
+
* Deno.serve(createSetCustomClaims({ allowedClaimKeys: ['theme', 'locale'] }));
|
|
41
81
|
* ```
|
|
42
82
|
*
|
|
43
|
-
* @version 0.
|
|
83
|
+
* @version 0.2.0
|
|
44
84
|
* @since 0.6.0
|
|
45
85
|
*/
|
|
46
|
-
export function createSetCustomClaims() {
|
|
86
|
+
export function createSetCustomClaims(options: SetCustomClaimsOptions) {
|
|
87
|
+
const allowedKeys = new Set(options.allowedClaimKeys);
|
|
88
|
+
|
|
89
|
+
// Fail fast if consumer accidentally allows a privilege key
|
|
90
|
+
for (const key of allowedKeys) {
|
|
91
|
+
if (BLOCKED_CLAIM_KEYS.has(key)) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`Claim key "${key}" is blocked - it is a privilege-escalation vector and cannot be self-assigned.`
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
47
98
|
return createSupabaseHandler(
|
|
48
99
|
'set-custom-claims',
|
|
49
100
|
setCustomClaimsSchema,
|
|
50
101
|
async (data, ctx) => {
|
|
102
|
+
// Only allow keys from the consumer-provided allowlist
|
|
103
|
+
const disallowedKeys = Object.keys(data.customClaims).filter(
|
|
104
|
+
(k) => !allowedKeys.has(k)
|
|
105
|
+
);
|
|
106
|
+
if (disallowedKeys.length > 0) {
|
|
107
|
+
throw new Error(
|
|
108
|
+
`Claim keys not allowed: ${disallowedKeys.join(', ')}`
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
51
112
|
// Get current app_metadata
|
|
52
113
|
const {
|
|
53
114
|
data: { user },
|
|
@@ -259,12 +259,36 @@ export function createSupabaseHandler<TReq, TRes>(
|
|
|
259
259
|
}
|
|
260
260
|
}
|
|
261
261
|
|
|
262
|
+
// Passthrough for streaming responses (e.g., AI SSE streams)
|
|
263
|
+
if (result instanceof Response) {
|
|
264
|
+
const headers = new Headers(result.headers);
|
|
265
|
+
headers.set('Access-Control-Allow-Origin', allowedOrigin);
|
|
266
|
+
return new Response(result.body, {
|
|
267
|
+
status: result.status,
|
|
268
|
+
statusText: result.statusText,
|
|
269
|
+
headers,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
262
273
|
return respond(result, 200);
|
|
263
274
|
} catch (error) {
|
|
264
275
|
console.error(`[${operationName}] Error:`, error);
|
|
265
|
-
const
|
|
276
|
+
const rawMessage =
|
|
266
277
|
error instanceof Error ? error.message : 'Internal server error';
|
|
267
|
-
const
|
|
278
|
+
const errorCode = getErrorCode(rawMessage);
|
|
279
|
+
// Only pass through messages for known safe error codes.
|
|
280
|
+
// All other/unknown errors get a generic message to prevent information leaks.
|
|
281
|
+
const SAFE_ERROR_CODES = new Set([
|
|
282
|
+
'rate-limit-exceeded',
|
|
283
|
+
'not-found',
|
|
284
|
+
'permission-denied',
|
|
285
|
+
'invalid-argument',
|
|
286
|
+
'already-exists',
|
|
287
|
+
]);
|
|
288
|
+
const message = SAFE_ERROR_CODES.has(errorCode)
|
|
289
|
+
? rawMessage
|
|
290
|
+
: 'Internal server error';
|
|
291
|
+
const status = getErrorStatus(rawMessage);
|
|
268
292
|
// allowedOrigin may not be set if error occurred before that line; fall back to '*'
|
|
269
293
|
const origin = getEnv('ALLOWED_ORIGIN', '*');
|
|
270
294
|
return jsonResponse({ error: message }, status, origin);
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import * as v from 'valibot';
|
|
13
13
|
|
|
14
|
-
import type
|
|
14
|
+
import { hasRoleAccess, type StripeBackConfig } from '@donotdev/core/server';
|
|
15
15
|
|
|
16
16
|
import { changeUserPlan } from '../../shared/billing/helpers/subscriptionManagement.js';
|
|
17
17
|
import { initStripe } from '../../shared/utils.js';
|
|
@@ -49,6 +49,11 @@ export function createChangePlan(billingConfig: StripeBackConfig) {
|
|
|
49
49
|
'change-plan',
|
|
50
50
|
changePlanSchema,
|
|
51
51
|
async (data, ctx) => {
|
|
52
|
+
// Non-admin users can only change their own plan
|
|
53
|
+
if (!hasRoleAccess(ctx.userRole, 'admin') && data.userId !== ctx.uid) {
|
|
54
|
+
throw new Error('Forbidden: cannot change another user\'s plan');
|
|
55
|
+
}
|
|
56
|
+
|
|
52
57
|
initStripe(getStripeKey());
|
|
53
58
|
const authProvider = createSupabaseAuthProvider(ctx.supabaseAdmin);
|
|
54
59
|
return changeUserPlan(
|
|
@@ -47,7 +47,10 @@ export function createCheckoutSession(billingConfig: StripeBackConfig) {
|
|
|
47
47
|
|
|
48
48
|
const stripeProvider = {
|
|
49
49
|
async createCheckoutSession(params: {
|
|
50
|
-
priceId
|
|
50
|
+
priceId?: string;
|
|
51
|
+
unitAmount?: number;
|
|
52
|
+
productName?: string;
|
|
53
|
+
currency?: string;
|
|
51
54
|
customerEmail?: string;
|
|
52
55
|
metadata: Record<string, string>;
|
|
53
56
|
allowPromotionCodes: boolean;
|
|
@@ -57,7 +60,18 @@ export function createCheckoutSession(billingConfig: StripeBackConfig) {
|
|
|
57
60
|
}) {
|
|
58
61
|
const session = await stripe.checkout.sessions.create({
|
|
59
62
|
mode: params.mode || 'payment',
|
|
60
|
-
line_items: [
|
|
63
|
+
line_items: [
|
|
64
|
+
params.priceId
|
|
65
|
+
? { price: params.priceId, quantity: 1 }
|
|
66
|
+
: {
|
|
67
|
+
price_data: {
|
|
68
|
+
currency: params.currency || 'eur',
|
|
69
|
+
unit_amount: params.unitAmount!,
|
|
70
|
+
product_data: { name: params.productName! },
|
|
71
|
+
},
|
|
72
|
+
quantity: 1,
|
|
73
|
+
},
|
|
74
|
+
],
|
|
61
75
|
customer_email: params.customerEmail || undefined,
|
|
62
76
|
success_url: params.successUrl,
|
|
63
77
|
cancel_url: params.cancelUrl,
|
|
@@ -19,6 +19,7 @@ import { createSupabaseHandler } from '../baseFunction.js';
|
|
|
19
19
|
|
|
20
20
|
const mapper = defaultFieldMapper;
|
|
21
21
|
|
|
22
|
+
/** Request payload for aggregate operations (COUNT, SUM, AVG, MIN, MAX) on entities. */
|
|
22
23
|
export type AggregateEntityRequest = {
|
|
23
24
|
where?: Array<[string, any, any]>;
|
|
24
25
|
aggregate: {
|
|
@@ -25,6 +25,7 @@ import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
|
|
|
25
25
|
|
|
26
26
|
const mapper = defaultFieldMapper;
|
|
27
27
|
|
|
28
|
+
/** Request payload for creating an entity with optional idempotency. */
|
|
28
29
|
export type CreateEntityRequest = {
|
|
29
30
|
payload: Record<string, any>;
|
|
30
31
|
idempotencyKey?: string;
|
|
@@ -16,6 +16,7 @@ import type { UserRole } from '@donotdev/core/server';
|
|
|
16
16
|
import { DoNotDevError } from '../../shared/utils.js';
|
|
17
17
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
18
18
|
|
|
19
|
+
/** Request payload for deleting a single entity by ID. */
|
|
19
20
|
export type DeleteEntityRequest = { id: string };
|
|
20
21
|
|
|
21
22
|
/**
|
package/src/supabase/crud/get.ts
CHANGED
|
@@ -40,6 +40,7 @@ function toBackendColumn(field: unknown): string {
|
|
|
40
40
|
);
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/** Request payload for listing entities with filtering, sorting, and pagination. */
|
|
43
44
|
export interface ListEntityRequest {
|
|
44
45
|
where?: Array<[string, any, any]>;
|
|
45
46
|
orderBy?: Array<[string, 'asc' | 'desc']>;
|
|
@@ -21,6 +21,7 @@ import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
|
|
|
21
21
|
|
|
22
22
|
const mapper = defaultFieldMapper;
|
|
23
23
|
|
|
24
|
+
/** Request payload for updating an entity by ID with optional idempotency. */
|
|
24
25
|
export type UpdateEntityRequest = {
|
|
25
26
|
id: string;
|
|
26
27
|
payload: Record<string, any>;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// packages/functions/src/supabase/edgeFunction.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Lightweight edge function wrapper
|
|
5
|
+
* @description Handles CORS, auth, and response formatting for custom Supabase
|
|
6
|
+
* Edge Functions that don't fit the typed createSupabaseHandler pattern.
|
|
7
|
+
*
|
|
8
|
+
* Use createSupabaseHandler for typed CRUD-style handlers with schema validation.
|
|
9
|
+
* Use createEdgeFunction for multi-action functions, AI chat, webhooks, etc.
|
|
10
|
+
*
|
|
11
|
+
* @version 0.1.0
|
|
12
|
+
* @since 0.6.0
|
|
13
|
+
* @author AMBROISE PARK Consulting
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { createClient } from '@supabase/supabase-js';
|
|
17
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
18
|
+
|
|
19
|
+
// =============================================================================
|
|
20
|
+
// Types
|
|
21
|
+
// =============================================================================
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Context passed to edge function handlers.
|
|
25
|
+
*
|
|
26
|
+
* @version 0.1.0
|
|
27
|
+
* @since 0.6.0
|
|
28
|
+
*/
|
|
29
|
+
export interface EdgeFunctionContext {
|
|
30
|
+
/** Authenticated user (null if no valid JWT or requireAuth=false) */
|
|
31
|
+
user: { id: string; email?: string } | null;
|
|
32
|
+
/** Admin client (service role, bypasses RLS) - always available */
|
|
33
|
+
supabaseAdmin: SupabaseClient;
|
|
34
|
+
/** User-scoped client (RLS) - null if no valid JWT */
|
|
35
|
+
userClient: SupabaseClient | null;
|
|
36
|
+
/** JSON response with CORS headers */
|
|
37
|
+
json: (data: unknown, status?: number) => Response;
|
|
38
|
+
/** JSON error response: { error: message } with CORS headers */
|
|
39
|
+
error: (message: string, status?: number) => Response;
|
|
40
|
+
/** Raw response with CORS headers (for structured payloads) */
|
|
41
|
+
respond: (data: unknown, status: number) => Response;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Configuration options for edge function creation. */
|
|
45
|
+
export interface EdgeFunctionOptions {
|
|
46
|
+
/** Require JWT auth - returns 401 if missing/invalid (default: true) */
|
|
47
|
+
requireAuth?: boolean;
|
|
48
|
+
/** Extra CORS allowed headers (e.g., 'stripe-signature', 'x-build-secret') */
|
|
49
|
+
extraHeaders?: string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// =============================================================================
|
|
53
|
+
// Factory
|
|
54
|
+
// =============================================================================
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Create a Supabase Edge Function handler with CORS, optional auth, and response helpers.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* // Auth required (default)
|
|
62
|
+
* Deno.serve(createEdgeFunction(async (req, ctx) => {
|
|
63
|
+
* const body = await req.json();
|
|
64
|
+
* return ctx.json({ result: 'ok' });
|
|
65
|
+
* }));
|
|
66
|
+
*
|
|
67
|
+
* // No auth (public endpoint)
|
|
68
|
+
* Deno.serve(createEdgeFunction(async (req, ctx) => {
|
|
69
|
+
* return ctx.json({ public: true });
|
|
70
|
+
* }, { requireAuth: false }));
|
|
71
|
+
*
|
|
72
|
+
* // Custom auth (webhook)
|
|
73
|
+
* Deno.serve(createEdgeFunction(async (req, ctx) => {
|
|
74
|
+
* const sig = req.headers.get('stripe-signature');
|
|
75
|
+
* if (!sig) return ctx.error('Missing signature', 401);
|
|
76
|
+
* return ctx.json({ received: true });
|
|
77
|
+
* }, { requireAuth: false, extraHeaders: ['stripe-signature'] }));
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export function createEdgeFunction(
|
|
81
|
+
handler: (req: Request, ctx: EdgeFunctionContext) => Promise<Response>,
|
|
82
|
+
options?: EdgeFunctionOptions,
|
|
83
|
+
): (req: Request) => Promise<Response> {
|
|
84
|
+
const requireAuth = options?.requireAuth ?? true;
|
|
85
|
+
const baseHeaders = 'authorization, content-type, x-client-info, apikey';
|
|
86
|
+
const allowedHeaders = options?.extraHeaders?.length
|
|
87
|
+
? `${baseHeaders}, ${options.extraHeaders.join(', ')}`
|
|
88
|
+
: baseHeaders;
|
|
89
|
+
|
|
90
|
+
return async (req: Request): Promise<Response> => {
|
|
91
|
+
const allowedOrigin = getEnv('ALLOWED_ORIGIN') || '*';
|
|
92
|
+
|
|
93
|
+
// Response helpers (closed over allowedOrigin)
|
|
94
|
+
const respond = (data: unknown, status: number) =>
|
|
95
|
+
jsonResponse(data, status, allowedOrigin);
|
|
96
|
+
const json = (data: unknown, status = 200) => respond(data, status);
|
|
97
|
+
const error = (message: string, status = 400) =>
|
|
98
|
+
respond({ error: message }, status);
|
|
99
|
+
|
|
100
|
+
// CORS preflight
|
|
101
|
+
if (req.method === 'OPTIONS') {
|
|
102
|
+
return new Response(null, {
|
|
103
|
+
status: 204,
|
|
104
|
+
headers: {
|
|
105
|
+
'Access-Control-Allow-Origin': allowedOrigin,
|
|
106
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
107
|
+
'Access-Control-Allow-Headers': allowedHeaders,
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Method check
|
|
113
|
+
if (req.method !== 'POST') {
|
|
114
|
+
return error('Method not allowed', 405);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Supabase clients
|
|
118
|
+
const supabaseUrl = getEnv('SUPABASE_URL');
|
|
119
|
+
const serviceKey =
|
|
120
|
+
getEnv('SUPABASE_SECRET_KEY') || getEnv('SUPABASE_SERVICE_ROLE_KEY');
|
|
121
|
+
|
|
122
|
+
if (!supabaseUrl || !serviceKey) {
|
|
123
|
+
console.error('Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY');
|
|
124
|
+
return error('Server misconfigured', 500);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const supabaseAdmin = createClient(supabaseUrl, serviceKey, {
|
|
128
|
+
auth: { autoRefreshToken: false, persistSession: false },
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
// Auth
|
|
132
|
+
let user: { id: string; email?: string } | null = null;
|
|
133
|
+
let userClient: SupabaseClient | null = null;
|
|
134
|
+
|
|
135
|
+
const authHeader = req.headers.get('authorization');
|
|
136
|
+
if (authHeader?.startsWith('Bearer ')) {
|
|
137
|
+
const jwt = authHeader.slice(7);
|
|
138
|
+
const anonKey = getEnv('SUPABASE_ANON_KEY');
|
|
139
|
+
if (anonKey) {
|
|
140
|
+
userClient = createClient(supabaseUrl, anonKey, {
|
|
141
|
+
global: { headers: { Authorization: `Bearer ${jwt}` } },
|
|
142
|
+
});
|
|
143
|
+
const { data, error: authError } = await supabaseAdmin.auth.getUser(jwt);
|
|
144
|
+
if (!authError && data.user) {
|
|
145
|
+
user = { id: data.user.id, email: data.user.email ?? undefined };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (requireAuth && !user) {
|
|
151
|
+
return error('Unauthorized', 401);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const ctx: EdgeFunctionContext = {
|
|
155
|
+
user,
|
|
156
|
+
supabaseAdmin,
|
|
157
|
+
userClient,
|
|
158
|
+
json,
|
|
159
|
+
error,
|
|
160
|
+
respond,
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
try {
|
|
164
|
+
return await handler(req, ctx);
|
|
165
|
+
} catch (e) {
|
|
166
|
+
console.error('Edge function error:', e);
|
|
167
|
+
return error('Internal error', 500);
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// =============================================================================
|
|
173
|
+
// Helpers
|
|
174
|
+
// =============================================================================
|
|
175
|
+
|
|
176
|
+
function jsonResponse(
|
|
177
|
+
data: unknown,
|
|
178
|
+
status: number,
|
|
179
|
+
allowedOrigin: string,
|
|
180
|
+
): Response {
|
|
181
|
+
return new Response(JSON.stringify(data), {
|
|
182
|
+
status,
|
|
183
|
+
headers: {
|
|
184
|
+
'Content-Type': 'application/json',
|
|
185
|
+
'Access-Control-Allow-Origin': allowedOrigin,
|
|
186
|
+
},
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function getEnv(key: string): string {
|
|
191
|
+
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
192
|
+
return (globalThis as any).Deno?.env?.get(key) ?? '';
|
|
193
|
+
}
|
|
194
|
+
return typeof process !== 'undefined' ? (process.env[key] ?? '') : '';
|
|
195
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// packages/functions/src/supabase/email/createEmailFunction.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Email Send - Supabase Edge Function Factory
|
|
5
|
+
* @description Wraps the shared email handler for Supabase Edge Functions.
|
|
6
|
+
* Resolves Resend provider from env, adds auth context.
|
|
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
|
+
} from '@donotdev/core/server';
|
|
17
|
+
import { SendEmailRequestSchema } from '@donotdev/core/server';
|
|
18
|
+
|
|
19
|
+
import { handleEmailRequest } from '../../shared/email/index.js';
|
|
20
|
+
import { createResendProvider } from '../../shared/email/resendProvider.js';
|
|
21
|
+
import { createSupabaseHandler } from '../baseFunction.js';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Create a Supabase Edge Function handler for sending emails.
|
|
25
|
+
* Requires RESEND_API_KEY environment variable.
|
|
26
|
+
*
|
|
27
|
+
* @param config - Email route configuration (templates, defaultFrom)
|
|
28
|
+
* @returns `(req: Request) => Promise<Response>` handler
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* // supabase/functions/send-email/index.ts
|
|
33
|
+
* import { createEmailFunction } from '@donotdev/functions/supabase';
|
|
34
|
+
*
|
|
35
|
+
* const handler = createEmailFunction({
|
|
36
|
+
* provider: 'resend',
|
|
37
|
+
* defaultFrom: 'Frabled <noreply@frabled.com>',
|
|
38
|
+
* templates: { 'order-confirmation': orderConfirmationTemplate },
|
|
39
|
+
* });
|
|
40
|
+
* Deno.serve(handler);
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export function createEmailFunction(config: EmailRouteConfig) {
|
|
44
|
+
return createSupabaseHandler(
|
|
45
|
+
'send-email',
|
|
46
|
+
SendEmailRequestSchema,
|
|
47
|
+
async (data: SendEmailRequest, _ctx) => {
|
|
48
|
+
const apiKey = getEnv('RESEND_API_KEY');
|
|
49
|
+
if (!apiKey) {
|
|
50
|
+
return new Response(
|
|
51
|
+
JSON.stringify({ success: false, error: 'Email provider not configured' }),
|
|
52
|
+
{ status: 500, headers: { 'Content-Type': 'application/json' } }
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const provider = createResendProvider(apiKey);
|
|
57
|
+
const result = await handleEmailRequest(data, config, provider);
|
|
58
|
+
|
|
59
|
+
return new Response(
|
|
60
|
+
JSON.stringify(result),
|
|
61
|
+
{
|
|
62
|
+
status: result.success ? 200 : 400,
|
|
63
|
+
headers: { 'Content-Type': 'application/json' },
|
|
64
|
+
}
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function getEnv(name: string): string | undefined {
|
|
71
|
+
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
72
|
+
return (globalThis as any).Deno?.env?.get(name);
|
|
73
|
+
}
|
|
74
|
+
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
75
|
+
}
|