@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,537 @@
1
+ // Tenant -> middleware MEMBERSHIP bus client (contract v0.3).
2
+ //
3
+ // D33 Phase 0.5 / Phase 10 batch 1: the generic half of gc-connect's
4
+ // _shared/membershipBusClient.ts. The protocol -- the canonical message, the
5
+ // normalization rules, the digest, the three call modes, the never-throw
6
+ // failure contract and every logOps kind/severity -- is platform behaviour and
7
+ // lives here. The tenant layer now supplies only its transport identity (bus
8
+ // origin, `source` string), the names of its own deployment gates, and whether
9
+ // it refuses a zero-member snapshot, via the `MembershipBusConfig` parameter on
10
+ // each call below. Behaviour is unchanged from the pre-split file.
11
+ //
12
+ // DELIBERATE SIBLING OF busClient.ts, NOT AN EXTENSION OF IT. busClient.ts signs a single
13
+ // booking with the canonical message
14
+ // v1\n{booking_id}\n{room_key}\n{start_utc}\n{end_utc}
15
+ // under BUS_HMAC_SECRET and posts to /bookings/*. That construction is byte-matched against
16
+ // bus_hmac.py on the middleware and MUST NOT be touched or generalized.
17
+ //
18
+ // This client signs a whole MEMBERSHIP SNAPSHOT with a different construction, a different
19
+ // first line ("m1" not "v1"), a different secret, and a different route namespace
20
+ // (/membership/*). The two can never be confused for each other, even if the secrets were
21
+ // somehow crossed.
22
+ //
23
+ // Canonical message -- 8 lines joined with "\n", no trailing newline:
24
+ //
25
+ // m1
26
+ // {source}
27
+ // {event}
28
+ // {snapshot_id}
29
+ // {generated_at}
30
+ // {mode}
31
+ // {member_count}
32
+ // {members_sha256_hex}
33
+ //
34
+ // members_sha256_hex is the lowercase hex SHA-256 of the canonicalized member block: one
35
+ // line per member, "{email_lower}\t{group_ids_sorted_unique_csv}\t{1|0}", lines sorted
36
+ // lexicographically, joined with "\n", no trailing newline. An empty member list digests to
37
+ // sha256("") -- "zero members" is a signed statement, not an empty one.
38
+ //
39
+ // Normalization (must match membership_hmac.py on the middleware EXACTLY):
40
+ // email -> trim().toLowerCase()
41
+ // group id -> trim(); empties dropped; deduped; sorted ascending
42
+ // wifi -> "1" if truthy else "0"
43
+ // member lines sorted ascending on the whole line
44
+ //
45
+ // STAGE 2 IS DIFF-ONLY. The middleware endpoint this calls performs zero writes to UniFi
46
+ // Access and zero writes to RADIUS/WiFi. It reads live state and returns a diff.
47
+ //
48
+ // FAILURE-MODE INVARIANT: this module NEVER throws to its caller. Every path returns either
49
+ // a parsed response object or null. Stage 1's compute must not be able to fail because of
50
+ // anything that happens here.
51
+
52
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
53
+ import { logOps } from './ops.ts';
54
+ import { assertDistinctEnvNames, signBusMessage } from './busSignature.ts';
55
+
56
+ // deno-lint-ignore no-explicit-any
57
+ type SupabaseLike = SupabaseClient<any, 'public', any>;
58
+
59
+ const CONTRACT = 'v0.3';
60
+ const EVENT = 'membership.sync';
61
+ export const MODE_DIFF_ONLY = 'diff_only';
62
+ export const MODE_ENFORCE_GRANT = 'enforce_grant';
63
+ export const MODE_ENFORCE_REVOKE = 'enforce_revoke';
64
+ const TIMEOUT_MS = 25_000;
65
+
66
+ /**
67
+ * The tenant's transport identity and deployment gates.
68
+ *
69
+ * `busBase` and `source` are the tenant's own middleware deployment -- the
70
+ * origin every /membership/* call is POSTed to, and the identifier signed into
71
+ * line 2 of the canonical message (and echoed in the request body). Neither has
72
+ * a platform default: a bus client that guessed its own identity would sign a
73
+ * snapshot as somebody else.
74
+ *
75
+ * The four `env` names are the names of the tenant's own environment gates, not
76
+ * their values. Each layer independently gates a single write, and which
77
+ * variable carries which gate is a deployment fact, not a protocol one.
78
+ */
79
+ export interface MembershipBusConfig {
80
+ /** Origin of the tenant's middleware, e.g. https://bus.example.com. No trailing slash. */
81
+ busBase: string;
82
+ /** Transport identity signed into the canonical message and sent as `source`. */
83
+ source: string;
84
+ env: {
85
+ /** Master gate. Every mode (sync, enforce, revoke) requires this one. */
86
+ busEnabledFlag: string;
87
+ /** Additional independent gate for mode=enforce_grant only. */
88
+ enforceEnabledFlag: string;
89
+ /** Additional independent gate for mode=enforce_revoke only. */
90
+ revokeEnabledFlag: string;
91
+ /** Env var holding the membership-bus HMAC secret. */
92
+ secret: string;
93
+ };
94
+ /**
95
+ * Refuse a zero-member snapshot instead of sending it.
96
+ *
97
+ * A zero-member snapshot is never legitimate for a tenant that manages its
98
+ * members here: the correct behavior is to send nothing, not to assert
99
+ * "manage nobody" to the middleware. Under an enforcing mode that assertion
100
+ * reads as "revoke everyone", so a tenant that cannot legitimately reach zero
101
+ * should refuse it while it is still harmless. Left as config rather than
102
+ * hardcoded because "zero managed members" is a statement about a tenant's
103
+ * roster, not about the protocol.
104
+ */
105
+ refuseEmptySnapshot: boolean;
106
+ }
107
+
108
+ export interface MembershipSnapshotMember {
109
+ email: string;
110
+ desired_group_ids: string[];
111
+ desired_wifi: boolean;
112
+ }
113
+
114
+ function toHex(bytes: Uint8Array): string {
115
+ let out = '';
116
+ for (const b of bytes) out += b.toString(16).padStart(2, '0');
117
+ return out;
118
+ }
119
+
120
+ function normEmail(e: string | null | undefined): string {
121
+ return (e ?? '').trim().toLowerCase();
122
+ }
123
+
124
+ function normGroupIds(g: string[] | null | undefined): string[] {
125
+ return Array.from(
126
+ new Set((g ?? []).map((x) => (x ?? '').trim()).filter((x) => x.length > 0)),
127
+ ).sort();
128
+ }
129
+
130
+ function memberLine(m: MembershipSnapshotMember): string {
131
+ return [normEmail(m.email), normGroupIds(m.desired_group_ids).join(','), m.desired_wifi ? '1' : '0']
132
+ .join('\t');
133
+ }
134
+
135
+ export async function membersDigest(members: MembershipSnapshotMember[]): Promise<string> {
136
+ const block = members.map(memberLine).sort().join('\n');
137
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(block)));
138
+ return toHex(d);
139
+ }
140
+
141
+ export async function canonicalMembershipMessage(
142
+ source: string, event: string, snapshotId: string, generatedAt: string, mode: string,
143
+ members: MembershipSnapshotMember[],
144
+ ): Promise<string> {
145
+ return [
146
+ 'm1',
147
+ (source ?? '').trim().toLowerCase(),
148
+ (event ?? '').trim().toLowerCase(),
149
+ (snapshotId ?? '').trim().toLowerCase(),
150
+ (generatedAt ?? '').trim(),
151
+ (mode ?? '').trim().toLowerCase(),
152
+ String(members.length),
153
+ await membersDigest(members),
154
+ ].join('\n');
155
+ }
156
+
157
+ export function signMembershipBus(msg: string, secret: string): Promise<string> {
158
+ return signBusMessage(msg, secret);
159
+ }
160
+
161
+ function normalizeMembers(members: MembershipSnapshotMember[]): MembershipSnapshotMember[] {
162
+ return members.map((m) => ({
163
+ email: normEmail(m.email),
164
+ desired_group_ids: normGroupIds(m.desired_group_ids),
165
+ desired_wifi: !!m.desired_wifi,
166
+ }));
167
+ }
168
+
169
+ /**
170
+ * POST the desired-state snapshot to the middleware and return the live diff.
171
+ *
172
+ * Returns null (never throws) when: the feature flag is off, the secret is unset, the
173
+ * snapshot is empty, the HTTP call fails, or the response is not 2xx. Non-2xx logs
174
+ * ops_events kind 'bus_call_failed' and a thrown/timed-out call logs 'bus_call_error' --
175
+ * the same two kinds and the same detail shape busClient.ts already uses, distinguished by
176
+ * detail.event === 'membership.sync'.
177
+ */
178
+ export async function membershipBusSync(
179
+ members: MembershipSnapshotMember[],
180
+ supabase: SupabaseLike,
181
+ config: MembershipBusConfig,
182
+ mode: string = MODE_DIFF_ONLY,
183
+ ): Promise<Record<string, unknown> | null> {
184
+ assertDistinctEnvNames([
185
+ config.env.busEnabledFlag, config.env.enforceEnabledFlag, config.env.revokeEnabledFlag,
186
+ ]);
187
+ if (Deno.env.get(config.env.busEnabledFlag) !== 'true') {
188
+ console.log(`[membershipBusClient] ${config.env.busEnabledFlag} != true; skip`);
189
+ return null;
190
+ }
191
+ const secret = Deno.env.get(config.env.secret);
192
+ if (!secret) {
193
+ console.log(`[membershipBusClient] ${config.env.secret} unset; skip`);
194
+ return null;
195
+ }
196
+ // Empty-snapshot guard -- see MembershipBusConfig.refuseEmptySnapshot. Null/undefined
197
+ // members is never valid input regardless of policy, so that half is unconditional; only
198
+ // the empty-but-valid-array half is gated by refuseEmptySnapshot.
199
+ if (!members) {
200
+ return null;
201
+ }
202
+ if (config.refuseEmptySnapshot && members.length === 0) {
203
+ await logOps(supabase, 'door_sync_live_diff_skipped',
204
+ { reason: 'empty_snapshot' }, { severity: 'warning' });
205
+ return null;
206
+ }
207
+
208
+ const snapshotId = crypto.randomUUID();
209
+ const generatedAt = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
210
+ const normalized = normalizeMembers(members);
211
+
212
+ try {
213
+ const msg = await canonicalMembershipMessage(
214
+ config.source, EVENT, snapshotId, generatedAt, mode, normalized);
215
+ const hmac = await signMembershipBus(msg, secret);
216
+ const body = {
217
+ schema: 1,
218
+ contract: CONTRACT,
219
+ event: EVENT,
220
+ source: config.source,
221
+ snapshot_id: snapshotId,
222
+ generated_at: generatedAt,
223
+ mode,
224
+ members: normalized,
225
+ hmac,
226
+ };
227
+ const res = await fetch(`${config.busBase}/membership/sync`, {
228
+ method: 'POST',
229
+ headers: { 'Content-Type': 'application/json' },
230
+ body: JSON.stringify(body),
231
+ signal: AbortSignal.timeout(TIMEOUT_MS),
232
+ });
233
+ const json = await res.json().catch(() => ({}));
234
+ if (!res.ok) {
235
+ await logOps(supabase, 'bus_call_failed', {
236
+ event: EVENT,
237
+ contract: CONTRACT,
238
+ snapshot_id: snapshotId,
239
+ members_sent: normalized.length,
240
+ status: res.status,
241
+ error: typeof (json as Record<string, unknown>)?.error === 'string'
242
+ ? (json as Record<string, unknown>).error
243
+ : undefined,
244
+ detail: JSON.stringify(json ?? {}).slice(0, 300),
245
+ }, { severity: 'error' });
246
+ return null;
247
+ }
248
+ return json as Record<string, unknown>;
249
+ } catch (e) {
250
+ await logOps(supabase, 'bus_call_error', {
251
+ event: EVENT,
252
+ contract: CONTRACT,
253
+ snapshot_id: snapshotId,
254
+ members_sent: normalized.length,
255
+ message: String(e),
256
+ }, { severity: 'error' });
257
+ return null;
258
+ }
259
+ }
260
+
261
+ /**
262
+ * STAGE 3 — GRANT-ONLY ENFORCE. POST the same desired-state snapshot with
263
+ * mode="enforce_grant". The middleware may then perform LIVE WRITES to UniFi
264
+ * Access and RADIUS: create a user, ADD groups, create a WiFi account, notify
265
+ * GHL. It can never remove anything -- revocation is Stage 4 and the middleware
266
+ * refuses any mode other than "enforce_grant".
267
+ *
268
+ * Gated by BOTH config.env.busEnabledFlag and config.env.enforceEnabledFlag
269
+ * (this function replicates both checks itself -- see the note below on why it
270
+ * does not delegate to membershipBusSync). The middleware carries two more
271
+ * independent gates of its own. All four must be permissive for a single write.
272
+ *
273
+ * DELIBERATELY DOES NOT DELEGATE to membershipBusSync() for the HTTP call, even
274
+ * though it shares the same wire format. The /membership/sync endpoint returns a
275
+ * distinct, meaningful HTTP status for every enforce-mode outcome: 403 for
276
+ * enforce_disabled (a NORMAL, EXPECTED refusal while the feature flag is off --
277
+ * not an error), 401 for hmac_verification_failed / snapshot_expired, 422 for
278
+ * unsupported_mode / invalid_payload / unknown_group_ids, 409 for
279
+ * enforce_in_progress / snapshot_already_processed, 503 for read failures, and
280
+ * 200 only on a real (possibly zero-write) success. membershipBusSync()'s
281
+ * `if (!res.ok)` handling was built for the diff-only path, where any non-2xx
282
+ * really is an error worth flattening into 'bus_call_failed'; reusing it here
283
+ * would misfile every one of those informative refusals -- including the
284
+ * enforce_disabled response an operator will see constantly during dry-run
285
+ * testing -- as a generic error. Instead: ANY response whose body parses as JSON
286
+ * and carries this endpoint's own shape (a 'contract', 'error', or 'ok' field)
287
+ * is returned to the caller unchanged, regardless of HTTP status, so the caller
288
+ * can log it at a severity derived from the response's own fields (mirroring how
289
+ * the diff phase already derives severity from resp.summary / resp.wifi.status
290
+ * rather than raw HTTP status). Only a body that does NOT parse as this
291
+ * endpoint's shape at all (an HTML error page, a bare 502, an empty body) is a
292
+ * genuine transport failure and logged as 'bus_call_failed'. Network errors,
293
+ * exceptions, and timeouts still log 'bus_call_error', exactly as
294
+ * membershipBusSync() does.
295
+ *
296
+ * Never throws. Returns null when disabled, misconfigured, or on genuine
297
+ * transport failure. Returns the parsed body on every other outcome, success
298
+ * or refusal alike.
299
+ */
300
+ export async function membershipBusEnforce(
301
+ members: MembershipSnapshotMember[],
302
+ supabase: SupabaseLike,
303
+ config: MembershipBusConfig,
304
+ ): Promise<Record<string, unknown> | null> {
305
+ if (Deno.env.get(config.env.enforceEnabledFlag) !== 'true') {
306
+ console.log(`[membershipBusClient] ${config.env.enforceEnabledFlag} != true; skip enforce`);
307
+ return null;
308
+ }
309
+ if (Deno.env.get(config.env.busEnabledFlag) !== 'true') {
310
+ console.log(`[membershipBusClient] ${config.env.busEnabledFlag} != true; skip enforce`);
311
+ return null;
312
+ }
313
+ const secret = Deno.env.get(config.env.secret);
314
+ if (!secret) {
315
+ console.log(`[membershipBusClient] ${config.env.secret} unset; skip enforce`);
316
+ return null;
317
+ }
318
+ // Same empty-snapshot guard as membershipBusSync(), for the same reason: a zero-member
319
+ // enforce snapshot would read as "grant nobody", which is fine, but under revocation
320
+ // logic that shape becomes indistinguishable from "revoke everyone" -- so refuse it here
321
+ // too while it is still harmless. Null/undefined members is never valid input regardless
322
+ // of policy, so that half is unconditional; only the empty-but-valid-array half is gated
323
+ // by refuseEmptySnapshot.
324
+ if (!members) {
325
+ return null;
326
+ }
327
+ if (config.refuseEmptySnapshot && members.length === 0) {
328
+ await logOps(supabase, 'door_sync_live_diff_skipped',
329
+ { reason: 'empty_snapshot', mode: MODE_ENFORCE_GRANT }, { severity: 'warning' });
330
+ return null;
331
+ }
332
+
333
+ const snapshotId = crypto.randomUUID();
334
+ const generatedAt = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
335
+ const normalized = normalizeMembers(members);
336
+
337
+ try {
338
+ const msg = await canonicalMembershipMessage(
339
+ config.source, EVENT, snapshotId, generatedAt, MODE_ENFORCE_GRANT, normalized);
340
+ const hmac = await signMembershipBus(msg, secret);
341
+ const body = {
342
+ schema: 1,
343
+ contract: CONTRACT,
344
+ event: EVENT,
345
+ source: config.source,
346
+ snapshot_id: snapshotId,
347
+ generated_at: generatedAt,
348
+ mode: MODE_ENFORCE_GRANT,
349
+ members: normalized,
350
+ hmac,
351
+ };
352
+ const res = await fetch(`${config.busBase}/membership/sync`, {
353
+ method: 'POST',
354
+ headers: { 'Content-Type': 'application/json' },
355
+ body: JSON.stringify(body),
356
+ signal: AbortSignal.timeout(TIMEOUT_MS),
357
+ });
358
+
359
+ // Read as text first -- a body that fails to parse as JSON at all (an HTML error page,
360
+ // an empty 502, etc.) must NOT be confused with a valid JSON refusal, regardless of
361
+ // status code.
362
+ const rawText = await res.text();
363
+ let parsed: Record<string, unknown> | null = null;
364
+ if (rawText.length > 0) {
365
+ try {
366
+ const candidate = JSON.parse(rawText);
367
+ if (candidate && typeof candidate === 'object') parsed = candidate as Record<string, unknown>;
368
+ } catch {
369
+ parsed = null;
370
+ }
371
+ }
372
+
373
+ // This endpoint's own response shape, on ANY status code: the real success body and
374
+ // every documented refusal/error body all carry at least one of these fields. Hand it
375
+ // back unchanged -- regardless of res.status -- and let the caller derive severity from
376
+ // the response's own fields instead of from the HTTP status.
377
+ const isOwnShape = parsed !== null &&
378
+ ('contract' in parsed || 'error' in parsed || 'ok' in parsed);
379
+ if (isOwnShape) {
380
+ return parsed;
381
+ }
382
+
383
+ // Body did not parse as this endpoint's expected shape at all. That is the genuine
384
+ // "something upstream is broken" case (not a semantic refusal), so it still gets
385
+ // flattened into the generic failure kind.
386
+ await logOps(supabase, 'bus_call_failed', {
387
+ event: EVENT,
388
+ contract: CONTRACT,
389
+ mode: MODE_ENFORCE_GRANT,
390
+ snapshot_id: snapshotId,
391
+ members_sent: normalized.length,
392
+ status: res.status,
393
+ detail: rawText.slice(0, 300),
394
+ }, { severity: 'error' });
395
+ return null;
396
+ } catch (e) {
397
+ await logOps(supabase, 'bus_call_error', {
398
+ event: EVENT,
399
+ contract: CONTRACT,
400
+ mode: MODE_ENFORCE_GRANT,
401
+ snapshot_id: snapshotId,
402
+ members_sent: normalized.length,
403
+ message: String(e),
404
+ }, { severity: 'error' });
405
+ return null;
406
+ }
407
+ }
408
+
409
+ /**
410
+ * STAGE 4 — REVOKE-ONLY ENFORCE. POST the desired-state snapshot with
411
+ * mode="enforce_revoke". The middleware may then REMOVE UniFi Access group
412
+ * membership and, when separately enabled, delete RADIUS accounts. It can
413
+ * never grant, never create a user, and never touch a PIN/Touch Pass/NFC/door
414
+ * -- that discipline lives entirely in membership_revoke.py on the middleware
415
+ * and is out of scope here.
416
+ *
417
+ * Gated by its OWN independent flag config.env.revokeEnabledFlag (tenant-side),
418
+ * in addition to config.env.busEnabledFlag. Deliberately NOT gated on
419
+ * config.env.enforceEnabledFlag -- reusing that flag would mean "turn on
420
+ * grants" silently also arms revocation, which defeats the point of having
421
+ * two independent switches. The middleware carries its own full stack of
422
+ * independent gates on top of this (a sync-revoke flag, halt file, upstream
423
+ * interlock, allowlist, circuit breaker) -- all of them must be permissive for
424
+ * a single write, same "every layer independently gates" philosophy as Stage 3.
425
+ *
426
+ * generatedAt is NOT self-minted here (unlike membershipBusSync /
427
+ * membershipBusEnforce) -- it is passed in from the caller's own compute phase,
428
+ * the actual moment the desired-state snapshot was computed. Stamping "now" at
429
+ * call time would assert freshness on data that is already 25-50s stale by the
430
+ * time the earlier phases' round trips have run, which would quietly defeat the
431
+ * middleware's snapshot-age / staleness guard on exactly the phase where that
432
+ * guard matters most (a member renews between the read and the write, and gets
433
+ * revoked anyway on falsely-fresh data).
434
+ *
435
+ * Never throws. Returns null when disabled, misconfigured, or on genuine
436
+ * transport failure. Returns the parsed body on every other outcome, success
437
+ * or documented refusal alike -- same "own-shape" handling as
438
+ * membershipBusEnforce(), because the revoke endpoint's refusal shape
439
+ * ({"ok": false, "contract", "mode", "error", ...}) is a sibling of the
440
+ * enforce endpoint's, not merged with it.
441
+ */
442
+ export async function membershipBusRevoke(
443
+ members: MembershipSnapshotMember[],
444
+ generatedAt: string,
445
+ supabase: SupabaseLike,
446
+ config: MembershipBusConfig,
447
+ ): Promise<Record<string, unknown> | null> {
448
+ if (Deno.env.get(config.env.revokeEnabledFlag) !== 'true') {
449
+ console.log(`[membershipBusClient] ${config.env.revokeEnabledFlag} != true; skip revoke`);
450
+ return null;
451
+ }
452
+ if (Deno.env.get(config.env.busEnabledFlag) !== 'true') {
453
+ console.log(`[membershipBusClient] ${config.env.busEnabledFlag} != true; skip revoke`);
454
+ return null;
455
+ }
456
+ const secret = Deno.env.get(config.env.secret);
457
+ if (!secret) {
458
+ console.log(`[membershipBusClient] ${config.env.secret} unset; skip revoke`);
459
+ return null;
460
+ }
461
+ // Null/undefined members is never valid input regardless of policy, so that half of the
462
+ // guard is unconditional; only the empty-but-valid-array half is gated by
463
+ // refuseEmptySnapshot.
464
+ if (!members) {
465
+ return null;
466
+ }
467
+ if (config.refuseEmptySnapshot && members.length === 0) {
468
+ await logOps(supabase, 'door_sync_revoke_skipped',
469
+ { reason: 'empty_snapshot', mode: MODE_ENFORCE_REVOKE }, { severity: 'warning' });
470
+ return null;
471
+ }
472
+
473
+ const snapshotId = crypto.randomUUID();
474
+ const generatedAtNormalized = generatedAt.replace(/\.\d{3}Z$/, 'Z');
475
+ const normalized = normalizeMembers(members);
476
+
477
+ try {
478
+ const msg = await canonicalMembershipMessage(
479
+ config.source, EVENT, snapshotId, generatedAtNormalized, MODE_ENFORCE_REVOKE, normalized);
480
+ const hmac = await signMembershipBus(msg, secret);
481
+ const body = {
482
+ schema: 1,
483
+ contract: CONTRACT,
484
+ event: EVENT,
485
+ source: config.source,
486
+ snapshot_id: snapshotId,
487
+ generated_at: generatedAtNormalized,
488
+ mode: MODE_ENFORCE_REVOKE,
489
+ members: normalized,
490
+ hmac,
491
+ };
492
+ const res = await fetch(`${config.busBase}/membership/sync`, {
493
+ method: 'POST',
494
+ headers: { 'Content-Type': 'application/json' },
495
+ body: JSON.stringify(body),
496
+ signal: AbortSignal.timeout(TIMEOUT_MS),
497
+ });
498
+
499
+ const rawText = await res.text();
500
+ let parsed: Record<string, unknown> | null = null;
501
+ if (rawText.length > 0) {
502
+ try {
503
+ const candidate = JSON.parse(rawText);
504
+ if (candidate && typeof candidate === 'object') parsed = candidate as Record<string, unknown>;
505
+ } catch {
506
+ parsed = null;
507
+ }
508
+ }
509
+
510
+ const isOwnShape = parsed !== null &&
511
+ ('contract' in parsed || 'error' in parsed || 'ok' in parsed);
512
+ if (isOwnShape) {
513
+ return parsed;
514
+ }
515
+
516
+ await logOps(supabase, 'bus_call_failed', {
517
+ event: EVENT,
518
+ contract: CONTRACT,
519
+ mode: MODE_ENFORCE_REVOKE,
520
+ snapshot_id: snapshotId,
521
+ members_sent: normalized.length,
522
+ status: res.status,
523
+ detail: rawText.slice(0, 300),
524
+ }, { severity: 'error' });
525
+ return null;
526
+ } catch (e) {
527
+ await logOps(supabase, 'bus_call_error', {
528
+ event: EVENT,
529
+ contract: CONTRACT,
530
+ mode: MODE_ENFORCE_REVOKE,
531
+ snapshot_id: snapshotId,
532
+ members_sent: normalized.length,
533
+ message: String(e),
534
+ }, { severity: 'error' });
535
+ return null;
536
+ }
537
+ }