@simplelayer/graniteer-core 0.2.2 → 0.3.0

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 (479) 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} +64 -71
  21. package/dist/checkoutCoupon.d.ts +156 -0
  22. package/dist/checkoutCoupon.js +369 -0
  23. package/dist/checkoutSessionParams.d.ts +32 -0
  24. package/dist/checkoutSessionParams.js +72 -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/entitlements.d.ts +17 -0
  52. package/dist/entitlements.js +33 -0
  53. package/dist/functions/admin-cancel-membership.d.ts +3 -0
  54. package/dist/functions/admin-cancel-membership.js +294 -0
  55. package/dist/functions/admin-change-membership-plan.d.ts +3 -0
  56. package/dist/functions/admin-change-membership-plan.js +289 -0
  57. package/dist/functions/admin-charge-guest-print.d.ts +1 -0
  58. package/dist/functions/admin-charge-guest-print.js +227 -0
  59. package/dist/functions/admin-correct-booking.d.ts +1 -0
  60. package/dist/functions/admin-correct-booking.js +326 -0
  61. package/dist/functions/admin-create-booking.d.ts +43 -0
  62. package/dist/functions/admin-create-booking.js +410 -0
  63. package/dist/functions/admin-create-commons-event.d.ts +1 -0
  64. package/dist/functions/admin-create-commons-event.js +237 -0
  65. package/dist/functions/admin-debug-boldsign-doc.d.ts +1 -0
  66. package/dist/functions/admin-debug-boldsign-doc.js +110 -0
  67. package/dist/functions/admin-door-write.d.ts +1 -0
  68. package/dist/functions/admin-door-write.js +267 -0
  69. package/dist/functions/admin-issue-day-pass.d.ts +14 -0
  70. package/dist/functions/admin-issue-day-pass.js +213 -0
  71. package/dist/functions/admin-mark-booking-paid.d.ts +1 -0
  72. package/dist/functions/admin-mark-booking-paid.js +202 -0
  73. package/dist/functions/admin-mint-billing-portal-link.d.ts +6 -0
  74. package/dist/functions/admin-mint-billing-portal-link.js +159 -0
  75. package/dist/functions/admin-mint-portal-link.d.ts +3 -0
  76. package/dist/functions/admin-mint-portal-link.js +54 -0
  77. package/dist/functions/admin-onboard-connect-account.d.ts +47 -0
  78. package/dist/functions/admin-onboard-connect-account.js +197 -0
  79. package/dist/functions/admin-photo-upload.d.ts +1 -0
  80. package/dist/functions/admin-photo-upload.js +104 -0
  81. package/dist/functions/admin-remove-team-member.d.ts +1 -0
  82. package/dist/functions/admin-remove-team-member.js +140 -0
  83. package/dist/functions/admin-request-trial.d.ts +5 -0
  84. package/dist/functions/admin-request-trial.js +349 -0
  85. package/dist/functions/admin-resend-commons-deposit-link.d.ts +7 -0
  86. package/dist/functions/admin-resend-commons-deposit-link.js +298 -0
  87. package/dist/functions/admin-reset-mfa.d.ts +1 -0
  88. package/dist/functions/admin-reset-mfa.js +129 -0
  89. package/dist/functions/admin-retry-invoice-payment.d.ts +76 -0
  90. package/dist/functions/admin-retry-invoice-payment.js +269 -0
  91. package/dist/functions/admin-reverse-coupon-redemption.d.ts +1 -0
  92. package/dist/functions/admin-reverse-coupon-redemption.js +91 -0
  93. package/dist/functions/admin-revoke-agreement.d.ts +4 -0
  94. package/dist/functions/admin-revoke-agreement.js +410 -0
  95. package/dist/functions/admin-send-commons-agreement.d.ts +1 -0
  96. package/dist/functions/admin-send-commons-agreement.js +212 -0
  97. package/dist/functions/admin-set-credit-amount.d.ts +1 -0
  98. package/dist/functions/admin-set-credit-amount.js +112 -0
  99. package/dist/functions/admin-skip-commons-contract.d.ts +1 -0
  100. package/dist/functions/admin-skip-commons-contract.js +170 -0
  101. package/dist/functions/admin-undo-membership-cancel.d.ts +3 -0
  102. package/dist/functions/admin-undo-membership-cancel.js +143 -0
  103. package/dist/functions/admin-wall-photo-write.d.ts +1 -0
  104. package/dist/functions/admin-wall-photo-write.js +137 -0
  105. package/dist/functions/auth-email-hook.d.ts +20 -0
  106. package/dist/functions/auth-email-hook.js +209 -0
  107. package/dist/functions/boldsign-sender-identity.d.ts +1 -0
  108. package/dist/functions/boldsign-sender-identity.js +109 -0
  109. package/dist/functions/booking-availability.d.ts +1 -0
  110. package/dist/functions/booking-availability.js +355 -0
  111. package/dist/functions/booking-member-preview.d.ts +1 -0
  112. package/dist/functions/booking-member-preview.js +123 -0
  113. package/dist/functions/booking-status.d.ts +3 -0
  114. package/dist/functions/booking-status.js +139 -0
  115. package/dist/functions/conductor.d.ts +3 -0
  116. package/dist/functions/conductor.js +451 -0
  117. package/dist/functions/create-agreement.d.ts +8 -0
  118. package/dist/functions/create-agreement.js +498 -0
  119. package/dist/functions/create-booking.d.ts +44 -0
  120. package/dist/functions/create-booking.js +538 -0
  121. package/dist/functions/create-day-pass-checkout.d.ts +6 -0
  122. package/dist/functions/create-day-pass-checkout.js +225 -0
  123. package/dist/functions/create-portal-session.d.ts +4 -0
  124. package/dist/functions/create-portal-session.js +127 -0
  125. package/dist/functions/create-subscription-checkout.d.ts +7 -0
  126. package/dist/functions/create-subscription-checkout.js +405 -0
  127. package/dist/functions/day-pass-status.d.ts +1 -0
  128. package/dist/functions/day-pass-status.js +70 -0
  129. package/dist/functions/dayStatus.d.ts +15 -0
  130. package/dist/functions/dayStatus.js +59 -0
  131. package/dist/functions/diag-webpush-test.d.ts +1 -0
  132. package/dist/functions/diag-webpush-test.js +42 -0
  133. package/dist/functions/event-access-admin.d.ts +17 -0
  134. package/dist/functions/event-access-admin.js +262 -0
  135. package/dist/functions/event-access-store.d.ts +1 -0
  136. package/dist/functions/event-access-store.js +343 -0
  137. package/dist/functions/ezeep-print-webhook.d.ts +1 -0
  138. package/dist/functions/ezeep-print-webhook.js +160 -0
  139. package/dist/functions/ezeep-usage-reconcile.d.ts +1 -0
  140. package/dist/functions/ezeep-usage-reconcile.js +305 -0
  141. package/dist/functions/fetch-avatar-original.d.ts +3 -0
  142. package/dist/functions/fetch-avatar-original.js +423 -0
  143. package/dist/functions/get-provider-sign-link.d.ts +3 -0
  144. package/dist/functions/get-provider-sign-link.js +146 -0
  145. package/dist/functions/get-signing-link.d.ts +1 -0
  146. package/dist/functions/get-signing-link.js +192 -0
  147. package/dist/functions/guest-print-setup-confirm.d.ts +1 -0
  148. package/dist/functions/guest-print-setup-confirm.js +126 -0
  149. package/dist/functions/guest-print-submit.d.ts +1 -0
  150. package/dist/functions/guest-print-submit.js +145 -0
  151. package/dist/functions/luma-webhook.d.ts +1 -0
  152. package/dist/functions/luma-webhook.js +123 -0
  153. package/dist/functions/manage-booking.d.ts +75 -0
  154. package/dist/functions/manage-booking.js +409 -0
  155. package/dist/functions/mcp.d.ts +16 -0
  156. package/dist/functions/mcp.js +51 -0
  157. package/dist/functions/member-door-action.d.ts +60 -0
  158. package/dist/functions/member-door-action.js +774 -0
  159. package/dist/functions/member-unifi-mapping.d.ts +15 -0
  160. package/dist/functions/member-unifi-mapping.js +198 -0
  161. package/dist/functions/membership-door-sync.d.ts +14 -0
  162. package/dist/functions/membership-door-sync.js +863 -0
  163. package/dist/functions/migration-collision-alert.copy.d.ts +7 -0
  164. package/dist/functions/migration-collision-alert.copy.js +207 -0
  165. package/dist/functions/migration-collision-alert.d.ts +7 -0
  166. package/dist/functions/migration-collision-alert.js +207 -0
  167. package/dist/functions/office-assignment-end.d.ts +12 -0
  168. package/dist/functions/office-assignment-end.js +140 -0
  169. package/dist/functions/portal-booking-access.d.ts +22 -0
  170. package/dist/functions/portal-booking-access.js +163 -0
  171. package/dist/functions/portal-list-invoices.d.ts +1 -0
  172. package/dist/functions/portal-list-invoices.js +90 -0
  173. package/dist/functions/portal-request-login.d.ts +7 -0
  174. package/dist/functions/portal-request-login.js +199 -0
  175. package/dist/functions/portal-resend-invite.d.ts +6 -0
  176. package/dist/functions/portal-resend-invite.js +225 -0
  177. package/dist/functions/portal-submit-event.d.ts +4 -0
  178. package/dist/functions/portal-submit-event.js +152 -0
  179. package/dist/functions/print-billing-recover.d.ts +1 -0
  180. package/dist/functions/print-billing-recover.js +83 -0
  181. package/dist/functions/print-billing-run.d.ts +1 -0
  182. package/dist/functions/print-billing-run.js +153 -0
  183. package/dist/functions/public-facts.d.ts +1 -0
  184. package/dist/functions/public-facts.js +141 -0
  185. package/dist/functions/push-send.d.ts +3 -0
  186. package/dist/functions/push-send.js +297 -0
  187. package/dist/functions/push-test.d.ts +3 -0
  188. package/dist/functions/push-test.js +215 -0
  189. package/dist/functions/request-portal-link.d.ts +7 -0
  190. package/dist/functions/request-portal-link.js +178 -0
  191. package/dist/functions/reschedule-booking.d.ts +50 -0
  192. package/dist/functions/reschedule-booking.js +571 -0
  193. package/dist/functions/review-ratings.d.ts +1 -0
  194. package/dist/functions/review-ratings.js +95 -0
  195. package/dist/functions/space-availability-range.d.ts +1 -0
  196. package/dist/functions/space-availability-range.js +109 -0
  197. package/dist/functions/stripe-db-reconcile.d.ts +7 -0
  198. package/dist/functions/stripe-db-reconcile.js +326 -0
  199. package/dist/functions/stripe-webhook.d.ts +46 -0
  200. package/dist/functions/stripe-webhook.js +2381 -0
  201. package/dist/functions/sync-gcal-blackouts.d.ts +1 -0
  202. package/dist/functions/sync-gcal-blackouts.js +251 -0
  203. package/dist/functions/timetable-event-register.d.ts +1 -0
  204. package/dist/functions/timetable-event-register.js +155 -0
  205. package/dist/functions/timetable-event-status.d.ts +1 -0
  206. package/dist/functions/timetable-event-status.js +86 -0
  207. package/dist/functions/timetable-spaces.d.ts +1 -0
  208. package/dist/functions/timetable-spaces.js +161 -0
  209. package/dist/functions/touch-pass-reconciler.d.ts +1 -0
  210. package/dist/functions/touch-pass-reconciler.js +688 -0
  211. package/dist/functions/touch-pass-signup.d.ts +1 -0
  212. package/dist/functions/touch-pass-signup.js +447 -0
  213. package/dist/functions/upload-booking-display-image.d.ts +4 -0
  214. package/dist/functions/upload-booking-display-image.js +159 -0
  215. package/dist/functions/virtual-onboarding-purge.d.ts +1 -0
  216. package/dist/functions/virtual-onboarding-purge.js +123 -0
  217. package/dist/functions/virtual-onboarding-submit.d.ts +1 -0
  218. package/dist/functions/virtual-onboarding-submit.js +303 -0
  219. package/dist/functions/voice-booking.d.ts +10 -0
  220. package/dist/functions/voice-booking.js +360 -0
  221. package/dist/functions/voice-day-pass.d.ts +15 -0
  222. package/dist/functions/voice-day-pass.js +269 -0
  223. package/dist/functions/voice-inquiry.d.ts +1 -0
  224. package/dist/functions/voice-inquiry.js +156 -0
  225. package/dist/functions/voice-membership-signup.d.ts +16 -0
  226. package/dist/functions/voice-membership-signup.js +277 -0
  227. package/dist/functions/voice-tour-availability.d.ts +1 -0
  228. package/dist/functions/voice-tour-availability.js +179 -0
  229. package/dist/functions/voice-tour-booking.d.ts +21 -0
  230. package/dist/functions/voice-tour-booking.js +308 -0
  231. package/dist/gcalSync.d.ts +29 -0
  232. package/dist/gcalSync.js +119 -0
  233. package/dist/ghlEventInquiry.d.ts +16 -0
  234. package/dist/ghlEventInquiry.js +116 -0
  235. package/dist/ghlNote.d.ts +5 -0
  236. package/dist/ghlNote.js +29 -0
  237. package/dist/ghlTask.d.ts +7 -0
  238. package/dist/ghlTask.js +39 -0
  239. package/dist/ghlVoiceInquiry.d.ts +26 -0
  240. package/dist/ghlVoiceInquiry.js +68 -0
  241. package/dist/guestPrintCapture.d.ts +217 -0
  242. package/dist/guestPrintCapture.js +362 -0
  243. package/dist/index.d.ts +3 -0
  244. package/{index.js → dist/index.js} +3 -2
  245. package/dist/lumaGhl.d.ts +19 -0
  246. package/dist/lumaGhl.js +147 -0
  247. package/dist/mailArrivalEmail.d.ts +15 -0
  248. package/dist/mailArrivalEmail.js +99 -0
  249. package/dist/manageToken.d.ts +64 -0
  250. package/dist/manageToken.js +261 -0
  251. package/dist/membership.d.ts +20 -0
  252. package/dist/membership.js +87 -0
  253. package/dist/membershipBusClient.d.ts +139 -0
  254. package/dist/membershipBusClient.js +443 -0
  255. package/dist/membershipWelcome.d.ts +117 -0
  256. package/dist/membershipWelcome.js +497 -0
  257. package/dist/migrationCheckout.d.ts +169 -0
  258. package/dist/migrationCheckout.js +250 -0
  259. package/dist/money.d.ts +20 -0
  260. package/dist/money.js +35 -0
  261. package/dist/ops.d.ts +27 -0
  262. package/dist/ops.js +87 -0
  263. package/dist/pacificDate.d.ts +8 -0
  264. package/{src/pacificDate.ts → dist/pacificDate.js} +76 -88
  265. package/dist/paymentLinkEmail.d.ts +15 -0
  266. package/dist/paymentLinkEmail.js +102 -0
  267. package/dist/policyAcknowledgment.d.ts +46 -0
  268. package/dist/policyAcknowledgment.js +58 -0
  269. package/dist/portalSession.d.ts +15 -0
  270. package/dist/portalSession.js +31 -0
  271. package/dist/pricing.d.ts +306 -0
  272. package/dist/pricing.js +788 -0
  273. package/dist/printBilling.d.ts +340 -0
  274. package/dist/printBilling.js +619 -0
  275. package/dist/printBillingAdapters.d.ts +29 -0
  276. package/dist/printBillingAdapters.js +130 -0
  277. package/dist/printCorrections.d.ts +175 -0
  278. package/dist/printCorrections.js +328 -0
  279. package/dist/rateLimit.d.ts +20 -0
  280. package/dist/rateLimit.js +70 -0
  281. package/dist/referralCredits.d.ts +5 -0
  282. package/{src/referralCredits.ts → dist/referralCredits.js} +27 -34
  283. package/dist/referralGrant.d.ts +49 -0
  284. package/dist/referralGrant.js +268 -0
  285. package/dist/rescheduleCredit.d.ts +98 -0
  286. package/dist/rescheduleCredit.js +263 -0
  287. package/dist/reservationWifiCode.d.ts +19 -0
  288. package/{src/reservationWifiCode.ts → dist/reservationWifiCode.js} +67 -81
  289. package/dist/retellCallAnalyzed.d.ts +18 -0
  290. package/dist/retellCallAnalyzed.js +91 -0
  291. package/dist/retellSignature.d.ts +14 -0
  292. package/dist/retellSignature.js +60 -0
  293. package/dist/signedUnpaidReminderEmail.d.ts +15 -0
  294. package/dist/signedUnpaidReminderEmail.js +111 -0
  295. package/dist/slackAlert.d.ts +13 -0
  296. package/dist/slackAlert.js +37 -0
  297. package/dist/stripeCoworkingPortal.d.ts +21 -0
  298. package/dist/stripeCoworkingPortal.js +80 -0
  299. package/dist/supabaseTestFakes.d.ts +67 -0
  300. package/dist/supabaseTestFakes.js +79 -0
  301. package/dist/supportTicketEmail.d.ts +16 -0
  302. package/dist/supportTicketEmail.js +98 -0
  303. package/dist/tier1Agreement.d.ts +51 -0
  304. package/dist/tier1Agreement.js +86 -0
  305. package/dist/unifiAccessPolicies.d.ts +36 -0
  306. package/dist/unifiAccessPolicies.js +185 -0
  307. package/dist/unifiGroups.d.ts +26 -0
  308. package/dist/unifiGroups.js +106 -0
  309. package/package.json +653 -169
  310. package/src/adminBookingCredit.test.ts +0 -451
  311. package/src/adminBookingCredit.ts +0 -239
  312. package/src/agreementCheckout.ts +0 -250
  313. package/src/agreementPortalEmail.ts +0 -128
  314. package/src/availability.test.ts +0 -25
  315. package/src/availability.ts +0 -201
  316. package/src/billingPortalLinkEmail.ts +0 -117
  317. package/src/bookingAgreementEmail.ts +0 -149
  318. package/src/bookingEffects.ts +0 -388
  319. package/src/bookingHoldReclaim.ts +0 -94
  320. package/src/busClient.ts +0 -268
  321. package/src/checkoutCoupon.test.ts +0 -675
  322. package/src/checkoutCoupon.ts +0 -455
  323. package/src/checkoutSessionParams.ts +0 -56
  324. package/src/commonsContract.ts +0 -175
  325. package/src/commonsDeposit.ts +0 -298
  326. package/src/commonsDepositWebhook.ts +0 -237
  327. package/src/conductorAdmin.ts +0 -141
  328. package/src/dayPassConfirmation.ts +0 -230
  329. package/src/dunningEmails.test.ts +0 -263
  330. package/src/dunningEmails.ts +0 -203
  331. package/src/email-templates/brand.ts +0 -93
  332. package/src/email-templates/email-change.tsx +0 -92
  333. package/src/email-templates/invite.tsx +0 -79
  334. package/src/email-templates/magic-link.tsx +0 -59
  335. package/src/email-templates/reauthentication.tsx +0 -60
  336. package/src/email-templates/recovery.tsx +0 -59
  337. package/src/email-templates/signup.tsx +0 -67
  338. package/src/functions/admin-cancel-membership.ts +0 -311
  339. package/src/functions/admin-change-membership-plan.ts +0 -312
  340. package/src/functions/admin-charge-guest-print.ts +0 -229
  341. package/src/functions/admin-correct-booking.ts +0 -333
  342. package/src/functions/admin-create-booking.ts +0 -460
  343. package/src/functions/admin-create-commons-event.ts +0 -244
  344. package/src/functions/admin-debug-boldsign-doc.ts +0 -93
  345. package/src/functions/admin-door-write.ts +0 -272
  346. package/src/functions/admin-issue-day-pass.ts +0 -231
  347. package/src/functions/admin-mark-booking-paid.ts +0 -203
  348. package/src/functions/admin-mint-billing-portal-link.ts +0 -168
  349. package/src/functions/admin-mint-portal-link.ts +0 -62
  350. package/src/functions/admin-photo-upload.ts +0 -128
  351. package/src/functions/admin-remove-team-member.ts +0 -150
  352. package/src/functions/admin-request-trial.ts +0 -366
  353. package/src/functions/admin-resend-commons-deposit-link.ts +0 -323
  354. package/src/functions/admin-reset-mfa.ts +0 -138
  355. package/src/functions/admin-retry-invoice-payment.test.ts +0 -567
  356. package/src/functions/admin-retry-invoice-payment.ts +0 -333
  357. package/src/functions/admin-reverse-coupon-redemption.ts +0 -98
  358. package/src/functions/admin-revoke-agreement.ts +0 -467
  359. package/src/functions/admin-send-commons-agreement.ts +0 -214
  360. package/src/functions/admin-set-credit-amount.ts +0 -123
  361. package/src/functions/admin-skip-commons-contract.ts +0 -165
  362. package/src/functions/admin-undo-membership-cancel.ts +0 -144
  363. package/src/functions/admin-wall-photo-write.ts +0 -141
  364. package/src/functions/auth-email-hook.ts +0 -259
  365. package/src/functions/boldsign-sender-identity.ts +0 -114
  366. package/src/functions/booking-availability.ts +0 -419
  367. package/src/functions/booking-member-preview.ts +0 -136
  368. package/src/functions/booking-status.ts +0 -149
  369. package/src/functions/conductor.ts +0 -505
  370. package/src/functions/create-agreement.ts +0 -537
  371. package/src/functions/create-booking.ts +0 -648
  372. package/src/functions/create-day-pass-checkout.ts +0 -218
  373. package/src/functions/create-portal-session.ts +0 -142
  374. package/src/functions/create-subscription-checkout.test.ts +0 -222
  375. package/src/functions/create-subscription-checkout.ts +0 -440
  376. package/src/functions/day-pass-status.ts +0 -89
  377. package/src/functions/dayStatus.ts +0 -71
  378. package/src/functions/diag-webpush-test.ts +0 -45
  379. package/src/functions/event-access-admin.ts +0 -277
  380. package/src/functions/event-access-store.ts +0 -334
  381. package/src/functions/ezeep-print-webhook.ts +0 -213
  382. package/src/functions/ezeep-usage-reconcile.ts +0 -299
  383. package/src/functions/fetch-avatar-original.ts +0 -457
  384. package/src/functions/get-provider-sign-link.ts +0 -155
  385. package/src/functions/get-signing-link.ts +0 -211
  386. package/src/functions/guest-print-setup-confirm.ts +0 -128
  387. package/src/functions/guest-print-submit.ts +0 -149
  388. package/src/functions/luma-webhook.ts +0 -165
  389. package/src/functions/manage-booking.ts +0 -472
  390. package/src/functions/mcp.ts +0 -67
  391. package/src/functions/member-door-action.test.ts +0 -1248
  392. package/src/functions/member-door-action.ts +0 -863
  393. package/src/functions/member-unifi-mapping.test.ts +0 -516
  394. package/src/functions/member-unifi-mapping.ts +0 -206
  395. package/src/functions/membership-door-sync.ts +0 -956
  396. package/src/functions/migration-collision-alert.copy.ts +0 -232
  397. package/src/functions/migration-collision-alert.test.ts +0 -349
  398. package/src/functions/migration-collision-alert.ts +0 -232
  399. package/src/functions/office-assignment-end.ts +0 -146
  400. package/src/functions/portal-booking-access.ts +0 -217
  401. package/src/functions/portal-list-invoices.ts +0 -99
  402. package/src/functions/portal-request-login.ts +0 -219
  403. package/src/functions/portal-resend-invite.ts +0 -248
  404. package/src/functions/portal-submit-event.ts +0 -168
  405. package/src/functions/print-billing-recover.ts +0 -97
  406. package/src/functions/print-billing-run.ts +0 -183
  407. package/src/functions/public-facts.ts +0 -168
  408. package/src/functions/push-send.ts +0 -348
  409. package/src/functions/push-test.ts +0 -234
  410. package/src/functions/request-portal-link.ts +0 -211
  411. package/src/functions/reschedule-booking.ts +0 -649
  412. package/src/functions/review-ratings.ts +0 -113
  413. package/src/functions/space-availability-range.acceptance.test.ts +0 -161
  414. package/src/functions/space-availability-range.ts +0 -142
  415. package/src/functions/stripe-db-reconcile.ts +0 -319
  416. package/src/functions/stripe-webhook.moved-regression.test.ts +0 -78
  417. package/src/functions/stripe-webhook.ts +0 -2595
  418. package/src/functions/sync-gcal-blackouts.ts +0 -298
  419. package/src/functions/timetable-event-register.ts +0 -162
  420. package/src/functions/timetable-event-status.ts +0 -90
  421. package/src/functions/timetable-spaces.ts +0 -219
  422. package/src/functions/touch-pass-reconciler.ts +0 -689
  423. package/src/functions/touch-pass-signup.ts +0 -478
  424. package/src/functions/upload-booking-display-image.ts +0 -179
  425. package/src/functions/virtual-onboarding-purge.ts +0 -134
  426. package/src/functions/virtual-onboarding-submit.ts +0 -315
  427. package/src/functions/voice-booking.ts +0 -453
  428. package/src/functions/voice-day-pass.ts +0 -346
  429. package/src/functions/voice-inquiry.test.ts +0 -301
  430. package/src/functions/voice-inquiry.ts +0 -198
  431. package/src/functions/voice-membership-signup.ts +0 -355
  432. package/src/functions/voice-tour-availability.ts +0 -204
  433. package/src/functions/voice-tour-booking.ts +0 -429
  434. package/src/gcalSync.ts +0 -142
  435. package/src/ghlEventInquiry.ts +0 -143
  436. package/src/ghlNote.ts +0 -34
  437. package/src/ghlTask.ts +0 -48
  438. package/src/ghlVoiceInquiry.ts +0 -90
  439. package/src/guestPrintCapture.test.ts +0 -722
  440. package/src/guestPrintCapture.ts +0 -538
  441. package/src/lumaGhl.ts +0 -195
  442. package/src/mailArrivalEmail.ts +0 -121
  443. package/src/manageToken.ts +0 -363
  444. package/src/membership.ts +0 -109
  445. package/src/membershipBusClient.ts +0 -537
  446. package/src/membershipWelcome.ts +0 -683
  447. package/src/migrationCheckout.ts +0 -366
  448. package/src/money.ts +0 -36
  449. package/src/ops.ts +0 -97
  450. package/src/paymentLinkEmail.ts +0 -123
  451. package/src/policyAcknowledgment.test.ts +0 -50
  452. package/src/policyAcknowledgment.ts +0 -96
  453. package/src/portalSession.ts +0 -46
  454. package/src/pricing.test.ts +0 -660
  455. package/src/pricing.ts +0 -1025
  456. package/src/printBilling.test.ts +0 -750
  457. package/src/printBilling.ts +0 -891
  458. package/src/printBillingAdapters.ts +0 -169
  459. package/src/printCorrections.test.ts +0 -348
  460. package/src/printCorrections.ts +0 -496
  461. package/src/rateLimit.ts +0 -82
  462. package/src/referralCredits.test.ts +0 -31
  463. package/src/referralGrant.ts +0 -321
  464. package/src/rescheduleCredit.test.ts +0 -521
  465. package/src/rescheduleCredit.ts +0 -337
  466. package/src/reservationWifiCode.test.ts +0 -69
  467. package/src/retellCallAnalyzed.test.ts +0 -167
  468. package/src/retellCallAnalyzed.ts +0 -113
  469. package/src/retellSignature.test.ts +0 -137
  470. package/src/retellSignature.ts +0 -82
  471. package/src/signedUnpaidReminderEmail.test.ts +0 -246
  472. package/src/signedUnpaidReminderEmail.ts +0 -132
  473. package/src/slackAlert.ts +0 -38
  474. package/src/stripeCoworkingPortal.ts +0 -91
  475. package/src/supabaseTestFakes.ts +0 -131
  476. package/src/supportTicketEmail.ts +0 -119
  477. package/src/tier1Agreement.ts +0 -125
  478. package/src/unifiAccessPolicies.ts +0 -228
  479. package/src/unifiGroups.ts +0 -129
