@simplelayer/graniteer-core 0.0.2 → 0.1.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.
- package/index.js +2 -2
- package/package.json +98 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/bookingHoldReclaim.ts +94 -0
- package/src/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/conductorAdmin.ts +141 -0
- package/src/email-templates/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/reauthentication.tsx +60 -0
- package/src/functions/admin-cancel-membership.ts +311 -0
- package/src/functions/admin-change-membership-plan.ts +308 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- package/src/functions/admin-photo-upload.ts +128 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- package/src/functions/admin-reset-mfa.ts +138 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- package/src/functions/day-pass-status.ts +89 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- package/src/functions/get-signing-link.ts +211 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- package/src/functions/print-billing-recover.ts +97 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -0
- package/src/functions/space-availability-range.ts +142 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- package/src/functions/voice-inquiry.test.ts +301 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/membership.ts +109 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +34 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/slackAlert.ts +38 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/tier1Agreement.ts +125 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
2
|
+
import Stripe from 'npm:stripe@17.5.0';
|
|
3
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
4
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
5
|
+
|
|
6
|
+
const corsHeaders = {
|
|
7
|
+
'Access-Control-Allow-Origin': '*',
|
|
8
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
9
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
interface CallerClaims {
|
|
13
|
+
sub: string;
|
|
14
|
+
email?: string;
|
|
15
|
+
aal?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
19
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
20
|
+
function getJwks(supabaseUrl: string) {
|
|
21
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
22
|
+
return jwksCache;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
26
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
27
|
+
const token = authHeader.slice(7).trim();
|
|
28
|
+
try {
|
|
29
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
30
|
+
const claims = payload as unknown as CallerClaims;
|
|
31
|
+
if (!claims.sub) return null;
|
|
32
|
+
return claims;
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function json(status: number, body: unknown) {
|
|
39
|
+
return new Response(JSON.stringify(body), {
|
|
40
|
+
status,
|
|
41
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function handle(req: Request): Promise<Response> {
|
|
46
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
47
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
48
|
+
|
|
49
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
50
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
51
|
+
|
|
52
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
53
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
54
|
+
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
55
|
+
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
56
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
57
|
+
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
58
|
+
|
|
59
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
60
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
64
|
+
checkRateLimit(admin, 'admin-undo-membership-cancel-ip', clientIp(req), 30, 300),
|
|
65
|
+
checkRateLimit(admin, 'admin-undo-membership-cancel-email', callerEmail, 20, 300),
|
|
66
|
+
]);
|
|
67
|
+
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
68
|
+
|
|
69
|
+
const { data: allow, error: allowErr } = await admin
|
|
70
|
+
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
71
|
+
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
72
|
+
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
73
|
+
|
|
74
|
+
let body: { membership_id?: string; idempotency_key?: string };
|
|
75
|
+
try {
|
|
76
|
+
body = await req.json();
|
|
77
|
+
} catch {
|
|
78
|
+
return json(400, { ok: false, error: 'invalid_json' });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const membershipId = (body.membership_id ?? '').trim();
|
|
82
|
+
if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
|
|
83
|
+
return json(400, { ok: false, error: 'invalid_membership_id' });
|
|
84
|
+
}
|
|
85
|
+
const idempotencyKey = (body.idempotency_key ?? '').trim();
|
|
86
|
+
if (!idempotencyKey || idempotencyKey.length > 100) {
|
|
87
|
+
return json(400, { ok: false, error: 'invalid_idempotency_key' });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// 1. Live state re-check.
|
|
91
|
+
const { data: membership, error: mErr } = await admin
|
|
92
|
+
.from('memberships')
|
|
93
|
+
.select('id,status,stripe_subscription_id,cancel_at')
|
|
94
|
+
.eq('id', membershipId)
|
|
95
|
+
.maybeSingle();
|
|
96
|
+
if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
|
|
97
|
+
if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
|
|
98
|
+
if (!membership.cancel_at) return json(400, { ok: false, error: 'no_scheduled_cancellation' });
|
|
99
|
+
const subscriptionId = membership.stripe_subscription_id;
|
|
100
|
+
if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
|
|
101
|
+
|
|
102
|
+
// 2. Idempotent audit insert.
|
|
103
|
+
const { error: insErr } = await admin.from('membership_admin_actions').insert({
|
|
104
|
+
membership_id: membershipId,
|
|
105
|
+
action: 'cancel_undone',
|
|
106
|
+
actor_email: callerEmail,
|
|
107
|
+
idempotency_key: idempotencyKey,
|
|
108
|
+
effective_at: new Date().toISOString(),
|
|
109
|
+
});
|
|
110
|
+
if (insErr) {
|
|
111
|
+
if ((insErr as { code?: string }).code === '23505') {
|
|
112
|
+
return json(200, { ok: true, duplicate: true });
|
|
113
|
+
}
|
|
114
|
+
return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
118
|
+
if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
|
|
119
|
+
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
|
|
120
|
+
|
|
121
|
+
// 3. Clear the scheduled cancellation in Stripe.
|
|
122
|
+
let updatedSub: Stripe.Subscription;
|
|
123
|
+
try {
|
|
124
|
+
updatedSub = await stripe.subscriptions.update(
|
|
125
|
+
subscriptionId,
|
|
126
|
+
{ cancel_at: null },
|
|
127
|
+
{ idempotencyKey },
|
|
128
|
+
);
|
|
129
|
+
} catch (e) {
|
|
130
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
131
|
+
return json(500, { ok: false, error: 'stripe_undo_failed', detail: msg });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// 4. Authoritative membership write.
|
|
135
|
+
const { error: updErr } = await admin
|
|
136
|
+
.from('memberships')
|
|
137
|
+
.update({ status: updatedSub.status, cancel_at: null })
|
|
138
|
+
.eq('id', membershipId);
|
|
139
|
+
if (updErr) {
|
|
140
|
+
return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return json(200, { ok: true, status: updatedSub.status });
|
|
144
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Member wall photo -- the ONLY write path (and the only way to mint a
|
|
2
|
+
// signed download URL) for the Wall Photos admin console. Auth mirrors
|
|
3
|
+
// admin-door-write exactly (JWKS verify -> aal2 -> admin_users allowlist
|
|
4
|
+
// re-check server-side -> rate limit), per member-wall-photo-plan-v1.md §3.6.
|
|
5
|
+
// Every mutation lands an ops_events audit row via the shared logOps helper,
|
|
6
|
+
// same as every other admin-*-write function in this codebase.
|
|
7
|
+
|
|
8
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
9
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
10
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
11
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
12
|
+
|
|
13
|
+
const corsHeaders = {
|
|
14
|
+
'Access-Control-Allow-Origin': '*',
|
|
15
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
16
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
20
|
+
|
|
21
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
22
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
23
|
+
function getJwks(supabaseUrl: string) {
|
|
24
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
25
|
+
return jwksCache;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
29
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
30
|
+
try {
|
|
31
|
+
const { payload } = await jwtVerify(authHeader.slice(7).trim(), getJwks(supabaseUrl));
|
|
32
|
+
const claims = payload as unknown as CallerClaims;
|
|
33
|
+
return claims.sub ? claims : null;
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function json(status: number, body: unknown) {
|
|
40
|
+
return new Response(JSON.stringify(body), {
|
|
41
|
+
status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const UUID = /^[0-9a-f-]{36}$/i;
|
|
46
|
+
const SIGNED_URL_TTL_SECONDS = 300; // 5 minutes, per plan §3.6
|
|
47
|
+
|
|
48
|
+
export async function handle(req: Request): Promise<Response> {
|
|
49
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
50
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
51
|
+
|
|
52
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
53
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
54
|
+
|
|
55
|
+
const caller = await verifyCaller(req.headers.get('Authorization') ?? req.headers.get('authorization'), SUPABASE_URL);
|
|
56
|
+
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
57
|
+
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
58
|
+
const actorEmail = (caller.email ?? '').toLowerCase();
|
|
59
|
+
if (!actorEmail) return json(403, { ok: false, error: 'no_email' });
|
|
60
|
+
|
|
61
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
62
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
66
|
+
checkRateLimit(admin, 'admin-wall-photo-write-ip', clientIp(req), 120, 300),
|
|
67
|
+
checkRateLimit(admin, 'admin-wall-photo-write-email', actorEmail, 80, 300),
|
|
68
|
+
]);
|
|
69
|
+
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
70
|
+
|
|
71
|
+
const { data: allow, error: allowErr } = await admin
|
|
72
|
+
.from('admin_users').select('email').eq('email', actorEmail).maybeSingle();
|
|
73
|
+
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
74
|
+
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
75
|
+
|
|
76
|
+
let body: Record<string, unknown>;
|
|
77
|
+
try { body = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
|
|
78
|
+
const action = String(body.action ?? '');
|
|
79
|
+
|
|
80
|
+
const audit = async (detail: Record<string, unknown>) => {
|
|
81
|
+
const { error: auditErr } = await admin.from('ops_events').insert({
|
|
82
|
+
kind: 'wall_photo_admin_write', severity: 'info', booking_id: null,
|
|
83
|
+
detail: { actor_email: actorEmail, action, ...detail },
|
|
84
|
+
});
|
|
85
|
+
if (auditErr) {
|
|
86
|
+
await logOps(
|
|
87
|
+
admin,
|
|
88
|
+
'wall_photo_admin_audit_failed',
|
|
89
|
+
{ intended_action: action, audit_error: auditErr.message, actor_email: actorEmail, ...detail },
|
|
90
|
+
{ severity: 'error' },
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
const id = String(body.id ?? '');
|
|
97
|
+
if (!UUID.test(id)) return json(400, { ok: false, error: 'invalid_id' });
|
|
98
|
+
|
|
99
|
+
const { data: row, error: rowErr } = await admin
|
|
100
|
+
.from('member_wall_photo_queue')
|
|
101
|
+
.select('id, auth_user_id, original_object_path, content_type, status')
|
|
102
|
+
.eq('id', id)
|
|
103
|
+
.maybeSingle();
|
|
104
|
+
if (rowErr) return json(500, { ok: false, error: 'read_failed' });
|
|
105
|
+
if (!row) return json(404, { ok: false, error: 'not_found' });
|
|
106
|
+
|
|
107
|
+
if (action === 'get_signed_url') {
|
|
108
|
+
if (!row.original_object_path) return json(400, { ok: false, error: 'no_original_captured' });
|
|
109
|
+
const ext = (row.content_type as string | null)?.split('/')[1] ?? 'jpg';
|
|
110
|
+
const { data: signed, error: signErr } = await admin.storage
|
|
111
|
+
.from('member-photo-originals')
|
|
112
|
+
.createSignedUrl(row.original_object_path as string, SIGNED_URL_TTL_SECONDS, {
|
|
113
|
+
download: `wall-photo-${row.auth_user_id}.${ext}`,
|
|
114
|
+
});
|
|
115
|
+
if (signErr || !signed) return json(500, { ok: false, error: signErr?.message ?? 'sign_failed' });
|
|
116
|
+
// Read-only -- no audit row. Every write action below still lands one.
|
|
117
|
+
return json(200, { ok: true, signed_url: signed.signedUrl, expires_in: SIGNED_URL_TTL_SECONDS });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (action === 'mark_printed' || action === 'mark_skipped') {
|
|
121
|
+
const nextStatus = action === 'mark_printed' ? 'printed' : 'skipped';
|
|
122
|
+
const patch: Record<string, unknown> =
|
|
123
|
+
action === 'mark_printed'
|
|
124
|
+
? { status: 'printed', printed_at: new Date().toISOString(), printed_by: actorEmail }
|
|
125
|
+
: { status: 'skipped', printed_at: null, printed_by: null };
|
|
126
|
+
const { data: after, error } = await admin
|
|
127
|
+
.from('member_wall_photo_queue')
|
|
128
|
+
.update(patch)
|
|
129
|
+
.eq('id', id)
|
|
130
|
+
.select('id, status')
|
|
131
|
+
.single();
|
|
132
|
+
if (error) return json(400, { ok: false, error: error.message });
|
|
133
|
+
await audit({ queue_id: id, auth_user_id: row.auth_user_id, from_status: row.status, to_status: nextStatus });
|
|
134
|
+
return json(200, { ok: true, row: after });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return json(400, { ok: false, error: 'unknown_action' });
|
|
138
|
+
} catch (e) {
|
|
139
|
+
return json(500, { ok: false, error: String(e) });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
2
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
3
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
4
|
+
|
|
5
|
+
const corsHeaders = {
|
|
6
|
+
'Access-Control-Allow-Origin': '*',
|
|
7
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
8
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
interface CallerClaims {
|
|
12
|
+
sub: string;
|
|
13
|
+
email?: string;
|
|
14
|
+
aal?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
18
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
19
|
+
function getJwks(supabaseUrl: string) {
|
|
20
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
21
|
+
return jwksCache;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
25
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
26
|
+
const token = authHeader.slice(7).trim();
|
|
27
|
+
try {
|
|
28
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
29
|
+
const claims = payload as unknown as CallerClaims;
|
|
30
|
+
if (!claims.sub) return null;
|
|
31
|
+
return claims;
|
|
32
|
+
} catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function json(status: number, body: unknown) {
|
|
38
|
+
return new Response(JSON.stringify(body), {
|
|
39
|
+
status,
|
|
40
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function handle(req: Request): Promise<Response> {
|
|
45
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
46
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
47
|
+
|
|
48
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
49
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
50
|
+
|
|
51
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
52
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
53
|
+
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
54
|
+
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
55
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
56
|
+
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
57
|
+
|
|
58
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
59
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
63
|
+
checkRateLimit(admin, 'boldsign-sender-identity-ip', clientIp(req), 30, 300),
|
|
64
|
+
checkRateLimit(admin, 'boldsign-sender-identity-email', callerEmail, 20, 300),
|
|
65
|
+
]);
|
|
66
|
+
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
67
|
+
|
|
68
|
+
const { data: allow, error: allowErr } = await admin
|
|
69
|
+
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
70
|
+
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
71
|
+
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
72
|
+
|
|
73
|
+
let body: { name?: unknown; email?: unknown };
|
|
74
|
+
try {
|
|
75
|
+
body = await req.json();
|
|
76
|
+
} catch {
|
|
77
|
+
return json(400, { ok: false, error: 'invalid_json' });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
|
81
|
+
const email = typeof body.email === 'string' ? body.email.trim() : '';
|
|
82
|
+
if (!name || name.length > 255) return json(400, { ok: false, error: 'invalid_name' });
|
|
83
|
+
if (!email || email.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
84
|
+
return json(400, { ok: false, error: 'invalid_email' });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const apiKey = Deno.env.get('BOLDSIGN_API_KEY');
|
|
88
|
+
if (!apiKey) return json(500, { ok: false, error: 'boldsign_not_configured' });
|
|
89
|
+
|
|
90
|
+
let res: Response;
|
|
91
|
+
try {
|
|
92
|
+
res = await fetch('https://api.boldsign.com/v1/senderIdentities/create', {
|
|
93
|
+
method: 'POST',
|
|
94
|
+
headers: {
|
|
95
|
+
'X-API-KEY': apiKey,
|
|
96
|
+
'Content-Type': 'application/json',
|
|
97
|
+
accept: 'application/json',
|
|
98
|
+
},
|
|
99
|
+
body: JSON.stringify({ Name: name, Email: email }),
|
|
100
|
+
});
|
|
101
|
+
} catch (e) {
|
|
102
|
+
return json(502, { ok: false, error: 'boldsign_unreachable', detail: String(e).slice(0, 500) });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const text = await res.text();
|
|
106
|
+
let parsed: unknown = null;
|
|
107
|
+
try {
|
|
108
|
+
parsed = text ? JSON.parse(text) : null;
|
|
109
|
+
} catch {
|
|
110
|
+
parsed = { raw: text.slice(0, 1000) };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return json(res.status, res.ok ? { ok: true, ...(parsed as object ?? {}) } : { ok: false, error: 'boldsign_failed', detail: parsed });
|
|
114
|
+
}
|