@simplelayer/graniteer-core 0.1.2 → 0.2.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 (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -0
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -1,272 +1,272 @@
1
- // D23 Phase 3 — the ONLY write path for the Door & Access admin console.
2
- //
3
- // Why an edge function and not direct PostgREST writes: every mutation here must land an
4
- // ops_events audit row, and ops_events is insert-denied to every client role by design.
5
- // Auth mirrors the other admin functions exactly (JWKS verify -> aal2 -> admin_users
6
- // allowlist re-check server-side -> rate limit). door_ops_staff are READ-ONLY in Phase 3
7
- // and are deliberately NOT accepted here.
8
-
9
- import { createClient } from 'npm:@supabase/supabase-js@2';
10
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
11
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
12
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
13
-
14
- const corsHeaders = {
15
- 'Access-Control-Allow-Origin': '*',
16
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
17
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
18
- };
19
-
20
- interface CallerClaims { sub: string; email?: string; aal?: string }
21
-
22
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
23
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
24
- function getJwks(supabaseUrl: string) {
25
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
26
- return jwksCache;
27
- }
28
-
29
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
30
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
31
- try {
32
- const { payload } = await jwtVerify(authHeader.slice(7).trim(), getJwks(supabaseUrl));
33
- const claims = payload as unknown as CallerClaims;
34
- return claims.sub ? claims : null;
35
- } catch {
36
- return null;
37
- }
38
- }
39
-
40
- function json(status: number, body: unknown) {
41
- return new Response(JSON.stringify(body), {
42
- status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
43
- });
44
- }
45
-
46
- const UUID = /^[0-9a-f-]{36}$/i;
47
- const DOOR_FIELDS = ['name', 'unifi_door_id', 'unifi_device_id', 'reader_capabilities', 'status', 'notes'] as const;
48
- type DoorField = typeof DOOR_FIELDS[number];
49
-
50
- // MUST match the doors_status_check CHECK constraint on public.doors exactly.
51
- const DOOR_STATUSES = [
52
- 'not_installed', 'pending_placeholder', 'mapped', 'live',
53
- 'orphaned_in_unifi', 'reachable_via_all_doors',
54
- ];
55
-
56
- const MAX_GROUP_IDS = 25;
57
- const MAX_GROUP_ID_LEN = 128;
58
-
59
- function norm(v: unknown): unknown {
60
- if (Array.isArray(v)) return v.map((x) => String(x ?? '').trim()).filter(Boolean);
61
- if (typeof v === 'string') {
62
- const t = v.trim();
63
- return t === '' ? null : t;
64
- }
65
- return v ?? null;
66
- }
67
-
68
- /** Before/after diff of only the fields that actually changed. */
69
- function diff(before: Record<string, unknown> | null, after: Record<string, unknown> | null) {
70
- const out: Record<string, { from: unknown; to: unknown }> = {};
71
- const keys = new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})]);
72
- for (const k of keys) {
73
- const b = before?.[k] ?? null;
74
- const a = after?.[k] ?? null;
75
- if (JSON.stringify(b) !== JSON.stringify(a)) out[k] = { from: b, to: a };
76
- }
77
- return out;
78
- }
79
-
80
- export async function handle(req: Request): Promise<Response> {
81
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
82
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
83
-
84
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
85
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
86
-
87
- const caller = await verifyCaller(req.headers.get('Authorization') ?? req.headers.get('authorization'), SUPABASE_URL);
88
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
89
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
90
- const actorEmail = (caller.email ?? '').toLowerCase();
91
- if (!actorEmail) return json(403, { ok: false, error: 'no_email' });
92
-
93
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
94
- auth: { persistSession: false, autoRefreshToken: false },
95
- });
96
-
97
- const [ipOk, emailOk] = await Promise.all([
98
- checkRateLimit(admin, 'admin-door-write-ip', clientIp(req), 120, 300),
99
- checkRateLimit(admin, 'admin-door-write-email', actorEmail, 80, 300),
100
- ]);
101
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
102
-
103
- const { data: allow, error: allowErr } = await admin
104
- .from('admin_users').select('email').eq('email', actorEmail).maybeSingle();
105
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
106
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
107
-
108
- let body: Record<string, unknown>;
109
- try { body = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
110
- const action = String(body.action ?? '');
111
-
112
- const audit = async (
113
- kind: 'door_admin_write' | 'group_map_admin_write',
114
- detail: Record<string, unknown>,
115
- ) => {
116
- // logOps is a shared helper that swallows insert failures by design — other
117
- // functions depend on that contract, so we do NOT change it globally. Instead this
118
- // call site verifies the row actually landed and escalates loudly if it did not:
119
- // a write with no audit trail is exactly what this console exists to prevent.
120
- const payload = { actor_email: actorEmail, action, ...detail };
121
- const { error: auditErr } = await admin.from('ops_events').insert({
122
- kind, severity: 'info', booking_id: null, detail: payload,
123
- });
124
- if (auditErr) {
125
- await logOps(
126
- admin,
127
- 'door_admin_audit_failed',
128
- { intended_kind: kind, audit_error: auditErr.message, ...payload },
129
- { severity: 'error' },
130
- );
131
- }
132
- };
133
-
134
- try {
135
- if (action === 'door_create' || action === 'door_update') {
136
- const patch: Record<string, unknown> = {};
137
- const input = (body.door ?? {}) as Record<string, unknown>;
138
- for (const f of DOOR_FIELDS) {
139
- if (f in input) patch[f as DoorField] = norm(input[f]);
140
- }
141
- if (patch.status != null && !DOOR_STATUSES.includes(String(patch.status))) {
142
- return json(400, { ok: false, error: 'invalid_status' });
143
- }
144
- if (patch.reader_capabilities == null) delete patch.reader_capabilities;
145
-
146
- if (action === 'door_create') {
147
- if (!patch.name) return json(400, { ok: false, error: 'name_required' });
148
- const row = {
149
- ...patch,
150
- unifi_door_id: patch.unifi_door_id ?? 'PENDING',
151
- status: patch.status ?? 'pending_placeholder',
152
- };
153
- const { data, error } = await admin.from('doors').insert(row).select('*').single();
154
- if (error) return json(400, { ok: false, error: error.message });
155
- await audit('door_admin_write', { table: 'doors', door_id: data.id, door_name: data.name, diff: diff(null, row) });
156
- return json(200, { ok: true, door: data });
157
- }
158
-
159
- const id = String(body.id ?? '');
160
- if (!UUID.test(id)) return json(400, { ok: false, error: 'invalid_id' });
161
- const { data: before, error: beforeErr } = await admin.from('doors').select('*').eq('id', id).maybeSingle();
162
- if (beforeErr) return json(500, { ok: false, error: 'read_failed' });
163
- if (!before) return json(404, { ok: false, error: 'not_found' });
164
- const { data: after, error } = await admin.from('doors').update(patch).eq('id', id).select('*').single();
165
- if (error) return json(400, { ok: false, error: error.message });
166
- const changed = diff(
167
- Object.fromEntries(Object.keys(patch).map((k) => [k, (before as Record<string, unknown>)[k]])),
168
- patch,
169
- );
170
- await audit('door_admin_write', { table: 'doors', door_id: id, door_name: after.name, diff: changed });
171
- return json(200, { ok: true, door: after });
172
- }
173
-
174
- if (action === 'door_delete') {
175
- const id = String(body.id ?? '');
176
- if (!UUID.test(id)) return json(400, { ok: false, error: 'invalid_id' });
177
- const { data: before } = await admin.from('doors').select('*').eq('id', id).maybeSingle();
178
- if (!before) return json(404, { ok: false, error: 'not_found' });
179
- const { error } = await admin.from('doors').delete().eq('id', id);
180
- if (error) return json(400, { ok: false, error: error.message });
181
- await audit('door_admin_write', {
182
- table: 'doors', door_id: id, door_name: (before as { name?: string }).name,
183
- diff: diff(before as Record<string, unknown>, null),
184
- });
185
- return json(200, { ok: true });
186
- }
187
-
188
- if (action === 'room_door_link' || action === 'room_door_unlink') {
189
- const roomId = String(body.room_id ?? '');
190
- const doorId = String(body.door_id ?? '');
191
- if (!UUID.test(roomId) || !UUID.test(doorId)) return json(400, { ok: false, error: 'invalid_id' });
192
-
193
- if (action === 'room_door_link') {
194
- const { data: existing } = await admin.from('door_area_map')
195
- .select('id').eq('room_id', roomId).eq('door_id', doorId).maybeSingle();
196
- if (existing) return json(200, { ok: true, unchanged: true });
197
- const { data, error } = await admin.from('door_area_map')
198
- .insert({ room_id: roomId, door_id: doorId }).select('*').single();
199
- if (error) return json(400, { ok: false, error: error.message });
200
- await audit('door_admin_write', {
201
- table: 'door_area_map', room_id: roomId, door_id: doorId,
202
- diff: diff(null, { room_id: roomId, door_id: doorId }),
203
- });
204
- return json(200, { ok: true, link: data });
205
- }
206
-
207
- const { error } = await admin.from('door_area_map').delete().eq('room_id', roomId).eq('door_id', doorId);
208
- if (error) return json(400, { ok: false, error: error.message });
209
- await audit('door_admin_write', {
210
- table: 'door_area_map', room_id: roomId, door_id: doorId,
211
- diff: diff({ room_id: roomId, door_id: doorId }, null),
212
- });
213
- return json(200, { ok: true });
214
- }
215
-
216
- if (action === 'plan_groups_set') {
217
- const planId = String(body.plan_id ?? '');
218
- if (!UUID.test(planId)) return json(400, { ok: false, error: 'invalid_plan_id' });
219
- const raw = Array.isArray(body.group_ids) ? body.group_ids : null;
220
- if (!raw) return json(400, { ok: false, error: 'invalid_group_ids' });
221
- const groupIds = Array.from(new Set(raw.map((g) => String(g ?? '').trim()).filter(Boolean))).sort();
222
- if (groupIds.length !== raw.length && raw.some((g) => String(g ?? '').trim() === '')) {
223
- return json(400, { ok: false, error: 'empty_group_id' });
224
- }
225
- if (groupIds.length > MAX_GROUP_IDS) return json(400, { ok: false, error: 'too_many_group_ids' });
226
- if (groupIds.some((g) => g.length > MAX_GROUP_ID_LEN)) {
227
- return json(400, { ok: false, error: 'group_id_too_long' });
228
- }
229
- const expectedRaw = body.expected_group_ids;
230
- if (!Array.isArray(expectedRaw)) return json(400, { ok: false, error: 'expected_group_ids_required' });
231
- const expected = Array.from(
232
- new Set((expectedRaw as unknown[]).map((g) => String(g ?? '').trim()).filter(Boolean)),
233
- ).sort();
234
-
235
- const { data: before, error: beforeErr } = await admin.from('membership_plans')
236
- .select('id,name,slug,unifi_group_ids').eq('id', planId).maybeSingle();
237
- if (beforeErr) return json(500, { ok: false, error: 'read_failed' });
238
- if (!before) return json(404, { ok: false, error: 'not_found' });
239
-
240
- const prev = ((before as { unifi_group_ids: string[] | null }).unifi_group_ids ?? []).slice().sort();
241
- // TOCTOU guard: the admin's diff was computed against `expected`. If the live value
242
- // moved since page load, refuse rather than clobber the other writer's change.
243
- if (JSON.stringify(prev) !== JSON.stringify(expected)) {
244
- return json(409, {
245
- ok: false,
246
- error: 'stale_plan_groups',
247
- message: 'This plan changed since you loaded it — please reload and redo your change.',
248
- current_group_ids: prev,
249
- });
250
- }
251
- // REPLACE semantics — never append.
252
- const { error } = await admin.from('membership_plans')
253
- .update({ unifi_group_ids: groupIds }).eq('id', planId);
254
- if (error) return json(400, { ok: false, error: error.message });
255
-
256
- await audit('group_map_admin_write', {
257
- table: 'membership_plans',
258
- plan_id: planId,
259
- plan_slug: (before as { slug?: string }).slug,
260
- added: groupIds.filter((g) => !prev.includes(g)),
261
- removed: prev.filter((g) => !groupIds.includes(g)),
262
- diff: diff({ unifi_group_ids: prev }, { unifi_group_ids: groupIds }),
263
- propagation: 'membership-door-sync cron (5 min)',
264
- });
265
- return json(200, { ok: true, unifi_group_ids: groupIds });
266
- }
267
-
268
- return json(400, { ok: false, error: 'unknown_action' });
269
- } catch (e) {
270
- return json(500, { ok: false, error: String(e) });
271
- }
272
- }
1
+ // D23 Phase 3 — the ONLY write path for the Door & Access admin console.
2
+ //
3
+ // Why an edge function and not direct PostgREST writes: every mutation here must land an
4
+ // ops_events audit row, and ops_events is insert-denied to every client role by design.
5
+ // Auth mirrors the other admin functions exactly (JWKS verify -> aal2 -> admin_users
6
+ // allowlist re-check server-side -> rate limit). door_ops_staff are READ-ONLY in Phase 3
7
+ // and are deliberately NOT accepted here.
8
+
9
+ import { createClient } from 'npm:@supabase/supabase-js@2';
10
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
11
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
12
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
13
+
14
+ const corsHeaders = {
15
+ 'Access-Control-Allow-Origin': '*',
16
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
17
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
18
+ };
19
+
20
+ interface CallerClaims { sub: string; email?: string; aal?: string }
21
+
22
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
23
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
24
+ function getJwks(supabaseUrl: string) {
25
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
26
+ return jwksCache;
27
+ }
28
+
29
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
30
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
31
+ try {
32
+ const { payload } = await jwtVerify(authHeader.slice(7).trim(), getJwks(supabaseUrl));
33
+ const claims = payload as unknown as CallerClaims;
34
+ return claims.sub ? claims : null;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ function json(status: number, body: unknown) {
41
+ return new Response(JSON.stringify(body), {
42
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
43
+ });
44
+ }
45
+
46
+ const UUID = /^[0-9a-f-]{36}$/i;
47
+ const DOOR_FIELDS = ['name', 'unifi_door_id', 'unifi_device_id', 'reader_capabilities', 'status', 'notes'] as const;
48
+ type DoorField = typeof DOOR_FIELDS[number];
49
+
50
+ // MUST match the doors_status_check CHECK constraint on public.doors exactly.
51
+ const DOOR_STATUSES = [
52
+ 'not_installed', 'pending_placeholder', 'mapped', 'live',
53
+ 'orphaned_in_unifi', 'reachable_via_all_doors',
54
+ ];
55
+
56
+ const MAX_GROUP_IDS = 25;
57
+ const MAX_GROUP_ID_LEN = 128;
58
+
59
+ function norm(v: unknown): unknown {
60
+ if (Array.isArray(v)) return v.map((x) => String(x ?? '').trim()).filter(Boolean);
61
+ if (typeof v === 'string') {
62
+ const t = v.trim();
63
+ return t === '' ? null : t;
64
+ }
65
+ return v ?? null;
66
+ }
67
+
68
+ /** Before/after diff of only the fields that actually changed. */
69
+ function diff(before: Record<string, unknown> | null, after: Record<string, unknown> | null) {
70
+ const out: Record<string, { from: unknown; to: unknown }> = {};
71
+ const keys = new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})]);
72
+ for (const k of keys) {
73
+ const b = before?.[k] ?? null;
74
+ const a = after?.[k] ?? null;
75
+ if (JSON.stringify(b) !== JSON.stringify(a)) out[k] = { from: b, to: a };
76
+ }
77
+ return out;
78
+ }
79
+
80
+ export async function handle(req: Request): Promise<Response> {
81
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
82
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
83
+
84
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
85
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
86
+
87
+ const caller = await verifyCaller(req.headers.get('Authorization') ?? req.headers.get('authorization'), SUPABASE_URL);
88
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
89
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
90
+ const actorEmail = (caller.email ?? '').toLowerCase();
91
+ if (!actorEmail) return json(403, { ok: false, error: 'no_email' });
92
+
93
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
94
+ auth: { persistSession: false, autoRefreshToken: false },
95
+ });
96
+
97
+ const [ipOk, emailOk] = await Promise.all([
98
+ checkRateLimit(admin, 'admin-door-write-ip', clientIp(req), 120, 300),
99
+ checkRateLimit(admin, 'admin-door-write-email', actorEmail, 80, 300),
100
+ ]);
101
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
102
+
103
+ const { data: allow, error: allowErr } = await admin
104
+ .from('admin_users').select('email').eq('email', actorEmail).maybeSingle();
105
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
106
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
107
+
108
+ let body: Record<string, unknown>;
109
+ try { body = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
110
+ const action = String(body.action ?? '');
111
+
112
+ const audit = async (
113
+ kind: 'door_admin_write' | 'group_map_admin_write',
114
+ detail: Record<string, unknown>,
115
+ ) => {
116
+ // logOps is a shared helper that swallows insert failures by design — other
117
+ // functions depend on that contract, so we do NOT change it globally. Instead this
118
+ // call site verifies the row actually landed and escalates loudly if it did not:
119
+ // a write with no audit trail is exactly what this console exists to prevent.
120
+ const payload = { actor_email: actorEmail, action, ...detail };
121
+ const { error: auditErr } = await admin.from('ops_events').insert({
122
+ kind, severity: 'info', booking_id: null, detail: payload,
123
+ });
124
+ if (auditErr) {
125
+ await logOps(
126
+ admin,
127
+ 'door_admin_audit_failed',
128
+ { intended_kind: kind, audit_error: auditErr.message, ...payload },
129
+ { severity: 'error' },
130
+ );
131
+ }
132
+ };
133
+
134
+ try {
135
+ if (action === 'door_create' || action === 'door_update') {
136
+ const patch: Record<string, unknown> = {};
137
+ const input = (body.door ?? {}) as Record<string, unknown>;
138
+ for (const f of DOOR_FIELDS) {
139
+ if (f in input) patch[f as DoorField] = norm(input[f]);
140
+ }
141
+ if (patch.status != null && !DOOR_STATUSES.includes(String(patch.status))) {
142
+ return json(400, { ok: false, error: 'invalid_status' });
143
+ }
144
+ if (patch.reader_capabilities == null) delete patch.reader_capabilities;
145
+
146
+ if (action === 'door_create') {
147
+ if (!patch.name) return json(400, { ok: false, error: 'name_required' });
148
+ const row = {
149
+ ...patch,
150
+ unifi_door_id: patch.unifi_door_id ?? 'PENDING',
151
+ status: patch.status ?? 'pending_placeholder',
152
+ };
153
+ const { data, error } = await admin.from('doors').insert(row).select('*').single();
154
+ if (error) return json(400, { ok: false, error: error.message });
155
+ await audit('door_admin_write', { table: 'doors', door_id: data.id, door_name: data.name, diff: diff(null, row) });
156
+ return json(200, { ok: true, door: data });
157
+ }
158
+
159
+ const id = String(body.id ?? '');
160
+ if (!UUID.test(id)) return json(400, { ok: false, error: 'invalid_id' });
161
+ const { data: before, error: beforeErr } = await admin.from('doors').select('*').eq('id', id).maybeSingle();
162
+ if (beforeErr) return json(500, { ok: false, error: 'read_failed' });
163
+ if (!before) return json(404, { ok: false, error: 'not_found' });
164
+ const { data: after, error } = await admin.from('doors').update(patch).eq('id', id).select('*').single();
165
+ if (error) return json(400, { ok: false, error: error.message });
166
+ const changed = diff(
167
+ Object.fromEntries(Object.keys(patch).map((k) => [k, (before as Record<string, unknown>)[k]])),
168
+ patch,
169
+ );
170
+ await audit('door_admin_write', { table: 'doors', door_id: id, door_name: after.name, diff: changed });
171
+ return json(200, { ok: true, door: after });
172
+ }
173
+
174
+ if (action === 'door_delete') {
175
+ const id = String(body.id ?? '');
176
+ if (!UUID.test(id)) return json(400, { ok: false, error: 'invalid_id' });
177
+ const { data: before } = await admin.from('doors').select('*').eq('id', id).maybeSingle();
178
+ if (!before) return json(404, { ok: false, error: 'not_found' });
179
+ const { error } = await admin.from('doors').delete().eq('id', id);
180
+ if (error) return json(400, { ok: false, error: error.message });
181
+ await audit('door_admin_write', {
182
+ table: 'doors', door_id: id, door_name: (before as { name?: string }).name,
183
+ diff: diff(before as Record<string, unknown>, null),
184
+ });
185
+ return json(200, { ok: true });
186
+ }
187
+
188
+ if (action === 'room_door_link' || action === 'room_door_unlink') {
189
+ const roomId = String(body.room_id ?? '');
190
+ const doorId = String(body.door_id ?? '');
191
+ if (!UUID.test(roomId) || !UUID.test(doorId)) return json(400, { ok: false, error: 'invalid_id' });
192
+
193
+ if (action === 'room_door_link') {
194
+ const { data: existing } = await admin.from('door_area_map')
195
+ .select('id').eq('room_id', roomId).eq('door_id', doorId).maybeSingle();
196
+ if (existing) return json(200, { ok: true, unchanged: true });
197
+ const { data, error } = await admin.from('door_area_map')
198
+ .insert({ room_id: roomId, door_id: doorId }).select('*').single();
199
+ if (error) return json(400, { ok: false, error: error.message });
200
+ await audit('door_admin_write', {
201
+ table: 'door_area_map', room_id: roomId, door_id: doorId,
202
+ diff: diff(null, { room_id: roomId, door_id: doorId }),
203
+ });
204
+ return json(200, { ok: true, link: data });
205
+ }
206
+
207
+ const { error } = await admin.from('door_area_map').delete().eq('room_id', roomId).eq('door_id', doorId);
208
+ if (error) return json(400, { ok: false, error: error.message });
209
+ await audit('door_admin_write', {
210
+ table: 'door_area_map', room_id: roomId, door_id: doorId,
211
+ diff: diff({ room_id: roomId, door_id: doorId }, null),
212
+ });
213
+ return json(200, { ok: true });
214
+ }
215
+
216
+ if (action === 'plan_groups_set') {
217
+ const planId = String(body.plan_id ?? '');
218
+ if (!UUID.test(planId)) return json(400, { ok: false, error: 'invalid_plan_id' });
219
+ const raw = Array.isArray(body.group_ids) ? body.group_ids : null;
220
+ if (!raw) return json(400, { ok: false, error: 'invalid_group_ids' });
221
+ const groupIds = Array.from(new Set(raw.map((g) => String(g ?? '').trim()).filter(Boolean))).sort();
222
+ if (groupIds.length !== raw.length && raw.some((g) => String(g ?? '').trim() === '')) {
223
+ return json(400, { ok: false, error: 'empty_group_id' });
224
+ }
225
+ if (groupIds.length > MAX_GROUP_IDS) return json(400, { ok: false, error: 'too_many_group_ids' });
226
+ if (groupIds.some((g) => g.length > MAX_GROUP_ID_LEN)) {
227
+ return json(400, { ok: false, error: 'group_id_too_long' });
228
+ }
229
+ const expectedRaw = body.expected_group_ids;
230
+ if (!Array.isArray(expectedRaw)) return json(400, { ok: false, error: 'expected_group_ids_required' });
231
+ const expected = Array.from(
232
+ new Set((expectedRaw as unknown[]).map((g) => String(g ?? '').trim()).filter(Boolean)),
233
+ ).sort();
234
+
235
+ const { data: before, error: beforeErr } = await admin.from('membership_plans')
236
+ .select('id,name,slug,unifi_group_ids').eq('id', planId).maybeSingle();
237
+ if (beforeErr) return json(500, { ok: false, error: 'read_failed' });
238
+ if (!before) return json(404, { ok: false, error: 'not_found' });
239
+
240
+ const prev = ((before as { unifi_group_ids: string[] | null }).unifi_group_ids ?? []).slice().sort();
241
+ // TOCTOU guard: the admin's diff was computed against `expected`. If the live value
242
+ // moved since page load, refuse rather than clobber the other writer's change.
243
+ if (JSON.stringify(prev) !== JSON.stringify(expected)) {
244
+ return json(409, {
245
+ ok: false,
246
+ error: 'stale_plan_groups',
247
+ message: 'This plan changed since you loaded it — please reload and redo your change.',
248
+ current_group_ids: prev,
249
+ });
250
+ }
251
+ // REPLACE semantics — never append.
252
+ const { error } = await admin.from('membership_plans')
253
+ .update({ unifi_group_ids: groupIds }).eq('id', planId);
254
+ if (error) return json(400, { ok: false, error: error.message });
255
+
256
+ await audit('group_map_admin_write', {
257
+ table: 'membership_plans',
258
+ plan_id: planId,
259
+ plan_slug: (before as { slug?: string }).slug,
260
+ added: groupIds.filter((g) => !prev.includes(g)),
261
+ removed: prev.filter((g) => !groupIds.includes(g)),
262
+ diff: diff({ unifi_group_ids: prev }, { unifi_group_ids: groupIds }),
263
+ propagation: 'membership-door-sync cron (5 min)',
264
+ });
265
+ return json(200, { ok: true, unifi_group_ids: groupIds });
266
+ }
267
+
268
+ return json(400, { ok: false, error: 'unknown_action' });
269
+ } catch (e) {
270
+ return json(500, { ok: false, error: String(e) });
271
+ }
272
+ }