@simplelayer/graniteer-core 0.2.1 → 0.2.3

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 (475) hide show
  1. package/dist/adminBookingCredit.d.ts +107 -0
  2. package/dist/adminBookingCredit.js +163 -0
  3. package/dist/agreementCheckout.d.ts +34 -0
  4. package/dist/agreementCheckout.js +211 -0
  5. package/dist/agreementPortalEmail.d.ts +15 -0
  6. package/dist/agreementPortalEmail.js +107 -0
  7. package/dist/availability.d.ts +51 -0
  8. package/dist/availability.js +152 -0
  9. package/dist/billingPortalLinkEmail.d.ts +14 -0
  10. package/dist/billingPortalLinkEmail.js +98 -0
  11. package/dist/bookingAgreementEmail.d.ts +23 -0
  12. package/dist/bookingAgreementEmail.js +116 -0
  13. package/dist/bookingEffects.d.ts +84 -0
  14. package/dist/bookingEffects.js +309 -0
  15. package/dist/bookingHoldReclaim.d.ts +16 -0
  16. package/dist/bookingHoldReclaim.js +74 -0
  17. package/dist/busClient.d.ts +44 -0
  18. package/dist/busClient.js +196 -0
  19. package/dist/busSignature.d.ts +19 -0
  20. package/{src/busSignature.ts → dist/busSignature.js} +26 -33
  21. package/dist/checkoutCoupon.d.ts +156 -0
  22. package/dist/checkoutCoupon.js +369 -0
  23. package/dist/checkoutSessionParams.d.ts +19 -0
  24. package/dist/checkoutSessionParams.js +36 -0
  25. package/dist/commonsContract.d.ts +70 -0
  26. package/dist/commonsContract.js +142 -0
  27. package/dist/commonsDeposit.d.ts +78 -0
  28. package/dist/commonsDeposit.js +199 -0
  29. package/dist/commonsDepositWebhook.d.ts +37 -0
  30. package/dist/commonsDepositWebhook.js +147 -0
  31. package/dist/conductorAdmin.d.ts +76 -0
  32. package/dist/conductorAdmin.js +88 -0
  33. package/dist/dayPassConfirmation.d.ts +17 -0
  34. package/dist/dayPassConfirmation.js +187 -0
  35. package/dist/dunningEmails.d.ts +40 -0
  36. package/dist/dunningEmails.js +174 -0
  37. package/dist/email-templates/brand.d.ts +82 -0
  38. package/dist/email-templates/brand.js +72 -0
  39. package/dist/email-templates/email-change.d.ts +10 -0
  40. package/dist/email-templates/email-change.js +50 -0
  41. package/dist/email-templates/invite.d.ts +8 -0
  42. package/dist/email-templates/invite.js +44 -0
  43. package/dist/email-templates/magic-link.d.ts +10 -0
  44. package/dist/email-templates/magic-link.js +26 -0
  45. package/dist/email-templates/reauthentication.d.ts +6 -0
  46. package/dist/email-templates/reauthentication.js +35 -0
  47. package/dist/email-templates/recovery.d.ts +10 -0
  48. package/dist/email-templates/recovery.js +26 -0
  49. package/dist/email-templates/signup.d.ts +12 -0
  50. package/dist/email-templates/signup.js +30 -0
  51. package/dist/functions/admin-cancel-membership.d.ts +1 -0
  52. package/dist/functions/admin-cancel-membership.js +286 -0
  53. package/dist/functions/admin-change-membership-plan.d.ts +1 -0
  54. package/dist/functions/admin-change-membership-plan.js +281 -0
  55. package/dist/functions/admin-charge-guest-print.d.ts +1 -0
  56. package/dist/functions/admin-charge-guest-print.js +227 -0
  57. package/dist/functions/admin-correct-booking.d.ts +1 -0
  58. package/dist/functions/admin-correct-booking.js +326 -0
  59. package/dist/functions/admin-create-booking.d.ts +43 -0
  60. package/dist/functions/admin-create-booking.js +410 -0
  61. package/dist/functions/admin-create-commons-event.d.ts +1 -0
  62. package/dist/functions/admin-create-commons-event.js +237 -0
  63. package/dist/functions/admin-debug-boldsign-doc.d.ts +1 -0
  64. package/dist/functions/admin-debug-boldsign-doc.js +110 -0
  65. package/dist/functions/admin-door-write.d.ts +1 -0
  66. package/dist/functions/admin-door-write.js +267 -0
  67. package/dist/functions/admin-issue-day-pass.d.ts +14 -0
  68. package/dist/functions/admin-issue-day-pass.js +213 -0
  69. package/dist/functions/admin-mark-booking-paid.d.ts +1 -0
  70. package/dist/functions/admin-mark-booking-paid.js +202 -0
  71. package/dist/functions/admin-mint-billing-portal-link.d.ts +6 -0
  72. package/dist/functions/admin-mint-billing-portal-link.js +159 -0
  73. package/dist/functions/admin-mint-portal-link.d.ts +3 -0
  74. package/dist/functions/admin-mint-portal-link.js +54 -0
  75. package/dist/functions/admin-photo-upload.d.ts +1 -0
  76. package/dist/functions/admin-photo-upload.js +104 -0
  77. package/dist/functions/admin-remove-team-member.d.ts +1 -0
  78. package/dist/functions/admin-remove-team-member.js +140 -0
  79. package/dist/functions/admin-request-trial.d.ts +5 -0
  80. package/dist/functions/admin-request-trial.js +349 -0
  81. package/dist/functions/admin-resend-commons-deposit-link.d.ts +7 -0
  82. package/dist/functions/admin-resend-commons-deposit-link.js +298 -0
  83. package/dist/functions/admin-reset-mfa.d.ts +1 -0
  84. package/dist/functions/admin-reset-mfa.js +129 -0
  85. package/dist/functions/admin-retry-invoice-payment.d.ts +76 -0
  86. package/dist/functions/admin-retry-invoice-payment.js +269 -0
  87. package/dist/functions/admin-reverse-coupon-redemption.d.ts +1 -0
  88. package/dist/functions/admin-reverse-coupon-redemption.js +91 -0
  89. package/dist/functions/admin-revoke-agreement.d.ts +4 -0
  90. package/dist/functions/admin-revoke-agreement.js +410 -0
  91. package/dist/functions/admin-send-commons-agreement.d.ts +1 -0
  92. package/dist/functions/admin-send-commons-agreement.js +212 -0
  93. package/dist/functions/admin-set-credit-amount.d.ts +1 -0
  94. package/dist/functions/admin-set-credit-amount.js +112 -0
  95. package/dist/functions/admin-skip-commons-contract.d.ts +1 -0
  96. package/dist/functions/admin-skip-commons-contract.js +170 -0
  97. package/dist/functions/admin-undo-membership-cancel.d.ts +1 -0
  98. package/dist/functions/admin-undo-membership-cancel.js +135 -0
  99. package/dist/functions/admin-wall-photo-write.d.ts +1 -0
  100. package/dist/functions/admin-wall-photo-write.js +137 -0
  101. package/dist/functions/auth-email-hook.d.ts +20 -0
  102. package/dist/functions/auth-email-hook.js +209 -0
  103. package/dist/functions/boldsign-sender-identity.d.ts +1 -0
  104. package/dist/functions/boldsign-sender-identity.js +109 -0
  105. package/dist/functions/booking-availability.d.ts +1 -0
  106. package/dist/functions/booking-availability.js +355 -0
  107. package/dist/functions/booking-member-preview.d.ts +1 -0
  108. package/dist/functions/booking-member-preview.js +123 -0
  109. package/dist/functions/booking-status.d.ts +3 -0
  110. package/dist/functions/booking-status.js +139 -0
  111. package/dist/functions/conductor.d.ts +3 -0
  112. package/dist/functions/conductor.js +451 -0
  113. package/dist/functions/create-agreement.d.ts +8 -0
  114. package/dist/functions/create-agreement.js +498 -0
  115. package/dist/functions/create-booking.d.ts +44 -0
  116. package/dist/functions/create-booking.js +538 -0
  117. package/dist/functions/create-day-pass-checkout.d.ts +4 -0
  118. package/dist/functions/create-day-pass-checkout.js +196 -0
  119. package/dist/functions/create-portal-session.d.ts +4 -0
  120. package/dist/functions/create-portal-session.js +127 -0
  121. package/dist/functions/create-subscription-checkout.d.ts +4 -0
  122. package/dist/functions/create-subscription-checkout.js +394 -0
  123. package/dist/functions/day-pass-status.d.ts +1 -0
  124. package/dist/functions/day-pass-status.js +70 -0
  125. package/dist/functions/dayStatus.d.ts +15 -0
  126. package/dist/functions/dayStatus.js +59 -0
  127. package/dist/functions/diag-webpush-test.d.ts +1 -0
  128. package/dist/functions/diag-webpush-test.js +42 -0
  129. package/dist/functions/event-access-admin.d.ts +17 -0
  130. package/dist/functions/event-access-admin.js +262 -0
  131. package/dist/functions/event-access-store.d.ts +1 -0
  132. package/dist/functions/event-access-store.js +343 -0
  133. package/dist/functions/ezeep-print-webhook.d.ts +1 -0
  134. package/dist/functions/ezeep-print-webhook.js +160 -0
  135. package/dist/functions/ezeep-usage-reconcile.d.ts +1 -0
  136. package/dist/functions/ezeep-usage-reconcile.js +305 -0
  137. package/dist/functions/fetch-avatar-original.d.ts +3 -0
  138. package/dist/functions/fetch-avatar-original.js +423 -0
  139. package/dist/functions/get-provider-sign-link.d.ts +3 -0
  140. package/dist/functions/get-provider-sign-link.js +146 -0
  141. package/dist/functions/get-signing-link.d.ts +1 -0
  142. package/dist/functions/get-signing-link.js +192 -0
  143. package/dist/functions/guest-print-setup-confirm.d.ts +1 -0
  144. package/dist/functions/guest-print-setup-confirm.js +126 -0
  145. package/dist/functions/guest-print-submit.d.ts +1 -0
  146. package/dist/functions/guest-print-submit.js +145 -0
  147. package/dist/functions/luma-webhook.d.ts +1 -0
  148. package/dist/functions/luma-webhook.js +123 -0
  149. package/dist/functions/manage-booking.d.ts +75 -0
  150. package/dist/functions/manage-booking.js +409 -0
  151. package/dist/functions/mcp.d.ts +16 -0
  152. package/dist/functions/mcp.js +51 -0
  153. package/dist/functions/member-door-action.d.ts +60 -0
  154. package/dist/functions/member-door-action.js +774 -0
  155. package/dist/functions/member-unifi-mapping.d.ts +15 -0
  156. package/dist/functions/member-unifi-mapping.js +198 -0
  157. package/dist/functions/membership-door-sync.d.ts +14 -0
  158. package/dist/functions/membership-door-sync.js +863 -0
  159. package/dist/functions/migration-collision-alert.copy.d.ts +7 -0
  160. package/dist/functions/migration-collision-alert.copy.js +207 -0
  161. package/dist/functions/migration-collision-alert.d.ts +7 -0
  162. package/dist/functions/migration-collision-alert.js +207 -0
  163. package/dist/functions/office-assignment-end.d.ts +12 -0
  164. package/dist/functions/office-assignment-end.js +140 -0
  165. package/dist/functions/portal-booking-access.d.ts +22 -0
  166. package/dist/functions/portal-booking-access.js +163 -0
  167. package/dist/functions/portal-list-invoices.d.ts +1 -0
  168. package/dist/functions/portal-list-invoices.js +90 -0
  169. package/dist/functions/portal-request-login.d.ts +7 -0
  170. package/dist/functions/portal-request-login.js +199 -0
  171. package/dist/functions/portal-resend-invite.d.ts +6 -0
  172. package/dist/functions/portal-resend-invite.js +225 -0
  173. package/dist/functions/portal-submit-event.d.ts +4 -0
  174. package/dist/functions/portal-submit-event.js +152 -0
  175. package/dist/functions/print-billing-recover.d.ts +1 -0
  176. package/dist/functions/print-billing-recover.js +83 -0
  177. package/dist/functions/print-billing-run.d.ts +1 -0
  178. package/dist/functions/print-billing-run.js +153 -0
  179. package/dist/functions/public-facts.d.ts +1 -0
  180. package/dist/functions/public-facts.js +141 -0
  181. package/dist/functions/push-send.d.ts +3 -0
  182. package/dist/functions/push-send.js +297 -0
  183. package/dist/functions/push-test.d.ts +3 -0
  184. package/dist/functions/push-test.js +215 -0
  185. package/dist/functions/request-portal-link.d.ts +7 -0
  186. package/dist/functions/request-portal-link.js +178 -0
  187. package/dist/functions/reschedule-booking.d.ts +50 -0
  188. package/dist/functions/reschedule-booking.js +571 -0
  189. package/dist/functions/review-ratings.d.ts +1 -0
  190. package/dist/functions/review-ratings.js +95 -0
  191. package/dist/functions/space-availability-range.d.ts +1 -0
  192. package/dist/functions/space-availability-range.js +109 -0
  193. package/dist/functions/stripe-db-reconcile.d.ts +3 -0
  194. package/dist/functions/stripe-db-reconcile.js +314 -0
  195. package/dist/functions/stripe-webhook.d.ts +46 -0
  196. package/dist/functions/stripe-webhook.js +2367 -0
  197. package/dist/functions/sync-gcal-blackouts.d.ts +1 -0
  198. package/dist/functions/sync-gcal-blackouts.js +251 -0
  199. package/dist/functions/timetable-event-register.d.ts +1 -0
  200. package/dist/functions/timetable-event-register.js +155 -0
  201. package/dist/functions/timetable-event-status.d.ts +1 -0
  202. package/dist/functions/timetable-event-status.js +86 -0
  203. package/dist/functions/timetable-spaces.d.ts +1 -0
  204. package/dist/functions/timetable-spaces.js +161 -0
  205. package/dist/functions/touch-pass-reconciler.d.ts +1 -0
  206. package/dist/functions/touch-pass-reconciler.js +688 -0
  207. package/dist/functions/touch-pass-signup.d.ts +1 -0
  208. package/dist/functions/touch-pass-signup.js +447 -0
  209. package/dist/functions/upload-booking-display-image.d.ts +4 -0
  210. package/dist/functions/upload-booking-display-image.js +159 -0
  211. package/dist/functions/virtual-onboarding-purge.d.ts +1 -0
  212. package/dist/functions/virtual-onboarding-purge.js +123 -0
  213. package/dist/functions/virtual-onboarding-submit.d.ts +1 -0
  214. package/dist/functions/virtual-onboarding-submit.js +303 -0
  215. package/dist/functions/voice-booking.d.ts +10 -0
  216. package/dist/functions/voice-booking.js +360 -0
  217. package/dist/functions/voice-day-pass.d.ts +15 -0
  218. package/dist/functions/voice-day-pass.js +269 -0
  219. package/dist/functions/voice-inquiry.d.ts +1 -0
  220. package/dist/functions/voice-inquiry.js +156 -0
  221. package/dist/functions/voice-membership-signup.d.ts +15 -0
  222. package/dist/functions/voice-membership-signup.js +273 -0
  223. package/dist/functions/voice-tour-availability.d.ts +1 -0
  224. package/dist/functions/voice-tour-availability.js +179 -0
  225. package/dist/functions/voice-tour-booking.d.ts +21 -0
  226. package/dist/functions/voice-tour-booking.js +308 -0
  227. package/dist/gcalSync.d.ts +29 -0
  228. package/dist/gcalSync.js +119 -0
  229. package/dist/ghlEventInquiry.d.ts +16 -0
  230. package/dist/ghlEventInquiry.js +116 -0
  231. package/dist/ghlNote.d.ts +5 -0
  232. package/dist/ghlNote.js +29 -0
  233. package/dist/ghlTask.d.ts +7 -0
  234. package/dist/ghlTask.js +39 -0
  235. package/dist/ghlVoiceInquiry.d.ts +26 -0
  236. package/dist/ghlVoiceInquiry.js +68 -0
  237. package/dist/guestPrintCapture.d.ts +217 -0
  238. package/dist/guestPrintCapture.js +362 -0
  239. package/dist/index.d.ts +3 -0
  240. package/{index.js → dist/index.js} +2 -1
  241. package/dist/lumaGhl.d.ts +19 -0
  242. package/dist/lumaGhl.js +147 -0
  243. package/dist/mailArrivalEmail.d.ts +15 -0
  244. package/dist/mailArrivalEmail.js +99 -0
  245. package/dist/manageToken.d.ts +64 -0
  246. package/dist/manageToken.js +261 -0
  247. package/dist/membership.d.ts +20 -0
  248. package/dist/membership.js +87 -0
  249. package/dist/membershipBusClient.d.ts +139 -0
  250. package/dist/membershipBusClient.js +443 -0
  251. package/dist/membershipWelcome.d.ts +117 -0
  252. package/dist/membershipWelcome.js +497 -0
  253. package/dist/migrationCheckout.d.ts +169 -0
  254. package/dist/migrationCheckout.js +250 -0
  255. package/dist/money.d.ts +20 -0
  256. package/dist/money.js +35 -0
  257. package/dist/ops.d.ts +27 -0
  258. package/dist/ops.js +87 -0
  259. package/dist/pacificDate.d.ts +8 -0
  260. package/{src/pacificDate.ts → dist/pacificDate.js} +76 -88
  261. package/dist/paymentLinkEmail.d.ts +15 -0
  262. package/dist/paymentLinkEmail.js +102 -0
  263. package/dist/policyAcknowledgment.d.ts +46 -0
  264. package/dist/policyAcknowledgment.js +58 -0
  265. package/dist/portalSession.d.ts +15 -0
  266. package/dist/portalSession.js +31 -0
  267. package/dist/pricing.d.ts +306 -0
  268. package/dist/pricing.js +788 -0
  269. package/dist/printBilling.d.ts +340 -0
  270. package/dist/printBilling.js +619 -0
  271. package/dist/printBillingAdapters.d.ts +29 -0
  272. package/dist/printBillingAdapters.js +130 -0
  273. package/dist/printCorrections.d.ts +175 -0
  274. package/dist/printCorrections.js +328 -0
  275. package/dist/rateLimit.d.ts +20 -0
  276. package/dist/rateLimit.js +70 -0
  277. package/dist/referralCredits.d.ts +5 -0
  278. package/{src/referralCredits.ts → dist/referralCredits.js} +27 -34
  279. package/dist/referralGrant.d.ts +49 -0
  280. package/dist/referralGrant.js +268 -0
  281. package/dist/rescheduleCredit.d.ts +98 -0
  282. package/dist/rescheduleCredit.js +263 -0
  283. package/dist/reservationWifiCode.d.ts +19 -0
  284. package/{src/reservationWifiCode.ts → dist/reservationWifiCode.js} +67 -81
  285. package/dist/retellCallAnalyzed.d.ts +18 -0
  286. package/dist/retellCallAnalyzed.js +91 -0
  287. package/dist/retellSignature.d.ts +14 -0
  288. package/dist/retellSignature.js +60 -0
  289. package/dist/signedUnpaidReminderEmail.d.ts +15 -0
  290. package/dist/signedUnpaidReminderEmail.js +111 -0
  291. package/dist/slackAlert.d.ts +13 -0
  292. package/dist/slackAlert.js +37 -0
  293. package/dist/stripeCoworkingPortal.d.ts +21 -0
  294. package/dist/stripeCoworkingPortal.js +80 -0
  295. package/dist/supabaseTestFakes.d.ts +67 -0
  296. package/dist/supabaseTestFakes.js +79 -0
  297. package/dist/supportTicketEmail.d.ts +16 -0
  298. package/dist/supportTicketEmail.js +98 -0
  299. package/dist/tier1Agreement.d.ts +51 -0
  300. package/dist/tier1Agreement.js +86 -0
  301. package/dist/unifiAccessPolicies.d.ts +36 -0
  302. package/dist/unifiAccessPolicies.js +185 -0
  303. package/dist/unifiGroups.d.ts +26 -0
  304. package/dist/unifiGroups.js +106 -0
  305. package/package.json +645 -169
  306. package/src/adminBookingCredit.test.ts +0 -451
  307. package/src/adminBookingCredit.ts +0 -239
  308. package/src/agreementCheckout.ts +0 -250
  309. package/src/agreementPortalEmail.ts +0 -128
  310. package/src/availability.test.ts +0 -25
  311. package/src/availability.ts +0 -201
  312. package/src/billingPortalLinkEmail.ts +0 -117
  313. package/src/bookingAgreementEmail.ts +0 -149
  314. package/src/bookingEffects.ts +0 -388
  315. package/src/bookingHoldReclaim.ts +0 -94
  316. package/src/busClient.ts +0 -268
  317. package/src/checkoutCoupon.test.ts +0 -675
  318. package/src/checkoutCoupon.ts +0 -455
  319. package/src/checkoutSessionParams.ts +0 -56
  320. package/src/commonsContract.ts +0 -175
  321. package/src/commonsDeposit.ts +0 -298
  322. package/src/commonsDepositWebhook.ts +0 -237
  323. package/src/conductorAdmin.ts +0 -141
  324. package/src/dayPassConfirmation.ts +0 -230
  325. package/src/dunningEmails.test.ts +0 -263
  326. package/src/dunningEmails.ts +0 -203
  327. package/src/email-templates/brand.ts +0 -93
  328. package/src/email-templates/email-change.tsx +0 -92
  329. package/src/email-templates/invite.tsx +0 -79
  330. package/src/email-templates/magic-link.tsx +0 -59
  331. package/src/email-templates/reauthentication.tsx +0 -60
  332. package/src/email-templates/recovery.tsx +0 -59
  333. package/src/email-templates/signup.tsx +0 -67
  334. package/src/functions/admin-cancel-membership.ts +0 -311
  335. package/src/functions/admin-change-membership-plan.ts +0 -312
  336. package/src/functions/admin-charge-guest-print.ts +0 -229
  337. package/src/functions/admin-correct-booking.ts +0 -333
  338. package/src/functions/admin-create-booking.ts +0 -460
  339. package/src/functions/admin-create-commons-event.ts +0 -244
  340. package/src/functions/admin-debug-boldsign-doc.ts +0 -93
  341. package/src/functions/admin-door-write.ts +0 -272
  342. package/src/functions/admin-issue-day-pass.ts +0 -231
  343. package/src/functions/admin-mark-booking-paid.ts +0 -203
  344. package/src/functions/admin-mint-billing-portal-link.ts +0 -168
  345. package/src/functions/admin-mint-portal-link.ts +0 -62
  346. package/src/functions/admin-photo-upload.ts +0 -128
  347. package/src/functions/admin-remove-team-member.ts +0 -150
  348. package/src/functions/admin-request-trial.ts +0 -366
  349. package/src/functions/admin-resend-commons-deposit-link.ts +0 -323
  350. package/src/functions/admin-reset-mfa.ts +0 -138
  351. package/src/functions/admin-retry-invoice-payment.test.ts +0 -567
  352. package/src/functions/admin-retry-invoice-payment.ts +0 -333
  353. package/src/functions/admin-reverse-coupon-redemption.ts +0 -98
  354. package/src/functions/admin-revoke-agreement.ts +0 -467
  355. package/src/functions/admin-send-commons-agreement.ts +0 -214
  356. package/src/functions/admin-set-credit-amount.ts +0 -123
  357. package/src/functions/admin-skip-commons-contract.ts +0 -165
  358. package/src/functions/admin-undo-membership-cancel.ts +0 -144
  359. package/src/functions/admin-wall-photo-write.ts +0 -141
  360. package/src/functions/auth-email-hook.ts +0 -259
  361. package/src/functions/boldsign-sender-identity.ts +0 -114
  362. package/src/functions/booking-availability.ts +0 -419
  363. package/src/functions/booking-member-preview.ts +0 -136
  364. package/src/functions/booking-status.ts +0 -149
  365. package/src/functions/conductor.ts +0 -505
  366. package/src/functions/create-agreement.ts +0 -537
  367. package/src/functions/create-booking.ts +0 -648
  368. package/src/functions/create-day-pass-checkout.ts +0 -218
  369. package/src/functions/create-portal-session.ts +0 -142
  370. package/src/functions/create-subscription-checkout.test.ts +0 -222
  371. package/src/functions/create-subscription-checkout.ts +0 -440
  372. package/src/functions/day-pass-status.ts +0 -89
  373. package/src/functions/dayStatus.ts +0 -71
  374. package/src/functions/diag-webpush-test.ts +0 -45
  375. package/src/functions/event-access-admin.ts +0 -277
  376. package/src/functions/event-access-store.ts +0 -334
  377. package/src/functions/ezeep-print-webhook.ts +0 -213
  378. package/src/functions/ezeep-usage-reconcile.ts +0 -299
  379. package/src/functions/fetch-avatar-original.ts +0 -457
  380. package/src/functions/get-provider-sign-link.ts +0 -155
  381. package/src/functions/get-signing-link.ts +0 -211
  382. package/src/functions/guest-print-setup-confirm.ts +0 -128
  383. package/src/functions/guest-print-submit.ts +0 -149
  384. package/src/functions/luma-webhook.ts +0 -165
  385. package/src/functions/manage-booking.ts +0 -472
  386. package/src/functions/mcp.ts +0 -67
  387. package/src/functions/member-door-action.test.ts +0 -1248
  388. package/src/functions/member-door-action.ts +0 -863
  389. package/src/functions/member-unifi-mapping.test.ts +0 -516
  390. package/src/functions/member-unifi-mapping.ts +0 -206
  391. package/src/functions/membership-door-sync.ts +0 -956
  392. package/src/functions/migration-collision-alert.copy.ts +0 -232
  393. package/src/functions/migration-collision-alert.test.ts +0 -349
  394. package/src/functions/migration-collision-alert.ts +0 -232
  395. package/src/functions/office-assignment-end.ts +0 -146
  396. package/src/functions/portal-booking-access.ts +0 -217
  397. package/src/functions/portal-list-invoices.ts +0 -99
  398. package/src/functions/portal-request-login.ts +0 -192
  399. package/src/functions/portal-resend-invite.ts +0 -248
  400. package/src/functions/portal-submit-event.ts +0 -168
  401. package/src/functions/print-billing-recover.ts +0 -97
  402. package/src/functions/print-billing-run.ts +0 -183
  403. package/src/functions/public-facts.ts +0 -168
  404. package/src/functions/push-send.ts +0 -348
  405. package/src/functions/push-test.ts +0 -234
  406. package/src/functions/request-portal-link.ts +0 -211
  407. package/src/functions/reschedule-booking.ts +0 -649
  408. package/src/functions/review-ratings.ts +0 -113
  409. package/src/functions/space-availability-range.acceptance.test.ts +0 -161
  410. package/src/functions/space-availability-range.ts +0 -142
  411. package/src/functions/stripe-db-reconcile.ts +0 -319
  412. package/src/functions/stripe-webhook.moved-regression.test.ts +0 -78
  413. package/src/functions/stripe-webhook.ts +0 -2595
  414. package/src/functions/sync-gcal-blackouts.ts +0 -298
  415. package/src/functions/timetable-event-register.ts +0 -162
  416. package/src/functions/timetable-event-status.ts +0 -90
  417. package/src/functions/timetable-spaces.ts +0 -219
  418. package/src/functions/touch-pass-reconciler.ts +0 -689
  419. package/src/functions/touch-pass-signup.ts +0 -478
  420. package/src/functions/upload-booking-display-image.ts +0 -179
  421. package/src/functions/virtual-onboarding-purge.ts +0 -134
  422. package/src/functions/virtual-onboarding-submit.ts +0 -315
  423. package/src/functions/voice-booking.ts +0 -453
  424. package/src/functions/voice-day-pass.ts +0 -346
  425. package/src/functions/voice-inquiry.test.ts +0 -301
  426. package/src/functions/voice-inquiry.ts +0 -198
  427. package/src/functions/voice-membership-signup.ts +0 -355
  428. package/src/functions/voice-tour-availability.ts +0 -204
  429. package/src/functions/voice-tour-booking.ts +0 -429
  430. package/src/gcalSync.ts +0 -142
  431. package/src/ghlEventInquiry.ts +0 -143
  432. package/src/ghlNote.ts +0 -34
  433. package/src/ghlTask.ts +0 -48
  434. package/src/ghlVoiceInquiry.ts +0 -90
  435. package/src/guestPrintCapture.test.ts +0 -722
  436. package/src/guestPrintCapture.ts +0 -538
  437. package/src/lumaGhl.ts +0 -195
  438. package/src/mailArrivalEmail.ts +0 -121
  439. package/src/manageToken.ts +0 -363
  440. package/src/membership.ts +0 -109
  441. package/src/membershipBusClient.ts +0 -537
  442. package/src/membershipWelcome.ts +0 -683
  443. package/src/migrationCheckout.ts +0 -366
  444. package/src/money.ts +0 -36
  445. package/src/ops.ts +0 -97
  446. package/src/paymentLinkEmail.ts +0 -123
  447. package/src/policyAcknowledgment.test.ts +0 -50
  448. package/src/policyAcknowledgment.ts +0 -96
  449. package/src/portalSession.ts +0 -46
  450. package/src/pricing.test.ts +0 -660
  451. package/src/pricing.ts +0 -1025
  452. package/src/printBilling.test.ts +0 -750
  453. package/src/printBilling.ts +0 -891
  454. package/src/printBillingAdapters.ts +0 -169
  455. package/src/printCorrections.test.ts +0 -348
  456. package/src/printCorrections.ts +0 -496
  457. package/src/rateLimit.ts +0 -82
  458. package/src/referralCredits.test.ts +0 -31
  459. package/src/referralGrant.ts +0 -321
  460. package/src/rescheduleCredit.test.ts +0 -521
  461. package/src/rescheduleCredit.ts +0 -337
  462. package/src/reservationWifiCode.test.ts +0 -69
  463. package/src/retellCallAnalyzed.test.ts +0 -167
  464. package/src/retellCallAnalyzed.ts +0 -113
  465. package/src/retellSignature.test.ts +0 -137
  466. package/src/retellSignature.ts +0 -82
  467. package/src/signedUnpaidReminderEmail.test.ts +0 -246
  468. package/src/signedUnpaidReminderEmail.ts +0 -132
  469. package/src/slackAlert.ts +0 -38
  470. package/src/stripeCoworkingPortal.ts +0 -91
  471. package/src/supabaseTestFakes.ts +0 -131
  472. package/src/supportTicketEmail.ts +0 -119
  473. package/src/tier1Agreement.ts +0 -125
  474. package/src/unifiAccessPolicies.ts +0 -228
  475. package/src/unifiGroups.ts +0 -129
@@ -1,956 +0,0 @@
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
- }