@simplelayer/graniteer-core 0.2.0 → 0.2.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 (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -460
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -309
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -95
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -1,323 +1,323 @@
1
- // Staff-triggered resend of a Commons (tier 3) event's deposit-payment link.
2
- //
3
- // The underlying Stripe Checkout Session expires after 24h, and the original
4
- // session is only ever created once (CAS-guarded) by
5
- // _shared/commonsDepositWebhook.ts on the genuine `Completed` transition —
6
- // there is no other path that reissues it. This is the staff-facing "the
7
- // client's link went stale" escape hatch.
8
- //
9
- // Auth/allowlist/rate-limit scaffold, the Stripe-session-status decision
10
- // tree, and the "unconditional overwrite, no CAS" resend-email policy are all
11
- // copied from admin-resend-payment-link-email (the tier-2 analog of exactly
12
- // this function) — adapted from Stripe Payment Link semantics to Checkout
13
- // Session semantics, since tier 3 uses `stripe.checkout.sessions`, not
14
- // payment links.
15
- import { createClient } from 'npm:@supabase/supabase-js@2';
16
- import Stripe from 'npm:stripe@17.5.0';
17
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
18
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
19
- import {
20
- buildCommonsDepositSessionParams,
21
- longDateFromIso,
22
- longDateFromYmd,
23
- sendCommonsDepositLinkEmail,
24
- type CommonsSnapshot,
25
- } from 'npm:@simplelayer/graniteer-core/commonsDeposit';
26
-
27
- const corsHeaders = {
28
- 'Access-Control-Allow-Origin': '*',
29
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
30
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
31
- };
32
-
33
- interface CallerClaims {
34
- sub: string;
35
- email?: string;
36
- aal?: string;
37
- }
38
-
39
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
40
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
41
- function getJwks(supabaseUrl: string) {
42
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
43
- return jwksCache;
44
- }
45
-
46
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
47
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
48
- const token = authHeader.slice(7).trim();
49
- try {
50
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
51
- const claims = payload as unknown as CallerClaims;
52
- if (!claims.sub) return null;
53
- return claims;
54
- } catch {
55
- return null;
56
- }
57
- }
58
-
59
- function json(status: number, body: unknown) {
60
- return new Response(JSON.stringify(body), {
61
- status,
62
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
63
- });
64
- }
65
-
66
- export async function handle(
67
- req: Request,
68
- operator: { operatorName: string; operatorShortName: string; domain: string; supportEmail: string; ccEmails: string[] },
69
- ): 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, 'admin-resend-commons-deposit-ip', clientIp(req), 60, 300),
89
- checkRateLimit(admin, 'admin-resend-commons-deposit-email', callerEmail, 40, 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: { booking_id?: string };
99
- try {
100
- body = await req.json();
101
- } catch {
102
- return json(400, { ok: false, error: 'invalid_json' });
103
- }
104
-
105
- const bookingId = (body.booking_id ?? '').trim();
106
- if (!/^[0-9a-f-]{36}$/i.test(bookingId)) {
107
- return json(400, { ok: false, error: 'invalid_booking_id' });
108
- }
109
-
110
- const { data: booking, error: bookingErr } = await admin
111
- .from('bookings')
112
- .select('id,status,deposit_amount_cents,list_amount_cents,hold_expires_at,contact_email,contact_name,stripe_session_id,room_id')
113
- .eq('id', bookingId)
114
- .maybeSingle();
115
- if (bookingErr) return json(500, { ok: false, error: 'lookup_failed' });
116
- if (!booking) return json(404, { ok: false, error: 'not_found' });
117
-
118
- // Most recent tier-3 agreement for this booking — a booking can have more
119
- // than one row if an earlier agreement was ever revoked and resent.
120
- const { data: agreement, error: agreementErr } = await admin
121
- .from('booking_agreements')
122
- .select('id,status,signer_email,signer_name,metadata,content_url')
123
- .eq('booking_id', bookingId)
124
- .eq('tier', 3)
125
- .order('created_at', { ascending: false })
126
- .limit(1)
127
- .maybeSingle();
128
- if (agreementErr) return json(500, { ok: false, error: 'agreement_lookup_failed' });
129
- if (!agreement || agreement.status !== 'completed') {
130
- // Nothing to resend until the contract itself is signed.
131
- return json(409, { ok: false, error: 'not_signed_yet' });
132
- }
133
-
134
- if (booking.status === 'deposit_paid') {
135
- return json(409, { ok: false, error: 'already_paid' });
136
- }
137
- if (booking.status !== 'pending') {
138
- return json(409, { ok: false, error: 'booking_not_active' });
139
- }
140
-
141
- const snapshot = ((agreement.metadata ?? {}) as Record<string, unknown>).commons as
142
- | CommonsSnapshot
143
- | undefined;
144
- if (!snapshot) {
145
- return json(500, { ok: false, error: 'commons_snapshot_missing' });
146
- }
147
-
148
- const depositCents = Number(booking.deposit_amount_cents ?? NaN);
149
- const totalCents = Number(booking.list_amount_cents ?? NaN);
150
- const balanceCents = Number(snapshot.balance_cents ?? Math.max(0, totalCents - depositCents));
151
- const eventDateLabel = longDateFromYmd(snapshot.event_date) ??
152
- longDateFromIso(snapshot.arrival_at) ?? 'your event date';
153
- const balanceDueLabel = longDateFromYmd(snapshot.balance_due_date) ??
154
- 'the date shown in your agreement';
155
-
156
- const signerEmail = String(agreement.signer_email ?? booking.contact_email ?? '').trim();
157
- if (!signerEmail) {
158
- return json(500, { ok: false, error: 'missing_signer_email' });
159
- }
160
-
161
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
162
- if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
163
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
164
-
165
- const existingSessionId = (booking.stripe_session_id as string | null) ?? '';
166
- let needsNewSession = false;
167
- let checkoutUrl: string | null = null;
168
-
169
- if (existingSessionId.trim() !== '') {
170
- try {
171
- const session = await stripe.checkout.sessions.retrieve(existingSessionId);
172
- if (session.status === 'complete') {
173
- // `complete` alone does NOT mean paid — check payment_status.
174
- if (session.payment_status === 'paid' || session.payment_status === 'no_payment_required') {
175
- return json(409, { ok: false, error: 'already_paid' });
176
- }
177
- // Completed but unpaid (declined card, pending ACH): refuse, don't reissue.
178
- return json(409, { ok: false, error: 'complete_unpaid' });
179
- }
180
- if (session.status === 'expired') {
181
- needsNewSession = true;
182
- } else {
183
- // status === 'open' -> resend the authoritative URL from the live object.
184
- checkoutUrl = session.url ?? null;
185
- }
186
- } catch (e) {
187
- const err = e as { code?: string; statusCode?: number };
188
- const genuinelyMissing = err?.code === 'resource_missing' || err?.statusCode === 404;
189
- if (!genuinelyMissing) {
190
- const detail = (e instanceof Error ? e.message : String(e)).slice(0, 500);
191
- console.error('[admin-resend-commons-deposit-link] stripe unavailable', detail);
192
- return json(503, { ok: false, error: 'stripe_unavailable', detail });
193
- }
194
- console.warn('[admin-resend-commons-deposit-link] session missing, will reissue');
195
- needsNewSession = true;
196
- }
197
- } else {
198
- needsNewSession = true;
199
- }
200
-
201
- if (needsNewSession) {
202
- // Tamper check — the money on the booking must still match what the
203
- // signed document says. Any drift means the document and the charge we're
204
- // about to mint disagree: fail closed rather than charge a different
205
- // amount than what was signed. Same check as commonsDepositWebhook.ts.
206
- if (
207
- !Number.isFinite(depositCents) || !Number.isFinite(totalCents) ||
208
- depositCents !== Number(snapshot.deposit_cents) || totalCents !== Number(snapshot.total_cents)
209
- ) {
210
- return json(500, {
211
- ok: false,
212
- error: 'commons_amount_drift',
213
- detail: {
214
- booking_deposit_cents: Number.isFinite(depositCents) ? depositCents : null,
215
- snapshot_deposit_cents: snapshot.deposit_cents ?? null,
216
- booking_total_cents: Number.isFinite(totalCents) ? totalCents : null,
217
- snapshot_total_cents: snapshot.total_cents ?? null,
218
- },
219
- });
220
- }
221
-
222
- const base = `https://${operator.domain}`;
223
- const params = buildCommonsDepositSessionParams({
224
- bookingId,
225
- agreementId: String(agreement.id),
226
- signerEmail,
227
- depositCents,
228
- totalCents,
229
- balanceCents,
230
- eventDateLabel,
231
- balanceDueLabel,
232
- successUrl: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
233
- cancelUrl: `${base}/contact?commons_deposit=canceled`,
234
- });
235
-
236
- let session: Stripe.Checkout.Session;
237
- try {
238
- // NOT commonsDepositIdempotencyKey(bookingId) alone — that key is
239
- // deterministic per booking and would collide with (and could return)
240
- // the original, now-expired session. Suffixing with the old session id
241
- // guarantees a fresh key each time the previous one has actually
242
- // expired, while staying safely idempotent against an accidental
243
- // double-click on the same stale session.
244
- session = await stripe.checkout.sessions.create(params, {
245
- idempotencyKey: `commons-deposit-resend-${bookingId}-${existingSessionId || 'none'}`,
246
- });
247
- } catch (e) {
248
- const detail = (e instanceof Error ? e.message : String(e)).slice(0, 500);
249
- console.error('[admin-resend-commons-deposit-link] session create failed', detail);
250
- return json(500, { ok: false, error: 'session_create_failed', detail });
251
- }
252
- if (!session.url) return json(500, { ok: false, error: 'stripe_session_missing_url' });
253
-
254
- // Compare-and-swap: only the caller that still sees the old (or, for a
255
- // booking that never had one, absent) session id wins the write. Legacy
256
- // rows with no session id at all CAS against NULL, same fallback pattern
257
- // as admin-resend-payment-link-email.
258
- const swapQuery = admin.from('bookings').update({ stripe_session_id: session.id }).eq('id', bookingId);
259
- const { data: swapped, error: swapErr } = await (
260
- existingSessionId.trim() === ''
261
- ? swapQuery.is('stripe_session_id', null)
262
- : swapQuery.eq('stripe_session_id', existingSessionId)
263
- ).select('id').maybeSingle();
264
- if (swapErr) {
265
- console.error('[admin-resend-commons-deposit-link] reissue persist failed', swapErr);
266
- return json(500, { ok: false, error: 'reissue_persist_failed' });
267
- }
268
-
269
- if (swapped) {
270
- checkoutUrl = session.url;
271
- } else {
272
- // Someone else already reissued first — email THEIR link, not ours.
273
- const { data: fresh, error: freshErr } = await admin
274
- .from('bookings')
275
- .select('stripe_session_id')
276
- .eq('id', bookingId)
277
- .maybeSingle();
278
- if (freshErr || !fresh?.stripe_session_id) {
279
- return json(500, { ok: false, error: 'reissue_reread_failed' });
280
- }
281
- try {
282
- const freshSession = await stripe.checkout.sessions.retrieve(fresh.stripe_session_id as string);
283
- if (!freshSession.url) return json(500, { ok: false, error: 'reissue_reread_failed' });
284
- checkoutUrl = freshSession.url;
285
- } catch (e) {
286
- const detail = (e instanceof Error ? e.message : String(e)).slice(0, 500);
287
- console.error('[admin-resend-commons-deposit-link] reissue reread failed', detail);
288
- return json(500, { ok: false, error: 'reissue_reread_failed', detail });
289
- }
290
- }
291
- }
292
-
293
- if (!checkoutUrl) {
294
- return json(500, { ok: false, error: 'checkout_url_missing' });
295
- }
296
-
297
- const result = await sendCommonsDepositLinkEmail(admin, {
298
- email: signerEmail,
299
- name: agreement.signer_name ?? booking.contact_name ?? null,
300
- checkoutUrl,
301
- eventDateLabel,
302
- depositCents,
303
- balanceCents,
304
- balanceDueLabel,
305
- bookingId,
306
- }, {
307
- name: operator.operatorName,
308
- shortName: operator.operatorShortName,
309
- supportEmail: operator.supportEmail,
310
- }, operator.ccEmails);
311
-
312
- if (result === 'sent') {
313
- // Explicit staff resend: overwrite unconditionally, no claim semantics —
314
- // same rationale as admin-resend-payment-link-email's own stamp.
315
- const { error: updErr } = await admin
316
- .from('booking_agreements')
317
- .update({ deposit_link_email_sent_at: new Date().toISOString() })
318
- .eq('id', agreement.id);
319
- if (updErr) console.warn('[admin-resend-commons-deposit-link] stamp failed', updErr);
320
- }
321
-
322
- return json(200, { ok: true, result });
323
- }
1
+ // Staff-triggered resend of a Commons (tier 3) event's deposit-payment link.
2
+ //
3
+ // The underlying Stripe Checkout Session expires after 24h, and the original
4
+ // session is only ever created once (CAS-guarded) by
5
+ // _shared/commonsDepositWebhook.ts on the genuine `Completed` transition —
6
+ // there is no other path that reissues it. This is the staff-facing "the
7
+ // client's link went stale" escape hatch.
8
+ //
9
+ // Auth/allowlist/rate-limit scaffold, the Stripe-session-status decision
10
+ // tree, and the "unconditional overwrite, no CAS" resend-email policy are all
11
+ // copied from admin-resend-payment-link-email (the tier-2 analog of exactly
12
+ // this function) — adapted from Stripe Payment Link semantics to Checkout
13
+ // Session semantics, since tier 3 uses `stripe.checkout.sessions`, not
14
+ // payment links.
15
+ import { createClient } from 'npm:@supabase/supabase-js@2';
16
+ import Stripe from 'npm:stripe@17.5.0';
17
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
18
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
19
+ import {
20
+ buildCommonsDepositSessionParams,
21
+ longDateFromIso,
22
+ longDateFromYmd,
23
+ sendCommonsDepositLinkEmail,
24
+ type CommonsSnapshot,
25
+ } from 'npm:@simplelayer/graniteer-core/commonsDeposit';
26
+
27
+ const corsHeaders = {
28
+ 'Access-Control-Allow-Origin': '*',
29
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
30
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
31
+ };
32
+
33
+ interface CallerClaims {
34
+ sub: string;
35
+ email?: string;
36
+ aal?: string;
37
+ }
38
+
39
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
40
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
41
+ function getJwks(supabaseUrl: string) {
42
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
43
+ return jwksCache;
44
+ }
45
+
46
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
47
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
48
+ const token = authHeader.slice(7).trim();
49
+ try {
50
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
51
+ const claims = payload as unknown as CallerClaims;
52
+ if (!claims.sub) return null;
53
+ return claims;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ function json(status: number, body: unknown) {
60
+ return new Response(JSON.stringify(body), {
61
+ status,
62
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
63
+ });
64
+ }
65
+
66
+ export async function handle(
67
+ req: Request,
68
+ operator: { operatorName: string; operatorShortName: string; domain: string; supportEmail: string; ccEmails: string[] },
69
+ ): 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, 'admin-resend-commons-deposit-ip', clientIp(req), 60, 300),
89
+ checkRateLimit(admin, 'admin-resend-commons-deposit-email', callerEmail, 40, 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: { booking_id?: string };
99
+ try {
100
+ body = await req.json();
101
+ } catch {
102
+ return json(400, { ok: false, error: 'invalid_json' });
103
+ }
104
+
105
+ const bookingId = (body.booking_id ?? '').trim();
106
+ if (!/^[0-9a-f-]{36}$/i.test(bookingId)) {
107
+ return json(400, { ok: false, error: 'invalid_booking_id' });
108
+ }
109
+
110
+ const { data: booking, error: bookingErr } = await admin
111
+ .from('bookings')
112
+ .select('id,status,deposit_amount_cents,list_amount_cents,hold_expires_at,contact_email,contact_name,stripe_session_id,room_id')
113
+ .eq('id', bookingId)
114
+ .maybeSingle();
115
+ if (bookingErr) return json(500, { ok: false, error: 'lookup_failed' });
116
+ if (!booking) return json(404, { ok: false, error: 'not_found' });
117
+
118
+ // Most recent tier-3 agreement for this booking — a booking can have more
119
+ // than one row if an earlier agreement was ever revoked and resent.
120
+ const { data: agreement, error: agreementErr } = await admin
121
+ .from('booking_agreements')
122
+ .select('id,status,signer_email,signer_name,metadata,content_url')
123
+ .eq('booking_id', bookingId)
124
+ .eq('tier', 3)
125
+ .order('created_at', { ascending: false })
126
+ .limit(1)
127
+ .maybeSingle();
128
+ if (agreementErr) return json(500, { ok: false, error: 'agreement_lookup_failed' });
129
+ if (!agreement || agreement.status !== 'completed') {
130
+ // Nothing to resend until the contract itself is signed.
131
+ return json(409, { ok: false, error: 'not_signed_yet' });
132
+ }
133
+
134
+ if (booking.status === 'deposit_paid') {
135
+ return json(409, { ok: false, error: 'already_paid' });
136
+ }
137
+ if (booking.status !== 'pending') {
138
+ return json(409, { ok: false, error: 'booking_not_active' });
139
+ }
140
+
141
+ const snapshot = ((agreement.metadata ?? {}) as Record<string, unknown>).commons as
142
+ | CommonsSnapshot
143
+ | undefined;
144
+ if (!snapshot) {
145
+ return json(500, { ok: false, error: 'commons_snapshot_missing' });
146
+ }
147
+
148
+ const depositCents = Number(booking.deposit_amount_cents ?? NaN);
149
+ const totalCents = Number(booking.list_amount_cents ?? NaN);
150
+ const balanceCents = Number(snapshot.balance_cents ?? Math.max(0, totalCents - depositCents));
151
+ const eventDateLabel = longDateFromYmd(snapshot.event_date) ??
152
+ longDateFromIso(snapshot.arrival_at) ?? 'your event date';
153
+ const balanceDueLabel = longDateFromYmd(snapshot.balance_due_date) ??
154
+ 'the date shown in your agreement';
155
+
156
+ const signerEmail = String(agreement.signer_email ?? booking.contact_email ?? '').trim();
157
+ if (!signerEmail) {
158
+ return json(500, { ok: false, error: 'missing_signer_email' });
159
+ }
160
+
161
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
162
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
163
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
164
+
165
+ const existingSessionId = (booking.stripe_session_id as string | null) ?? '';
166
+ let needsNewSession = false;
167
+ let checkoutUrl: string | null = null;
168
+
169
+ if (existingSessionId.trim() !== '') {
170
+ try {
171
+ const session = await stripe.checkout.sessions.retrieve(existingSessionId);
172
+ if (session.status === 'complete') {
173
+ // `complete` alone does NOT mean paid — check payment_status.
174
+ if (session.payment_status === 'paid' || session.payment_status === 'no_payment_required') {
175
+ return json(409, { ok: false, error: 'already_paid' });
176
+ }
177
+ // Completed but unpaid (declined card, pending ACH): refuse, don't reissue.
178
+ return json(409, { ok: false, error: 'complete_unpaid' });
179
+ }
180
+ if (session.status === 'expired') {
181
+ needsNewSession = true;
182
+ } else {
183
+ // status === 'open' -> resend the authoritative URL from the live object.
184
+ checkoutUrl = session.url ?? null;
185
+ }
186
+ } catch (e) {
187
+ const err = e as { code?: string; statusCode?: number };
188
+ const genuinelyMissing = err?.code === 'resource_missing' || err?.statusCode === 404;
189
+ if (!genuinelyMissing) {
190
+ const detail = (e instanceof Error ? e.message : String(e)).slice(0, 500);
191
+ console.error('[admin-resend-commons-deposit-link] stripe unavailable', detail);
192
+ return json(503, { ok: false, error: 'stripe_unavailable', detail });
193
+ }
194
+ console.warn('[admin-resend-commons-deposit-link] session missing, will reissue');
195
+ needsNewSession = true;
196
+ }
197
+ } else {
198
+ needsNewSession = true;
199
+ }
200
+
201
+ if (needsNewSession) {
202
+ // Tamper check — the money on the booking must still match what the
203
+ // signed document says. Any drift means the document and the charge we're
204
+ // about to mint disagree: fail closed rather than charge a different
205
+ // amount than what was signed. Same check as commonsDepositWebhook.ts.
206
+ if (
207
+ !Number.isFinite(depositCents) || !Number.isFinite(totalCents) ||
208
+ depositCents !== Number(snapshot.deposit_cents) || totalCents !== Number(snapshot.total_cents)
209
+ ) {
210
+ return json(500, {
211
+ ok: false,
212
+ error: 'commons_amount_drift',
213
+ detail: {
214
+ booking_deposit_cents: Number.isFinite(depositCents) ? depositCents : null,
215
+ snapshot_deposit_cents: snapshot.deposit_cents ?? null,
216
+ booking_total_cents: Number.isFinite(totalCents) ? totalCents : null,
217
+ snapshot_total_cents: snapshot.total_cents ?? null,
218
+ },
219
+ });
220
+ }
221
+
222
+ const base = `https://${operator.domain}`;
223
+ const params = buildCommonsDepositSessionParams({
224
+ bookingId,
225
+ agreementId: String(agreement.id),
226
+ signerEmail,
227
+ depositCents,
228
+ totalCents,
229
+ balanceCents,
230
+ eventDateLabel,
231
+ balanceDueLabel,
232
+ successUrl: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
233
+ cancelUrl: `${base}/contact?commons_deposit=canceled`,
234
+ });
235
+
236
+ let session: Stripe.Checkout.Session;
237
+ try {
238
+ // NOT commonsDepositIdempotencyKey(bookingId) alone — that key is
239
+ // deterministic per booking and would collide with (and could return)
240
+ // the original, now-expired session. Suffixing with the old session id
241
+ // guarantees a fresh key each time the previous one has actually
242
+ // expired, while staying safely idempotent against an accidental
243
+ // double-click on the same stale session.
244
+ session = await stripe.checkout.sessions.create(params, {
245
+ idempotencyKey: `commons-deposit-resend-${bookingId}-${existingSessionId || 'none'}`,
246
+ });
247
+ } catch (e) {
248
+ const detail = (e instanceof Error ? e.message : String(e)).slice(0, 500);
249
+ console.error('[admin-resend-commons-deposit-link] session create failed', detail);
250
+ return json(500, { ok: false, error: 'session_create_failed', detail });
251
+ }
252
+ if (!session.url) return json(500, { ok: false, error: 'stripe_session_missing_url' });
253
+
254
+ // Compare-and-swap: only the caller that still sees the old (or, for a
255
+ // booking that never had one, absent) session id wins the write. Legacy
256
+ // rows with no session id at all CAS against NULL, same fallback pattern
257
+ // as admin-resend-payment-link-email.
258
+ const swapQuery = admin.from('bookings').update({ stripe_session_id: session.id }).eq('id', bookingId);
259
+ const { data: swapped, error: swapErr } = await (
260
+ existingSessionId.trim() === ''
261
+ ? swapQuery.is('stripe_session_id', null)
262
+ : swapQuery.eq('stripe_session_id', existingSessionId)
263
+ ).select('id').maybeSingle();
264
+ if (swapErr) {
265
+ console.error('[admin-resend-commons-deposit-link] reissue persist failed', swapErr);
266
+ return json(500, { ok: false, error: 'reissue_persist_failed' });
267
+ }
268
+
269
+ if (swapped) {
270
+ checkoutUrl = session.url;
271
+ } else {
272
+ // Someone else already reissued first — email THEIR link, not ours.
273
+ const { data: fresh, error: freshErr } = await admin
274
+ .from('bookings')
275
+ .select('stripe_session_id')
276
+ .eq('id', bookingId)
277
+ .maybeSingle();
278
+ if (freshErr || !fresh?.stripe_session_id) {
279
+ return json(500, { ok: false, error: 'reissue_reread_failed' });
280
+ }
281
+ try {
282
+ const freshSession = await stripe.checkout.sessions.retrieve(fresh.stripe_session_id as string);
283
+ if (!freshSession.url) return json(500, { ok: false, error: 'reissue_reread_failed' });
284
+ checkoutUrl = freshSession.url;
285
+ } catch (e) {
286
+ const detail = (e instanceof Error ? e.message : String(e)).slice(0, 500);
287
+ console.error('[admin-resend-commons-deposit-link] reissue reread failed', detail);
288
+ return json(500, { ok: false, error: 'reissue_reread_failed', detail });
289
+ }
290
+ }
291
+ }
292
+
293
+ if (!checkoutUrl) {
294
+ return json(500, { ok: false, error: 'checkout_url_missing' });
295
+ }
296
+
297
+ const result = await sendCommonsDepositLinkEmail(admin, {
298
+ email: signerEmail,
299
+ name: agreement.signer_name ?? booking.contact_name ?? null,
300
+ checkoutUrl,
301
+ eventDateLabel,
302
+ depositCents,
303
+ balanceCents,
304
+ balanceDueLabel,
305
+ bookingId,
306
+ }, {
307
+ name: operator.operatorName,
308
+ shortName: operator.operatorShortName,
309
+ supportEmail: operator.supportEmail,
310
+ }, operator.ccEmails);
311
+
312
+ if (result === 'sent') {
313
+ // Explicit staff resend: overwrite unconditionally, no claim semantics —
314
+ // same rationale as admin-resend-payment-link-email's own stamp.
315
+ const { error: updErr } = await admin
316
+ .from('booking_agreements')
317
+ .update({ deposit_link_email_sent_at: new Date().toISOString() })
318
+ .eq('id', agreement.id);
319
+ if (updErr) console.warn('[admin-resend-commons-deposit-link] stamp failed', updErr);
320
+ }
321
+
322
+ return json(200, { ok: true, result });
323
+ }