@simplelayer/graniteer-core 0.1.2 → 0.2.1

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 (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  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 -0
  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 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  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 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +334 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +217 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -0,0 +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
+ }
@@ -0,0 +1,71 @@
1
+ // Shared HMAC-SHA256 + base64url(no-pad) helper for the MEMBERSHIP-side bus
2
+ // contracts (membershipBusClient.ts's "m1" snapshot signature, unifiGroups.ts's
3
+ // "g1" group-list header signature, unifiAccessPolicies.ts's "ap1" policy-list
4
+ // header signature), plus a fourth consumer, event-access-admin.ts, which uses
5
+ // sha256Hex/signBusMessage (not busB64UrlNoPad directly) for its "e1" scheme.
6
+ //
7
+ // D33 Phase 0.5 / Phase 10 batch 1: these three modules each carried a
8
+ // character-for-character identical private copy of this function
9
+ // (`signMembershipBus`, `signGroupList`, `signRequest`). Hoisted here unchanged
10
+ // -- same importKey params, same sign call, same byte->latin1->btoa->url-safe
11
+ // encoding, same no-padding strip.
12
+ //
13
+ // DELIBERATELY NOT USED BY busClient.ts. That module's private b64urlNoPad uses
14
+ // the spread-argument form `btoa(String.fromCharCode(...bytes))` rather than
15
+ // the accumulate-loop form used here -- they happen to agree for a 32-byte
16
+ // digest today, but are different code, and busClient.ts's crypto path is kept
17
+ // exactly as it was rather than re-pointed at a helper with a different
18
+ // implementation.
19
+
20
+ /** Base64url, no padding. Accumulate-loop form (see module note above). */
21
+ export function busB64UrlNoPad(bytes: Uint8Array): string {
22
+ let s = '';
23
+ for (const b of bytes) s += String.fromCharCode(b);
24
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
25
+ }
26
+
27
+ /** HMAC-SHA256 `msg` under `secret`, returned base64url with no padding. */
28
+ export async function signBusMessage(msg: string, secret: string): Promise<string> {
29
+ const key = await crypto.subtle.importKey(
30
+ 'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
31
+ );
32
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
33
+ return busB64UrlNoPad(sig);
34
+ }
35
+
36
+ /** Lowercase hex encoding of `bytes`, two chars per byte. */
37
+ export function toHex(bytes: Uint8Array): string {
38
+ let out = '';
39
+ for (const b of bytes) out += b.toString(16).padStart(2, '0');
40
+ return out;
41
+ }
42
+
43
+ /** SHA-256 digest of `text` (UTF-8), returned as lowercase hex. */
44
+ export async function sha256Hex(text: string): Promise<string> {
45
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
46
+ return toHex(new Uint8Array(digest));
47
+ }
48
+
49
+ /**
50
+ * Throws if any two entries in `names` are the same env var name.
51
+ *
52
+ * Guards against a tenant config accidentally pointing two independent
53
+ * deployment gates (e.g. membershipBusClient.ts's busEnabledFlag /
54
+ * enforceEnabledFlag / revokeEnabledFlag) at the same underlying env var,
55
+ * which would silently collapse an independence guarantee those gates exist
56
+ * to provide. Case-sensitive exact match -- these are env var names, not
57
+ * free text.
58
+ */
59
+ export function assertDistinctEnvNames(names: string[]): void {
60
+ const seen = new Map<string, number>();
61
+ for (let i = 0; i < names.length; i++) {
62
+ const name = names[i];
63
+ const prior = seen.get(name);
64
+ if (prior !== undefined) {
65
+ throw new Error(
66
+ `assertDistinctEnvNames: env var names at index ${prior} and ${i} are both "${name}" -- these must be distinct env vars.`,
67
+ );
68
+ }
69
+ seen.set(name, i);
70
+ }
71
+ }