@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
package/src/busClient.ts CHANGED
@@ -1,268 +1,268 @@
1
- // Tenant -> middleware booking bus client. Signs the verb-bound canonical v2
2
- // message with BUS_HMAC_SECRET (byte-identical scheme to bus_hmac.py on the
3
- // middleware) and POSTs provision/cancel.
4
- //
5
- // D33 Phase 0.5 / Phase 10 batch 1: the generic half of gc-connect's
6
- // _shared/busClient.ts. ONLY callBus() was parameterized -- it now takes the
7
- // tenant's bus origin, `source` and `access_scope` as config instead of three
8
- // module-level literals. EVERY CRYPTOGRAPHIC FUNCTION BELOW (b64urlNoPad,
9
- // signBus, customerDigest, signBusV3, deriveCalendarAttestationKey,
10
- // canonicalCalendarAttestationV2, signCalendarAttestationV2) AND toBusUtc WERE
11
- // MOVED CHARACTER-FOR-CHARACTER UNCHANGED. Their inputs were already fully
12
- // caller-supplied parameters -- including `gcSource` and `secret` -- so nothing
13
- // about them needed to be made pluggable, and nothing about them was touched.
14
- // This is a pinned cross-repo contract that ftw-middleware's own reconciler
15
- // verifies independently on a separate deploy; it is not local logic that may
16
- // be freely refactored.
17
- //
18
- // CONTRACT SCOPE — this is a deliberate PARTIAL implementation of
19
- // door-access-design/BUS-CONTRACT-v2-SPEC.md. Only the spec's verb-binding
20
- // (§3.4) is implemented. NOT implemented, and out of scope by decision:
21
- // §3.1's extra canonical fields (source, access_scope, occurred_at,
22
- // customer_digest), §3.3's occurred_at freshness window, and §4's separate
23
- // HKDF-derived calendar-attestation key (K_cal). `source`, `access_scope`,
24
- // `occurred_at`, `schema` and `customer` are therefore still sent UNSIGNED
25
- // and must not be treated as authenticated by any receiver.
26
- //
27
- // FAILURE-MODE INVARIANT: payment is never blocked by provisioning -- every
28
- // call here is a post-commit side effect. NEVER throws into a money path.
29
-
30
- import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
31
- import { logOps } from './ops.ts';
32
-
33
- // Loose generics, matching ops.ts. A real createClient(url, key, opts)
34
- // call infers SupabaseClient<any, 'public', 'public', ...>, which is NOT
35
- // assignable to the un-inferred ReturnType<typeof createClient> default — that
36
- // mismatch is what made every call site here fail deno check.
37
- // deno-lint-ignore no-explicit-any
38
- type SupabaseLike = SupabaseClient<any, any, any>;
39
-
40
- /**
41
- * The tenant's booking-bus transport identity.
42
- *
43
- * `source` and `accessScope` are sent UNSIGNED under the v2 scheme (see the
44
- * CONTRACT SCOPE note above) but ARE signed under signBusV3, which callBus()
45
- * uses -- so they are part of the canonical message and cannot be defaulted by
46
- * the platform without silently signing somebody else's identity.
47
- */
48
- export interface BusClientConfig {
49
- /** Origin of the tenant's middleware, e.g. https://bus.example.com. No trailing slash. */
50
- busBase: string;
51
- /** `source` field, signed into the v3 canonical message and sent in the body. */
52
- source: string;
53
- /** `access_scope` field, signed into the v3 canonical message and sent in the body. */
54
- accessScope: string;
55
- }
56
-
57
- // RFC3339 UTC, second precision, Z — the only timestamp shape the contract signs.
58
- export function toBusUtc(iso: string): string {
59
- return new Date(iso).toISOString().replace(/\.\d{3}Z$/, 'Z');
60
- }
61
-
62
- function b64urlNoPad(bytes: Uint8Array): string {
63
- const s = btoa(String.fromCharCode(...bytes));
64
- return s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
65
- }
66
-
67
- // Canonical message MUST match bus_hmac.canonical_message() on ftw-middleware
68
- // byte-for-byte (verified 2026-08-12 by a live sign->verify round trip inside
69
- // the production container for all three verbs, incl. confirming cross-verb
70
- // replay is rejected):
71
- // v2\n{verb}\n{booking_id.lower()}\n{room_key}\n{start_utc}\n{end_utc}[\n{ts}]
72
- // ts is included ONLY when provided (credential reads, which transport it in
73
- // the X-GC-Timestamp header); provision/cancel omit the ts line entirely.
74
- // PINNED CROSS-REPO CONTRACT: changing the field order, the field set, the
75
- // "v2" prefix, or the conditional-ts rule requires the same change to
76
- // ftw-middleware's bus_hmac.py in the same coordinated deploy, or every door
77
- // provision, cancel and PIN read fails closed with 401 in production.
78
- export async function signBus(
79
- verb: 'provision' | 'cancel' | 'credential',
80
- bookingId: string, roomKey: string, startUtc: string, endUtc: string, secret: string,
81
- ts?: number,
82
- ): Promise<string> {
83
- const parts = ['v2', (verb || '').trim(), (bookingId || '').trim().toLowerCase(),
84
- (roomKey || '').trim(), (startUtc || '').trim(), (endUtc || '').trim()];
85
- if (ts !== undefined && ts !== null) parts.push(String(Math.trunc(ts)));
86
- const msg = parts.join('\n');
87
- const key = await crypto.subtle.importKey(
88
- 'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
89
- const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
90
- return b64urlNoPad(sig);
91
- }
92
-
93
- // --- v3 extended-fields scheme (closes finding U1: event/source/access_scope/
94
- // customer were previously sent unsigned). Mirrors bus_hmac.py's
95
- // canonical_message_v3 / sign_v3 / customer_digest byte-for-byte — per that
96
- // module's own "reference implementation for a future tenant-app signing side" note
97
- // on sign_v3. Field order is pinned cross-repo: v3, verb, booking_id,
98
- // room_key, start, end, event, source, access_scope, customer_digest, with ts
99
- // appended only when provided (same conditional-ts rule as v2).
100
- export async function customerDigest(
101
- email?: string, name?: string, phone?: string, ghlContactId?: string,
102
- ): Promise<string> {
103
- const lines = [
104
- (email ?? '').trim().toLowerCase(),
105
- (name ?? '').trim(),
106
- (phone ?? '').replace(/[^0-9]/g, ''),
107
- (ghlContactId ?? '').trim(),
108
- ];
109
- const digest = new Uint8Array(
110
- await crypto.subtle.digest('SHA-256', new TextEncoder().encode(lines.join('\n'))));
111
- return b64urlNoPad(digest);
112
- }
113
-
114
- export async function signBusV3(
115
- verb: 'provision' | 'cancel' | 'credential',
116
- bookingId: string, roomKey: string, startUtc: string, endUtc: string,
117
- event: string, source: string, accessScope: string,
118
- customerEmail?: string, customerName?: string, customerPhone?: string,
119
- customerGhlContactId?: string,
120
- secret?: string, ts?: number,
121
- ): Promise<string> {
122
- const digest = await customerDigest(customerEmail, customerName, customerPhone, customerGhlContactId);
123
- const parts = ['v3', (verb || '').trim(), (bookingId || '').trim().toLowerCase(),
124
- (roomKey || '').trim(), (startUtc || '').trim(), (endUtc || '').trim(),
125
- (event || '').trim().toLowerCase(), (source || '').trim().toLowerCase(),
126
- (accessScope || '').trim().toLowerCase(), digest];
127
- if (ts !== undefined && ts !== null) parts.push(String(Math.trunc(ts)));
128
- const msg = parts.join('\n');
129
- const key = await crypto.subtle.importKey(
130
- 'raw', new TextEncoder().encode(secret ?? ''), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
131
- const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
132
- return b64urlNoPad(sig);
133
- }
134
-
135
- // --- Calendar attestation key (BUS-CONTRACT-v2-SPEC.md sec.4) ---------------
136
- // NAMING NOTE: "V2" in the names below refers to bus-contract v2 sec.4, and
137
- // is unrelated to signBus's own "v2" canonical-message prefix a few lines up
138
- // -- same word, two independent version numbers. K_cal is a ONE-WAY HKDF
139
- // derivation of BUS_HMAC_SECRET; it signs calendar-event attestations ONLY
140
- // and is never usable to forge a request signature (see signBus above),
141
- // which is the whole point of sec.4: a calendar reader who recovers
142
- // gc_sig_v2 gains nothing against /bookings/* because it is a different key
143
- // over a different canonical string. Mirrors ftw-middleware's bus_hmac.py
144
- // derive_calendar_attestation_key / canonical_calendar_attestation_v2 /
145
- // sign_calendar_attestation_v2 byte-for-byte -- verified against that
146
- // module's own golden test vector before this was written. Do not change
147
- // the info string, the empty salt, or the canonical field order/casing
148
- // without updating bus_hmac.py in the same coordinated deploy.
149
- async function deriveCalendarAttestationKey(secret: string): Promise<ArrayBuffer> {
150
- const ikm = await crypto.subtle.importKey(
151
- 'raw', new TextEncoder().encode(secret), { name: 'HKDF' }, false, ['deriveBits']);
152
- return await crypto.subtle.deriveBits(
153
- { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0),
154
- info: new TextEncoder().encode('gc-bus-v2-calendar-attestation') },
155
- ikm, 256);
156
- }
157
-
158
- // Rejects an empty identity field or a literal newline inside any field
159
- // (matches bus_hmac.py's verifier-side hardening -- an unescaped
160
- // newline-joined encoding is not injective over fields that could
161
- // themselves embed "\n", and an all-empty tuple would otherwise be a
162
- // well-formed signable message with no identity at all).
163
- function canonicalCalendarAttestationV2(
164
- bookingId: string, roomKey: string, startUtc: string, endUtc: string, gcSource: string,
165
- ): string {
166
- const bid = (bookingId || '').trim().toLowerCase();
167
- const room = (roomKey || '').trim();
168
- const start = (startUtc || '').trim();
169
- const end = (endUtc || '').trim();
170
- const src = (gcSource || '').trim().toLowerCase();
171
- if (!bid || !room || !start || !end) {
172
- throw new Error('canonicalCalendarAttestationV2: booking_id/room_key/start/end must be non-empty');
173
- }
174
- const parts = [bid, room, start, end, src];
175
- if (parts.some((p) => p.includes('\n'))) {
176
- throw new Error('canonicalCalendarAttestationV2: field must not contain a newline');
177
- }
178
- return 'gcal-v2\n' + parts.join('\n');
179
- }
180
-
181
- export async function signCalendarAttestationV2(
182
- bookingId: string, roomKey: string, startUtc: string, endUtc: string, gcSource: string, secret: string,
183
- ): Promise<string> {
184
- const kCal = await deriveCalendarAttestationKey(secret);
185
- const msg = canonicalCalendarAttestationV2(bookingId, roomKey, startUtc, endUtc, gcSource);
186
- const key = await crypto.subtle.importKey('raw', kCal, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
187
- const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
188
- return b64urlNoPad(sig);
189
- }
190
-
191
- export interface BusBooking {
192
- bookingId: string;
193
- roomKey: string; // rooms.slug
194
- startUtc: string; // any ISO input; normalized via toBusUtc
195
- endUtc: string;
196
- customer?: { name?: string; email?: string; phone?: string };
197
- }
198
-
199
- export async function callBus(
200
- event: 'provision' | 'cancel', b: BusBooking, supabase: SupabaseLike, config: BusClientConfig,
201
- ): Promise<Record<string, unknown> | null> {
202
- const secret = Deno.env.get('BUS_HMAC_SECRET');
203
- if (!secret) { console.log('[busClient] BUS_HMAC_SECRET unset; skip'); return null; }
204
- try {
205
- const startUtc = toBusUtc(b.startUtc);
206
- const endUtc = toBusUtc(b.endUtc);
207
- const hmac = await signBusV3(event, b.bookingId, b.roomKey, startUtc, endUtc,
208
- event, config.source, config.accessScope,
209
- b.customer?.email, b.customer?.name, b.customer?.phone, undefined, secret);
210
- const body = {
211
- schema: 1, event, booking_id: b.bookingId, source: config.source,
212
- room_key: b.roomKey, start_utc: startUtc, end_utc: endUtc,
213
- access_scope: config.accessScope, customer: b.customer ?? undefined, hmac,
214
- occurred_at: toBusUtc(new Date().toISOString()),
215
- };
216
- const res = await fetch(`${config.busBase}/bookings/${event}`, {
217
- method: 'POST', headers: { 'Content-Type': 'application/json' },
218
- body: JSON.stringify(body),
219
- signal: AbortSignal.timeout(10000),
220
- });
221
- const json = await res.json().catch(() => ({}));
222
- if (!res.ok) {
223
- const { credential: _cred, ...safe } = (json ?? {}) as Record<string, unknown>;
224
- await logOps(supabase, 'bus_call_failed', {
225
- event,
226
- status: res.status,
227
- error: typeof safe.error === 'string' ? safe.error : undefined,
228
- detail: JSON.stringify(safe).slice(0, 300),
229
- }, { severity: 'error', bookingId: b.bookingId });
230
- return null;
231
- }
232
- return json as Record<string, unknown>;
233
- } catch (e) {
234
- await logOps(supabase, 'bus_call_error', { event, message: String(e) },
235
- { severity: 'error', bookingId: b.bookingId });
236
- return null;
237
- }
238
- }
239
-
240
- export function busProvision(b: BusBooking, supabase: SupabaseLike, config: BusClientConfig) {
241
- return callBus('provision', b, supabase, config);
242
- }
243
- export function busCancel(b: BusBooking, supabase: SupabaseLike, config: BusClientConfig) {
244
- return callBus('cancel', b, supabase, config);
245
- }
246
-
247
- // Door access material extracted from a busProvision response. The middleware
248
- // returns credential.{pin, valid_from_utc, valid_to_utc} for issued PINs; a
249
- // gate-off/pending response (status !== 'issued') has no pin. NEVER logged
250
- // here — callers must never persist or log the pin.
251
- export interface DoorAccess {
252
- pin: string;
253
- validFromUtc?: string;
254
- validToUtc?: string;
255
- }
256
-
257
- export function extractDoorAccess(resp: Record<string, unknown> | null): DoorAccess | null {
258
- if (!resp) return null;
259
- const cred = (resp as { credential?: unknown }).credential;
260
- if (!cred || typeof cred !== 'object') return null;
261
- const c = cred as Record<string, unknown>;
262
- const pin = c.pin;
263
- if (typeof pin !== 'string' || pin.length === 0) return null;
264
- const out: DoorAccess = { pin };
265
- if (typeof c.valid_from_utc === 'string') out.validFromUtc = c.valid_from_utc;
266
- if (typeof c.valid_to_utc === 'string') out.validToUtc = c.valid_to_utc;
267
- return out;
268
- }
1
+ // Tenant -> middleware booking bus client. Signs the verb-bound canonical v2
2
+ // message with BUS_HMAC_SECRET (byte-identical scheme to bus_hmac.py on the
3
+ // middleware) and POSTs provision/cancel.
4
+ //
5
+ // D33 Phase 0.5 / Phase 10 batch 1: the generic half of gc-connect's
6
+ // _shared/busClient.ts. ONLY callBus() was parameterized -- it now takes the
7
+ // tenant's bus origin, `source` and `access_scope` as config instead of three
8
+ // module-level literals. EVERY CRYPTOGRAPHIC FUNCTION BELOW (b64urlNoPad,
9
+ // signBus, customerDigest, signBusV3, deriveCalendarAttestationKey,
10
+ // canonicalCalendarAttestationV2, signCalendarAttestationV2) AND toBusUtc WERE
11
+ // MOVED CHARACTER-FOR-CHARACTER UNCHANGED. Their inputs were already fully
12
+ // caller-supplied parameters -- including `gcSource` and `secret` -- so nothing
13
+ // about them needed to be made pluggable, and nothing about them was touched.
14
+ // This is a pinned cross-repo contract that ftw-middleware's own reconciler
15
+ // verifies independently on a separate deploy; it is not local logic that may
16
+ // be freely refactored.
17
+ //
18
+ // CONTRACT SCOPE — this is a deliberate PARTIAL implementation of
19
+ // door-access-design/BUS-CONTRACT-v2-SPEC.md. Only the spec's verb-binding
20
+ // (§3.4) is implemented. NOT implemented, and out of scope by decision:
21
+ // §3.1's extra canonical fields (source, access_scope, occurred_at,
22
+ // customer_digest), §3.3's occurred_at freshness window, and §4's separate
23
+ // HKDF-derived calendar-attestation key (K_cal). `source`, `access_scope`,
24
+ // `occurred_at`, `schema` and `customer` are therefore still sent UNSIGNED
25
+ // and must not be treated as authenticated by any receiver.
26
+ //
27
+ // FAILURE-MODE INVARIANT: payment is never blocked by provisioning -- every
28
+ // call here is a post-commit side effect. NEVER throws into a money path.
29
+
30
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
31
+ import { logOps } from './ops.ts';
32
+
33
+ // Loose generics, matching ops.ts. A real createClient(url, key, opts)
34
+ // call infers SupabaseClient<any, 'public', 'public', ...>, which is NOT
35
+ // assignable to the un-inferred ReturnType<typeof createClient> default — that
36
+ // mismatch is what made every call site here fail deno check.
37
+ // deno-lint-ignore no-explicit-any
38
+ type SupabaseLike = SupabaseClient<any, any, any>;
39
+
40
+ /**
41
+ * The tenant's booking-bus transport identity.
42
+ *
43
+ * `source` and `accessScope` are sent UNSIGNED under the v2 scheme (see the
44
+ * CONTRACT SCOPE note above) but ARE signed under signBusV3, which callBus()
45
+ * uses -- so they are part of the canonical message and cannot be defaulted by
46
+ * the platform without silently signing somebody else's identity.
47
+ */
48
+ export interface BusClientConfig {
49
+ /** Origin of the tenant's middleware, e.g. https://bus.example.com. No trailing slash. */
50
+ busBase: string;
51
+ /** `source` field, signed into the v3 canonical message and sent in the body. */
52
+ source: string;
53
+ /** `access_scope` field, signed into the v3 canonical message and sent in the body. */
54
+ accessScope: string;
55
+ }
56
+
57
+ // RFC3339 UTC, second precision, Z — the only timestamp shape the contract signs.
58
+ export function toBusUtc(iso: string): string {
59
+ return new Date(iso).toISOString().replace(/\.\d{3}Z$/, 'Z');
60
+ }
61
+
62
+ function b64urlNoPad(bytes: Uint8Array): string {
63
+ const s = btoa(String.fromCharCode(...bytes));
64
+ return s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
65
+ }
66
+
67
+ // Canonical message MUST match bus_hmac.canonical_message() on ftw-middleware
68
+ // byte-for-byte (verified 2026-08-12 by a live sign->verify round trip inside
69
+ // the production container for all three verbs, incl. confirming cross-verb
70
+ // replay is rejected):
71
+ // v2\n{verb}\n{booking_id.lower()}\n{room_key}\n{start_utc}\n{end_utc}[\n{ts}]
72
+ // ts is included ONLY when provided (credential reads, which transport it in
73
+ // the X-GC-Timestamp header); provision/cancel omit the ts line entirely.
74
+ // PINNED CROSS-REPO CONTRACT: changing the field order, the field set, the
75
+ // "v2" prefix, or the conditional-ts rule requires the same change to
76
+ // ftw-middleware's bus_hmac.py in the same coordinated deploy, or every door
77
+ // provision, cancel and PIN read fails closed with 401 in production.
78
+ export async function signBus(
79
+ verb: 'provision' | 'cancel' | 'credential',
80
+ bookingId: string, roomKey: string, startUtc: string, endUtc: string, secret: string,
81
+ ts?: number,
82
+ ): Promise<string> {
83
+ const parts = ['v2', (verb || '').trim(), (bookingId || '').trim().toLowerCase(),
84
+ (roomKey || '').trim(), (startUtc || '').trim(), (endUtc || '').trim()];
85
+ if (ts !== undefined && ts !== null) parts.push(String(Math.trunc(ts)));
86
+ const msg = parts.join('\n');
87
+ const key = await crypto.subtle.importKey(
88
+ 'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
89
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
90
+ return b64urlNoPad(sig);
91
+ }
92
+
93
+ // --- v3 extended-fields scheme (closes finding U1: event/source/access_scope/
94
+ // customer were previously sent unsigned). Mirrors bus_hmac.py's
95
+ // canonical_message_v3 / sign_v3 / customer_digest byte-for-byte — per that
96
+ // module's own "reference implementation for a future tenant-app signing side" note
97
+ // on sign_v3. Field order is pinned cross-repo: v3, verb, booking_id,
98
+ // room_key, start, end, event, source, access_scope, customer_digest, with ts
99
+ // appended only when provided (same conditional-ts rule as v2).
100
+ export async function customerDigest(
101
+ email?: string, name?: string, phone?: string, ghlContactId?: string,
102
+ ): Promise<string> {
103
+ const lines = [
104
+ (email ?? '').trim().toLowerCase(),
105
+ (name ?? '').trim(),
106
+ (phone ?? '').replace(/[^0-9]/g, ''),
107
+ (ghlContactId ?? '').trim(),
108
+ ];
109
+ const digest = new Uint8Array(
110
+ await crypto.subtle.digest('SHA-256', new TextEncoder().encode(lines.join('\n'))));
111
+ return b64urlNoPad(digest);
112
+ }
113
+
114
+ export async function signBusV3(
115
+ verb: 'provision' | 'cancel' | 'credential',
116
+ bookingId: string, roomKey: string, startUtc: string, endUtc: string,
117
+ event: string, source: string, accessScope: string,
118
+ customerEmail?: string, customerName?: string, customerPhone?: string,
119
+ customerGhlContactId?: string,
120
+ secret?: string, ts?: number,
121
+ ): Promise<string> {
122
+ const digest = await customerDigest(customerEmail, customerName, customerPhone, customerGhlContactId);
123
+ const parts = ['v3', (verb || '').trim(), (bookingId || '').trim().toLowerCase(),
124
+ (roomKey || '').trim(), (startUtc || '').trim(), (endUtc || '').trim(),
125
+ (event || '').trim().toLowerCase(), (source || '').trim().toLowerCase(),
126
+ (accessScope || '').trim().toLowerCase(), digest];
127
+ if (ts !== undefined && ts !== null) parts.push(String(Math.trunc(ts)));
128
+ const msg = parts.join('\n');
129
+ const key = await crypto.subtle.importKey(
130
+ 'raw', new TextEncoder().encode(secret ?? ''), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
131
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
132
+ return b64urlNoPad(sig);
133
+ }
134
+
135
+ // --- Calendar attestation key (BUS-CONTRACT-v2-SPEC.md sec.4) ---------------
136
+ // NAMING NOTE: "V2" in the names below refers to bus-contract v2 sec.4, and
137
+ // is unrelated to signBus's own "v2" canonical-message prefix a few lines up
138
+ // -- same word, two independent version numbers. K_cal is a ONE-WAY HKDF
139
+ // derivation of BUS_HMAC_SECRET; it signs calendar-event attestations ONLY
140
+ // and is never usable to forge a request signature (see signBus above),
141
+ // which is the whole point of sec.4: a calendar reader who recovers
142
+ // gc_sig_v2 gains nothing against /bookings/* because it is a different key
143
+ // over a different canonical string. Mirrors ftw-middleware's bus_hmac.py
144
+ // derive_calendar_attestation_key / canonical_calendar_attestation_v2 /
145
+ // sign_calendar_attestation_v2 byte-for-byte -- verified against that
146
+ // module's own golden test vector before this was written. Do not change
147
+ // the info string, the empty salt, or the canonical field order/casing
148
+ // without updating bus_hmac.py in the same coordinated deploy.
149
+ async function deriveCalendarAttestationKey(secret: string): Promise<ArrayBuffer> {
150
+ const ikm = await crypto.subtle.importKey(
151
+ 'raw', new TextEncoder().encode(secret), { name: 'HKDF' }, false, ['deriveBits']);
152
+ return await crypto.subtle.deriveBits(
153
+ { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0),
154
+ info: new TextEncoder().encode('gc-bus-v2-calendar-attestation') },
155
+ ikm, 256);
156
+ }
157
+
158
+ // Rejects an empty identity field or a literal newline inside any field
159
+ // (matches bus_hmac.py's verifier-side hardening -- an unescaped
160
+ // newline-joined encoding is not injective over fields that could
161
+ // themselves embed "\n", and an all-empty tuple would otherwise be a
162
+ // well-formed signable message with no identity at all).
163
+ function canonicalCalendarAttestationV2(
164
+ bookingId: string, roomKey: string, startUtc: string, endUtc: string, gcSource: string,
165
+ ): string {
166
+ const bid = (bookingId || '').trim().toLowerCase();
167
+ const room = (roomKey || '').trim();
168
+ const start = (startUtc || '').trim();
169
+ const end = (endUtc || '').trim();
170
+ const src = (gcSource || '').trim().toLowerCase();
171
+ if (!bid || !room || !start || !end) {
172
+ throw new Error('canonicalCalendarAttestationV2: booking_id/room_key/start/end must be non-empty');
173
+ }
174
+ const parts = [bid, room, start, end, src];
175
+ if (parts.some((p) => p.includes('\n'))) {
176
+ throw new Error('canonicalCalendarAttestationV2: field must not contain a newline');
177
+ }
178
+ return 'gcal-v2\n' + parts.join('\n');
179
+ }
180
+
181
+ export async function signCalendarAttestationV2(
182
+ bookingId: string, roomKey: string, startUtc: string, endUtc: string, gcSource: string, secret: string,
183
+ ): Promise<string> {
184
+ const kCal = await deriveCalendarAttestationKey(secret);
185
+ const msg = canonicalCalendarAttestationV2(bookingId, roomKey, startUtc, endUtc, gcSource);
186
+ const key = await crypto.subtle.importKey('raw', kCal, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
187
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
188
+ return b64urlNoPad(sig);
189
+ }
190
+
191
+ export interface BusBooking {
192
+ bookingId: string;
193
+ roomKey: string; // rooms.slug
194
+ startUtc: string; // any ISO input; normalized via toBusUtc
195
+ endUtc: string;
196
+ customer?: { name?: string; email?: string; phone?: string };
197
+ }
198
+
199
+ export async function callBus(
200
+ event: 'provision' | 'cancel', b: BusBooking, supabase: SupabaseLike, config: BusClientConfig,
201
+ ): Promise<Record<string, unknown> | null> {
202
+ const secret = Deno.env.get('BUS_HMAC_SECRET');
203
+ if (!secret) { console.log('[busClient] BUS_HMAC_SECRET unset; skip'); return null; }
204
+ try {
205
+ const startUtc = toBusUtc(b.startUtc);
206
+ const endUtc = toBusUtc(b.endUtc);
207
+ const hmac = await signBusV3(event, b.bookingId, b.roomKey, startUtc, endUtc,
208
+ event, config.source, config.accessScope,
209
+ b.customer?.email, b.customer?.name, b.customer?.phone, undefined, secret);
210
+ const body = {
211
+ schema: 1, event, booking_id: b.bookingId, source: config.source,
212
+ room_key: b.roomKey, start_utc: startUtc, end_utc: endUtc,
213
+ access_scope: config.accessScope, customer: b.customer ?? undefined, hmac,
214
+ occurred_at: toBusUtc(new Date().toISOString()),
215
+ };
216
+ const res = await fetch(`${config.busBase}/bookings/${event}`, {
217
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
218
+ body: JSON.stringify(body),
219
+ signal: AbortSignal.timeout(10000),
220
+ });
221
+ const json = await res.json().catch(() => ({}));
222
+ if (!res.ok) {
223
+ const { credential: _cred, ...safe } = (json ?? {}) as Record<string, unknown>;
224
+ await logOps(supabase, 'bus_call_failed', {
225
+ event,
226
+ status: res.status,
227
+ error: typeof safe.error === 'string' ? safe.error : undefined,
228
+ detail: JSON.stringify(safe).slice(0, 300),
229
+ }, { severity: 'error', bookingId: b.bookingId });
230
+ return null;
231
+ }
232
+ return json as Record<string, unknown>;
233
+ } catch (e) {
234
+ await logOps(supabase, 'bus_call_error', { event, message: String(e) },
235
+ { severity: 'error', bookingId: b.bookingId });
236
+ return null;
237
+ }
238
+ }
239
+
240
+ export function busProvision(b: BusBooking, supabase: SupabaseLike, config: BusClientConfig) {
241
+ return callBus('provision', b, supabase, config);
242
+ }
243
+ export function busCancel(b: BusBooking, supabase: SupabaseLike, config: BusClientConfig) {
244
+ return callBus('cancel', b, supabase, config);
245
+ }
246
+
247
+ // Door access material extracted from a busProvision response. The middleware
248
+ // returns credential.{pin, valid_from_utc, valid_to_utc} for issued PINs; a
249
+ // gate-off/pending response (status !== 'issued') has no pin. NEVER logged
250
+ // here — callers must never persist or log the pin.
251
+ export interface DoorAccess {
252
+ pin: string;
253
+ validFromUtc?: string;
254
+ validToUtc?: string;
255
+ }
256
+
257
+ export function extractDoorAccess(resp: Record<string, unknown> | null): DoorAccess | null {
258
+ if (!resp) return null;
259
+ const cred = (resp as { credential?: unknown }).credential;
260
+ if (!cred || typeof cred !== 'object') return null;
261
+ const c = cred as Record<string, unknown>;
262
+ const pin = c.pin;
263
+ if (typeof pin !== 'string' || pin.length === 0) return null;
264
+ const out: DoorAccess = { pin };
265
+ if (typeof c.valid_from_utc === 'string') out.validFromUtc = c.valid_from_utc;
266
+ if (typeof c.valid_to_utc === 'string') out.validToUtc = c.valid_to_utc;
267
+ return out;
268
+ }