@simplelayer/graniteer-core 0.2.1 → 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 -334
  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 -217
  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,366 +1,366 @@
1
- import { createClient } from 'npm:@supabase/supabase-js@2';
2
- import { z } from 'npm:zod@3.23.8';
3
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
4
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
6
-
7
- const corsHeaders = {
8
- 'Access-Control-Allow-Origin': '*',
9
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
10
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
11
- };
12
-
13
- const LA_TZ = 'America/Los_Angeles';
14
- const TRIAL_DAYS = 7;
15
- const TIMEOUT_MS = 20_000;
16
-
17
- export interface AdminRequestTrialConfig {
18
- busBase: string;
19
- defaultDailyWindowLabel: string;
20
- }
21
-
22
- interface CallerClaims { sub: string; email?: string; aal?: string }
23
-
24
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
25
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
26
- function getJwks(supabaseUrl: string) {
27
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
28
- return jwksCache;
29
- }
30
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
31
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
32
- const token = authHeader.slice(7).trim();
33
- try {
34
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
35
- const claims = payload as unknown as CallerClaims;
36
- if (!claims.sub) return null;
37
- return claims;
38
- } catch { return null; }
39
- }
40
-
41
- function json(status: number, body: unknown) {
42
- return new Response(JSON.stringify(body), {
43
- status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
44
- });
45
- }
46
-
47
- async function sha256Hex(text: string): Promise<string> {
48
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
49
- return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, '0')).join('');
50
- }
51
-
52
- // Same construction as event-access-admin's b64urlNoPad (kept byte-identical
53
- // in behavior): standard base64, then URL-safe substitution, then strip padding.
54
- function b64urlNoPad(bytes: Uint8Array): string {
55
- let s = '';
56
- for (const b of bytes) s += String.fromCharCode(b);
57
- return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
58
- }
59
-
60
- // t1 canonical message per ftw-middleware's trial_hmac.py — a body-hash
61
- // form, NOT event-access-admin's e1 field-list form:
62
- // t1\n{verb}\n{ts}\n{body_sha256_hex}
63
- // verb is the literal "provision"/"cancel" URL path segment; ts is stamped
64
- // immediately before the fetch call (300s replay window, 30s skew tolerance
65
- // on the server, so a stale ts here fails closed).
66
- async function signT1(secret: string, verb: string, ts: string, bodyHashHex: string): Promise<string> {
67
- const key = await crypto.subtle.importKey(
68
- 'raw', new TextEncoder().encode(secret),
69
- { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
70
- );
71
- const msg = ['t1', verb, ts, bodyHashHex].join('\n');
72
- const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg));
73
- return b64urlNoPad(new Uint8Array(sig));
74
- }
75
-
76
- // LA-calendar-day math, mirroring the todayLA()-style Intl.DateTimeFormat
77
- // pattern in admin-issue-day-pass/index.ts, extended to add N days and land
78
- // on that day's midnight boundary rather than just adding N*24h — a plain
79
- // hour offset would land trial_end_at an hour off across a DST transition.
80
- function laOffsetHours(atUtc: Date): number {
81
- const parts = new Intl.DateTimeFormat('en-US', {
82
- timeZone: LA_TZ,
83
- timeZoneName: 'longOffset',
84
- }).formatToParts(atUtc);
85
- const tz = parts.find((p) => p.type === 'timeZoneName')?.value ?? 'GMT-08:00';
86
- const m = tz.match(/GMT([+-])(\d{1,2}):?(\d{2})?/);
87
- if (!m) return -8;
88
- const sign = m[1] === '+' ? 1 : -1;
89
- return sign * (parseInt(m[2], 10) + parseInt(m[3] || '0', 10) / 60);
90
- }
91
-
92
- function laDateParts(d: Date): { y: number; mo: number; day: number } {
93
- const fmt = new Intl.DateTimeFormat('en-CA', {
94
- timeZone: LA_TZ, year: 'numeric', month: '2-digit', day: '2-digit',
95
- }).formatToParts(d);
96
- const get = (t: string) => fmt.find((p) => p.type === t)?.value ?? '';
97
- return { y: parseInt(get('year'), 10), mo: parseInt(get('month'), 10), day: parseInt(get('day'), 10) };
98
- }
99
-
100
- function laWallToUtc(y: number, mo: number, day: number, hh: number, mm: number): Date {
101
- const guess = new Date(Date.UTC(y, mo - 1, day, 12));
102
- const off = laOffsetHours(guess);
103
- return new Date(Date.UTC(y, mo - 1, day, hh - Math.trunc(off), mm));
104
- }
105
-
106
- /** LA midnight at the end of the 7th calendar day from `start`'s LA-local
107
- * date — i.e. add TRIAL_DAYS calendar days to that date, then take 00:00
108
- * LA of the result. */
109
- function trialEndAtLA(start: Date): Date {
110
- const { y, mo, day } = laDateParts(start);
111
- // Date.UTC normalizes an overflowing day-of-month (e.g. day 31 + 7 in a
112
- // 30-day month), so this correctly rolls into the next month/year.
113
- const target = new Date(Date.UTC(y, mo - 1, day + TRIAL_DAYS, 12));
114
- const t = laDateParts(target);
115
- return laWallToUtc(t.y, t.mo, t.day, 0, 0);
116
- }
117
-
118
- const Body = z.object({
119
- first_name: z.string().trim().min(1).max(200),
120
- last_name: z.string().trim().min(1).max(200),
121
- email: z.string().trim().email().max(255),
122
- phone: z.string().trim().max(32).optional(),
123
- trial_start_at: z.string().datetime().optional(),
124
- daily_window_label: z.string().trim().min(1).max(200).optional(),
125
- override_prior_grant_id: z.string().uuid().optional(),
126
- override_reason: z.string().trim().min(1).max(500).optional(),
127
- }).refine((data) => !data.override_prior_grant_id || !!data.override_reason, {
128
- message: 'override_reason is required when override_prior_grant_id is set',
129
- path: ['override_reason'],
130
- });
131
-
132
- export async function handle(req: Request, config: AdminRequestTrialConfig): Promise<Response> {
133
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
134
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
135
-
136
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
137
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
138
-
139
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
140
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
141
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
142
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
143
- const callerEmail = (caller.email ?? '').toLowerCase();
144
- if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
145
-
146
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
147
- auth: { persistSession: false, autoRefreshToken: false },
148
- });
149
-
150
- const [ipOk, emailOk] = await Promise.all([
151
- checkRateLimit(admin, 'admin-request-trial-ip', clientIp(req), 30, 300),
152
- checkRateLimit(admin, 'admin-request-trial-email', callerEmail, 20, 300),
153
- ]);
154
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
155
-
156
- const { data: allow, error: allowErr } = await admin
157
- .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
158
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
159
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
160
-
161
- let raw: unknown;
162
- try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
163
- const parsed = Body.safeParse(raw);
164
- if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
165
- const {
166
- first_name, last_name, email, phone,
167
- trial_start_at, daily_window_label,
168
- override_prior_grant_id, override_reason,
169
- } = parsed.data;
170
-
171
- const emailNormalized = email.trim().toLowerCase();
172
- const isOverride = !!override_prior_grant_id && !!override_reason;
173
- const eligibilityKeyHash = await sha256Hex(emailNormalized);
174
-
175
- try {
176
- const { data: existingLedger, error: ledgerErr } = await admin
177
- .from('trial_eligibility_ledger')
178
- .select('id')
179
- .eq('key_type', 'email')
180
- .eq('key_hash', eligibilityKeyHash)
181
- .maybeSingle();
182
- if (ledgerErr) return json(500, { ok: false, error: 'eligibility_lookup_failed', detail: ledgerErr.message });
183
- if (existingLedger && !isOverride) {
184
- return json(409, { ok: false, error: 'already_used_trial' });
185
- }
186
-
187
- const trialStart = trial_start_at ? new Date(trial_start_at) : new Date();
188
- if (isNaN(trialStart.getTime())) return json(400, { ok: false, error: 'invalid_trial_start_at' });
189
- const trialEnd = trialEndAtLA(trialStart);
190
- const windowLabel = daily_window_label ?? config.defaultDailyWindowLabel;
191
-
192
- const { data: grant, error: grantErr } = await admin
193
- .from('trial_grants')
194
- .insert({
195
- status: 'requested',
196
- email_normalized: emailNormalized,
197
- phone_e164: phone ?? null,
198
- first_name,
199
- last_name,
200
- eligibility_key_hash: eligibilityKeyHash,
201
- source: 'staff_console',
202
- created_by: callerEmail,
203
- trial_start_at: trialStart.toISOString(),
204
- trial_end_at: trialEnd.toISOString(),
205
- daily_window_label: windowLabel,
206
- override_prior_grant_id: override_prior_grant_id ?? null,
207
- override_reason: override_reason ?? null,
208
- })
209
- .select('id, trial_start_at, trial_end_at, status, provisioning_attempts')
210
- .single();
211
- if (grantErr) return json(500, { ok: false, error: 'insert_failed', detail: grantErr.message });
212
-
213
- // Provision door access right away. Every path below (missing secret,
214
- // network/timeout, non-200) is caught and logged, never thrown — the
215
- // trial_grants row already committed above must never be blocked by a
216
- // downstream provisioning failure.
217
- let finalStatus: string = grant.status;
218
- let credential: { pin: string } | undefined;
219
- let provisioningErrorForResponse: string | undefined;
220
- let provisionOk = false;
221
- let provisionUnifiUserId: string | undefined;
222
- let provisionPin: string | undefined;
223
- let provisionErrorCode: string | undefined;
224
-
225
- const trialHmacSecret = Deno.env.get('TRIAL_HMAC_SECRET');
226
- if (!trialHmacSecret) {
227
- await logOps(admin, 'admin_request_trial_provision_secret_missing',
228
- { grant_id: grant.id }, { severity: 'error' });
229
- provisionErrorCode = 'provisioning_unconfigured';
230
- } else {
231
- const outboundProvision = {
232
- grant_id: grant.id,
233
- first_name,
234
- last_name,
235
- email: emailNormalized,
236
- phone: phone ?? undefined,
237
- trial_start_at: grant.trial_start_at,
238
- trial_end_at: grant.trial_end_at,
239
- daily_window_label: windowLabel,
240
- };
241
- // Exact bytes posted are the exact bytes digested.
242
- const rawProvisionBody = JSON.stringify(outboundProvision);
243
- const provisionBodyHash = await sha256Hex(rawProvisionBody);
244
- // Stamp ts last, immediately before the fetch — 300s replay window.
245
- const provisionTs = String(Math.floor(Date.now() / 1000));
246
- const provisionSignature = await signT1(trialHmacSecret, 'provision', provisionTs, provisionBodyHash);
247
-
248
- let provisionRes: Response | null = null;
249
- try {
250
- provisionRes = await fetch(`${config.busBase}/trial/provision`, {
251
- method: 'POST',
252
- headers: {
253
- 'Content-Type': 'application/json',
254
- 'X-Trial-Signature': provisionSignature,
255
- 'X-Trial-Timestamp': provisionTs,
256
- },
257
- body: rawProvisionBody,
258
- signal: AbortSignal.timeout(TIMEOUT_MS),
259
- });
260
- } catch (e) {
261
- const isTimeout = e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError');
262
- await logOps(admin, 'admin_request_trial_provision_call_error',
263
- { grant_id: grant.id, message: String(e) }, { severity: 'error' });
264
- provisionErrorCode = isTimeout ? 'middleware_timeout' : 'middleware_unreachable';
265
- }
266
-
267
- if (provisionRes) {
268
- const provisionText = await provisionRes.text();
269
- let provisionParsed: Record<string, unknown> | null = null;
270
- try { provisionParsed = provisionText ? JSON.parse(provisionText) : null; } catch { provisionParsed = null; }
271
-
272
- if (!provisionRes.ok) {
273
- // Never log the raw response body/text — a 200 body can carry
274
- // credential.pin, and non-200 bodies aren't guaranteed pin-free either.
275
- provisionErrorCode = typeof provisionParsed?.error === 'string'
276
- ? provisionParsed.error : `http_${provisionRes.status}`;
277
- await logOps(admin, 'admin_request_trial_provision_failed',
278
- { grant_id: grant.id, status: provisionRes.status, error: provisionErrorCode }, { severity: 'error' });
279
- } else {
280
- provisionOk = true;
281
- provisionUnifiUserId = typeof provisionParsed?.unifi_user_id === 'string'
282
- ? provisionParsed.unifi_user_id : undefined;
283
- const cred = provisionParsed?.credential as Record<string, unknown> | undefined;
284
- provisionPin = cred && typeof cred.pin === 'string' ? cred.pin : undefined;
285
- }
286
- }
287
- }
288
-
289
- if (provisionOk) {
290
- const updatePayload: Record<string, unknown> = {
291
- status: 'active',
292
- unifi_user_id: provisionUnifiUserId ?? null,
293
- credential_type: 'pin',
294
- activated_at: new Date().toISOString(),
295
- };
296
- if (provisionPin) {
297
- updatePayload.pin_issued_at = new Date().toISOString();
298
- } else {
299
- updatePayload.notes = 'Provisioned without a PIN — mint/set failed on ftw-middleware.';
300
- }
301
- const { error: statusUpdateErr } = await admin.from('trial_grants').update(updatePayload).eq('id', grant.id);
302
- if (statusUpdateErr) {
303
- await logOps(admin, 'admin_request_trial_status_update_failed',
304
- { grant_id: grant.id, message: statusUpdateErr.message }, { severity: 'error' });
305
- }
306
- finalStatus = 'active';
307
- if (provisionPin) credential = { pin: provisionPin };
308
- } else {
309
- const errorCode = provisionErrorCode ?? 'middleware_unreachable';
310
- const { error: statusUpdateErr } = await admin.from('trial_grants').update({
311
- status: 'failed',
312
- provisioning_attempts: (grant.provisioning_attempts ?? 0) + 1,
313
- last_provisioning_error: errorCode,
314
- }).eq('id', grant.id);
315
- if (statusUpdateErr) {
316
- await logOps(admin, 'admin_request_trial_status_update_failed',
317
- { grant_id: grant.id, message: statusUpdateErr.message }, { severity: 'error' });
318
- }
319
- finalStatus = 'failed';
320
- provisioningErrorForResponse = errorCode;
321
- }
322
-
323
- const { error: ledgerInsertErr } = await admin
324
- .from('trial_eligibility_ledger')
325
- .insert({
326
- key_type: 'email',
327
- key_hash: eligibilityKeyHash,
328
- grant_id: grant.id,
329
- outcome: 'granted',
330
- });
331
- // Append-only, best-effort: a duplicate-key retry on the unique
332
- // (key_type, key_hash) index is harmless — the grant row above is
333
- // already the source of truth for this request.
334
- if (ledgerInsertErr && (ledgerInsertErr as { code?: string }).code !== '23505') {
335
- await logOps(admin, 'admin_request_trial_ledger_insert_failed',
336
- { message: ledgerInsertErr.message, grant_id: grant.id, actor: callerEmail },
337
- { severity: 'warning' });
338
- }
339
-
340
- await admin.from('trial_grant_events').insert({
341
- grant_id: grant.id,
342
- actor_user_id: callerEmail,
343
- action: 'grant_requested',
344
- request_payload: parsed.data,
345
- ok: true,
346
- });
347
-
348
- return json(200, {
349
- ok: true,
350
- grant_id: grant.id,
351
- trial_start_at: grant.trial_start_at,
352
- trial_end_at: grant.trial_end_at,
353
- status: finalStatus,
354
- ...(credential ? { credential } : {}),
355
- ...(provisioningErrorForResponse ? { provisioning_error: provisioningErrorForResponse } : {}),
356
- });
357
- } catch (e) {
358
- console.error('admin-request-trial error', e);
359
- try {
360
- await logOps(admin, 'admin_request_trial_error',
361
- { message: e instanceof Error ? e.message : String(e), actor: callerEmail },
362
- { severity: 'error' });
363
- } catch { /* ignore */ }
364
- return json(500, { ok: false, error: 'unexpected_error' });
365
- }
366
- }
1
+ import { createClient } from 'npm:@supabase/supabase-js@2';
2
+ import { z } from 'npm:zod@3.23.8';
3
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
4
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
6
+
7
+ const corsHeaders = {
8
+ 'Access-Control-Allow-Origin': '*',
9
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
10
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
11
+ };
12
+
13
+ const LA_TZ = 'America/Los_Angeles';
14
+ const TRIAL_DAYS = 7;
15
+ const TIMEOUT_MS = 20_000;
16
+
17
+ export interface AdminRequestTrialConfig {
18
+ busBase: string;
19
+ defaultDailyWindowLabel: string;
20
+ }
21
+
22
+ interface CallerClaims { sub: string; email?: string; aal?: string }
23
+
24
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
25
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
26
+ function getJwks(supabaseUrl: string) {
27
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
28
+ return jwksCache;
29
+ }
30
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
31
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
32
+ const token = authHeader.slice(7).trim();
33
+ try {
34
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
35
+ const claims = payload as unknown as CallerClaims;
36
+ if (!claims.sub) return null;
37
+ return claims;
38
+ } catch { return null; }
39
+ }
40
+
41
+ function json(status: number, body: unknown) {
42
+ return new Response(JSON.stringify(body), {
43
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
44
+ });
45
+ }
46
+
47
+ async function sha256Hex(text: string): Promise<string> {
48
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
49
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, '0')).join('');
50
+ }
51
+
52
+ // Same construction as event-access-admin's b64urlNoPad (kept byte-identical
53
+ // in behavior): standard base64, then URL-safe substitution, then strip padding.
54
+ function b64urlNoPad(bytes: Uint8Array): string {
55
+ let s = '';
56
+ for (const b of bytes) s += String.fromCharCode(b);
57
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
58
+ }
59
+
60
+ // t1 canonical message per ftw-middleware's trial_hmac.py — a body-hash
61
+ // form, NOT event-access-admin's e1 field-list form:
62
+ // t1\n{verb}\n{ts}\n{body_sha256_hex}
63
+ // verb is the literal "provision"/"cancel" URL path segment; ts is stamped
64
+ // immediately before the fetch call (300s replay window, 30s skew tolerance
65
+ // on the server, so a stale ts here fails closed).
66
+ async function signT1(secret: string, verb: string, ts: string, bodyHashHex: string): Promise<string> {
67
+ const key = await crypto.subtle.importKey(
68
+ 'raw', new TextEncoder().encode(secret),
69
+ { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
70
+ );
71
+ const msg = ['t1', verb, ts, bodyHashHex].join('\n');
72
+ const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg));
73
+ return b64urlNoPad(new Uint8Array(sig));
74
+ }
75
+
76
+ // LA-calendar-day math, mirroring the todayLA()-style Intl.DateTimeFormat
77
+ // pattern in admin-issue-day-pass/index.ts, extended to add N days and land
78
+ // on that day's midnight boundary rather than just adding N*24h — a plain
79
+ // hour offset would land trial_end_at an hour off across a DST transition.
80
+ function laOffsetHours(atUtc: Date): number {
81
+ const parts = new Intl.DateTimeFormat('en-US', {
82
+ timeZone: LA_TZ,
83
+ timeZoneName: 'longOffset',
84
+ }).formatToParts(atUtc);
85
+ const tz = parts.find((p) => p.type === 'timeZoneName')?.value ?? 'GMT-08:00';
86
+ const m = tz.match(/GMT([+-])(\d{1,2}):?(\d{2})?/);
87
+ if (!m) return -8;
88
+ const sign = m[1] === '+' ? 1 : -1;
89
+ return sign * (parseInt(m[2], 10) + parseInt(m[3] || '0', 10) / 60);
90
+ }
91
+
92
+ function laDateParts(d: Date): { y: number; mo: number; day: number } {
93
+ const fmt = new Intl.DateTimeFormat('en-CA', {
94
+ timeZone: LA_TZ, year: 'numeric', month: '2-digit', day: '2-digit',
95
+ }).formatToParts(d);
96
+ const get = (t: string) => fmt.find((p) => p.type === t)?.value ?? '';
97
+ return { y: parseInt(get('year'), 10), mo: parseInt(get('month'), 10), day: parseInt(get('day'), 10) };
98
+ }
99
+
100
+ function laWallToUtc(y: number, mo: number, day: number, hh: number, mm: number): Date {
101
+ const guess = new Date(Date.UTC(y, mo - 1, day, 12));
102
+ const off = laOffsetHours(guess);
103
+ return new Date(Date.UTC(y, mo - 1, day, hh - Math.trunc(off), mm));
104
+ }
105
+
106
+ /** LA midnight at the end of the 7th calendar day from `start`'s LA-local
107
+ * date — i.e. add TRIAL_DAYS calendar days to that date, then take 00:00
108
+ * LA of the result. */
109
+ function trialEndAtLA(start: Date): Date {
110
+ const { y, mo, day } = laDateParts(start);
111
+ // Date.UTC normalizes an overflowing day-of-month (e.g. day 31 + 7 in a
112
+ // 30-day month), so this correctly rolls into the next month/year.
113
+ const target = new Date(Date.UTC(y, mo - 1, day + TRIAL_DAYS, 12));
114
+ const t = laDateParts(target);
115
+ return laWallToUtc(t.y, t.mo, t.day, 0, 0);
116
+ }
117
+
118
+ const Body = z.object({
119
+ first_name: z.string().trim().min(1).max(200),
120
+ last_name: z.string().trim().min(1).max(200),
121
+ email: z.string().trim().email().max(255),
122
+ phone: z.string().trim().max(32).optional(),
123
+ trial_start_at: z.string().datetime().optional(),
124
+ daily_window_label: z.string().trim().min(1).max(200).optional(),
125
+ override_prior_grant_id: z.string().uuid().optional(),
126
+ override_reason: z.string().trim().min(1).max(500).optional(),
127
+ }).refine((data) => !data.override_prior_grant_id || !!data.override_reason, {
128
+ message: 'override_reason is required when override_prior_grant_id is set',
129
+ path: ['override_reason'],
130
+ });
131
+
132
+ export async function handle(req: Request, config: AdminRequestTrialConfig): Promise<Response> {
133
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
134
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
135
+
136
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
137
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
138
+
139
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
140
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
141
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
142
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
143
+ const callerEmail = (caller.email ?? '').toLowerCase();
144
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
145
+
146
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
147
+ auth: { persistSession: false, autoRefreshToken: false },
148
+ });
149
+
150
+ const [ipOk, emailOk] = await Promise.all([
151
+ checkRateLimit(admin, 'admin-request-trial-ip', clientIp(req), 30, 300),
152
+ checkRateLimit(admin, 'admin-request-trial-email', callerEmail, 20, 300),
153
+ ]);
154
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
155
+
156
+ const { data: allow, error: allowErr } = await admin
157
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
158
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
159
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
160
+
161
+ let raw: unknown;
162
+ try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
163
+ const parsed = Body.safeParse(raw);
164
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
165
+ const {
166
+ first_name, last_name, email, phone,
167
+ trial_start_at, daily_window_label,
168
+ override_prior_grant_id, override_reason,
169
+ } = parsed.data;
170
+
171
+ const emailNormalized = email.trim().toLowerCase();
172
+ const isOverride = !!override_prior_grant_id && !!override_reason;
173
+ const eligibilityKeyHash = await sha256Hex(emailNormalized);
174
+
175
+ try {
176
+ const { data: existingLedger, error: ledgerErr } = await admin
177
+ .from('trial_eligibility_ledger')
178
+ .select('id')
179
+ .eq('key_type', 'email')
180
+ .eq('key_hash', eligibilityKeyHash)
181
+ .maybeSingle();
182
+ if (ledgerErr) return json(500, { ok: false, error: 'eligibility_lookup_failed', detail: ledgerErr.message });
183
+ if (existingLedger && !isOverride) {
184
+ return json(409, { ok: false, error: 'already_used_trial' });
185
+ }
186
+
187
+ const trialStart = trial_start_at ? new Date(trial_start_at) : new Date();
188
+ if (isNaN(trialStart.getTime())) return json(400, { ok: false, error: 'invalid_trial_start_at' });
189
+ const trialEnd = trialEndAtLA(trialStart);
190
+ const windowLabel = daily_window_label ?? config.defaultDailyWindowLabel;
191
+
192
+ const { data: grant, error: grantErr } = await admin
193
+ .from('trial_grants')
194
+ .insert({
195
+ status: 'requested',
196
+ email_normalized: emailNormalized,
197
+ phone_e164: phone ?? null,
198
+ first_name,
199
+ last_name,
200
+ eligibility_key_hash: eligibilityKeyHash,
201
+ source: 'staff_console',
202
+ created_by: callerEmail,
203
+ trial_start_at: trialStart.toISOString(),
204
+ trial_end_at: trialEnd.toISOString(),
205
+ daily_window_label: windowLabel,
206
+ override_prior_grant_id: override_prior_grant_id ?? null,
207
+ override_reason: override_reason ?? null,
208
+ })
209
+ .select('id, trial_start_at, trial_end_at, status, provisioning_attempts')
210
+ .single();
211
+ if (grantErr) return json(500, { ok: false, error: 'insert_failed', detail: grantErr.message });
212
+
213
+ // Provision door access right away. Every path below (missing secret,
214
+ // network/timeout, non-200) is caught and logged, never thrown — the
215
+ // trial_grants row already committed above must never be blocked by a
216
+ // downstream provisioning failure.
217
+ let finalStatus: string = grant.status;
218
+ let credential: { pin: string } | undefined;
219
+ let provisioningErrorForResponse: string | undefined;
220
+ let provisionOk = false;
221
+ let provisionUnifiUserId: string | undefined;
222
+ let provisionPin: string | undefined;
223
+ let provisionErrorCode: string | undefined;
224
+
225
+ const trialHmacSecret = Deno.env.get('TRIAL_HMAC_SECRET');
226
+ if (!trialHmacSecret) {
227
+ await logOps(admin, 'admin_request_trial_provision_secret_missing',
228
+ { grant_id: grant.id }, { severity: 'error' });
229
+ provisionErrorCode = 'provisioning_unconfigured';
230
+ } else {
231
+ const outboundProvision = {
232
+ grant_id: grant.id,
233
+ first_name,
234
+ last_name,
235
+ email: emailNormalized,
236
+ phone: phone ?? undefined,
237
+ trial_start_at: grant.trial_start_at,
238
+ trial_end_at: grant.trial_end_at,
239
+ daily_window_label: windowLabel,
240
+ };
241
+ // Exact bytes posted are the exact bytes digested.
242
+ const rawProvisionBody = JSON.stringify(outboundProvision);
243
+ const provisionBodyHash = await sha256Hex(rawProvisionBody);
244
+ // Stamp ts last, immediately before the fetch — 300s replay window.
245
+ const provisionTs = String(Math.floor(Date.now() / 1000));
246
+ const provisionSignature = await signT1(trialHmacSecret, 'provision', provisionTs, provisionBodyHash);
247
+
248
+ let provisionRes: Response | null = null;
249
+ try {
250
+ provisionRes = await fetch(`${config.busBase}/trial/provision`, {
251
+ method: 'POST',
252
+ headers: {
253
+ 'Content-Type': 'application/json',
254
+ 'X-Trial-Signature': provisionSignature,
255
+ 'X-Trial-Timestamp': provisionTs,
256
+ },
257
+ body: rawProvisionBody,
258
+ signal: AbortSignal.timeout(TIMEOUT_MS),
259
+ });
260
+ } catch (e) {
261
+ const isTimeout = e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError');
262
+ await logOps(admin, 'admin_request_trial_provision_call_error',
263
+ { grant_id: grant.id, message: String(e) }, { severity: 'error' });
264
+ provisionErrorCode = isTimeout ? 'middleware_timeout' : 'middleware_unreachable';
265
+ }
266
+
267
+ if (provisionRes) {
268
+ const provisionText = await provisionRes.text();
269
+ let provisionParsed: Record<string, unknown> | null = null;
270
+ try { provisionParsed = provisionText ? JSON.parse(provisionText) : null; } catch { provisionParsed = null; }
271
+
272
+ if (!provisionRes.ok) {
273
+ // Never log the raw response body/text — a 200 body can carry
274
+ // credential.pin, and non-200 bodies aren't guaranteed pin-free either.
275
+ provisionErrorCode = typeof provisionParsed?.error === 'string'
276
+ ? provisionParsed.error : `http_${provisionRes.status}`;
277
+ await logOps(admin, 'admin_request_trial_provision_failed',
278
+ { grant_id: grant.id, status: provisionRes.status, error: provisionErrorCode }, { severity: 'error' });
279
+ } else {
280
+ provisionOk = true;
281
+ provisionUnifiUserId = typeof provisionParsed?.unifi_user_id === 'string'
282
+ ? provisionParsed.unifi_user_id : undefined;
283
+ const cred = provisionParsed?.credential as Record<string, unknown> | undefined;
284
+ provisionPin = cred && typeof cred.pin === 'string' ? cred.pin : undefined;
285
+ }
286
+ }
287
+ }
288
+
289
+ if (provisionOk) {
290
+ const updatePayload: Record<string, unknown> = {
291
+ status: 'active',
292
+ unifi_user_id: provisionUnifiUserId ?? null,
293
+ credential_type: 'pin',
294
+ activated_at: new Date().toISOString(),
295
+ };
296
+ if (provisionPin) {
297
+ updatePayload.pin_issued_at = new Date().toISOString();
298
+ } else {
299
+ updatePayload.notes = 'Provisioned without a PIN — mint/set failed on ftw-middleware.';
300
+ }
301
+ const { error: statusUpdateErr } = await admin.from('trial_grants').update(updatePayload).eq('id', grant.id);
302
+ if (statusUpdateErr) {
303
+ await logOps(admin, 'admin_request_trial_status_update_failed',
304
+ { grant_id: grant.id, message: statusUpdateErr.message }, { severity: 'error' });
305
+ }
306
+ finalStatus = 'active';
307
+ if (provisionPin) credential = { pin: provisionPin };
308
+ } else {
309
+ const errorCode = provisionErrorCode ?? 'middleware_unreachable';
310
+ const { error: statusUpdateErr } = await admin.from('trial_grants').update({
311
+ status: 'failed',
312
+ provisioning_attempts: (grant.provisioning_attempts ?? 0) + 1,
313
+ last_provisioning_error: errorCode,
314
+ }).eq('id', grant.id);
315
+ if (statusUpdateErr) {
316
+ await logOps(admin, 'admin_request_trial_status_update_failed',
317
+ { grant_id: grant.id, message: statusUpdateErr.message }, { severity: 'error' });
318
+ }
319
+ finalStatus = 'failed';
320
+ provisioningErrorForResponse = errorCode;
321
+ }
322
+
323
+ const { error: ledgerInsertErr } = await admin
324
+ .from('trial_eligibility_ledger')
325
+ .insert({
326
+ key_type: 'email',
327
+ key_hash: eligibilityKeyHash,
328
+ grant_id: grant.id,
329
+ outcome: 'granted',
330
+ });
331
+ // Append-only, best-effort: a duplicate-key retry on the unique
332
+ // (key_type, key_hash) index is harmless — the grant row above is
333
+ // already the source of truth for this request.
334
+ if (ledgerInsertErr && (ledgerInsertErr as { code?: string }).code !== '23505') {
335
+ await logOps(admin, 'admin_request_trial_ledger_insert_failed',
336
+ { message: ledgerInsertErr.message, grant_id: grant.id, actor: callerEmail },
337
+ { severity: 'warning' });
338
+ }
339
+
340
+ await admin.from('trial_grant_events').insert({
341
+ grant_id: grant.id,
342
+ actor_user_id: callerEmail,
343
+ action: 'grant_requested',
344
+ request_payload: parsed.data,
345
+ ok: true,
346
+ });
347
+
348
+ return json(200, {
349
+ ok: true,
350
+ grant_id: grant.id,
351
+ trial_start_at: grant.trial_start_at,
352
+ trial_end_at: grant.trial_end_at,
353
+ status: finalStatus,
354
+ ...(credential ? { credential } : {}),
355
+ ...(provisioningErrorForResponse ? { provisioning_error: provisioningErrorForResponse } : {}),
356
+ });
357
+ } catch (e) {
358
+ console.error('admin-request-trial error', e);
359
+ try {
360
+ await logOps(admin, 'admin_request_trial_error',
361
+ { message: e instanceof Error ? e.message : String(e), actor: callerEmail },
362
+ { severity: 'error' });
363
+ } catch { /* ignore */ }
364
+ return json(500, { ok: false, error: 'unexpected_error' });
365
+ }
366
+ }