@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,363 +1,363 @@
1
- // HMAC-SHA256 signed token for self-serve booking management. Payload is a
2
- // small JSON object identifying the booking and the customer email, plus an
3
- // expiry. Never accept a bare booking UUID for PII — the token is the only key.
4
-
5
- export interface ManageTokenPayload {
6
- bid: string; // booking uuid
7
- eml: string; // lowercased contact_email
8
- exp: number; // unix seconds
9
- }
10
-
11
- function b64urlEncode(bytes: Uint8Array): string {
12
- const s = btoa(String.fromCharCode(...bytes));
13
- return s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
14
- }
15
-
16
- function b64urlDecode(s: string): Uint8Array<ArrayBuffer> {
17
- const pad = s.length % 4 === 0 ? '' : '='.repeat(4 - (s.length % 4));
18
- const b = atob(s.replace(/-/g, '+').replace(/_/g, '/') + pad);
19
- const out = new Uint8Array(b.length);
20
- for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i);
21
- return out;
22
- }
23
-
24
- async function getKey(secret: string): Promise<CryptoKey> {
25
- return await crypto.subtle.importKey(
26
- 'raw',
27
- new TextEncoder().encode(secret),
28
- { name: 'HMAC', hash: 'SHA-256' },
29
- false,
30
- ['sign', 'verify'],
31
- );
32
- }
33
-
34
- function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
35
- if (a.length !== b.length) return false;
36
- let diff = 0;
37
- for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
38
- return diff === 0;
39
- }
40
-
41
- export async function signManageToken(
42
- payload: ManageTokenPayload,
43
- secret: string,
44
- ): Promise<string> {
45
- const key = await getKey(secret);
46
- const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
47
- const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
48
- return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
49
- }
50
-
51
- export async function verifyManageToken(
52
- token: string,
53
- secret: string,
54
- ): Promise<ManageTokenPayload | null> {
55
- const parts = token.split('.');
56
- if (parts.length !== 2) return null;
57
- // Explicitly ArrayBuffer-backed: a bare `Uint8Array` widens to
58
- // Uint8Array<ArrayBufferLike>, which crypto.subtle.sign() rejects because a
59
- // SharedArrayBuffer-backed view is not a BufferSource.
60
- let payloadBytes: Uint8Array<ArrayBuffer>;
61
- let sigBytes: Uint8Array<ArrayBuffer>;
62
- try {
63
- payloadBytes = b64urlDecode(parts[0]);
64
- sigBytes = b64urlDecode(parts[1]);
65
- } catch {
66
- return null;
67
- }
68
- const key = await getKey(secret);
69
- const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
70
- if (!timingSafeEqual(expected, sigBytes)) return null;
71
- let payload: ManageTokenPayload;
72
- try {
73
- payload = JSON.parse(new TextDecoder().decode(payloadBytes)) as ManageTokenPayload;
74
- } catch {
75
- return null;
76
- }
77
- if (
78
- typeof payload?.bid !== 'string' ||
79
- typeof payload?.eml !== 'string' ||
80
- typeof payload?.exp !== 'number'
81
- ) return null;
82
- if (payload.exp < Math.floor(Date.now() / 1000)) return null;
83
- return payload;
84
- }
85
-
86
- /**
87
- * Build a manage-booking URL for the given payload. Base is the site origin
88
- * (no trailing slash), e.g. https://acme.example.com.
89
- */
90
- export async function buildManageUrl(
91
- base: string,
92
- payload: ManageTokenPayload,
93
- secret: string,
94
- ): Promise<string> {
95
- const token = await signManageToken(payload, secret);
96
- return `${base.replace(/\/+$/, '')}/manage-booking?token=${encodeURIComponent(token)}`;
97
- }
98
-
99
- // ---------------------------------------------------------------------------
100
- // Membership customer portal token.
101
- // Same HMAC-SHA256 primitives + MANAGE_TOKEN_SECRET as the booking token,
102
- // with a distinct payload shape so we never confuse the two credentials.
103
- // ---------------------------------------------------------------------------
104
-
105
- export interface MemberTokenPayload {
106
- mbr: string; // lowercased member email
107
- exp: number; // unix seconds
108
- }
109
-
110
- export async function signMemberToken(
111
- payload: MemberTokenPayload,
112
- secret: string,
113
- ): Promise<string> {
114
- const key = await getKey(secret);
115
- const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
116
- const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
117
- return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
118
- }
119
-
120
- export async function verifyMemberToken(
121
- token: string,
122
- secret: string,
123
- ): Promise<MemberTokenPayload | null> {
124
- const parts = token.split('.');
125
- if (parts.length !== 2) return null;
126
- // Explicitly ArrayBuffer-backed: a bare `Uint8Array` widens to
127
- // Uint8Array<ArrayBufferLike>, which crypto.subtle.sign() rejects because a
128
- // SharedArrayBuffer-backed view is not a BufferSource.
129
- let payloadBytes: Uint8Array<ArrayBuffer>;
130
- let sigBytes: Uint8Array<ArrayBuffer>;
131
- try {
132
- payloadBytes = b64urlDecode(parts[0]);
133
- sigBytes = b64urlDecode(parts[1]);
134
- } catch {
135
- return null;
136
- }
137
- const key = await getKey(secret);
138
- const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
139
- if (!timingSafeEqual(expected, sigBytes)) return null;
140
- let payload: MemberTokenPayload;
141
- try {
142
- payload = JSON.parse(new TextDecoder().decode(payloadBytes)) as MemberTokenPayload;
143
- } catch {
144
- return null;
145
- }
146
- if (typeof payload?.mbr !== 'string' || typeof payload?.exp !== 'number') return null;
147
- if (payload.exp < Math.floor(Date.now() / 1000)) return null;
148
- return payload;
149
- }
150
-
151
- export async function buildMemberManageUrl(
152
- base: string,
153
- payload: MemberTokenPayload,
154
- secret: string,
155
- ): Promise<string> {
156
- const token = await signMemberToken(payload, secret);
157
- return `${base.replace(/\/+$/, '')}/membership/manage?token=${encodeURIComponent(token)}`;
158
- }
159
-
160
- // ---------------------------------------------------------------------------
161
- // Unified agreement portal token. Same HMAC-SHA256 primitives + MANAGE_TOKEN_SECRET
162
- // as the other tokens above, with its own payload shape and an explicit `aud`
163
- // claim so a token minted for booking/member management can never verify here
164
- // by accident, and vice versa.
165
- // ---------------------------------------------------------------------------
166
-
167
- export interface AgreementPortalTokenPayload {
168
- sdid: string; // signature_documents.id
169
- eml: string; // lowercased signer_email
170
- aud: 'agreement-portal';
171
- iat: number; // unix seconds, minting time
172
- exp: number; // unix seconds
173
- }
174
-
175
- export async function signAgreementPortalToken(
176
- payload: AgreementPortalTokenPayload,
177
- secret: string,
178
- ): Promise<string> {
179
- const key = await getKey(secret);
180
- const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
181
- const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
182
- return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
183
- }
184
-
185
- /**
186
- * Verify an agreement portal token. `revokedAtIso`, if provided, rejects only
187
- * tokens minted AT OR BEFORE that instant -- a fresh re-mint after a revoke
188
- * verifies again without any separate un-revoke step.
189
- */
190
- export async function verifyAgreementPortalToken(
191
- token: string,
192
- secret: string,
193
- revokedAtIso?: string | null,
194
- ): Promise<AgreementPortalTokenPayload | null> {
195
- const parts = token.split('.');
196
- if (parts.length !== 2) return null;
197
- // Explicitly ArrayBuffer-backed: a bare `Uint8Array` widens to
198
- // Uint8Array<ArrayBufferLike>, which crypto.subtle.sign() rejects because a
199
- // SharedArrayBuffer-backed view is not a BufferSource.
200
- let payloadBytes: Uint8Array<ArrayBuffer>;
201
- let sigBytes: Uint8Array<ArrayBuffer>;
202
- try {
203
- payloadBytes = b64urlDecode(parts[0]);
204
- sigBytes = b64urlDecode(parts[1]);
205
- } catch {
206
- return null;
207
- }
208
- const key = await getKey(secret);
209
- const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
210
- if (!timingSafeEqual(expected, sigBytes)) return null;
211
- let payload: AgreementPortalTokenPayload;
212
- try {
213
- payload = JSON.parse(new TextDecoder().decode(payloadBytes)) as AgreementPortalTokenPayload;
214
- } catch {
215
- return null;
216
- }
217
- if (
218
- typeof payload?.sdid !== 'string' ||
219
- typeof payload?.eml !== 'string' ||
220
- payload?.aud !== 'agreement-portal' ||
221
- typeof payload?.iat !== 'number' ||
222
- typeof payload?.exp !== 'number'
223
- ) return null;
224
- if (payload.exp < Math.floor(Date.now() / 1000)) return null;
225
- if (revokedAtIso) {
226
- const revokedSec = Math.floor(Date.parse(revokedAtIso) / 1000);
227
- if (Number.isFinite(revokedSec) && payload.iat <= revokedSec) return null;
228
- }
229
- return payload;
230
- }
231
-
232
- /** 30-day expiry, matches §5.1 of the design. */
233
- export async function buildAgreementPortalUrl(
234
- base: string,
235
- signatureDocumentId: string,
236
- signerEmail: string,
237
- secret: string,
238
- ): Promise<string> {
239
- const nowSec = Math.floor(Date.now() / 1000);
240
- const payload: AgreementPortalTokenPayload = {
241
- sdid: signatureDocumentId,
242
- eml: signerEmail.toLowerCase(),
243
- aud: 'agreement-portal',
244
- iat: nowSec,
245
- exp: nowSec + 30 * 24 * 3600,
246
- };
247
- const token = await signAgreementPortalToken(payload, secret);
248
- return `${base.replace(/\/+$/, '')}/agreement-portal?token=${encodeURIComponent(token)}`;
249
- }
250
-
251
- // ---------------------------------------------------------------------------
252
- // Legacy-member migration checkout token — plan v13 §2.3.
253
- //
254
- // Same HMAC-SHA256 primitives + MANAGE_TOKEN_SECRET as every token above, with
255
- // its own `aud: 'migration-checkout'` claim so an agreement-portal or booking
256
- // token can never verify here by accident, and vice versa.
257
- //
258
- // TWO-PHASE VERIFICATION, and the split is deliberate:
259
- // phase 1 — verifyMigrationCheckoutToken(): decode, HMAC, shape, expiry.
260
- // Pure, no I/O, no DB. Deliberately does NOT take a revokedAt
261
- // argument (unlike verifyAgreementPortalToken above), because the
262
- // revocation timestamp lives on migration_checkout_state, which
263
- // the caller cannot load until it knows which email to load — and
264
- // it only knows that once phase 1 has returned a payload.
265
- // phase 2 — migrationCheckoutTokenIsRevoked(): called by the edge function
266
- // AFTER it has loaded the state row for payload.eml.
267
- // ---------------------------------------------------------------------------
268
-
269
- export interface MigrationCheckoutTokenPayload {
270
- eml: string; // lowercased roster email — migration_checkout_state.email
271
- aud: 'migration-checkout';
272
- iat: number; // unix seconds, minting time
273
- exp: number; // unix seconds
274
- }
275
-
276
- /**
277
- * 60-day flat default (plan §6 item 1 — Kyle's decision). The plan noted a
278
- * migration-window-close-date variant as "better"; it was explicitly declined,
279
- * so this is a flat constant on purpose. Do not re-derive it from a window
280
- * date without a new decision.
281
- */
282
- export const MIGRATION_CHECKOUT_TOKEN_TTL_SECONDS = 60 * 24 * 3600;
283
-
284
- export async function signMigrationCheckoutToken(
285
- payload: MigrationCheckoutTokenPayload,
286
- secret: string,
287
- ): Promise<string> {
288
- const key = await getKey(secret);
289
- const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
290
- const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
291
- return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
292
- }
293
-
294
- /** Phase 1: decode + HMAC + shape + expiry. Pure — no DB, no revocation check. */
295
- export async function verifyMigrationCheckoutToken(
296
- token: string,
297
- secret: string,
298
- ): Promise<MigrationCheckoutTokenPayload | null> {
299
- const parts = token.split('.');
300
- if (parts.length !== 2) return null;
301
- let payloadBytes: Uint8Array<ArrayBuffer>;
302
- let sigBytes: Uint8Array<ArrayBuffer>;
303
- try {
304
- payloadBytes = b64urlDecode(parts[0]);
305
- sigBytes = b64urlDecode(parts[1]);
306
- } catch {
307
- return null;
308
- }
309
- const key = await getKey(secret);
310
- const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
311
- if (!timingSafeEqual(expected, sigBytes)) return null;
312
- let payload: MigrationCheckoutTokenPayload;
313
- try {
314
- payload = JSON.parse(new TextDecoder().decode(payloadBytes)) as MigrationCheckoutTokenPayload;
315
- } catch {
316
- return null;
317
- }
318
- if (
319
- typeof payload?.eml !== 'string' ||
320
- payload?.aud !== 'migration-checkout' ||
321
- typeof payload?.iat !== 'number' ||
322
- typeof payload?.exp !== 'number'
323
- ) return null;
324
- if (payload.exp < Math.floor(Date.now() / 1000)) return null;
325
- return payload;
326
- }
327
-
328
- /**
329
- * Phase 2: revocation, checked by the caller once migration_checkout_state has
330
- * been loaded for payload.eml. Same iat-vs-revoked_at comparison
331
- * verifyAgreementPortalToken makes internally, so revoking invalidates every
332
- * token minted at or before the revocation instant while leaving a later
333
- * re-mint valid.
334
- *
335
- * Fails CLOSED on an unparseable timestamp: a revoked_at we cannot read is
336
- * treated as revoked, not as absent.
337
- */
338
- export function migrationCheckoutTokenIsRevoked(
339
- payload: MigrationCheckoutTokenPayload,
340
- revokedAtIso?: string | null,
341
- ): boolean {
342
- if (!revokedAtIso) return false;
343
- const revokedSec = Math.floor(Date.parse(revokedAtIso) / 1000);
344
- if (!Number.isFinite(revokedSec)) return true;
345
- return payload.iat <= revokedSec;
346
- }
347
-
348
- /** 60-day expiry, flat default per §6 item 1. */
349
- export async function buildMigrationCheckoutUrl(
350
- base: string,
351
- rosterEmail: string,
352
- secret: string,
353
- ): Promise<string> {
354
- const nowSec = Math.floor(Date.now() / 1000);
355
- const payload: MigrationCheckoutTokenPayload = {
356
- eml: rosterEmail.toLowerCase(),
357
- aud: 'migration-checkout',
358
- iat: nowSec,
359
- exp: nowSec + MIGRATION_CHECKOUT_TOKEN_TTL_SECONDS,
360
- };
361
- const token = await signMigrationCheckoutToken(payload, secret);
362
- return `${base.replace(/\/+$/, '')}/functions/v1/migration-checkout-confirm?token=${encodeURIComponent(token)}`;
363
- }
1
+ // HMAC-SHA256 signed token for self-serve booking management. Payload is a
2
+ // small JSON object identifying the booking and the customer email, plus an
3
+ // expiry. Never accept a bare booking UUID for PII — the token is the only key.
4
+
5
+ export interface ManageTokenPayload {
6
+ bid: string; // booking uuid
7
+ eml: string; // lowercased contact_email
8
+ exp: number; // unix seconds
9
+ }
10
+
11
+ function b64urlEncode(bytes: Uint8Array): string {
12
+ const s = btoa(String.fromCharCode(...bytes));
13
+ return s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
14
+ }
15
+
16
+ function b64urlDecode(s: string): Uint8Array<ArrayBuffer> {
17
+ const pad = s.length % 4 === 0 ? '' : '='.repeat(4 - (s.length % 4));
18
+ const b = atob(s.replace(/-/g, '+').replace(/_/g, '/') + pad);
19
+ const out = new Uint8Array(b.length);
20
+ for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i);
21
+ return out;
22
+ }
23
+
24
+ async function getKey(secret: string): Promise<CryptoKey> {
25
+ return await crypto.subtle.importKey(
26
+ 'raw',
27
+ new TextEncoder().encode(secret),
28
+ { name: 'HMAC', hash: 'SHA-256' },
29
+ false,
30
+ ['sign', 'verify'],
31
+ );
32
+ }
33
+
34
+ function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
35
+ if (a.length !== b.length) return false;
36
+ let diff = 0;
37
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
38
+ return diff === 0;
39
+ }
40
+
41
+ export async function signManageToken(
42
+ payload: ManageTokenPayload,
43
+ secret: string,
44
+ ): Promise<string> {
45
+ const key = await getKey(secret);
46
+ const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
47
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
48
+ return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
49
+ }
50
+
51
+ export async function verifyManageToken(
52
+ token: string,
53
+ secret: string,
54
+ ): Promise<ManageTokenPayload | null> {
55
+ const parts = token.split('.');
56
+ if (parts.length !== 2) return null;
57
+ // Explicitly ArrayBuffer-backed: a bare `Uint8Array` widens to
58
+ // Uint8Array<ArrayBufferLike>, which crypto.subtle.sign() rejects because a
59
+ // SharedArrayBuffer-backed view is not a BufferSource.
60
+ let payloadBytes: Uint8Array<ArrayBuffer>;
61
+ let sigBytes: Uint8Array<ArrayBuffer>;
62
+ try {
63
+ payloadBytes = b64urlDecode(parts[0]);
64
+ sigBytes = b64urlDecode(parts[1]);
65
+ } catch {
66
+ return null;
67
+ }
68
+ const key = await getKey(secret);
69
+ const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
70
+ if (!timingSafeEqual(expected, sigBytes)) return null;
71
+ let payload: ManageTokenPayload;
72
+ try {
73
+ payload = JSON.parse(new TextDecoder().decode(payloadBytes)) as ManageTokenPayload;
74
+ } catch {
75
+ return null;
76
+ }
77
+ if (
78
+ typeof payload?.bid !== 'string' ||
79
+ typeof payload?.eml !== 'string' ||
80
+ typeof payload?.exp !== 'number'
81
+ ) return null;
82
+ if (payload.exp < Math.floor(Date.now() / 1000)) return null;
83
+ return payload;
84
+ }
85
+
86
+ /**
87
+ * Build a manage-booking URL for the given payload. Base is the site origin
88
+ * (no trailing slash), e.g. https://acme.example.com.
89
+ */
90
+ export async function buildManageUrl(
91
+ base: string,
92
+ payload: ManageTokenPayload,
93
+ secret: string,
94
+ ): Promise<string> {
95
+ const token = await signManageToken(payload, secret);
96
+ return `${base.replace(/\/+$/, '')}/manage-booking?token=${encodeURIComponent(token)}`;
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Membership customer portal token.
101
+ // Same HMAC-SHA256 primitives + MANAGE_TOKEN_SECRET as the booking token,
102
+ // with a distinct payload shape so we never confuse the two credentials.
103
+ // ---------------------------------------------------------------------------
104
+
105
+ export interface MemberTokenPayload {
106
+ mbr: string; // lowercased member email
107
+ exp: number; // unix seconds
108
+ }
109
+
110
+ export async function signMemberToken(
111
+ payload: MemberTokenPayload,
112
+ secret: string,
113
+ ): Promise<string> {
114
+ const key = await getKey(secret);
115
+ const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
116
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
117
+ return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
118
+ }
119
+
120
+ export async function verifyMemberToken(
121
+ token: string,
122
+ secret: string,
123
+ ): Promise<MemberTokenPayload | null> {
124
+ const parts = token.split('.');
125
+ if (parts.length !== 2) return null;
126
+ // Explicitly ArrayBuffer-backed: a bare `Uint8Array` widens to
127
+ // Uint8Array<ArrayBufferLike>, which crypto.subtle.sign() rejects because a
128
+ // SharedArrayBuffer-backed view is not a BufferSource.
129
+ let payloadBytes: Uint8Array<ArrayBuffer>;
130
+ let sigBytes: Uint8Array<ArrayBuffer>;
131
+ try {
132
+ payloadBytes = b64urlDecode(parts[0]);
133
+ sigBytes = b64urlDecode(parts[1]);
134
+ } catch {
135
+ return null;
136
+ }
137
+ const key = await getKey(secret);
138
+ const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
139
+ if (!timingSafeEqual(expected, sigBytes)) return null;
140
+ let payload: MemberTokenPayload;
141
+ try {
142
+ payload = JSON.parse(new TextDecoder().decode(payloadBytes)) as MemberTokenPayload;
143
+ } catch {
144
+ return null;
145
+ }
146
+ if (typeof payload?.mbr !== 'string' || typeof payload?.exp !== 'number') return null;
147
+ if (payload.exp < Math.floor(Date.now() / 1000)) return null;
148
+ return payload;
149
+ }
150
+
151
+ export async function buildMemberManageUrl(
152
+ base: string,
153
+ payload: MemberTokenPayload,
154
+ secret: string,
155
+ ): Promise<string> {
156
+ const token = await signMemberToken(payload, secret);
157
+ return `${base.replace(/\/+$/, '')}/membership/manage?token=${encodeURIComponent(token)}`;
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Unified agreement portal token. Same HMAC-SHA256 primitives + MANAGE_TOKEN_SECRET
162
+ // as the other tokens above, with its own payload shape and an explicit `aud`
163
+ // claim so a token minted for booking/member management can never verify here
164
+ // by accident, and vice versa.
165
+ // ---------------------------------------------------------------------------
166
+
167
+ export interface AgreementPortalTokenPayload {
168
+ sdid: string; // signature_documents.id
169
+ eml: string; // lowercased signer_email
170
+ aud: 'agreement-portal';
171
+ iat: number; // unix seconds, minting time
172
+ exp: number; // unix seconds
173
+ }
174
+
175
+ export async function signAgreementPortalToken(
176
+ payload: AgreementPortalTokenPayload,
177
+ secret: string,
178
+ ): Promise<string> {
179
+ const key = await getKey(secret);
180
+ const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
181
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
182
+ return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
183
+ }
184
+
185
+ /**
186
+ * Verify an agreement portal token. `revokedAtIso`, if provided, rejects only
187
+ * tokens minted AT OR BEFORE that instant -- a fresh re-mint after a revoke
188
+ * verifies again without any separate un-revoke step.
189
+ */
190
+ export async function verifyAgreementPortalToken(
191
+ token: string,
192
+ secret: string,
193
+ revokedAtIso?: string | null,
194
+ ): Promise<AgreementPortalTokenPayload | null> {
195
+ const parts = token.split('.');
196
+ if (parts.length !== 2) return null;
197
+ // Explicitly ArrayBuffer-backed: a bare `Uint8Array` widens to
198
+ // Uint8Array<ArrayBufferLike>, which crypto.subtle.sign() rejects because a
199
+ // SharedArrayBuffer-backed view is not a BufferSource.
200
+ let payloadBytes: Uint8Array<ArrayBuffer>;
201
+ let sigBytes: Uint8Array<ArrayBuffer>;
202
+ try {
203
+ payloadBytes = b64urlDecode(parts[0]);
204
+ sigBytes = b64urlDecode(parts[1]);
205
+ } catch {
206
+ return null;
207
+ }
208
+ const key = await getKey(secret);
209
+ const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
210
+ if (!timingSafeEqual(expected, sigBytes)) return null;
211
+ let payload: AgreementPortalTokenPayload;
212
+ try {
213
+ payload = JSON.parse(new TextDecoder().decode(payloadBytes)) as AgreementPortalTokenPayload;
214
+ } catch {
215
+ return null;
216
+ }
217
+ if (
218
+ typeof payload?.sdid !== 'string' ||
219
+ typeof payload?.eml !== 'string' ||
220
+ payload?.aud !== 'agreement-portal' ||
221
+ typeof payload?.iat !== 'number' ||
222
+ typeof payload?.exp !== 'number'
223
+ ) return null;
224
+ if (payload.exp < Math.floor(Date.now() / 1000)) return null;
225
+ if (revokedAtIso) {
226
+ const revokedSec = Math.floor(Date.parse(revokedAtIso) / 1000);
227
+ if (Number.isFinite(revokedSec) && payload.iat <= revokedSec) return null;
228
+ }
229
+ return payload;
230
+ }
231
+
232
+ /** 30-day expiry, matches §5.1 of the design. */
233
+ export async function buildAgreementPortalUrl(
234
+ base: string,
235
+ signatureDocumentId: string,
236
+ signerEmail: string,
237
+ secret: string,
238
+ ): Promise<string> {
239
+ const nowSec = Math.floor(Date.now() / 1000);
240
+ const payload: AgreementPortalTokenPayload = {
241
+ sdid: signatureDocumentId,
242
+ eml: signerEmail.toLowerCase(),
243
+ aud: 'agreement-portal',
244
+ iat: nowSec,
245
+ exp: nowSec + 30 * 24 * 3600,
246
+ };
247
+ const token = await signAgreementPortalToken(payload, secret);
248
+ return `${base.replace(/\/+$/, '')}/agreement-portal?token=${encodeURIComponent(token)}`;
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // Legacy-member migration checkout token — plan v13 §2.3.
253
+ //
254
+ // Same HMAC-SHA256 primitives + MANAGE_TOKEN_SECRET as every token above, with
255
+ // its own `aud: 'migration-checkout'` claim so an agreement-portal or booking
256
+ // token can never verify here by accident, and vice versa.
257
+ //
258
+ // TWO-PHASE VERIFICATION, and the split is deliberate:
259
+ // phase 1 — verifyMigrationCheckoutToken(): decode, HMAC, shape, expiry.
260
+ // Pure, no I/O, no DB. Deliberately does NOT take a revokedAt
261
+ // argument (unlike verifyAgreementPortalToken above), because the
262
+ // revocation timestamp lives on migration_checkout_state, which
263
+ // the caller cannot load until it knows which email to load — and
264
+ // it only knows that once phase 1 has returned a payload.
265
+ // phase 2 — migrationCheckoutTokenIsRevoked(): called by the edge function
266
+ // AFTER it has loaded the state row for payload.eml.
267
+ // ---------------------------------------------------------------------------
268
+
269
+ export interface MigrationCheckoutTokenPayload {
270
+ eml: string; // lowercased roster email — migration_checkout_state.email
271
+ aud: 'migration-checkout';
272
+ iat: number; // unix seconds, minting time
273
+ exp: number; // unix seconds
274
+ }
275
+
276
+ /**
277
+ * 60-day flat default (plan §6 item 1 — Kyle's decision). The plan noted a
278
+ * migration-window-close-date variant as "better"; it was explicitly declined,
279
+ * so this is a flat constant on purpose. Do not re-derive it from a window
280
+ * date without a new decision.
281
+ */
282
+ export const MIGRATION_CHECKOUT_TOKEN_TTL_SECONDS = 60 * 24 * 3600;
283
+
284
+ export async function signMigrationCheckoutToken(
285
+ payload: MigrationCheckoutTokenPayload,
286
+ secret: string,
287
+ ): Promise<string> {
288
+ const key = await getKey(secret);
289
+ const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
290
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
291
+ return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
292
+ }
293
+
294
+ /** Phase 1: decode + HMAC + shape + expiry. Pure — no DB, no revocation check. */
295
+ export async function verifyMigrationCheckoutToken(
296
+ token: string,
297
+ secret: string,
298
+ ): Promise<MigrationCheckoutTokenPayload | null> {
299
+ const parts = token.split('.');
300
+ if (parts.length !== 2) return null;
301
+ let payloadBytes: Uint8Array<ArrayBuffer>;
302
+ let sigBytes: Uint8Array<ArrayBuffer>;
303
+ try {
304
+ payloadBytes = b64urlDecode(parts[0]);
305
+ sigBytes = b64urlDecode(parts[1]);
306
+ } catch {
307
+ return null;
308
+ }
309
+ const key = await getKey(secret);
310
+ const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes as unknown as BufferSource));
311
+ if (!timingSafeEqual(expected, sigBytes)) return null;
312
+ let payload: MigrationCheckoutTokenPayload;
313
+ try {
314
+ payload = JSON.parse(new TextDecoder().decode(payloadBytes)) as MigrationCheckoutTokenPayload;
315
+ } catch {
316
+ return null;
317
+ }
318
+ if (
319
+ typeof payload?.eml !== 'string' ||
320
+ payload?.aud !== 'migration-checkout' ||
321
+ typeof payload?.iat !== 'number' ||
322
+ typeof payload?.exp !== 'number'
323
+ ) return null;
324
+ if (payload.exp < Math.floor(Date.now() / 1000)) return null;
325
+ return payload;
326
+ }
327
+
328
+ /**
329
+ * Phase 2: revocation, checked by the caller once migration_checkout_state has
330
+ * been loaded for payload.eml. Same iat-vs-revoked_at comparison
331
+ * verifyAgreementPortalToken makes internally, so revoking invalidates every
332
+ * token minted at or before the revocation instant while leaving a later
333
+ * re-mint valid.
334
+ *
335
+ * Fails CLOSED on an unparseable timestamp: a revoked_at we cannot read is
336
+ * treated as revoked, not as absent.
337
+ */
338
+ export function migrationCheckoutTokenIsRevoked(
339
+ payload: MigrationCheckoutTokenPayload,
340
+ revokedAtIso?: string | null,
341
+ ): boolean {
342
+ if (!revokedAtIso) return false;
343
+ const revokedSec = Math.floor(Date.parse(revokedAtIso) / 1000);
344
+ if (!Number.isFinite(revokedSec)) return true;
345
+ return payload.iat <= revokedSec;
346
+ }
347
+
348
+ /** 60-day expiry, flat default per §6 item 1. */
349
+ export async function buildMigrationCheckoutUrl(
350
+ base: string,
351
+ rosterEmail: string,
352
+ secret: string,
353
+ ): Promise<string> {
354
+ const nowSec = Math.floor(Date.now() / 1000);
355
+ const payload: MigrationCheckoutTokenPayload = {
356
+ eml: rosterEmail.toLowerCase(),
357
+ aud: 'migration-checkout',
358
+ iat: nowSec,
359
+ exp: nowSec + MIGRATION_CHECKOUT_TOKEN_TTL_SECONDS,
360
+ };
361
+ const token = await signMigrationCheckoutToken(payload, secret);
362
+ return `${base.replace(/\/+$/, '')}/functions/v1/migration-checkout-confirm?token=${encodeURIComponent(token)}`;
363
+ }