@@ -0,0 +1,774 @@
1
+ // Graniteer Access v1 — the tenant-app side of the four member-initiated access actions.
2
+ // Implements the "tenant-app Supabase edge function member-door-action (NEW)" box in
3
+ // graniteer-access-v8-plan.md §4, for the four ftw-middleware member routes:
4
+ //
5
+ // unlock -> POST /member/unlock
6
+ // pin_regenerate -> POST /member/pin/regenerate
7
+ // activity -> GET /member/activity
8
+ // wifi_voucher -> POST /member/wifi-voucher
9
+ //
10
+ // The tenant app is the SOLE gateway between Graniteer and ftw-middleware/UniFi (plan §4,
11
+ // "not fixed by design"). This function performs NO UniFi work itself and holds no
12
+ // UniFi credential; it authenticates the member, decides the tenant app's half of the dual
13
+ // authorization check, mints the identity assertion, and forwards.
14
+ //
15
+ // ---------------------------------------------------------------------------
16
+ // IDENTITY — the whole point of this function (plan, Identity section)
17
+ // ---------------------------------------------------------------------------
18
+ // The member subject is taken ONLY from the Supabase session Supabase itself
19
+ // validated (resolvePortalSession -> admin.auth.getUser(jwt)). A request body
20
+ // `sub` / `user_id` / `unifi_user_id` / `actor_id` is NEVER read, compared, or
21
+ // preferred — see IGNORED_BODY_FIELDS below, which exists so that a future editor
22
+ // adding a field has to notice.
23
+ //
24
+ // The assertion is minted SERVER-SIDE here and never round-tripped through the
25
+ // client (plan R2-5): the browser never sees or holds it. Claims are
26
+ // {sub, aud, iss, act, door_id, iat, nbf, exp, jti} with exp <= 120s out, signed
27
+ // Ed25519 ("EdDSA"). ftw-middleware MUST pin the algorithm server-side and never
28
+ // read `alg` from the header (closes the alg:none acceptance class).
29
+ //
30
+ // `door_id` travels in the assertion, not the outbound body — the outbound bodies
31
+ // are literally `{}` — so there is no body field for the middleware to be tempted
32
+ // to prefer.
33
+ //
34
+ // ---------------------------------------------------------------------------
35
+ // FOURTH SIBLING HMAC SCHEME — "d1"
36
+ // ---------------------------------------------------------------------------
37
+ // This repo has no single "shared admin token" to ftw-middleware; it has four
38
+ // byte-distinct per-route HMAC constructions (busClient "v1" / BUS_HMAC_SECRET,
39
+ // membershipBusClient "m1" / BUS_HMAC_SECRET_MEMBERSHIP, portal-resend-invite
40
+ // "r1" / BUS_HMAC_SECRET_RESEND, event-access-admin "e1" / the
41
+ // get_event_access_hmac_secret RPC). This is the fifth prefix and the fourth
42
+ // env-held secret: "d1" under MEMBER_ACTIONS_HMAC_SECRET. It proves only "this
43
+ // call came from the tenant app", NEVER "this call is about member X" — that is the
44
+ // assertion's job, and the two must not be conflated.
45
+ //
46
+ // Canonical message — 5 lines joined with "\n", no trailing newline:
47
+ // d1
48
+ // {action} one of MEMBER_ACTIONS, verbatim
49
+ // {ts} unix seconds, decimal, as sent in the timestamp header
50
+ // {assertion_sha256} sha256 hex of the exact assertion JWT string sent
51
+ // {payload_sha256} sha256 hex of the exact POST body bytes, or of the
52
+ // canonical query string for the GET (see PAYLOAD below)
53
+ //
54
+ // Binding the assertion hash into the HMAC means a leaked assertion cannot be
55
+ // replayed at the middleware by anyone who does not also hold the d1 secret, and
56
+ // binding {action} means an assertion minted for `activity` cannot be presented
57
+ // at /member/unlock.
58
+ //
59
+ // PAYLOAD: every POST body is `{}` (all parameters are either in the assertion or
60
+ // fixed server-side on the middleware per plan §6.2's "non-member-configurable"
61
+ // rule). The GET carries `?limit=N`, and its canonical query string `limit=N` is
62
+ // what gets hashed.
63
+ //
64
+ // ---------------------------------------------------------------------------
65
+ // FAIL DIRECTIONS (deliberately not uniform — plan, Rate limiting section)
66
+ // ---------------------------------------------------------------------------
67
+ // * Auth / identity / entitlement / signing: FAIL CLOSED. Anything unknown denies.
68
+ // * Rate limiter backend: FAILS OPEN (allow + warn) — that is checkRateLimit's
69
+ // existing documented behaviour and is the correct direction for availability
70
+ // protection, deliberately opposite to the middleware's jti replay cache.
71
+ // * Ambiguous unlock outcome (timeout, 5xx, missing/!= 'unlocked' outcome): report
72
+ // "couldn't confirm — use your card", NEVER "unlocked", never "denied", and
73
+ // never auto-retry (plan finding #12: a retry risks a double-pulse or a late
74
+ // unlock with nobody present).
75
+ //
76
+ // Every authorization refusal returns ONE uniform opaque body (`not_permitted`)
77
+ // regardless of which check failed, so the response cannot be used to enumerate
78
+ // door inventory or another member's tier (plan entitlement step 7). The specific
79
+ // reason goes to ops_events only.
80
+ import { createClient } from '@supabase/supabase-js';
81
+ import { clientIp, checkRateLimit } from '../rateLimit.js';
82
+ import { resolvePortalSession } from '../portalSession.js';
83
+ import { computeEntitlement } from '../membership.js';
84
+ import { logOps } from '../ops.js';
85
+ const corsHeaders = {
86
+ 'Access-Control-Allow-Origin': '*',
87
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
88
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
89
+ };
90
+ // ---------------------------------------------------------------------------
91
+ // REQUIRED SUPABASE SECRETS for Graniteer Access v1 (this feature, both
92
+ // functions). This repo has no central secret manifest — the convention is the
93
+ // per-function `*_ENV` constant block, so this list is the manifest. Everything
94
+ // here defaults to absent, and absent means the feature is inert, never open.
95
+ //
96
+ // FTW_MIDDLEWARE_BASE_URL https:// base of the ftw-middleware deploy
97
+ // MEMBER_ACTIONS_HMAC_SECRET the "d1" outbound HMAC secret
98
+ // MEMBER_ASSERTION_SIGNING_KEY Ed25519 PKCS#8 (PEM or bare base64)
99
+ // MEMBER_ASSERTION_ISS assertion `iss`
100
+ // MEMBER_ASSERTION_AUD assertion `aud` (per-deployment/tenant)
101
+ // MEMBER_ASSERTION_TTL_SECONDS optional; clamped to [10, 120], default 60
102
+ // MEMBER_ACTIONS_ENABLED master gate, default false
103
+ // MEMBER_ACTIONS_ALLOWLIST Supabase `sub` list; EMPTY DENIES EVERYONE
104
+ // MEMBER_ACTIONS_MAPPING_SECRET inbound bearer for member-unifi-mapping
105
+ // (see that function; must differ from every
106
+ // secret above and from the service-role key —
107
+ // keyIsolationViolations() enforces it)
108
+ //
109
+ // No hardcoded live host. Every other tenant-app -> middleware caller in this repo
110
+ // hardcodes `https://ftw.granitecity.io`; this one does not, so the function is
111
+ // inert (503 not_configured) until an operator sets the base URL as a secret.
112
+ // That also keeps a mis-deployed member-facing door route from ever reaching the
113
+ // real middleware by default.
114
+ // ---------------------------------------------------------------------------
115
+ const BASE_URL_ENV = 'FTW_MIDDLEWARE_BASE_URL';
116
+ const HMAC_SECRET_ENV = 'MEMBER_ACTIONS_HMAC_SECRET';
117
+ const SIGNING_KEY_ENV = 'MEMBER_ASSERTION_SIGNING_KEY';
118
+ const ASSERTION_ISS_ENV = 'MEMBER_ASSERTION_ISS';
119
+ const ASSERTION_AUD_ENV = 'MEMBER_ASSERTION_AUD';
120
+ const ASSERTION_TTL_ENV = 'MEMBER_ASSERTION_TTL_SECONDS';
121
+ export const ASSERTION_HEADER = 'X-Member-Action-Assertion';
122
+ export const SIGNATURE_HEADER = 'X-Member-Action-Signature';
123
+ export const TIMESTAMP_HEADER = 'X-Member-Action-Timestamp';
124
+ export const SCHEME_HEADER = 'X-Member-Action-Scheme';
125
+ export const HMAC_SCHEME = 'd1';
126
+ /** Plan pins exp at <= 120s out throughout; the jti retention floor derives from it. */
127
+ export const ASSERTION_MAX_TTL_SECONDS = 120;
128
+ const ASSERTION_MIN_TTL_SECONDS = 10;
129
+ const ASSERTION_DEFAULT_TTL_SECONDS = 60;
130
+ const MAX_BODY_BYTES = 4096;
131
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
132
+ export const MEMBER_ACTIONS = ['unlock', 'pin_regenerate', 'activity', 'wifi_voucher'];
133
+ const ROUTES = {
134
+ unlock: {
135
+ method: 'POST',
136
+ path: '/member/unlock',
137
+ // Shorter than the other writes on purpose: the middleware's own chain deadline
138
+ // sits inside its 5s lock-acquire budget, so a call still open at 15s is already
139
+ // an outcome we must report as unconfirmed rather than keep waiting on.
140
+ timeoutMs: 15_000,
141
+ limits: [
142
+ ['member-door-unlock-burst', 1, 5],
143
+ ['member-door-unlock', 10, 300],
144
+ ],
145
+ },
146
+ pin_regenerate: {
147
+ method: 'POST',
148
+ path: '/member/pin/regenerate',
149
+ timeoutMs: 15_000,
150
+ limits: [['member-door-pin-regenerate', 3, 3600]],
151
+ },
152
+ activity: {
153
+ method: 'GET',
154
+ path: '/member/activity',
155
+ timeoutMs: 10_000,
156
+ limits: [['member-door-activity', 60, 300]],
157
+ },
158
+ wifi_voucher: {
159
+ method: 'POST',
160
+ path: '/member/wifi-voucher',
161
+ timeoutMs: 15_000,
162
+ // Plan §6.2's placeholder cap of 3/member/day, pending Kyle's product call.
163
+ limits: [['member-door-wifi-voucher', 3, 86_400]],
164
+ },
165
+ };
166
+ /**
167
+ * Fields a caller might send hoping they get read. They never are. Listed so this
168
+ * is a deliberate, greppable refusal rather than an omission, and so a future
169
+ * editor adding body handling has to walk past it.
170
+ */
171
+ export const IGNORED_BODY_FIELDS = [
172
+ 'sub', 'user_id', 'auth_user_id', 'member_id', 'membership_id', 'email',
173
+ 'unifi_user_id', 'unifi_access_user_id', 'actor_id', 'actor_name',
174
+ ];
175
+ /**
176
+ * Explicit SCALAR allowlists for what may be handed back to the browser. Same
177
+ * discipline as membership-door-sync's two-field allowlist: never spread a
178
+ * middleware object, never pass a `_source` through raw (plan finding #5).
179
+ */
180
+ const RESPONSE_FIELDS = {
181
+ unlock: ['outcome', 'door_name', 'confirmed_at'],
182
+ // `pin` is shown once and never persisted anywhere (plan finding #11's resolved
183
+ // recommendation: status-only + regenerate-to-reveal). It is deliberately absent
184
+ // from every audit payload built below.
185
+ //
186
+ // `group_check` is the middleware's before/after `GET /user_groups/{id}/users`
187
+ // reverse-index verdict around the PIN write (plan, PIN regeneration section).
188
+ // It is allowlisted specifically so a 'mismatch' — a PIN write that also
189
+ // silently cost the member a door-group membership, the §4.2b incident class
190
+ // this check exists to catch — SURVIVES projection and reaches the tenant app's own
191
+ // ops_events. Dropping it here would have left the audit row reading
192
+ // `outcome: 'ok'` while the middleware was shouting.
193
+ pin_regenerate: ['pin', 'pin_length', 'issued_at', 'group_check'],
194
+ activity: [],
195
+ wifi_voucher: ['code', 'expires_at', 'time_limit_minutes', 'authorized_guest_limit'],
196
+ };
197
+ const ACTIVITY_HIT_FIELDS = ['at', 'door_id', 'door_name', 'result', 'method'];
198
+ const ACTIVITY_DEFAULT_LIMIT = 25;
199
+ const ACTIVITY_MAX_LIMIT = 50;
200
+ function json(status, body) {
201
+ return new Response(JSON.stringify(body), {
202
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
203
+ });
204
+ }
205
+ /**
206
+ * The ONE uniform opaque refusal. Used for every authorization outcome —
207
+ * unknown member, no UniFi mapping, ambiguous mapping, not entitled, not
208
+ * allowlisted, unknown/unprovisioned door, and the middleware's own denial —
209
+ * so differential responses cannot enumerate doors or tiers.
210
+ */
211
+ function denied() {
212
+ return json(403, { ok: false, error: 'not_permitted' });
213
+ }
214
+ function b64urlNoPad(bytes) {
215
+ let s = '';
216
+ for (const b of bytes)
217
+ s += String.fromCharCode(b);
218
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
219
+ }
220
+ function b64urlText(text) {
221
+ return b64urlNoPad(new TextEncoder().encode(text));
222
+ }
223
+ function toHex(bytes) {
224
+ let out = '';
225
+ for (const b of bytes)
226
+ out += b.toString(16).padStart(2, '0');
227
+ return out;
228
+ }
229
+ async function sha256Hex(text) {
230
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
231
+ return toHex(new Uint8Array(digest));
232
+ }
233
+ /** Canonical "d1" message. Must match member_actions.py on ftw-middleware exactly. */
234
+ export function canonicalMemberActionMessage(action, ts, assertionHashHex, payloadHashHex) {
235
+ return [HMAC_SCHEME, action, ts, assertionHashHex, payloadHashHex].join('\n');
236
+ }
237
+ async function signD1(secret, msg) {
238
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
239
+ const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg));
240
+ return b64urlNoPad(new Uint8Array(sig));
241
+ }
242
+ /** Accepts a PKCS#8 key as PEM or as bare base64 DER. */
243
+ function decodePkcs8(raw) {
244
+ const b64 = raw
245
+ .replace(/-----BEGIN [A-Z0-9 ]+-----/g, '')
246
+ .replace(/-----END [A-Z0-9 ]+-----/g, '')
247
+ .replace(/\s+/g, '');
248
+ if (!b64)
249
+ return null;
250
+ try {
251
+ const bin = atob(b64);
252
+ const out = new Uint8Array(bin.length);
253
+ for (let i = 0; i < bin.length; i++)
254
+ out[i] = bin.charCodeAt(i);
255
+ return out;
256
+ }
257
+ catch {
258
+ return null;
259
+ }
260
+ }
261
+ let signingKeyCache = null;
262
+ async function getSigningKey(raw) {
263
+ if (signingKeyCache?.raw === raw)
264
+ return signingKeyCache.key;
265
+ const der = decodePkcs8(raw);
266
+ if (!der)
267
+ return null;
268
+ try {
269
+ const key = await crypto.subtle.importKey('pkcs8', der, { name: 'Ed25519' }, false, ['sign']);
270
+ signingKeyCache = { raw, key };
271
+ return key;
272
+ }
273
+ catch {
274
+ return null;
275
+ }
276
+ }
277
+ export function assertionTtlSeconds(raw) {
278
+ const t = (raw ?? '').trim();
279
+ // Blank must fall to the default, not through Number('') === 0 into the floor.
280
+ if (t === '')
281
+ return ASSERTION_DEFAULT_TTL_SECONDS;
282
+ const n = Number(t);
283
+ if (!Number.isFinite(n))
284
+ return ASSERTION_DEFAULT_TTL_SECONDS;
285
+ return Math.min(ASSERTION_MAX_TTL_SECONDS, Math.max(ASSERTION_MIN_TTL_SECONDS, Math.floor(n)));
286
+ }
287
+ /**
288
+ * Mints the Ed25519 assertion. `alg` is written, never read: the verifier pins
289
+ * Ed25519 server-side, so this header is documentation for humans and must not
290
+ * be treated as an algorithm selector by ftw-middleware.
291
+ */
292
+ export async function mintAssertion(keyRaw, claims) {
293
+ const key = await getSigningKey(keyRaw);
294
+ if (!key)
295
+ return null;
296
+ const signingInput = `${b64urlText(JSON.stringify({ alg: 'EdDSA', crv: 'Ed25519', typ: 'JWT' }))}.` +
297
+ `${b64urlText(JSON.stringify(claims))}`;
298
+ const sig = await crypto.subtle.sign({ name: 'Ed25519' }, key, new TextEncoder().encode(signingInput));
299
+ return `${signingInput}.${b64urlNoPad(new Uint8Array(sig))}`;
300
+ }
301
+ /**
302
+ * Plan R2-2: "refuse to start if the assertion-signing key equals the
303
+ * membership-sync admin token value." An edge function has no boot phase, so the
304
+ * closest equivalent is: evaluate at module load, and refuse EVERY request while
305
+ * a violation stands. Checked against every tenant-app -> middleware secret this repo
306
+ * holds in env, plus the service-role key, plus d1's own secret.
307
+ */
308
+ export function keyIsolationViolations(env) {
309
+ const signing = (env[SIGNING_KEY_ENV] ?? '').trim();
310
+ const d1 = (env[HMAC_SECRET_ENV] ?? '').trim();
311
+ const others = [
312
+ ['BUS_HMAC_SECRET', (env.BUS_HMAC_SECRET ?? '').trim()],
313
+ ['BUS_HMAC_SECRET_MEMBERSHIP', (env.BUS_HMAC_SECRET_MEMBERSHIP ?? '').trim()],
314
+ ['BUS_HMAC_SECRET_RESEND', (env.BUS_HMAC_SECRET_RESEND ?? '').trim()],
315
+ ['SUPABASE_SERVICE_ROLE_KEY', (env.SUPABASE_SERVICE_ROLE_KEY ?? '').trim()],
316
+ // member-unifi-mapping's inbound bearer. It gates ftw-middleware's INDEPENDENT
317
+ // sub -> UniFi-user-id resolution, so if it were the same value as anything
318
+ // the tenant app signs with, the dual check would collapse back into a single one.
319
+ ['MEMBER_ACTIONS_MAPPING_SECRET', (env.MEMBER_ACTIONS_MAPPING_SECRET ?? '').trim()],
320
+ ];
321
+ const out = [];
322
+ for (const [name, value] of others) {
323
+ if (value && signing && value === signing)
324
+ out.push(`${SIGNING_KEY_ENV}==${name}`);
325
+ if (value && d1 && value === d1)
326
+ out.push(`${HMAC_SECRET_ENV}==${name}`);
327
+ }
328
+ if (signing && d1 && signing === d1)
329
+ out.push(`${SIGNING_KEY_ENV}==${HMAC_SECRET_ENV}`);
330
+ return out;
331
+ }
332
+ // --------------------------------------------------------------------------
333
+ // Gating (plan, Gating section — ships WITH identity, not later)
334
+ // --------------------------------------------------------------------------
335
+ const TRUTHY = new Set(['1', 'true', 't', 'yes', 'y', 'on']);
336
+ const FALSY = new Set(['', '0', 'false', 'f', 'no', 'n', 'off']);
337
+ /**
338
+ * Parsed as a STRING with an explicit truthy check, never a coerced bool:
339
+ * anything unrecognized becomes `false` plus a warning. A malformed bool on this
340
+ * system's existing flags is a documented whole-container crash on the
341
+ * middleware, and a new feature flag must not be able to cause that.
342
+ */
343
+ export function parseEnabled(raw) {
344
+ const v = (raw ?? '').trim().toLowerCase();
345
+ if (TRUTHY.has(v))
346
+ return { enabled: true, malformed: false };
347
+ if (FALSY.has(v))
348
+ return { enabled: false, malformed: false };
349
+ return { enabled: false, malformed: true };
350
+ }
351
+ /**
352
+ * Keyed on the verified Supabase `sub`, explicitly NOT a fourth email list
353
+ * alongside PROTECTED_EMAILS / MEMBERSHIP_REVOKE_ALLOWLIST / QA_FIXTURE_EMAILS.
354
+ * An EMPTY allowlist denies everyone — not "no filter applied".
355
+ */
356
+ export function parseAllowlist(raw) {
357
+ return new Set((raw ?? '').split(/[\s,;]+/).map((s) => s.trim()).filter(Boolean));
358
+ }
359
+ // --------------------------------------------------------------------------
360
+ // Response projection
361
+ // --------------------------------------------------------------------------
362
+ function isScalar(v) {
363
+ return v === null || ['string', 'number', 'boolean'].includes(typeof v);
364
+ }
365
+ function pickScalars(src, fields) {
366
+ const out = {};
367
+ for (const f of fields) {
368
+ if (f in src && isScalar(src[f]))
369
+ out[f] = src[f];
370
+ }
371
+ return out;
372
+ }
373
+ /** Mirrors doorGateOk() in membership-door-sync/index.ts. Kept identical on purpose. */
374
+ function doorGateOk(notBefore, now) {
375
+ if (notBefore == null)
376
+ return true;
377
+ const t = Date.parse(notBefore);
378
+ if (!Number.isFinite(t))
379
+ return false;
380
+ return t <= now;
381
+ }
382
+ export async function handleMemberDoorAction(req) {
383
+ if (req.method === 'OPTIONS')
384
+ return new Response('ok', { headers: corsHeaders });
385
+ if (req.method !== 'POST')
386
+ return json(405, { ok: false, error: 'method_not_allowed' });
387
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? '';
388
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '';
389
+ if (!SUPABASE_URL || !SERVICE_ROLE_KEY)
390
+ return json(503, { ok: false, error: 'not_configured' });
391
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
392
+ auth: { persistSession: false, autoRefreshToken: false },
393
+ });
394
+ // ---- Step 1: identity, from Supabase's own verified auth context ---------
395
+ // Nothing below this line reads a caller-supplied subject. Note that a
396
+ // Supabase anon/publishable key presented as a bearer simply fails getUser,
397
+ // which is exactly what we want — verify_jwt at the gateway accepts it, so
398
+ // this check, not the gateway, is the real gate.
399
+ const session = await resolvePortalSession(req, admin);
400
+ if (!session)
401
+ return json(401, { ok: false, error: 'unauthorized' });
402
+ // ---- Step 2: body shape (parsed before authorization only to know which
403
+ // action's buckets and rules to apply; no identity is read from it) --------
404
+ const declaredLen = Number(req.headers.get('content-length') ?? '');
405
+ if (Number.isFinite(declaredLen) && declaredLen > MAX_BODY_BYTES) {
406
+ return json(413, { ok: false, error: 'payload_too_large' });
407
+ }
408
+ const bodyText = await req.text().catch(() => '');
409
+ if (new TextEncoder().encode(bodyText).byteLength > MAX_BODY_BYTES) {
410
+ return json(413, { ok: false, error: 'payload_too_large' });
411
+ }
412
+ let body = {};
413
+ try {
414
+ const parsed = JSON.parse(bodyText || '{}');
415
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
416
+ body = parsed;
417
+ }
418
+ }
419
+ catch {
420
+ return json(400, { ok: false, error: 'invalid_json' });
421
+ }
422
+ const action = String(body.action ?? '');
423
+ if (!MEMBER_ACTIONS.includes(action)) {
424
+ return json(400, { ok: false, error: 'unknown_action' });
425
+ }
426
+ const route = ROUTES[action];
427
+ // ---- Step 3: rate limits, keyed on the verified sub (never email, never a
428
+ // single global bucket — plan's global-lockout hazard) --------------------
429
+ const buckets = await Promise.all([
430
+ checkRateLimit(admin, 'member-door-action-ip', clientIp(req), 120, 300),
431
+ ...route.limits.map(([name, max, win]) => checkRateLimit(admin, name, session.id, max, win)),
432
+ ]);
433
+ if (buckets.some((ok) => !ok))
434
+ return json(429, { ok: false, error: 'rate_limited' });
435
+ // ---- Step 4: feature gate + allowlist ----------------------------------
436
+ const gate = parseEnabled(Deno.env.get('MEMBER_ACTIONS_ENABLED'));
437
+ if (gate.malformed) {
438
+ console.warn('[member-door-action] MEMBER_ACTIONS_ENABLED is not a recognized boolean; treating as false');
439
+ }
440
+ if (!gate.enabled)
441
+ return json(503, { ok: false, error: 'not_configured' });
442
+ const allowlist = parseAllowlist(Deno.env.get('MEMBER_ACTIONS_ALLOWLIST'));
443
+ if (!allowlist.has(session.id)) {
444
+ await logOps(admin, 'member_door_action_denied', {
445
+ action, actor_uid: session.id, reason: 'not_allowlisted',
446
+ }, { severity: 'warning' });
447
+ return denied();
448
+ }
449
+ // ---- Step 5: the tenant app's half of the dual authorization check ---------------
450
+ // Requires a real auth_user_id linkage. Deliberately NO email fallback for
451
+ // still-unlinked rows (portal-resend-invite has one): an email-matched,
452
+ // unlinked membership is a weaker identity binding than a physical door
453
+ // should accept.
454
+ const { data: rowsRaw, error: rowsErr } = await admin
455
+ .from('memberships')
456
+ .select('id,status,pricing_grace_ends_at,door_managed,door_access_not_before,unifi_access_user_id')
457
+ .eq('auth_user_id', session.id)
458
+ .order('created_at', { ascending: true })
459
+ .limit(20);
460
+ if (rowsErr) {
461
+ await logOps(admin, 'member_door_action_lookup_failed', {
462
+ action, actor_uid: session.id, message: rowsErr.message,
463
+ }, { severity: 'error' });
464
+ return json(500, { ok: false, error: 'lookup_failed' });
465
+ }
466
+ const rows = (rowsRaw ?? []);
467
+ const deny = async (reason, extra = {}) => {
468
+ await logOps(admin, 'member_door_action_denied', {
469
+ action, actor_uid: session.id, reason, ...extra,
470
+ }, { severity: 'warning' });
471
+ return denied();
472
+ };
473
+ // Ambiguity is evaluated across ALL of this member's rows, entitled or not: if
474
+ // two rows disagree about which UniFi user this human is, the mapping is not
475
+ // authoritative and no door decision may rest on it (plan R2-4/R2-30).
476
+ const mappedIds = Array.from(new Set(rows.map((r) => (r.unifi_access_user_id ?? '').trim()).filter(Boolean)));
477
+ if (mappedIds.length > 1) {
478
+ await logOps(admin, 'member_door_action_ambiguous_mapping', {
479
+ action, actor_uid: session.id, mapping_count: mappedIds.length,
480
+ }, { severity: 'error' });
481
+ return denied();
482
+ }
483
+ const unifiUserId = mappedIds[0] ?? '';
484
+ if (!unifiUserId)
485
+ return await deny('no_unifi_mapping');
486
+ const now = Date.now();
487
+ const managed = rows.filter((r) => r.door_managed === true);
488
+ if (managed.length === 0)
489
+ return await deny('not_door_managed');
490
+ // computeEntitlement is imported, never forked — _shared/membership.ts is the
491
+ // single source of truth shared with pricing and membership-door-sync. The
492
+ // door_access_not_before gate is layered after it, same order as the sync.
493
+ const entitled = managed.filter((r) => computeEntitlement(r, now) && doorGateOk(r.door_access_not_before, now));
494
+ if (entitled.length === 0)
495
+ return await deny('not_entitled');
496
+ const membershipId = entitled[0].id;
497
+ // ---- Step 6: per-action parameters (still no identity from the body) ----
498
+ let unifiDoorId = null;
499
+ let gcDoorId = null;
500
+ let activityLimit = ACTIVITY_DEFAULT_LIMIT;
501
+ if (action === 'unlock') {
502
+ gcDoorId = typeof body.door_id === 'string' ? body.door_id.trim() : '';
503
+ // Only a malformed *shape* answers with a distinguishable 400. An id that is
504
+ // well-formed but unknown/unprovisioned falls through to the uniform opaque
505
+ // refusal, so this cannot be used to probe door inventory.
506
+ if (!gcDoorId || !UUID.test(gcDoorId))
507
+ return json(400, { ok: false, error: 'invalid_payload' });
508
+ const { data: door, error: doorErr } = await admin
509
+ .from('doors').select('id,name,unifi_door_id,status').eq('id', gcDoorId).maybeSingle();
510
+ if (doorErr) {
511
+ await logOps(admin, 'member_door_action_lookup_failed', {
512
+ action, actor_uid: session.id, message: doorErr.message,
513
+ }, { severity: 'error' });
514
+ return json(500, { ok: false, error: 'lookup_failed' });
515
+ }
516
+ const resolved = door?.unifi_door_id ?? null;
517
+ if (!door)
518
+ return await deny('door_not_found', { gc_door_id: gcDoorId });
519
+ if (!resolved || resolved === 'PENDING') {
520
+ return await deny('door_not_provisioned', { gc_door_id: gcDoorId });
521
+ }
522
+ // Outbound door_id MUST be the UniFi id — the middleware calls the controller
523
+ // directly and has never heard of the tenant app's doors.id.
524
+ unifiDoorId = resolved;
525
+ }
526
+ if (action === 'activity') {
527
+ const raw = Number(body.limit ?? ACTIVITY_DEFAULT_LIMIT);
528
+ activityLimit = Number.isFinite(raw)
529
+ ? Math.min(ACTIVITY_MAX_LIMIT, Math.max(1, Math.floor(raw)))
530
+ : ACTIVITY_DEFAULT_LIMIT;
531
+ }
532
+ // ---- Step 7: signing material ------------------------------------------
533
+ const baseUrl = (Deno.env.get(BASE_URL_ENV) ?? '').trim().replace(/\/+$/, '');
534
+ const hmacSecret = (Deno.env.get(HMAC_SECRET_ENV) ?? '').trim();
535
+ const signingKeyRaw = (Deno.env.get(SIGNING_KEY_ENV) ?? '').trim();
536
+ const iss = (Deno.env.get(ASSERTION_ISS_ENV) ?? '').trim();
537
+ const aud = (Deno.env.get(ASSERTION_AUD_ENV) ?? '').trim();
538
+ if (!baseUrl || !hmacSecret || !signingKeyRaw || !iss || !aud) {
539
+ await logOps(admin, 'member_door_action_not_configured', {
540
+ action,
541
+ missing: [
542
+ !baseUrl ? BASE_URL_ENV : null,
543
+ !hmacSecret ? HMAC_SECRET_ENV : null,
544
+ !signingKeyRaw ? SIGNING_KEY_ENV : null,
545
+ !iss ? ASSERTION_ISS_ENV : null,
546
+ !aud ? ASSERTION_AUD_ENV : null,
547
+ ].filter(Boolean),
548
+ }, { severity: 'error' });
549
+ return json(503, { ok: false, error: 'not_configured' });
550
+ }
551
+ if (!/^https:\/\//i.test(baseUrl)) {
552
+ await logOps(admin, 'member_door_action_not_configured', {
553
+ action, reason: 'base_url_not_https',
554
+ }, { severity: 'error' });
555
+ return json(503, { ok: false, error: 'not_configured' });
556
+ }
557
+ const violations = keyIsolationViolations(Deno.env.toObject());
558
+ if (violations.length > 0) {
559
+ await logOps(admin, 'member_door_action_key_reuse', { action, violations }, { severity: 'error' });
560
+ return json(500, { ok: false, error: 'signing_unavailable' });
561
+ }
562
+ // ---- Step 8: mint the assertion ----------------------------------------
563
+ const iat = Math.floor(Date.now() / 1000);
564
+ const jti = crypto.randomUUID();
565
+ const claims = {
566
+ sub: session.id,
567
+ aud,
568
+ iss,
569
+ act: action,
570
+ door_id: unifiDoorId,
571
+ iat,
572
+ // nbf == iat. The +/-30s clock-skew leeway is the VERIFIER's to apply
573
+ // (plan R2-6); baking it in here would only widen the real validity window.
574
+ nbf: iat,
575
+ exp: iat + assertionTtlSeconds(Deno.env.get(ASSERTION_TTL_ENV)),
576
+ jti,
577
+ };
578
+ const assertion = await mintAssertion(signingKeyRaw, claims);
579
+ if (!assertion) {
580
+ await logOps(admin, 'member_door_action_signing_failed', { action }, { severity: 'error' });
581
+ return json(500, { ok: false, error: 'signing_unavailable' });
582
+ }
583
+ // ---- Step 9: sign and forward ------------------------------------------
584
+ const isGet = route.method === 'GET';
585
+ const canonicalQuery = isGet ? `limit=${activityLimit}` : '';
586
+ const rawBody = isGet ? '' : '{}';
587
+ const payloadHash = await sha256Hex(isGet ? canonicalQuery : rawBody);
588
+ const assertionHash = await sha256Hex(assertion);
589
+ const ts = String(Math.floor(Date.now() / 1000));
590
+ const signature = await signD1(hmacSecret, canonicalMemberActionMessage(action, ts, assertionHash, payloadHash));
591
+ const url = `${baseUrl}${route.path}${canonicalQuery ? `?${canonicalQuery}` : ''}`;
592
+ const headers = {
593
+ [ASSERTION_HEADER]: assertion,
594
+ [SIGNATURE_HEADER]: signature,
595
+ [TIMESTAMP_HEADER]: ts,
596
+ [SCHEME_HEADER]: HMAC_SCHEME,
597
+ };
598
+ if (!isGet)
599
+ headers['Content-Type'] = 'application/json';
600
+ // Audit detail is assembled explicitly, field by field. It never contains a
601
+ // PIN, a voucher code, or the member's email (ids and counts only).
602
+ const auditBase = {
603
+ action,
604
+ actor_uid: session.id,
605
+ membership_id: membershipId,
606
+ unifi_user_id: unifiUserId,
607
+ jti,
608
+ gc_door_id: gcDoorId,
609
+ unifi_door_id: unifiDoorId,
610
+ };
611
+ const audit = async (detail, severity = 'info') => {
612
+ const payload = { ...auditBase, ...detail };
613
+ const { error } = await admin.from('ops_events').insert({
614
+ kind: 'member_door_action', severity, booking_id: null, detail: payload,
615
+ });
616
+ // Same escalation as admin-door-write: a door write with no audit trail is
617
+ // precisely what this row exists to prevent, so a failed insert is loud.
618
+ if (error) {
619
+ await logOps(admin, 'member_door_action_audit_failed', {
620
+ audit_error: error.message, ...payload,
621
+ }, { severity: 'error' });
622
+ }
623
+ };
624
+ // "Couldn't confirm" — never "unlocked", never "denied", never retried.
625
+ const unconfirmed = () => json(502, {
626
+ ok: false,
627
+ error: 'unlock_unconfirmed',
628
+ message: "We couldn't confirm that unlock — please use your card or fob.",
629
+ });
630
+ let res;
631
+ try {
632
+ res = await fetch(url, {
633
+ method: route.method,
634
+ headers,
635
+ ...(isGet ? {} : { body: rawBody }),
636
+ signal: AbortSignal.timeout(route.timeoutMs),
637
+ });
638
+ }
639
+ catch (e) {
640
+ await audit({ outcome: 'unknown', transport_error: String(e).slice(0, 300) }, 'error');
641
+ await logOps(admin, 'member_door_action_call_error', {
642
+ action, actor_uid: session.id, jti, message: String(e).slice(0, 300),
643
+ }, { severity: 'error' });
644
+ // A write that timed out may or may not have landed upstream. For unlock the
645
+ // plan is explicit: report unconfirmed. For the others there is nothing to be
646
+ // ambiguous about from the member's point of view.
647
+ return action === 'unlock' ? unconfirmed() : json(502, { ok: false, error: 'middleware_unreachable' });
648
+ }
649
+ const text = await res.text();
650
+ let parsed = null;
651
+ try {
652
+ const candidate = text ? JSON.parse(text) : null;
653
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
654
+ parsed = candidate;
655
+ }
656
+ }
657
+ catch {
658
+ parsed = null;
659
+ }
660
+ if (!res.ok) {
661
+ // 401/403 covers BOTH "the middleware rejected our signature/assertion" and
662
+ // "the member is not entitled". We cannot tell them apart from the status, so
663
+ // the member gets the uniform opaque refusal and ops_events gets the detail
664
+ // at error severity — a signing misconfiguration must not hide inside a
665
+ // stream of ordinary denials.
666
+ const authRejected = res.status === 401 || res.status === 403;
667
+ await audit({
668
+ outcome: authRejected ? 'denied' : 'error',
669
+ middleware_status: res.status,
670
+ middleware_body: text.slice(0, 300),
671
+ }, 'error');
672
+ await logOps(admin, 'member_door_action_call_failed', {
673
+ action, actor_uid: session.id, jti, status: res.status, response: text.slice(0, 300),
674
+ }, { severity: 'error' });
675
+ if (authRejected)
676
+ return denied();
677
+ if (res.status === 429)
678
+ return json(429, { ok: false, error: 'rate_limited' });
679
+ return action === 'unlock' ? unconfirmed() : json(502, { ok: false, error: 'middleware_error' });
680
+ }
681
+ if (!parsed) {
682
+ await audit({ outcome: 'unknown', middleware_status: res.status, reason: 'unparseable_body' }, 'error');
683
+ await logOps(admin, 'member_door_action_bad_response', {
684
+ action, actor_uid: session.id, jti, status: res.status, response: text.slice(0, 300),
685
+ }, { severity: 'error' });
686
+ return action === 'unlock' ? unconfirmed() : json(502, { ok: false, error: 'middleware_error' });
687
+ }
688
+ // A 200 carrying an explicit refusal is still a refusal.
689
+ if (parsed.ok === false) {
690
+ await audit({
691
+ outcome: 'denied',
692
+ middleware_status: res.status,
693
+ middleware_reason: typeof parsed.error === 'string' ? parsed.error.slice(0, 120) : null,
694
+ }, 'error');
695
+ return denied();
696
+ }
697
+ if (action === 'activity') {
698
+ const hitsRaw = Array.isArray(parsed.hits) ? parsed.hits : null;
699
+ if (!hitsRaw) {
700
+ await audit({ outcome: 'unknown', middleware_status: res.status, reason: 'missing_hits' }, 'error');
701
+ await logOps(admin, 'member_door_action_bad_response', {
702
+ action, actor_uid: session.id, jti, status: res.status, reason: 'missing_hits',
703
+ }, { severity: 'error' });
704
+ return json(502, { ok: false, error: 'middleware_error' });
705
+ }
706
+ // Defence in depth on the middleware's own server-side actor_id forcing
707
+ // (plan finding #5): if a hit carries an actor id at all, it MUST be this
708
+ // member's. One mismatch discards the ENTIRE response — a feed that is
709
+ // partly someone else's history is not salvageable by filtering.
710
+ const hits = [];
711
+ for (const h of hitsRaw) {
712
+ if (!h || typeof h !== 'object' || Array.isArray(h))
713
+ continue;
714
+ const hit = h;
715
+ const hitActor = typeof hit.actor_id === 'string' ? hit.actor_id.trim() : '';
716
+ if (hitActor && hitActor !== unifiUserId) {
717
+ await audit({ outcome: 'scope_violation', middleware_status: res.status }, 'error');
718
+ await logOps(admin, 'member_door_action_scope_violation', {
719
+ action, actor_uid: session.id, jti, hit_count: hitsRaw.length,
720
+ }, { severity: 'error' });
721
+ return json(502, { ok: false, error: 'middleware_error' });
722
+ }
723
+ // actor_id is asserted above and then dropped: the browser has no use for
724
+ // a UniFi internal id.
725
+ hits.push(pickScalars(hit, ACTIVITY_HIT_FIELDS));
726
+ }
727
+ await audit({ outcome: 'ok', middleware_status: res.status, hit_count: hits.length });
728
+ return json(200, { ok: true, hits });
729
+ }
730
+ const result = pickScalars(parsed, RESPONSE_FIELDS[action]);
731
+ if (action === 'unlock') {
732
+ // Success is asserted, never inferred. The middleware's post-unlock
733
+ // GET /doors/:id read-back is what turns `outcome` into 'unlocked'; anything
734
+ // else (missing, 'unconfirmed', unexpected) is reported as unconfirmed.
735
+ if (result.outcome !== 'unlocked') {
736
+ await audit({
737
+ outcome: 'unknown',
738
+ middleware_status: res.status,
739
+ middleware_outcome: typeof result.outcome === 'string' ? result.outcome : null,
740
+ }, 'error');
741
+ await logOps(admin, 'member_door_action_unlock_unconfirmed', {
742
+ action, actor_uid: session.id, jti, middleware_status: res.status,
743
+ middleware_outcome: typeof result.outcome === 'string' ? result.outcome : null,
744
+ }, { severity: 'error' });
745
+ return unconfirmed();
746
+ }
747
+ await audit({ outcome: 'unlocked', middleware_status: res.status });
748
+ return json(200, { ok: true, ...result });
749
+ }
750
+ // pin_regenerate: the middleware's group reverse-index verdict is the one
751
+ // signal on this path that can turn a nominally-successful PIN write into a
752
+ // defect. Anything other than 'ok' (or absent) escalates this audit row to
753
+ // error severity AND raises a logOps alert — a direct ops_events insert alone
754
+ // does not page anyone; only logOps fans out to the webhook/Slack. The PIN
755
+ // itself still goes back to the member: it was really written, and withholding
756
+ // it would leave them locked out on top of the anomaly.
757
+ if (action === 'pin_regenerate') {
758
+ const groupCheck = typeof result.group_check === 'string' ? result.group_check : null;
759
+ if (groupCheck !== null && groupCheck !== 'ok') {
760
+ await audit({
761
+ outcome: 'ok', middleware_status: res.status, group_check: groupCheck,
762
+ }, 'error');
763
+ await logOps(admin, 'member_door_action_group_check_mismatch', {
764
+ action, actor_uid: session.id, membership_id: membershipId, jti,
765
+ middleware_status: res.status, group_check: groupCheck,
766
+ }, { severity: 'error' });
767
+ return json(200, { ok: true, ...result });
768
+ }
769
+ }
770
+ // pin_regenerate (clean) / wifi_voucher: the secret value is returned to the
771
+ // member once and is NOT part of the audit payload (auditBase carries ids only).
772
+ await audit({ outcome: 'ok', middleware_status: res.status });
773
+ return json(200, { ok: true, ...result });
774
+ }