@simplelayer/graniteer-core 0.2.1 → 0.2.2

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 (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  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 -460
  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 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  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 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -334
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -217
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -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
+ }