@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,956 @@
1
+ // PHASE 1 — STAGE 1 SHADOW COMPUTE (unchanged). Pure Supabase-internal compute + logging.
2
+ // Writes only the tenant app's own memberships.access_* columns and ops_events, logs kind
3
+ // 'door_sync_shadow'. Phase 1 MUST NOT gain any outbound call, ever.
4
+ //
5
+ // PHASE 2 — STAGE 2 LIVE DIFF (read-only). Runs strictly AFTER Phase 1 has finished all of
6
+ // its work, in its own try/catch, behind the MEMBERSHIP_BUS_ENABLED flag. It POSTs the
7
+ // desired-state snapshot Phase 1 just computed to the FTW middleware's /membership/sync
8
+ // endpoint (bus contract v0.3, membershipBusClient.ts) and logs the live diff under
9
+ // ops_events kind 'door_sync_live_diff'. The middleware endpoint performs ZERO writes to
10
+ // UniFi Access and ZERO writes to RADIUS/WiFi -- it reads live state and returns a diff.
11
+ //
12
+ // PHASE 3 — STAGE 3 GRANT-ONLY ENFORCE (LIVE WRITES). Runs strictly AFTER Phase 2, in its
13
+ // own try/catch, behind MEMBERSHIP_ENFORCE_ENABLED (separate from MEMBERSHIP_BUS_ENABLED).
14
+ // It re-POSTs the SAME snapshot with mode="enforce_grant". The middleware may then create
15
+ // UniFi users, ADD UniFi groups and create RADIUS accounts. It can NEVER remove a group,
16
+ // delete a user, delete a RADIUS account, or provision a PIN/Touch Pass -- revocation is
17
+ // Stage 4. Phase 3 logs ops_events kind 'door_sync_enforce'. Phase 3's bus call itself
18
+ // writes nothing to the memberships table; the only memberships writes outside Phase 1 are
19
+ // (a) the T8 identity-status write-back inside Phase 3, which sets identity_invited_at and
20
+ // unifi_access_user_id via an explicit two-field allowlist, and (b) the Phase 2 stuck-member
21
+ // alarm block, which sets/clears unprovisioned_since and unprovisioned_alerted_at via an
22
+ // explicit two-field allowlist. access_state / access_synced_at remain Phase 1's exclusive
23
+ // business, and every one of these writes is write-on-change-only so that updated_at is not
24
+ // pinned (which would disable the membership_stuck_nonterminal tripwire).
25
+ //
26
+ // PHASE 4 — STAGE 4 REVOKE-ONLY ENFORCE (LIVE WRITES). Runs strictly AFTER Phase 3 has
27
+ // finished, in its own try/catch, gated on Phase 2 having succeeded (liveDiffSummary !==
28
+ // null proves the bus is reachable this tick) plus its own independent flag
29
+ // MEMBERSHIP_REVOKE_ENABLED (tenant-app side) plus MEMBERSHIP_BUS_ENABLED -- deliberately NOT
30
+ // gated on Phase 3's enforceSummary or MEMBERSHIP_ENFORCE_ENABLED, so grants and revokes can
31
+ // be independently paused. It re-POSTs the Phase 1 snapshot, stamped with Phase 1's REAL
32
+ // generated_at (not a re-minted "now"), with mode="enforce_revoke". The middleware may then
33
+ // REMOVE UniFi Access group membership and, when separately enabled, delete RADIUS accounts.
34
+ // It can never grant, never create a user, and never touch a PIN/Touch Pass/NFC/door --
35
+ // Stage 4 (membership_revoke.py) enforces that on the middleware side; Phase 4 here is only
36
+ // the sender. A sender-side plausibility floor refuses to send if the snapshot has shrunk
37
+ // implausibly versus the prior tick (a partial Phase 1 read must never look like "revoke
38
+ // everyone missing"). Phase 4 logs ops_events kind 'door_sync_revoke' (or
39
+ // 'door_sync_revoke_skipped' for the plausibility refusal). Phase 4 writes NOTHING to the
40
+ // memberships table.
41
+ //
42
+ // INVARIANTS:
43
+ // - Phase 2 can never throw into Phase 1. membershipBusClient never throws; the call site
44
+ // is additionally wrapped.
45
+ // - Phase 2 never mutates memberships, access_state, or any Phase 1 counter.
46
+ // - Phase 2 uses a DIFFERENT secret, a DIFFERENT canonical message and a DIFFERENT route
47
+ // namespace from the booking bus client (_shared/busClient.ts). Never merge the two.
48
+ // - Actually acting on the diff (granting/revoking in UniFi) is Stage 3 and does not
49
+ // belong in this file or in the middleware endpoint it calls.
50
+ // - Phase 4 uses a THIRD independent flag (MEMBERSHIP_REVOKE_ENABLED) from Phase 3's
51
+ // MEMBERSHIP_ENFORCE_ENABLED -- turning on grants must never silently arm revocation.
52
+
53
+ import { createClient } from 'npm:@supabase/supabase-js@2';
54
+ import { computeEntitlement, type EntitlementRow } from 'npm:@simplelayer/graniteer-core/membership';
55
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
56
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
57
+ import type { MembershipSnapshotMember } from '../membershipBusClient.ts';
58
+
59
+ // deno-lint-ignore no-explicit-any
60
+ type SupabaseLike = SupabaseClient<any, 'public', any>;
61
+
62
+ export interface MembershipDoorSyncConfig {
63
+ /** Emails that must never be touched by this system, ever — never
64
+ * computed for, never granted, never revoked. Always allowed
65
+ * through by other means. */
66
+ protectedAllowlist: readonly string[];
67
+ membershipBusSync: (
68
+ members: MembershipSnapshotMember[],
69
+ supabase: SupabaseLike,
70
+ mode?: string,
71
+ ) => Promise<Record<string, unknown> | null>;
72
+ membershipBusEnforce: (
73
+ members: MembershipSnapshotMember[],
74
+ supabase: SupabaseLike,
75
+ ) => Promise<Record<string, unknown> | null>;
76
+ membershipBusRevoke: (
77
+ members: MembershipSnapshotMember[],
78
+ generatedAt: string,
79
+ supabase: SupabaseLike,
80
+ ) => Promise<Record<string, unknown> | null>;
81
+ }
82
+
83
+ // Stage 1: threshold only escalates the ops_event severity from info -> warning
84
+ // so a spike is visible. It does NOT abort, throttle, or circuit-break.
85
+ const WOULD_CHANGE_WARN_THRESHOLD = 5;
86
+
87
+ // Cap the arrays we embed inside the ops_events JSONB detail so it can't grow
88
+ // unbounded on a bad tick.
89
+ const OPS_DETAIL_LIST_CAP = 100;
90
+
91
+ function safeEqual(a: string, b: string): boolean {
92
+ const enc = new TextEncoder();
93
+ const ab = enc.encode(a), bb = enc.encode(b);
94
+ if (ab.length !== bb.length) return false;
95
+ let diff = 0;
96
+ for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
97
+ return diff === 0;
98
+ }
99
+
100
+ type MembershipRow = {
101
+ id: string;
102
+ email: string | null;
103
+ status: string;
104
+ pricing_grace_ends_at: string | null;
105
+ door_managed: boolean;
106
+ access_state: { entitled: boolean; group_ids: string[]; wifi_enabled: boolean } | null;
107
+ plan_id: string | null;
108
+ membership_plans: { unifi_group_ids: string[] | null; wifi_enabled: boolean | null } | null;
109
+ door_access_not_before: string | null;
110
+ };
111
+
112
+ type Desired = { entitled: boolean; group_ids: string[]; wifi_enabled: boolean };
113
+
114
+ function stateEquals(a: Desired, b: Desired | null): boolean {
115
+ if (!b) return false;
116
+ if (a.entitled !== b.entitled) return false;
117
+ if (a.wifi_enabled !== b.wifi_enabled) return false;
118
+ if (a.group_ids.length !== (b.group_ids?.length ?? 0)) return false;
119
+ for (let i = 0; i < a.group_ids.length; i++) {
120
+ if (a.group_ids[i] !== b.group_ids[i]) return false;
121
+ }
122
+ return true;
123
+ }
124
+
125
+ /**
126
+ * Door-access start-date gate, separate from (and layered AFTER) pricing
127
+ * entitlement. An UNGATED row (door_access_not_before === null) is never
128
+ * held back by this at all. A row whose gate date is malformed fails closed
129
+ * for that ONE row (logged elsewhere as part of normal per-row handling) --
130
+ * it must never be allowed to make the whole tick look like "revoke
131
+ * everyone," which is exactly what the tick-level shape guard above this
132
+ * function's call site exists to prevent.
133
+ */
134
+ function doorGateOk(row: MembershipRow, now: number): boolean {
135
+ if (row.door_access_not_before == null) return true;
136
+ const t = Date.parse(row.door_access_not_before);
137
+ if (!Number.isFinite(t)) return false;
138
+ return t <= now;
139
+ }
140
+
141
+ export function createMembershipDoorSyncHandler(
142
+ config: MembershipDoorSyncConfig,
143
+ ): (req: Request) => Promise<Response> {
144
+ const PROTECTED_ALLOWLIST = new Set<string>(
145
+ config.protectedAllowlist.map((e) => e.trim().toLowerCase()),
146
+ );
147
+ const { membershipBusSync, membershipBusEnforce, membershipBusRevoke } = config;
148
+
149
+ return async (req) => {
150
+ if (req.method !== 'POST') {
151
+ return new Response('Method not allowed', { status: 405 });
152
+ }
153
+
154
+ const provided = req.headers.get('x-door-sync-secret');
155
+ if (!provided) return new Response('Unauthorized', { status: 401 });
156
+
157
+ const supabase = createClient(
158
+ Deno.env.get('SUPABASE_URL')!,
159
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
160
+ );
161
+
162
+ const { data: gate, error: gateErr } = await supabase.rpc('get_door_sync_secret');
163
+ const expected = typeof gate === 'string' ? gate : null;
164
+ if (gateErr || !expected || !safeEqual(provided, expected)) {
165
+ return new Response('Unauthorized', { status: 401 });
166
+ }
167
+
168
+ try {
169
+ const { data: rowsRaw, error: readErr } = await supabase
170
+ .from('memberships')
171
+ .select(
172
+ 'id,email,status,pricing_grace_ends_at,door_managed,access_state,plan_id,door_access_not_before,' +
173
+ 'membership_plans:plan_id ( unifi_group_ids, wifi_enabled )',
174
+ )
175
+ .order('created_at');
176
+ if (readErr) throw new Error('memberships read failed: ' + readErr.message);
177
+ const rows = (rowsRaw ?? []) as unknown as MembershipRow[];
178
+
179
+ // Tick-level shape guard for the new column. A non-empty result missing
180
+ // the key entirely means the query/schema drifted (a real problem,
181
+ // caught HERE, loudly, once per tick) -- NOT that no row happens to have
182
+ // a gate date set (that's the normal, common case and is `null`, which
183
+ // the `in` check below still finds as a present key). An EMPTY table is
184
+ // not a shape problem and must not trip this.
185
+ if (rows.length > 0 && !('door_access_not_before' in rows[0])) {
186
+ throw new Error(
187
+ 'shape_guard_failed: door_access_not_before missing from memberships select result -- aborting tick before any Phase 2/3/4 call',
188
+ );
189
+ }
190
+
191
+ // Group by lowercased email. Rows with no email are ignored (nothing to
192
+ // key door/WiFi state to). resolveIsMember() likewise treats "" as "not
193
+ // a member" — keep that behavior aligned.
194
+ const byEmail = new Map<string, MembershipRow[]>();
195
+ for (const r of rows) {
196
+ const key = (r.email ?? '').toLowerCase();
197
+ if (!key) continue;
198
+ const list = byEmail.get(key) ?? [];
199
+ list.push(r);
200
+ byEmail.set(key, list);
201
+ }
202
+
203
+ const now = Date.now();
204
+ const nowIso = new Date(now).toISOString();
205
+ const wouldGrant: Array<{ email: string; from: string[]; to: string[]; wifi: boolean }> = [];
206
+ const wouldRevoke: Array<{ email: string; from: string[]; to: string[]; wifi: boolean }> = [];
207
+ let skippedAllowlist = 0;
208
+ let skippedNotManaged = 0;
209
+ let unchanged = 0;
210
+ let bootstrapped = 0;
211
+ const totalEvaluated = byEmail.size;
212
+
213
+ // PHASE 2 snapshot accumulator. Populated inside the Phase 1 loop so the two phases can
214
+ // never disagree about what "desired" means.
215
+ const snapshot: MembershipSnapshotMember[] = [];
216
+
217
+ for (const [email, emailRows] of byEmail) {
218
+ // 1. Protected allowlist — never compute, never touch.
219
+ if (PROTECTED_ALLOWLIST.has(email)) {
220
+ skippedAllowlist++;
221
+ continue;
222
+ }
223
+
224
+ // 2. door_managed=false handling. If NONE of this email's rows is
225
+ // managed, skip entirely. If SOME are, evaluate using only the managed
226
+ // rows and annotate as partial.
227
+ const managed = emailRows.filter((r) => r.door_managed);
228
+ if (managed.length === 0) {
229
+ skippedNotManaged++;
230
+ continue;
231
+ }
232
+ const partialManaged = managed.length !== emailRows.length;
233
+
234
+ // 3. Compute entitlement using the SAME predicate as pricing.
235
+ const eligibleForPricing = managed.filter((r) =>
236
+ ['active', 'trialing', 'past_due', 'canceled', 'unpaid'].includes(r.status),
237
+ );
238
+ const pricingEntitledRows = eligibleForPricing.filter((r) =>
239
+ computeEntitlement({ status: r.status, pricing_grace_ends_at: r.pricing_grace_ends_at } as EntitlementRow, now),
240
+ );
241
+ // Door/WiFi gate layered AFTER pricing entitlement -- computeEntitlement
242
+ // itself (used elsewhere for billing) is never touched by this; a member
243
+ // can be correctly billed before their physical access turns on.
244
+ const entitledRows = pricingEntitledRows.filter((r) => doorGateOk(r, now));
245
+ const entitled = entitledRows.length > 0;
246
+
247
+ let groupIds: string[] = [];
248
+ let wifiEnabled = false;
249
+ if (entitled) {
250
+ const set = new Set<string>();
251
+ for (const r of entitledRows) {
252
+ const gids = r.membership_plans?.unifi_group_ids ?? [];
253
+ for (const g of gids) if (g) set.add(g);
254
+ if (r.membership_plans?.wifi_enabled === true) wifiEnabled = true;
255
+ }
256
+ groupIds = Array.from(set).sort();
257
+ }
258
+
259
+ const desired: Desired = { entitled, group_ids: groupIds, wifi_enabled: wifiEnabled };
260
+
261
+ // Every managed, non-protected email goes into the snapshot -- entitled or not.
262
+ // The NOT-entitled ones are exactly the revoke candidates, so omitting them would
263
+ // make Stage 2 blind to the whole reason Stage 2 exists. This is placed before the
264
+ // unchanged/continue branch below so unchanged rows are included too: Stage 1's
265
+ // "unchanged" means "the tenant app's stored intent didn't move", which says nothing about
266
+ // whether UniFi matches that intent.
267
+ snapshot.push({
268
+ email,
269
+ desired_group_ids: desired.group_ids,
270
+ desired_wifi: desired.wifi_enabled,
271
+ });
272
+
273
+ // Per-email change detection uses the FIRST managed row's stored
274
+ // access_state as the reference; write-on-change updates every managed
275
+ // row for this email so they stay mutually consistent.
276
+ const reference = managed[0].access_state ?? null;
277
+ const changed = !stateEquals(desired, reference);
278
+
279
+ if (!changed) {
280
+ unchanged++;
281
+ continue;
282
+ }
283
+
284
+ const prevGroups = reference?.group_ids ?? [];
285
+ const wasEntitled = reference?.entitled === true;
286
+ // Classify the transition:
287
+ // - grant: wasEntitled=false AND desired.entitled=true (real entry into access)
288
+ // - revoke: wasEntitled=true AND desired.entitled=false (real loss of access)
289
+ // - bootstrap: state changed but nothing meaningful is being revoked
290
+ // (reference null or already-not-entitled, and still not entitled).
291
+ // Persist so subsequent ticks see 'unchanged', but do NOT log as a
292
+ // would_revoke — that would pollute shadow-mode signal.
293
+ let bucket: 'grant' | 'revoke' | 'bootstrap';
294
+ if (!wasEntitled && desired.entitled) bucket = 'grant';
295
+ else if (wasEntitled && !desired.entitled) bucket = 'revoke';
296
+ else if (desired.entitled) bucket = 'grant'; // entitled→entitled with group/wifi delta
297
+ else bucket = 'bootstrap';
298
+
299
+ const record = { email, from: prevGroups, to: desired.group_ids, wifi: desired.wifi_enabled };
300
+ if (bucket === 'grant') wouldGrant.push(record);
301
+ else if (bucket === 'revoke') wouldRevoke.push(record);
302
+ else bootstrapped++;
303
+
304
+ const baseNote = bucket === 'bootstrap' ? 'shadow_bootstrap' : 'shadow_compute';
305
+ const note = partialManaged ? `${baseNote}; partial_door_managed` : baseNote;
306
+
307
+ const ids = managed.map((r) => r.id);
308
+ const { error: upErr } = await supabase
309
+ .from('memberships')
310
+ .update({
311
+ access_state: desired,
312
+ access_synced_at: nowIso,
313
+ access_sync_note: note,
314
+ })
315
+ .in('id', ids);
316
+ if (upErr) {
317
+ // Log and keep going — Stage 1 is best-effort compute; a single
318
+ // email's write failure should not abort the whole tick.
319
+ await logOps(supabase, 'door_sync_write_failed', { email, error: upErr.message }, { severity: 'warning' });
320
+ }
321
+ }
322
+
323
+ const wouldChangeTotal = wouldGrant.length + wouldRevoke.length;
324
+ const severity: 'info' | 'warning' = wouldChangeTotal > WOULD_CHANGE_WARN_THRESHOLD ? 'warning' : 'info';
325
+
326
+ await logOps(
327
+ supabase,
328
+ 'door_sync_shadow',
329
+ {
330
+ counts: {
331
+ total_evaluated: totalEvaluated,
332
+ skipped_allowlist: skippedAllowlist,
333
+ skipped_not_managed: skippedNotManaged,
334
+ would_grant: wouldGrant.length,
335
+ would_revoke: wouldRevoke.length,
336
+ bootstrapped,
337
+ unchanged,
338
+ },
339
+ snapshot_size: snapshot.length,
340
+ would_grant: wouldGrant.slice(0, OPS_DETAIL_LIST_CAP),
341
+ would_revoke: wouldRevoke.slice(0, OPS_DETAIL_LIST_CAP),
342
+ },
343
+ { severity },
344
+ );
345
+
346
+ // ===================== PHASE 2 — STAGE 2 LIVE DIFF (READ-ONLY) =====================
347
+ // Everything Phase 1 does is already durable at this point. Nothing below may modify
348
+ // any Phase 1 variable, table row, or ops event.
349
+ let liveDiffSummary: Record<string, unknown> | null = null;
350
+ try {
351
+ const resp = await membershipBusSync(snapshot, supabase);
352
+ if (resp && resp.ok === true) {
353
+ const summary = (resp.summary ?? {}) as Record<string, number>;
354
+ const wifi = (resp.wifi ?? {}) as Record<string, unknown>;
355
+ const results = Array.isArray(resp.results) ? (resp.results as Record<string, unknown>[]) : [];
356
+ // Only the rows that actually diverge are worth persisting; 'unchanged' and
357
+ // 'skipped_protected' rows are counted in the summary and dropped from the detail.
358
+ const divergent = results.filter((r) =>
359
+ r.classification !== 'unchanged' && r.classification !== 'skipped_protected');
360
+
361
+ await logOps(supabase, 'door_sync_live_diff', {
362
+ contract: resp.contract,
363
+ mode: resp.mode,
364
+ enforcement: resp.enforcement,
365
+ writes_performed: resp.writes_performed,
366
+ snapshot_id: resp.snapshot_id,
367
+ members_sent: snapshot.length,
368
+ elapsed_ms: resp.elapsed_ms,
369
+ summary,
370
+ unifi: resp.unifi,
371
+ wifi,
372
+ divergent: divergent.slice(0, OPS_DETAIL_LIST_CAP),
373
+ holders_not_in_snapshot: resp.holders_not_in_snapshot,
374
+ protected_holders_skipped: resp.protected_holders_skipped,
375
+ }, { severity: 'info' });
376
+
377
+ // ---- WiFi subsystem health alarm (separate from the now-'info' live diff) ----
378
+ // WiFi/RADIUS provisioning is the most fragile dependency in this pipeline
379
+ // (SSH + Mongo write on the gateway). door_sync_live_diff is unconditionally
380
+ // 'info' now, so the WiFi signal gets its own event. Deduped to once per 24h
381
+ // via an ops_events lookup — the function is stateless between invocations,
382
+ // so in-memory dedupe would not survive. Only runs when already degraded.
383
+ if (wifi.status != null && wifi.status !== 'ok') {
384
+ try {
385
+ const WIFI_REALERT_HOURS = 24;
386
+ const { data: lastRows, error: lastErr } = await supabase
387
+ .from('ops_events')
388
+ .select('created_at')
389
+ .eq('kind', 'door_sync_wifi_subsystem_degraded')
390
+ .order('created_at', { ascending: false })
391
+ .limit(1);
392
+ // Fail OPEN: a dedupe read error must never suppress an error-severity
393
+ // WiFi-outage alarm. Log the read failure and fall through to alerting.
394
+ if (lastErr) {
395
+ await logOps(supabase, 'wifi_degraded_dedupe_read_failed', {
396
+ message: lastErr.message,
397
+ }, { severity: 'warning' });
398
+ }
399
+ const lastIso = lastErr ? undefined : (lastRows ?? [])[0]?.created_at;
400
+ const nowMsWifi = Date.parse(nowIso);
401
+ const lastMs = typeof lastIso === 'string' ? Date.parse(lastIso) : NaN;
402
+ // If either clock read fails, err toward alerting.
403
+ const recentlyAlerted = Number.isFinite(nowMsWifi) && Number.isFinite(lastMs) &&
404
+ (nowMsWifi - lastMs) < WIFI_REALERT_HOURS * 3600000;
405
+ if (!recentlyAlerted) {
406
+ // EXPLICIT SCALAR ALLOWLIST — never spread the middleware `wifi` object
407
+ // into an error-severity detail: it is permanent JSONB and is POSTed to
408
+ // the alert webhook, so an unvetted field (e.g. a credential) would leak.
409
+ await logOps(supabase, 'door_sync_wifi_subsystem_degraded', {
410
+ wifi_status: wifi.status ?? null,
411
+ wifi_error: typeof wifi.error === 'string' ? wifi.error : null,
412
+ wifi_message: typeof wifi.message === 'string' ? wifi.message : null,
413
+ wifi_granted: typeof wifi.granted === 'number' ? wifi.granted : null,
414
+ wifi_failed: typeof wifi.failed === 'number' ? wifi.failed : null,
415
+ snapshot_id: resp.snapshot_id,
416
+ }, { severity: 'error' });
417
+ }
418
+ } catch (e) {
419
+ console.error('[door-sync] wifi degraded alarm failed (ignored):', String(e));
420
+ await logOps(supabase, 'wifi_degraded_alarm_failed', {
421
+ message: String(e),
422
+ }, { severity: 'warning' }).catch(() => {});
423
+ }
424
+ }
425
+
426
+ liveDiffSummary = {
427
+ snapshot_id: resp.snapshot_id,
428
+ summary,
429
+ wifi_status: wifi.status,
430
+ writes_performed: resp.writes_performed,
431
+ };
432
+
433
+ // ---- Stuck-member alarm: entitled but not provisioned (REPORTING ONLY) ----
434
+ // The live diff above fires every tick by design and is now severity 'info'.
435
+ // This block extracts the one fact that actually needs a human: a member we
436
+ // asked to be granted is still missing groups and/or WiFi, persistently.
437
+ // Fully self-contained try/catch — it must never abort the tick or block
438
+ // Phase 3 / Phase 4.
439
+ try {
440
+ const STUCK_MIN_MINUTES = 15;
441
+ const REALERT_HOURS = 24;
442
+ const nowMs = Date.parse(nowIso);
443
+ if (!Number.isFinite(nowMs)) {
444
+ await logOps(supabase, 'unprovisioned_timestamp_parse_failed', {
445
+ field: 'now',
446
+ raw: nowIso,
447
+ }, { severity: 'warning' });
448
+ throw new Error(`unparseable nowIso: ${nowIso}`);
449
+ }
450
+ const snapEmails = new Set(snapshot.map((m) => m.email));
451
+
452
+ type StuckRow = {
453
+ email: string;
454
+ stuck: boolean;
455
+ groups_to_grant: unknown;
456
+ wifi_action: unknown;
457
+ classification: unknown;
458
+ };
459
+ const candidates: StuckRow[] = [];
460
+ for (const r of results) {
461
+ const email = typeof r.email === 'string' ? r.email.toLowerCase() : '';
462
+ if (!email) continue;
463
+ if (!snapEmails.has(email) || PROTECTED_ALLOWLIST.has(email)) continue;
464
+ const g = r.groups_to_grant;
465
+ const stuck = (Array.isArray(g) && g.length > 0) || r.wifi_action === 'grant';
466
+ candidates.push({
467
+ email,
468
+ stuck,
469
+ groups_to_grant: Array.isArray(g) ? g : [],
470
+ wifi_action: r.wifi_action ?? null,
471
+ classification: r.classification ?? null,
472
+ });
473
+ }
474
+
475
+ if (candidates.length > 0) {
476
+ // Bounded alerting: logOps at 'error' does an insert AND a serial outbound
477
+ // webhook POST. A middleware/RADIUS outage makes EVERY member stuck at once,
478
+ // so per-member alerting would issue N sequential POSTs inside Phase 2 and
479
+ // could burn the wall clock before Phase 3 / Phase 4 run. Alert individually
480
+ // for the first N, then one aggregate event for the rest.
481
+ const MAX_INDIVIDUAL_ALERTS = 10;
482
+ const alertQueue: Array<Record<string, unknown>> = [];
483
+ // One read for the whole tick — no per-member round-trips. memberships.email
484
+ // is plain text, so an .in() filter on lowercased values would silently
485
+ // miss mixed-case rows. The table is tiny; read it all and match
486
+ // case-insensitively in memory.
487
+ const { data: stateRows, error: stateErr } = await supabase
488
+ .from('memberships')
489
+ .select('id,email,plan_id,unprovisioned_since,unprovisioned_alerted_at');
490
+ if (stateErr) throw new Error(stateErr.message);
491
+
492
+ // Plurality: 2+ membership rows per email is NORMAL, not ambiguous. Keep the
493
+ // tripwire's state PER PERSON (the pipeline is per-person-by-email by
494
+ // contract -- MembershipSnapshotMember carries no membership id) and
495
+ // aggregate the two clock columns deterministically across that person's
496
+ // rows, then write via .in('id', ids). No row is ever "guessed at."
497
+ const stateByEmail = new Map<string, {
498
+ ids: string[]; rawEmail: string; plan_id: unknown;
499
+ unprovisioned_since: string | null; unprovisioned_alerted_at: string | null;
500
+ }>();
501
+ const minIso = (a: string | null, b: string | null) =>
502
+ a === null ? b : b === null ? a : (a < b ? a : b);
503
+ const maxIso = (a: string | null, b: string | null) =>
504
+ a === null ? b : b === null ? a : (a > b ? a : b);
505
+ for (const row of (stateRows ?? []) as Record<string, unknown>[]) {
506
+ const e = typeof row.email === 'string' ? row.email.toLowerCase() : '';
507
+ if (!e) continue;
508
+ const since = typeof row.unprovisioned_since === 'string' ? row.unprovisioned_since : null;
509
+ const alerted = typeof row.unprovisioned_alerted_at === 'string' ? row.unprovisioned_alerted_at : null;
510
+ const prev = stateByEmail.get(e);
511
+ if (!prev) {
512
+ stateByEmail.set(e, {
513
+ ids: [String(row.id)],
514
+ rawEmail: typeof row.email === 'string' ? row.email : e,
515
+ plan_id: row.plan_id ?? null,
516
+ unprovisioned_since: since,
517
+ unprovisioned_alerted_at: alerted,
518
+ });
519
+ } else {
520
+ prev.ids.push(String(row.id));
521
+ // OLDEST stuck-since (the tripwire must not have its clock reset by a
522
+ // newer sibling row) and NEWEST alerted-at (so the 24h dedupe holds).
523
+ prev.unprovisioned_since = minIso(prev.unprovisioned_since, since);
524
+ prev.unprovisioned_alerted_at = maxIso(prev.unprovisioned_alerted_at, alerted);
525
+ }
526
+ }
527
+
528
+ for (const c of candidates) {
529
+ const st = stateByEmail.get(c.email);
530
+ if (!st) continue;
531
+ const rawEmail = st.rawEmail;
532
+ const since = st.unprovisioned_since;
533
+ const alerted = st.unprovisioned_alerted_at;
534
+
535
+ // EXPLICIT FIELD ALLOWLIST — only these two columns, never a spread.
536
+ const patch: { unprovisioned_since?: string | null; unprovisioned_alerted_at?: string | null } = {};
537
+
538
+ if (c.stuck) {
539
+ if (since === null) {
540
+ // Case 1: first observation. Start the clock, do not alert yet.
541
+ patch.unprovisioned_since = nowIso;
542
+ } else {
543
+ // A tripwire that cannot read its own clock must err toward alerting.
544
+ const sinceMs = Date.parse(since);
545
+ let parseFailed = false;
546
+ if (!Number.isFinite(sinceMs)) {
547
+ parseFailed = true;
548
+ await logOps(supabase, 'unprovisioned_timestamp_parse_failed', {
549
+ email: rawEmail,
550
+ field: 'unprovisioned_since',
551
+ raw: since,
552
+ }, { severity: 'warning' });
553
+ }
554
+ let alertedMs = NaN;
555
+ if (alerted !== null) {
556
+ alertedMs = Date.parse(alerted);
557
+ if (!Number.isFinite(alertedMs)) {
558
+ parseFailed = true;
559
+ await logOps(supabase, 'unprovisioned_timestamp_parse_failed', {
560
+ email: rawEmail,
561
+ field: 'unprovisioned_alerted_at',
562
+ raw: alerted,
563
+ }, { severity: 'warning' });
564
+ }
565
+ }
566
+ const minutesStuck = Number.isFinite(sinceMs)
567
+ ? Math.floor((nowMs - sinceMs) / 60000)
568
+ : -1;
569
+ // A corrupt unprovisioned_since must SELF-HEAL, otherwise the row
570
+ // re-alerts and re-writes every 5-minute tick forever (pinning
571
+ // updated_at and disabling membership_stuck_nonterminal).
572
+ if (!Number.isFinite(sinceMs)) patch.unprovisioned_since = nowIso;
573
+ // The 24h dedupe applies to parse-failure alerts too.
574
+ const notRecentlyAlerted = alerted === null ||
575
+ !Number.isFinite(alertedMs) ||
576
+ (nowMs - alertedMs) > REALERT_HOURS * 3600000;
577
+ const dueToAlert = notRecentlyAlerted &&
578
+ (parseFailed || minutesStuck >= STUCK_MIN_MINUTES);
579
+ if (dueToAlert) {
580
+ // Case 2: persistent and not recently alerted.
581
+ alertQueue.push({
582
+ email: rawEmail,
583
+ plan_id: st.plan_id ?? null,
584
+ groups_to_grant: c.groups_to_grant,
585
+ wifi_action: c.wifi_action,
586
+ classification: c.classification,
587
+ unprovisioned_since: since,
588
+ minutes_stuck: minutesStuck,
589
+ timestamp_parse_failed: parseFailed,
590
+ });
591
+ patch.unprovisioned_alerted_at = nowIso;
592
+ }
593
+ // else Case 4: nothing to write.
594
+ }
595
+ } else if (since !== null || alerted !== null) {
596
+ // Case 3: recovered — clear both.
597
+ patch.unprovisioned_since = null;
598
+ patch.unprovisioned_alerted_at = null;
599
+ }
600
+
601
+ // WRITE-ON-CHANGE ONLY. An unconditional update would pin updated_at and
602
+ // silently disable the membership_stuck_nonterminal tripwire.
603
+ if (Object.keys(patch).length === 0) continue;
604
+ const { error: upErr } = await supabase
605
+ .from('memberships')
606
+ .update(patch)
607
+ .in('id', st.ids);
608
+ if (upErr) {
609
+ await logOps(supabase, 'unprovisioned_state_write_failed', {
610
+ email: rawEmail,
611
+ error: upErr.message,
612
+ }, { severity: 'warning' });
613
+ }
614
+ }
615
+
616
+ // State columns above are written for EVERY member; only the alert fan-out
617
+ // is bounded here.
618
+ for (const detail of alertQueue.slice(0, MAX_INDIVIDUAL_ALERTS)) {
619
+ await logOps(supabase, 'member_entitled_but_unprovisioned', detail,
620
+ { severity: 'error' });
621
+ }
622
+ if (alertQueue.length > MAX_INDIVIDUAL_ALERTS) {
623
+ const rest = alertQueue.slice(MAX_INDIVIDUAL_ALERTS);
624
+ await logOps(supabase, 'member_entitled_but_unprovisioned_bulk', {
625
+ total_alerting: alertQueue.length,
626
+ individually_alerted: MAX_INDIVIDUAL_ALERTS,
627
+ remaining_count: rest.length,
628
+ remaining_emails: rest
629
+ .map((d) => d.email)
630
+ .slice(0, OPS_DETAIL_LIST_CAP),
631
+ }, { severity: 'error' });
632
+ }
633
+ }
634
+ } catch (e) {
635
+ console.error('[door-sync] stuck-member alarm failed (ignored):', String(e));
636
+ await logOps(supabase, 'unprovisioned_alarm_failed', {
637
+ message: String(e),
638
+ }, { severity: 'warning' });
639
+ }
640
+ // ---- end stuck-member alarm ----
641
+ }
642
+ } catch (e) {
643
+ // membershipBusSync already swallows everything; this is belt and braces so that a
644
+ // future edit to it can still never take Phase 1 down.
645
+ console.error('[door-sync] phase 2 unexpected throw (ignored):', String(e));
646
+ }
647
+ // =================== END PHASE 2 — Phase 1's result is unaffected ===================
648
+
649
+ // ================= PHASE 3 — STAGE 3 GRANT-ONLY ENFORCE (LIVE WRITES) =================
650
+ // Phases 1 and 2 are fully durable by this point. Nothing below may modify any Phase 1
651
+ // or Phase 2 variable, table row, or ops event. Skipped entirely if Phase 2 did not
652
+ // succeed -- there is no sense enforcing against a middleware we just failed to reach.
653
+ let enforceSummary: Record<string, unknown> | null = null;
654
+ if (liveDiffSummary !== null) {
655
+ try {
656
+ const eres = await membershipBusEnforce(snapshot, supabase);
657
+ if (eres && eres.ok === true) {
658
+ const esummary = (eres.summary ?? {}) as Record<string, number>;
659
+ const cb = (eres.circuit_breaker ?? {}) as Record<string, unknown>;
660
+ const writes = Number(eres.writes_performed ?? 0);
661
+ const werrors = Array.isArray(eres.write_errors) ? eres.write_errors : [];
662
+ const eresults = Array.isArray(eres.results)
663
+ ? (eres.results as Record<string, unknown>[])
664
+ : [];
665
+
666
+ // Only rows where something happened or was deliberately withheld.
667
+ const acted = eresults.filter((r) =>
668
+ r.action_taken !== 'none' && r.action_taken !== 'no_write_needed');
669
+
670
+ const eseverity: 'info' | 'warning' | 'error' =
671
+ (werrors.length > 0 || cb.tripped === true)
672
+ ? 'error'
673
+ : (writes > 0 ? 'warning' : 'info');
674
+
675
+ // EXPLICIT FIELD ALLOWLIST. Do not spread `eres` here. ops_events.detail is a
676
+ // permanent JSONB column; a future middleware change must not be able to land a
677
+ // WiFi credential in it by accident.
678
+ await logOps(supabase, 'door_sync_enforce', {
679
+ contract: eres.contract,
680
+ mode: eres.mode,
681
+ enforcement: eres.enforcement,
682
+ snapshot_id: eres.snapshot_id,
683
+ members_sent: snapshot.length,
684
+ elapsed_ms: eres.elapsed_ms,
685
+ writes_performed: writes,
686
+ members_touched: eres.members_touched,
687
+ write_allowlist_size: eres.write_allowlist_size,
688
+ write_allowlist_effective: eres.write_allowlist_effective,
689
+ enforce_scope: eres.enforce_scope,
690
+ dry_run: eres.dry_run,
691
+ governors: eres.governors,
692
+ plausibility: eres.plausibility,
693
+ wifi_grants_enabled: eres.wifi_grants_enabled,
694
+ foreign_groups_read: eres.foreign_groups_read,
695
+ circuit_breaker: cb,
696
+ summary: esummary,
697
+ unifi: eres.unifi,
698
+ wifi: eres.wifi,
699
+ acted: acted.slice(0, OPS_DETAIL_LIST_CAP),
700
+ write_errors: werrors.slice(0, OPS_DETAIL_LIST_CAP),
701
+ }, { severity: eseverity });
702
+
703
+ enforceSummary = {
704
+ snapshot_id: eres.snapshot_id,
705
+ enforce_scope: eres.enforce_scope,
706
+ dry_run: eres.dry_run,
707
+ writes_performed: writes,
708
+ members_touched: eres.members_touched,
709
+ circuit_breaker_tripped: cb.tripped === true,
710
+ write_errors: werrors.length,
711
+ };
712
+
713
+ // ---- T8: identity status persistence (SEPARATE from the ops_events write) ----
714
+ // Narrow, explicit field allowlist for the same reason as the ops_events
715
+ // detail above: `memberships` is durable state and a future middleware
716
+ // change must not be able to land an arbitrary field (or a credential) in
717
+ // it by accident. Do NOT spread `eres` or any per-row object here.
718
+ //
719
+ // Iterates `eresults` -- the FULL per-member results array -- not `acted`.
720
+ // A member can legitimately carry an existing unifi_user_id while its
721
+ // action_taken is 'none'/'no_write_needed'; the acted filter (and its
722
+ // OPS_DETAIL_LIST_CAP slice) would silently drop exactly those rows.
723
+ //
724
+ // identity_invited_at is only ever set from the literal string 'sent'.
725
+ // 'dry_run', 'failed', 'error' and 'unknown_response_shape' all mean no
726
+ // invite actually reached the member, so none of them may stamp it.
727
+ const snapshotEmails = new Set(snapshot.map((m) => m.email));
728
+ for (const row of eresults) {
729
+ const rowEmail = typeof row.email === 'string' ? row.email.toLowerCase() : '';
730
+ if (!rowEmail) continue;
731
+ if (!snapshotEmails.has(rowEmail) || PROTECTED_ALLOWLIST.has(rowEmail)) {
732
+ await logOps(supabase, 'identity_status_write_skipped', {
733
+ email: rowEmail,
734
+ reason: !snapshotEmails.has(rowEmail) ? 'not_in_sent_snapshot' : 'protected_allowlist',
735
+ }, { severity: 'warning' });
736
+ continue;
737
+ }
738
+ const patch: Record<string, unknown> = {};
739
+ if (typeof row.unifi_user_id === 'string' && row.unifi_user_id.length > 0) {
740
+ patch.unifi_access_user_id = row.unifi_user_id;
741
+ }
742
+ if (row.identity_invitation === 'sent') {
743
+ patch.identity_invited_at = nowIso;
744
+ }
745
+ if (Object.keys(patch).length === 0) continue;
746
+ // NEVER a bare .ilike() on a write: `_` is a legal, common email
747
+ // character AND a wildcard, and this payload is a door-credential
748
+ // identity id -- a false positive attaches someone else's
749
+ // credential. byEmail (Phase 1's Map<string, MembershipRow[]>,
750
+ // already carrying id and email) gives the intended per-person
751
+ // fan-out with an exact match. unifi_user_id and
752
+ // identity_invited_at are per-person facts, not per-membership
753
+ // ones, so writing every row sharing the email IS the intent.
754
+ const ids = (byEmail.get(rowEmail) ?? []).map((r) => r.id);
755
+ if (ids.length === 0) continue;
756
+ const { error: idErr } = await supabase
757
+ .from('memberships').update(patch).in('id', ids);
758
+ if (idErr) {
759
+ await logOps(supabase, 'identity_status_write_failed', {
760
+ email: rowEmail,
761
+ error: idErr.message,
762
+ }, { severity: 'warning' });
763
+ }
764
+ }
765
+ // ---- end T8 identity status persistence ----
766
+ } else if (eres && eres.ok === false) {
767
+ // Expected while Stage 3 is deployed-but-disabled: the middleware answers
768
+ // 403 enforce_disabled. Logged at info so a disabled deployment is visible
769
+ // and quiet rather than invisible or noisy.
770
+ await logOps(supabase, 'door_sync_enforce', {
771
+ ok: false,
772
+ error: eres.error,
773
+ detail: eres.detail,
774
+ snapshot_id: eres.snapshot_id,
775
+ members_sent: snapshot.length,
776
+ writes_performed: 0,
777
+ }, { severity: eres.error === 'enforce_disabled' ? 'info' : 'error' });
778
+ enforceSummary = { refused: eres.error, writes_performed: 0 };
779
+ }
780
+ } catch (e) {
781
+ // membershipBusEnforce already swallows everything; belt and braces so a future
782
+ // edit to it can never take Phase 1 or Phase 2 down.
783
+ console.error('[door-sync] phase 3 unexpected throw (ignored):', String(e));
784
+ }
785
+ }
786
+ // ============== END PHASE 3 — Phases 1 and 2 results are unaffected ==================
787
+
788
+ // ================= PHASE 4 — STAGE 4 REVOKE-ONLY ENFORCE (LIVE WRITES) =================
789
+ // Phases 1, 2 and 3 are fully durable by this point. Nothing below may modify any
790
+ // earlier phase's variable, table row, or ops event.
791
+ let revokeSummary: Record<string, unknown> | null = null;
792
+ if (liveDiffSummary !== null) {
793
+ try {
794
+ // Plausibility floor: the tenant app is the only party that can tell "legitimately small
795
+ // snapshot" from "Phase 1's query partially failed". A silently-truncated snapshot
796
+ // reads, in revoke mode, as an instruction to strip access from everyone who didn't
797
+ // make it into the list. Refuse rather than revoke on a tick that looks implausible.
798
+ const { data: priorShadowTicks } = await supabase
799
+ .from('ops_events')
800
+ .select('detail, created_at')
801
+ .eq('kind', 'door_sync_shadow')
802
+ .order('created_at', { ascending: false })
803
+ .limit(2);
804
+ const priorSize = Array.isArray(priorShadowTicks) && priorShadowTicks.length === 2
805
+ ? Number((priorShadowTicks[1]?.detail as Record<string, unknown> | null)?.snapshot_size ?? NaN)
806
+ : NaN;
807
+ const implausibleShrink = Number.isFinite(priorSize) && priorSize >= 3 &&
808
+ snapshot.length < priorSize * 0.8;
809
+
810
+ if (implausibleShrink) {
811
+ await logOps(supabase, 'door_sync_revoke_skipped', {
812
+ reason: 'implausible_snapshot_shrink',
813
+ snapshot_size: snapshot.length,
814
+ prior_snapshot_size: priorSize,
815
+ }, { severity: 'error' });
816
+ revokeSummary = { refused: 'implausible_snapshot_shrink', writes_performed: 0 };
817
+ } else {
818
+ const rres = await membershipBusRevoke(snapshot, nowIso, supabase);
819
+ if (rres && rres.ok === true) {
820
+ const rsummary = (rres.summary ?? {}) as Record<string, number>;
821
+ const cb = (rres.circuit_breaker ?? {}) as Record<string, unknown>;
822
+ const writes = Number(rres.writes_performed ?? 0);
823
+ const rerrors = Array.isArray(rres.revoke_errors) ? rres.revoke_errors : [];
824
+ const rresults = Array.isArray(rres.results)
825
+ ? (rres.results as Record<string, unknown>[])
826
+ : [];
827
+ // Explicit include-list: Stage 4's action_taken vocabulary is its own (verified
828
+ // against membership_revoke.py source directly), not Stage 3's. Any value
829
+ // containing "revoked" (groups_revoked, wifi_revoked, or their "+"-joined
830
+ // combination) is a real write. Everything else -- none, no_write_needed,
831
+ // skipped_not_in_scope, skipped_dwell, skipped_flap,
832
+ // skipped_duplicate_unifi_user, pending -- is not, and with the revoke
833
+ // allowlist currently empty, "everything else" is most rows every tick.
834
+ const acted = rresults.filter((r) =>
835
+ typeof r.action_taken === 'string' && r.action_taken.includes('revoked'));
836
+ // Separately bounded: refusals/aborts worth auditing even though nothing was
837
+ // written -- these explain why a real revoke candidate did NOT get revoked.
838
+ const notable = rresults.filter((r) =>
839
+ typeof r.action_taken === 'string' &&
840
+ /^(aborted_|error_|refused_assertion_|deferred_governor_cap|skipped_budget_exhausted)/
841
+ .test(r.action_taken));
842
+
843
+ const rseverity: 'info' | 'warning' | 'error' =
844
+ (rerrors.length > 0 || cb.tripped === true)
845
+ ? 'error'
846
+ : (writes > 0 ? 'warning' : 'info');
847
+
848
+ // EXPLICIT FIELD ALLOWLIST -- same discipline as Phase 3. Do not spread `rres`.
849
+ // The quintet (snapshot_age_sec, spacebring, governors, double_read_consistent,
850
+ // post_write_verified) IS the audit evidence that a revoke was legitimate --
851
+ // deliberately included, not an afterthought.
852
+ await logOps(supabase, 'door_sync_revoke', {
853
+ contract: rres.contract,
854
+ mode: rres.mode,
855
+ enforcement: rres.enforcement,
856
+ snapshot_id: rres.snapshot_id,
857
+ members_sent: snapshot.length,
858
+ elapsed_ms: rres.elapsed_ms,
859
+ writes_performed: writes,
860
+ revokes_performed: rres.revokes_performed,
861
+ members_touched: rres.members_touched,
862
+ snapshot_age_sec: rres.snapshot_age_sec,
863
+ scope: rres.scope,
864
+ spacebring: rres.spacebring,
865
+ governors: rres.governors,
866
+ circuit_breaker: cb,
867
+ double_read_consistent: rres.double_read_consistent,
868
+ post_write_verified: rres.post_write_verified,
869
+ unifi: rres.unifi,
870
+ wifi: rres.wifi,
871
+ summary: rsummary,
872
+ acted: acted.slice(0, OPS_DETAIL_LIST_CAP),
873
+ notable: notable.slice(0, OPS_DETAIL_LIST_CAP),
874
+ revoke_errors: rerrors.slice(0, OPS_DETAIL_LIST_CAP),
875
+ holders_not_in_snapshot: Array.isArray(rres.holders_not_in_snapshot)
876
+ ? rres.holders_not_in_snapshot.slice(0, OPS_DETAIL_LIST_CAP)
877
+ : rres.holders_not_in_snapshot,
878
+ protected_holders_skipped: Array.isArray(rres.protected_holders_skipped)
879
+ ? rres.protected_holders_skipped.slice(0, OPS_DETAIL_LIST_CAP)
880
+ : rres.protected_holders_skipped,
881
+ }, { severity: rseverity });
882
+
883
+ revokeSummary = {
884
+ snapshot_id: rres.snapshot_id,
885
+ writes_performed: writes,
886
+ members_touched: rres.members_touched,
887
+ circuit_breaker_tripped: cb.tripped === true,
888
+ revoke_errors: rerrors.length,
889
+ };
890
+ } else if (rres && rres.ok === false) {
891
+ const code = typeof rres.error === 'string' ? rres.error : undefined;
892
+ const severity: 'info' | 'warning' | 'error' =
893
+ code === 'revoke_disabled'
894
+ ? 'info'
895
+ : (code === 'revoke_halted' || code === 'spacebring_still_armed')
896
+ ? 'warning'
897
+ : 'error';
898
+ await logOps(supabase, 'door_sync_revoke', {
899
+ ok: false,
900
+ error: rres.error,
901
+ detail: rres.detail,
902
+ snapshot_id: rres.snapshot_id,
903
+ members_sent: snapshot.length,
904
+ writes_performed: 0,
905
+ circuit_breaker: rres.circuit_breaker,
906
+ }, { severity });
907
+ revokeSummary = {
908
+ refused: rres.error,
909
+ writes_performed: 0,
910
+ circuit_breaker_tripped: (rres.circuit_breaker as Record<string, unknown> | undefined)?.tripped === true,
911
+ };
912
+ } else if (rres) {
913
+ await logOps(supabase, 'door_sync_revoke', {
914
+ unexpected_shape: true,
915
+ snapshot_id: (rres as Record<string, unknown>).snapshot_id,
916
+ members_sent: snapshot.length,
917
+ writes_performed: 0,
918
+ }, { severity: 'error' });
919
+ revokeSummary = { refused: 'unexpected_response_shape', writes_performed: 0 };
920
+ }
921
+ }
922
+ } catch (e) {
923
+ console.error('[door-sync] phase 4 unexpected throw (ignored):', String(e));
924
+ }
925
+ }
926
+ // ============== END PHASE 4 — Phases 1, 2 and 3 results are unaffected ================
927
+
928
+ return new Response(
929
+ JSON.stringify({
930
+ ok: true,
931
+ generated_at: nowIso,
932
+ counts: {
933
+ total_evaluated: totalEvaluated,
934
+ skipped_allowlist: skippedAllowlist,
935
+ skipped_not_managed: skippedNotManaged,
936
+ would_grant: wouldGrant.length,
937
+ would_revoke: wouldRevoke.length,
938
+ bootstrapped,
939
+ unchanged,
940
+ },
941
+ would_grant: wouldGrant,
942
+ would_revoke: wouldRevoke,
943
+ live_diff: liveDiffSummary,
944
+ enforce: enforceSummary,
945
+ revoke: revokeSummary,
946
+ }),
947
+ { headers: { 'Content-Type': 'application/json' }, status: 200 },
948
+ );
949
+ } catch (e) {
950
+ await logOps(supabase, 'door_sync_shadow_failed', { error: String(e) }, { severity: 'error' });
951
+ return new Response(JSON.stringify({ ok: false, error: String(e) }), {
952
+ headers: { 'Content-Type': 'application/json' }, status: 500,
953
+ });
954
+ }
955
+ };
956
+ }