@simplelayer/graniteer-core 0.0.1 → 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.
Files changed (100) hide show
  1. package/index.js +2 -2
  2. package/package.json +98 -15
  3. package/src/adminBookingCredit.test.ts +451 -0
  4. package/src/adminBookingCredit.ts +239 -0
  5. package/src/availability.test.ts +25 -0
  6. package/src/availability.ts +201 -0
  7. package/src/bookingHoldReclaim.ts +94 -0
  8. package/src/checkoutSessionParams.ts +56 -0
  9. package/src/commonsContract.ts +175 -0
  10. package/src/conductorAdmin.ts +141 -0
  11. package/src/email-templates/email-change.tsx +92 -0
  12. package/src/email-templates/invite.tsx +79 -0
  13. package/src/email-templates/reauthentication.tsx +60 -0
  14. package/src/functions/admin-cancel-membership.ts +311 -0
  15. package/src/functions/admin-change-membership-plan.ts +308 -0
  16. package/src/functions/admin-charge-guest-print.ts +229 -0
  17. package/src/functions/admin-correct-booking.ts +333 -0
  18. package/src/functions/admin-create-commons-event.ts +244 -0
  19. package/src/functions/admin-debug-boldsign-doc.ts +93 -0
  20. package/src/functions/admin-door-write.ts +272 -0
  21. package/src/functions/admin-mark-booking-paid.ts +203 -0
  22. package/src/functions/admin-photo-upload.ts +128 -0
  23. package/src/functions/admin-remove-team-member.ts +150 -0
  24. package/src/functions/admin-reset-mfa.ts +138 -0
  25. package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
  26. package/src/functions/admin-send-commons-agreement.ts +214 -0
  27. package/src/functions/admin-set-credit-amount.ts +123 -0
  28. package/src/functions/admin-skip-commons-contract.ts +165 -0
  29. package/src/functions/admin-undo-membership-cancel.ts +144 -0
  30. package/src/functions/admin-wall-photo-write.ts +141 -0
  31. package/src/functions/boldsign-sender-identity.ts +114 -0
  32. package/src/functions/booking-availability.ts +419 -0
  33. package/src/functions/booking-member-preview.ts +136 -0
  34. package/src/functions/day-pass-status.ts +89 -0
  35. package/src/functions/dayStatus.ts +71 -0
  36. package/src/functions/diag-webpush-test.ts +45 -0
  37. package/src/functions/event-access-store.ts +309 -0
  38. package/src/functions/ezeep-print-webhook.ts +213 -0
  39. package/src/functions/ezeep-usage-reconcile.ts +299 -0
  40. package/src/functions/get-signing-link.ts +211 -0
  41. package/src/functions/guest-print-setup-confirm.ts +128 -0
  42. package/src/functions/guest-print-submit.ts +149 -0
  43. package/src/functions/luma-webhook.ts +165 -0
  44. package/src/functions/migration-collision-alert.copy.ts +232 -0
  45. package/src/functions/migration-collision-alert.test.ts +349 -0
  46. package/src/functions/migration-collision-alert.ts +232 -0
  47. package/src/functions/office-assignment-end.ts +146 -0
  48. package/src/functions/portal-booking-access.ts +95 -0
  49. package/src/functions/portal-list-invoices.ts +99 -0
  50. package/src/functions/print-billing-recover.ts +97 -0
  51. package/src/functions/print-billing-run.ts +183 -0
  52. package/src/functions/public-facts.ts +168 -0
  53. package/src/functions/space-availability-range.acceptance.test.ts +161 -0
  54. package/src/functions/space-availability-range.ts +142 -0
  55. package/src/functions/sync-gcal-blackouts.ts +298 -0
  56. package/src/functions/timetable-event-register.ts +162 -0
  57. package/src/functions/timetable-event-status.ts +90 -0
  58. package/src/functions/timetable-spaces.ts +219 -0
  59. package/src/functions/touch-pass-reconciler.ts +689 -0
  60. package/src/functions/virtual-onboarding-purge.ts +134 -0
  61. package/src/functions/virtual-onboarding-submit.ts +315 -0
  62. package/src/functions/voice-inquiry.test.ts +301 -0
  63. package/src/functions/voice-inquiry.ts +198 -0
  64. package/src/functions/voice-tour-availability.ts +204 -0
  65. package/src/gcalSync.ts +142 -0
  66. package/src/ghlNote.ts +34 -0
  67. package/src/ghlTask.ts +48 -0
  68. package/src/ghlVoiceInquiry.ts +90 -0
  69. package/src/guestPrintCapture.test.ts +722 -0
  70. package/src/guestPrintCapture.ts +538 -0
  71. package/src/lumaGhl.ts +195 -0
  72. package/src/membership.ts +109 -0
  73. package/src/money.ts +36 -0
  74. package/src/ops.ts +97 -0
  75. package/src/pacificDate.ts +34 -0
  76. package/src/policyAcknowledgment.test.ts +50 -0
  77. package/src/policyAcknowledgment.ts +96 -0
  78. package/src/portalSession.ts +46 -0
  79. package/src/pricing.test.ts +660 -0
  80. package/src/pricing.ts +1025 -0
  81. package/src/printBilling.test.ts +750 -0
  82. package/src/printBilling.ts +891 -0
  83. package/src/printBillingAdapters.ts +169 -0
  84. package/src/printCorrections.test.ts +348 -0
  85. package/src/printCorrections.ts +496 -0
  86. package/src/rateLimit.ts +82 -0
  87. package/src/referralCredits.test.ts +31 -0
  88. package/src/referralCredits.ts +34 -0
  89. package/src/referralGrant.ts +321 -0
  90. package/src/rescheduleCredit.test.ts +521 -0
  91. package/src/rescheduleCredit.ts +337 -0
  92. package/src/reservationWifiCode.test.ts +69 -0
  93. package/src/reservationWifiCode.ts +81 -0
  94. package/src/retellCallAnalyzed.test.ts +167 -0
  95. package/src/retellCallAnalyzed.ts +113 -0
  96. package/src/retellSignature.test.ts +137 -0
  97. package/src/retellSignature.ts +82 -0
  98. package/src/slackAlert.ts +38 -0
  99. package/src/supabaseTestFakes.ts +131 -0
  100. package/src/tier1Agreement.ts +125 -0
@@ -0,0 +1,299 @@
1
+ // supabase/functions/ezeep-usage-reconcile/index.ts
2
+ //
3
+ // PERMANENT, SECRET-GATED reconciliation gate for ezeep print-usage billing.
4
+ // Pulls ezeep's official Reporting API CSV for a calendar month and diffs
5
+ // it job-by-job against public.print_jobs. FAILS CLOSED: any missing/extra/
6
+ // mismatched job for the month blocks ALL print_usage_periods rows for that
7
+ // month from being marked reconciled -- no partial credit, no silent
8
+ // auto-correction (Kyle's 2026-08-21 decision). Only a clean diff stamps
9
+ // reconciled_at on every pending_bill period for that month -- the gate
10
+ // Phase 2's print-usage-bill (not yet built) must read instead of
11
+ // pending_bill alone.
12
+ //
13
+ // Scheduled by pg_cron (monthly, 1st @ 09:20 UTC) via
14
+ // private.trigger_ezeep_reconcile() -> net.http_post {}.
15
+ //
16
+ // ezeep OAuth is Authorization Code Flow. refresh_token ROTATES ON EVERY
17
+ // USE (confirmed empirically 2026-08-21) and lives in
18
+ // private.ezeep_oauth_state, not a static function secret. The new
19
+ // refresh_token is persisted immediately after exchange, before any other
20
+ // work, so a downstream failure never strands this on a dead token.
21
+
22
+ import { createClient } from 'npm:@supabase/supabase-js@2';
23
+
24
+ const EZEEP_TOKEN_URL = 'https://account.ezeep.com/oauth/access_token/';
25
+ const EZEEP_API_BASE = 'https://api2.ezeep.com';
26
+ const REPORT_POLL_ATTEMPTS = 10;
27
+ const REPORT_POLL_DELAY_MS = 3000;
28
+
29
+ function safeEqual(a: string, b: string): boolean {
30
+ const enc = new TextEncoder();
31
+ const ab = enc.encode(a), bb = enc.encode(b);
32
+ if (ab.length !== bb.length) return false;
33
+ let diff = 0;
34
+ for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
35
+ return diff === 0;
36
+ }
37
+
38
+ function priorMonthRange(now = new Date()): { start: string; end: string; periodMonth: string } {
39
+ const y = now.getUTCFullYear();
40
+ const m = now.getUTCMonth();
41
+ const start = new Date(Date.UTC(y, m - 1, 1));
42
+ const end = new Date(Date.UTC(y, m, 1));
43
+ const iso = (d: Date) => d.toISOString().slice(0, 10);
44
+ return { start: iso(start), end: iso(end), periodMonth: iso(start) };
45
+ }
46
+
47
+ function nextMonthIso(iso: string): string {
48
+ const d = new Date(iso + 'T00:00:00Z');
49
+ const next = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1));
50
+ return next.toISOString().slice(0, 10);
51
+ }
52
+
53
+ // Minimal RFC4180 CSV parser: handles quoted fields, embedded commas/quotes,
54
+ // and CRLF/LF/CR line endings. ezeep's export needs this -- a naive
55
+ // split(',') misaligns columns on rows with commas inside a field.
56
+ function parseCsv(text: string): Record<string, string>[] {
57
+ const rows: string[][] = [];
58
+ let row: string[] = [];
59
+ let field = '';
60
+ let inQuotes = false;
61
+ const clean = text.replace(/^/, '');
62
+ for (let i = 0; i < clean.length; i++) {
63
+ const c = clean[i];
64
+ if (inQuotes) {
65
+ if (c === '"') {
66
+ if (clean[i + 1] === '"') { field += '"'; i++; } else { inQuotes = false; }
67
+ } else field += c;
68
+ } else if (c === '"') inQuotes = true;
69
+ else if (c === ',') { row.push(field); field = ''; }
70
+ else if (c === '\n' || c === '\r') {
71
+ if (c === '\r' && clean[i + 1] === '\n') i++;
72
+ row.push(field); field = '';
73
+ if (row.length > 1 || row[0] !== '') rows.push(row);
74
+ row = [];
75
+ } else field += c;
76
+ }
77
+ if (field !== '' || row.length > 0) { row.push(field); rows.push(row); }
78
+ if (rows.length === 0) return [];
79
+ const header = rows[0];
80
+ return rows.slice(1).map((r) => {
81
+ const obj: Record<string, string> = {};
82
+ header.forEach((h, idx) => { obj[h] = r[idx] ?? ''; });
83
+ return obj;
84
+ });
85
+ }
86
+
87
+ async function getOAuthCreds(supabase: any) {
88
+ const { data, error } = await supabase.rpc('get_ezeep_oauth_credentials');
89
+ if (error || !data) {
90
+ throw new Error('failed to load ezeep oauth credentials: ' + (error?.message ?? 'none'));
91
+ }
92
+ return data as { client_id: string; client_secret: string; refresh_token: string };
93
+ }
94
+
95
+ async function refreshEzeepToken(
96
+ supabase: any,
97
+ creds: { client_id: string; client_secret: string; refresh_token: string },
98
+ ): Promise<string> {
99
+ const basic = btoa(`${creds.client_id}:${creds.client_secret}`);
100
+ const res = await fetch(EZEEP_TOKEN_URL, {
101
+ method: 'POST',
102
+ headers: {
103
+ 'Authorization': `Basic ${basic}`,
104
+ 'Content-Type': 'application/x-www-form-urlencoded',
105
+ },
106
+ body: new URLSearchParams({
107
+ grant_type: 'refresh_token',
108
+ refresh_token: creds.refresh_token,
109
+ }),
110
+ });
111
+ if (!res.ok) {
112
+ throw new Error(`ezeep token refresh failed: ${res.status} ${await res.text().catch(() => '')}`);
113
+ }
114
+ const json = await res.json();
115
+ // Persist the rotated refresh token IMMEDIATELY -- before anything else
116
+ // that could fail and strand us on a token ezeep has already invalidated.
117
+ const { error: writeErr } = await supabase.rpc('set_ezeep_refresh_token', {
118
+ new_token: json.refresh_token,
119
+ });
120
+ if (writeErr) {
121
+ throw new Error('CRITICAL: got new ezeep refresh_token but failed to persist it: ' + writeErr.message);
122
+ }
123
+ return json.access_token as string;
124
+ }
125
+
126
+ export async function handle(req: Request): Promise<Response> {
127
+ if (req.method !== 'POST' && req.method !== 'GET') {
128
+ return new Response('Method not allowed', { status: 405 });
129
+ }
130
+ const provided = req.headers.get('x-reconcile-secret');
131
+ if (!provided) return new Response('Unauthorized', { status: 401 });
132
+
133
+ const supabase = createClient(
134
+ Deno.env.get('SUPABASE_URL')!,
135
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
136
+ );
137
+
138
+ const { data: gate, error: gateErr } = await supabase.rpc('get_ezeep_reconcile_secret');
139
+ const expected = typeof gate === 'string' ? gate : null;
140
+ if (gateErr || !expected || !safeEqual(provided, expected)) {
141
+ return new Response('Unauthorized', { status: 401 });
142
+ }
143
+
144
+ let overridePeriod: string | null = null;
145
+ if (req.method === 'POST') {
146
+ const body = await req.json().catch(() => ({} as any));
147
+ if (typeof body?.period_month === 'string') overridePeriod = body.period_month;
148
+ }
149
+
150
+ try {
151
+ const creds = await getOAuthCreds(supabase);
152
+ const accessToken = await refreshEzeepToken(supabase, creds);
153
+
154
+ const { start, end, periodMonth } = overridePeriod
155
+ ? { start: overridePeriod, end: nextMonthIso(overridePeriod), periodMonth: overridePeriod }
156
+ : priorMonthRange();
157
+
158
+ const createRes = await fetch(`${EZEEP_API_BASE}/reporting/reports`, {
159
+ method: 'POST',
160
+ headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
161
+ body: JSON.stringify({ start, end, csv_delimiter: ',', timestamp_offset: 0 }),
162
+ });
163
+ if (!createRes.ok) {
164
+ throw new Error(`ezeep report create failed: ${createRes.status} ${await createRes.text().catch(() => '')}`);
165
+ }
166
+ const created = await createRes.json();
167
+ const reportId = created.report_id as string;
168
+
169
+ let status = created.status as string;
170
+ for (let i = 0; i < REPORT_POLL_ATTEMPTS && status === 'pending'; i++) {
171
+ await new Promise((r) => setTimeout(r, REPORT_POLL_DELAY_MS));
172
+ const pollRes = await fetch(`${EZEEP_API_BASE}/reporting/reports/${reportId}`, {
173
+ headers: { 'Authorization': `Bearer ${accessToken}` },
174
+ });
175
+ if (!pollRes.ok) throw new Error(`ezeep report poll failed: ${pollRes.status}`);
176
+ const polled = await pollRes.json();
177
+ status = polled.status;
178
+ }
179
+ if (status !== 'succeeded') {
180
+ throw new Error(`ezeep report did not succeed in time (status=${status}, report_id=${reportId})`);
181
+ }
182
+
183
+ const dlRes = await fetch(`${EZEEP_API_BASE}/reporting/reports/${reportId}/download`, {
184
+ headers: { 'Authorization': `Bearer ${accessToken}` },
185
+ });
186
+ if (!dlRes.ok) throw new Error(`ezeep report download failed: ${dlRes.status}`);
187
+ const csvText = await dlRes.text();
188
+ const rows = parseCsv(csvText);
189
+
190
+ // ezeep's own official succeeded-job set for the month.
191
+ const ezeepJobs = new Map<string, { pages: number; color: boolean }>();
192
+ for (const r of rows) {
193
+ if (r['Final status'] !== 'succeeded') continue;
194
+ const id = r['Print job ID'];
195
+ if (!id) continue;
196
+ ezeepJobs.set(id, {
197
+ pages: Number(r['Total printed pages'] || 0),
198
+ color: r['Chromaticity'] === 'color',
199
+ });
200
+ }
201
+
202
+ const { data: ourJobsRaw, error: jobsErr } = await supabase
203
+ .from('print_jobs')
204
+ .select('ezeep_printjob_id,total_printed_pages,color,job_created_at,topic')
205
+ .eq('topic', 'printjob_succeeded')
206
+ .gte('job_created_at', `${start}T00:00:00Z`)
207
+ .lt('job_created_at', `${end}T00:00:00Z`);
208
+ if (jobsErr) throw new Error('print_jobs read failed: ' + jobsErr.message);
209
+
210
+ const ourJobs = new Map<string, { pages: number; color: boolean }>();
211
+ for (const j of ourJobsRaw ?? []) {
212
+ ourJobs.set(j.ezeep_printjob_id, { pages: j.total_printed_pages, color: j.color });
213
+ }
214
+
215
+ const missingInOurs: string[] = [];
216
+ const mismatched: Array<Record<string, unknown>> = [];
217
+ for (const [id, ez] of ezeepJobs) {
218
+ const ours = ourJobs.get(id);
219
+ if (!ours) { missingInOurs.push(id); continue; }
220
+ if (ours.pages !== ez.pages || ours.color !== ez.color) {
221
+ mismatched.push({ ezeep_printjob_id: id, ezeep: ez, ours });
222
+ }
223
+ }
224
+ const extraInOurs: string[] = [];
225
+ for (const id of ourJobs.keys()) {
226
+ if (!ezeepJobs.has(id)) extraInOurs.push(id);
227
+ }
228
+
229
+ const clean = missingInOurs.length === 0 && extraInOurs.length === 0 && mismatched.length === 0;
230
+
231
+ if (!clean) {
232
+ await supabase.from('ops_events').insert({
233
+ kind: 'ezeep_reconciliation_mismatch',
234
+ severity: 'error',
235
+ detail: {
236
+ period_month: periodMonth,
237
+ report_id: reportId,
238
+ ezeep_job_count: ezeepJobs.size,
239
+ our_job_count: ourJobs.size,
240
+ missing_in_ours: missingInOurs.slice(0, 25),
241
+ missing_in_ours_count: missingInOurs.length,
242
+ extra_in_ours: extraInOurs.slice(0, 25),
243
+ extra_in_ours_count: extraInOurs.length,
244
+ mismatched: mismatched.slice(0, 25),
245
+ mismatched_count: mismatched.length,
246
+ },
247
+ });
248
+ return new Response(JSON.stringify({
249
+ ok: true,
250
+ clean: false,
251
+ period_month: periodMonth,
252
+ report_id: reportId,
253
+ missing_in_ours_count: missingInOurs.length,
254
+ extra_in_ours_count: extraInOurs.length,
255
+ mismatched_count: mismatched.length,
256
+ }), { headers: { 'Content-Type': 'application/json' }, status: 200 });
257
+ }
258
+
259
+ const { data: stamped, error: stampErr } = await supabase
260
+ .from('print_usage_periods')
261
+ .update({ reconciled_at: new Date().toISOString(), reconciliation_report_id: reportId })
262
+ .eq('period_month', periodMonth)
263
+ .eq('status', 'pending_bill')
264
+ .is('reconciled_at', null)
265
+ .select('id');
266
+ if (stampErr) throw new Error('failed to stamp reconciled_at: ' + stampErr.message);
267
+
268
+ await supabase.from('ops_events').insert({
269
+ kind: 'ezeep_reconciliation_ok',
270
+ severity: 'info',
271
+ detail: {
272
+ period_month: periodMonth,
273
+ report_id: reportId,
274
+ ezeep_job_count: ezeepJobs.size,
275
+ periods_reconciled: (stamped ?? []).length,
276
+ },
277
+ });
278
+
279
+ return new Response(JSON.stringify({
280
+ ok: true,
281
+ clean: true,
282
+ period_month: periodMonth,
283
+ report_id: reportId,
284
+ ezeep_job_count: ezeepJobs.size,
285
+ periods_reconciled: (stamped ?? []).length,
286
+ }), { headers: { 'Content-Type': 'application/json' }, status: 200 });
287
+ } catch (e) {
288
+ try {
289
+ await supabase.from('ops_events').insert({
290
+ kind: 'ezeep_reconciliation_error',
291
+ severity: 'error',
292
+ detail: { error: String(e) },
293
+ });
294
+ } catch { /* ignore */ }
295
+ return new Response(JSON.stringify({ ok: false, error: String(e) }), {
296
+ headers: { 'Content-Type': 'application/json' }, status: 500,
297
+ });
298
+ }
299
+ }
@@ -0,0 +1,211 @@
1
+ // Staff-only tool: fetch a fresh BoldSign embedded signing link for whichever
2
+ // recipient on a private-office-agreement document hasn't signed yet, so it
3
+ // can be copied and sent by hand (e.g. over the phone). Never triggers any
4
+ // BoldSign or app email -- this only reads BoldSign state and mints a link.
5
+ import { createClient } from 'npm:@supabase/supabase-js@2';
6
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
7
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
8
+
9
+ const corsHeaders = {
10
+ 'Access-Control-Allow-Origin': '*',
11
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
12
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
13
+ };
14
+
15
+ interface CallerClaims {
16
+ sub: string;
17
+ email?: string;
18
+ aal?: string;
19
+ }
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
+ const token = authHeader.slice(7).trim();
31
+ try {
32
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
33
+ const claims = payload as unknown as CallerClaims;
34
+ if (!claims.sub) return null;
35
+ return claims;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ function json(status: number, body: unknown) {
42
+ return new Response(JSON.stringify(body), {
43
+ status,
44
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
45
+ });
46
+ }
47
+
48
+ interface Recipient {
49
+ name: string;
50
+ email: string;
51
+ status: string;
52
+ }
53
+
54
+ // BoldSign has shipped several field spellings across API versions for the
55
+ // same concept -- accept any of them rather than depending on one. Mirrors
56
+ // the same tolerant parsing used in _shared/agreementActivation.ts.
57
+ function emailOf(s: Record<string, unknown>): string {
58
+ return String(s.signerEmail ?? s.emailAddress ?? s.email ?? '').trim();
59
+ }
60
+ function nameOf(s: Record<string, unknown>): string {
61
+ return String(s.signerName ?? s.name ?? '').trim();
62
+ }
63
+ function statusOf(s: Record<string, unknown>): string {
64
+ return String(s.status ?? '').trim();
65
+ }
66
+
67
+ const COMPLETED_STATUSES = new Set(['completed', 'signed']);
68
+
69
+ export async function handle(req: Request): Promise<Response> {
70
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
71
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
72
+
73
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
74
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
75
+
76
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
77
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
78
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
79
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
80
+ const callerEmail = (caller.email ?? '').toLowerCase();
81
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
82
+
83
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
84
+ auth: { persistSession: false, autoRefreshToken: false },
85
+ });
86
+
87
+ const [ipOk, emailOk] = await Promise.all([
88
+ checkRateLimit(admin, 'get-signing-link-ip', clientIp(req), 30, 300),
89
+ checkRateLimit(admin, 'get-signing-link-email', callerEmail, 20, 300),
90
+ ]);
91
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
92
+
93
+ const { data: allow, error: allowErr } = await admin
94
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
95
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
96
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
97
+
98
+ let body: { signature_document_id?: string; signer_email?: string };
99
+ try {
100
+ body = await req.json();
101
+ } catch {
102
+ return json(400, { ok: false, error: 'invalid_json' });
103
+ }
104
+ const docId = (body.signature_document_id ?? '').trim();
105
+ if (!/^[0-9a-f-]{36}$/i.test(docId)) {
106
+ return json(400, { ok: false, error: 'invalid_signature_document_id' });
107
+ }
108
+ const requestedSignerEmail = (body.signer_email ?? '').trim();
109
+
110
+ try {
111
+ const { data: row, error: rowErr } = await admin
112
+ .from('signature_documents')
113
+ .select('id,boldsign_document_id,signer_name,signer_email')
114
+ .eq('id', docId)
115
+ .maybeSingle();
116
+ if (rowErr) return json(500, { ok: false, error: 'row_lookup_failed', detail: rowErr.message });
117
+ if (!row) return json(404, { ok: false, error: 'not_found' });
118
+ if (!row.boldsign_document_id) {
119
+ return json(400, {
120
+ ok: false,
121
+ error: 'not_sent',
122
+ detail: 'This agreement has not been sent to BoldSign yet, so there is nothing to sign.',
123
+ });
124
+ }
125
+
126
+ const apiKey = Deno.env.get('BOLDSIGN_API_KEY');
127
+ if (!apiKey) return json(500, { ok: false, error: 'boldsign_not_configured' });
128
+
129
+ const propsRes = await fetch(
130
+ `https://api.boldsign.com/v1/document/properties?documentId=${encodeURIComponent(row.boldsign_document_id)}`,
131
+ { headers: { 'X-API-KEY': apiKey, accept: 'application/json' } },
132
+ );
133
+ const propsText = await propsRes.text();
134
+ if (!propsRes.ok) {
135
+ return json(500, {
136
+ ok: false,
137
+ error: 'boldsign_failed',
138
+ detail: `BoldSign ${propsRes.status}: ${propsText}`.slice(0, 500),
139
+ });
140
+ }
141
+
142
+ let props: unknown;
143
+ try {
144
+ props = JSON.parse(propsText);
145
+ } catch {
146
+ return json(500, { ok: false, error: 'boldsign_properties_bad_json' });
147
+ }
148
+
149
+ const signerDetails: Record<string, unknown>[] = Array.isArray((props as { signerDetails?: unknown })?.signerDetails)
150
+ ? ((props as { signerDetails: unknown[] }).signerDetails as Record<string, unknown>[])
151
+ : [];
152
+ const recipients: Recipient[] = signerDetails.map((s) => ({
153
+ name: nameOf(s),
154
+ email: emailOf(s),
155
+ status: statusOf(s),
156
+ }));
157
+
158
+ let targetEmail: string;
159
+ if (requestedSignerEmail) {
160
+ const match = recipients.find((r) => r.email.toLowerCase() === requestedSignerEmail.toLowerCase());
161
+ if (!match) return json(400, { ok: false, error: 'unknown_signer', recipients });
162
+ targetEmail = match.email;
163
+ } else {
164
+ const pending = recipients.find((r) => !COMPLETED_STATUSES.has(r.status.toLowerCase()));
165
+ if (!pending) {
166
+ return json(409, { ok: false, error: 'already_completed', recipients });
167
+ }
168
+ targetEmail = pending.email;
169
+ }
170
+
171
+ const linkRes = await fetch(
172
+ 'https://api.boldsign.com/v1/document/getEmbeddedSignLink' +
173
+ `?documentId=${encodeURIComponent(row.boldsign_document_id)}` +
174
+ `&signerEmail=${encodeURIComponent(targetEmail)}`,
175
+ { headers: { 'X-API-KEY': apiKey, accept: 'application/json' } },
176
+ );
177
+ const linkText = await linkRes.text();
178
+ if (!linkRes.ok) {
179
+ return json(500, {
180
+ ok: false,
181
+ error: 'boldsign_failed',
182
+ detail: `BoldSign ${linkRes.status}: ${linkText}`.slice(0, 500),
183
+ });
184
+ }
185
+
186
+ let signLink: string | null = null;
187
+ try {
188
+ signLink = (JSON.parse(linkText) as { signLink?: string }).signLink ?? null;
189
+ } catch {
190
+ signLink = null;
191
+ }
192
+ if (!signLink) {
193
+ return json(500, {
194
+ ok: false,
195
+ error: 'no_sign_link',
196
+ detail: `BoldSign returned no signLink: ${linkText}`.slice(0, 500),
197
+ });
198
+ }
199
+
200
+ const matchedRecipient = recipients.find((r) => r.email.toLowerCase() === targetEmail.toLowerCase());
201
+ return json(200, {
202
+ ok: true,
203
+ signerEmail: targetEmail,
204
+ signerName: matchedRecipient?.name || row.signer_name || '',
205
+ signLink,
206
+ recipients,
207
+ });
208
+ } catch (e) {
209
+ return json(500, { ok: false, error: 'unhandled', detail: String(e).slice(0, 500) });
210
+ }
211
+ }
@@ -0,0 +1,128 @@
1
+ // Guest-facing: called by the frontend right after Stripe.js confirms the
2
+ // SetupIntent client-side (confirmCardSetup). We never trust that client
3
+ // report on its own -- see the ownership check below and
4
+ // confirmGuestPrintSetup's own re-retrieve-from-Stripe discipline.
5
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
6
+ import { createClient } from 'npm:@supabase/supabase-js@2';
7
+ import Stripe from 'npm:stripe@17.5.0';
8
+ import { z } from 'npm:zod@3.23.8';
9
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
10
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
11
+ import {
12
+ confirmGuestPrintSetup,
13
+ type GuestPrintDbLike,
14
+ type GuestPrintStripeLike,
15
+ } from 'npm:@simplelayer/graniteer-core/guestPrintCapture';
16
+
17
+ const Body = z.object({
18
+ submission_id: z.string().uuid(),
19
+ setup_intent_id: z.string().min(1).max(200),
20
+ });
21
+
22
+ function json(status: number, body: unknown) {
23
+ return new Response(JSON.stringify(body), {
24
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
25
+ });
26
+ }
27
+
28
+ export async function handle(req: Request): Promise<Response> {
29
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
30
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
31
+
32
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
33
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
34
+ const supabase = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
35
+ auth: { persistSession: false, autoRefreshToken: false },
36
+ });
37
+
38
+ let raw: unknown;
39
+ try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
40
+ const parsed = Body.safeParse(raw);
41
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
42
+ const { submission_id, setup_intent_id } = parsed.data;
43
+
44
+ const ip = clientIp(req);
45
+ const ipOk = await checkRateLimit(supabase, 'guest-print-setup-confirm-ip', ip, 30, 600);
46
+ if (!ipOk) return json(429, { ok: false, error: 'rate_limited' });
47
+
48
+ // Ownership check BEFORE touching Stripe: the submission_id + setup_intent_id
49
+ // pair must belong to the same row, or a guessed submission_id + an
50
+ // attacker's own real setup_intent_id could mark someone else's row
51
+ // 'card_saved' with the attacker's payment method. This check plus
52
+ // confirmGuestPrintSetup's own re-retrieve-from-Stripe are BOTH required --
53
+ // this proves the pair is bound to one row; that proves what Stripe itself
54
+ // says about it.
55
+ const { data: row, error: rowErr } = await supabase
56
+ .from('print_guest_submissions')
57
+ .select('id,status,stripe_setup_intent_id')
58
+ .eq('id', submission_id)
59
+ .maybeSingle();
60
+ if (rowErr) return json(500, { ok: false, error: 'lookup_failed' });
61
+ if (!row || row.stripe_setup_intent_id !== setup_intent_id) {
62
+ return json(404, { ok: false, error: 'not_found' });
63
+ }
64
+ if (row.status === 'card_saved') {
65
+ // Idempotent: the frontend can safely call this twice.
66
+ return json(200, { ok: true, status: 'card_saved' });
67
+ }
68
+ if (row.status !== 'pending_card') {
69
+ return json(409, { ok: false, error: 'not_confirmable', status: row.status });
70
+ }
71
+
72
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
73
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
74
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
75
+
76
+ const stripeLike: GuestPrintStripeLike = {
77
+ customers: {
78
+ search: (p) => stripe.customers.search(p),
79
+ list: (p) => stripe.customers.list(p),
80
+ create: (p) => stripe.customers.create(p),
81
+ },
82
+ setupIntents: {
83
+ create: (p, o) => stripe.setupIntents.create(p, o),
84
+ retrieve: (id, p) => stripe.setupIntents.retrieve(id, p),
85
+ },
86
+ paymentIntents: {
87
+ // See guest-print-submit/index.ts for why this cast is needed.
88
+ create: (p, o) => stripe.paymentIntents.create(p as never, o),
89
+ retrieve: (id) => stripe.paymentIntents.retrieve(id),
90
+ },
91
+ };
92
+
93
+ const dbLike: GuestPrintDbLike = {
94
+ async insertPending() { throw new Error('not used by setup-confirm'); },
95
+ async attachStripeIds() { throw new Error('not used by setup-confirm'); },
96
+ async markCardSaved(id, paymentMethodId) {
97
+ const { error } = await supabase
98
+ .from('print_guest_submissions')
99
+ .update({ status: 'card_saved', stripe_payment_method_id: paymentMethodId })
100
+ .eq('id', id);
101
+ if (error) throw error;
102
+ },
103
+ async markFailed(id, reason) {
104
+ const { error } = await supabase
105
+ .from('print_guest_submissions')
106
+ .update({ last_error: reason.slice(0, 2000) })
107
+ .eq('id', id);
108
+ if (error) console.error('[guest-print-setup-confirm] markFailed write failed', error);
109
+ },
110
+ async getById() { throw new Error('not used by setup-confirm'); },
111
+ async claimForCharge() { throw new Error('not used by setup-confirm'); },
112
+ async writebackCharged() { throw new Error('not used by setup-confirm'); },
113
+ async writebackChargeFailed() { throw new Error('not used by setup-confirm'); },
114
+ };
115
+
116
+ try {
117
+ const outcome = await confirmGuestPrintSetup(stripeLike, dbLike, submission_id, setup_intent_id);
118
+ if (!outcome.ok) {
119
+ return json(409, { ok: false, error: outcome.detail ?? 'not_succeeded', status: outcome.status });
120
+ }
121
+ return json(200, { ok: true, status: outcome.status });
122
+ } catch (e) {
123
+ console.error('guest-print-setup-confirm error', e);
124
+ await logOps(supabase, 'guest_print_setup_confirm_error',
125
+ { submission_id, message: e instanceof Error ? e.message : String(e) }, { severity: 'error' });
126
+ return json(500, { ok: false, error: 'unexpected_error' });
127
+ }
128
+ }