@simplelayer/graniteer-core 0.0.2 → 0.1.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.
- package/index.js +2 -2
- package/package.json +98 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/bookingHoldReclaim.ts +94 -0
- package/src/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/conductorAdmin.ts +141 -0
- package/src/email-templates/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/reauthentication.tsx +60 -0
- package/src/functions/admin-cancel-membership.ts +311 -0
- package/src/functions/admin-change-membership-plan.ts +308 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- package/src/functions/admin-photo-upload.ts +128 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- package/src/functions/admin-reset-mfa.ts +138 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- package/src/functions/day-pass-status.ts +89 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- package/src/functions/get-signing-link.ts +211 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- package/src/functions/print-billing-recover.ts +97 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -0
- package/src/functions/space-availability-range.ts +142 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- package/src/functions/voice-inquiry.test.ts +301 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/membership.ts +109 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +34 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/slackAlert.ts +38 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/tier1Agreement.ts +125 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// supabase/functions/admin-create-commons-event/index.ts
|
|
2
|
+
//
|
|
3
|
+
// Stage 2 of the Commons (Tier 3) contract + deposit feature.
|
|
4
|
+
// Staff-only creation of a Commons event booking: a `pending` bookings row
|
|
5
|
+
// carrying the negotiated total (list_amount_cents) and a 50% deposit
|
|
6
|
+
// (deposit_amount_cents). NOTHING is charged here and no contract is sent —
|
|
7
|
+
// BoldSign / Stripe wiring lands in a later stage.
|
|
8
|
+
//
|
|
9
|
+
// Auth scaffold is the same shape as admin-create-booking: JWKS-verified
|
|
10
|
+
// caller JWT, aal2 required, admin_users allowlist re-checked server-side,
|
|
11
|
+
// rate limited on distinct buckets.
|
|
12
|
+
//
|
|
13
|
+
// Pricing is deliberately NOT routed through _shared/pricing.ts — Commons is
|
|
14
|
+
// a negotiated quote room, so the total is staff-entered and validated here.
|
|
15
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
16
|
+
import { z } from 'npm:zod@3.23.8';
|
|
17
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
18
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
19
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
20
|
+
|
|
21
|
+
const corsHeaders = {
|
|
22
|
+
'Access-Control-Allow-Origin': '*',
|
|
23
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
24
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
28
|
+
|
|
29
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
30
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
31
|
+
function getJwks(supabaseUrl: string) {
|
|
32
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
33
|
+
return jwksCache;
|
|
34
|
+
}
|
|
35
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
36
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
37
|
+
const token = authHeader.slice(7).trim();
|
|
38
|
+
try {
|
|
39
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
40
|
+
const claims = payload as unknown as CallerClaims;
|
|
41
|
+
if (!claims.sub) return null;
|
|
42
|
+
return claims;
|
|
43
|
+
} catch { return null; }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function json(status: number, body: unknown) {
|
|
47
|
+
return new Response(JSON.stringify(body), {
|
|
48
|
+
status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function fail(status: number, code: string, error: string) {
|
|
52
|
+
return json(status, { ok: false, status, code, error });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const Client = z.object({
|
|
56
|
+
legal_name: z.string().trim().min(1).max(300),
|
|
57
|
+
contact_name: z.string().trim().min(1).max(200),
|
|
58
|
+
email: z.string().trim().email().max(255),
|
|
59
|
+
phone: z.string().trim().max(40).optional(),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const Body = z.object({
|
|
63
|
+
room_id: z.string().uuid(),
|
|
64
|
+
start_at: z.string().datetime({ offset: true }),
|
|
65
|
+
end_at: z.string().datetime({ offset: true }),
|
|
66
|
+
total_price_cents: z.number().int(),
|
|
67
|
+
security_deposit_cents: z.number().int(),
|
|
68
|
+
client: Client,
|
|
69
|
+
event_name: z.string().trim().max(200).optional(),
|
|
70
|
+
hold_days: z.number().int().optional(),
|
|
71
|
+
notes: z.string().trim().max(2000).optional(),
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
const MAX_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
|
|
75
|
+
|
|
76
|
+
// Event packages are priced as a single negotiated total and are
|
|
77
|
+
// intentionally excluded from the member monthly room credit — this is a
|
|
78
|
+
// product decision, not an oversight. The credit mechanism (credit_hold /
|
|
79
|
+
// credit_consume) only ever applies to hourly/day-rate room bookings in
|
|
80
|
+
// create-booking. Never wire this up without a deliberate product call.
|
|
81
|
+
const EVENT_PACKAGE_CREDIT_APPLIED_CENTS = 0;
|
|
82
|
+
|
|
83
|
+
export async function handle(req: Request): Promise<Response> {
|
|
84
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
85
|
+
if (req.method !== 'POST') return fail(405, 'method_not_allowed', 'Method not allowed.');
|
|
86
|
+
|
|
87
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
88
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
89
|
+
|
|
90
|
+
// === Admin auth: same shape as admin-create-booking ===
|
|
91
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
92
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
93
|
+
if (!caller) return fail(401, 'unauthenticated', 'Not signed in.');
|
|
94
|
+
if (caller.aal !== 'aal2') return fail(403, 'mfa_required', 'Two-factor authentication is required.');
|
|
95
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
96
|
+
if (!callerEmail) return fail(403, 'no_email', 'Caller has no email claim.');
|
|
97
|
+
|
|
98
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
99
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
103
|
+
checkRateLimit(admin, 'admin-create-commons-event-ip', clientIp(req), 30, 300),
|
|
104
|
+
checkRateLimit(admin, 'admin-create-commons-event-email', callerEmail, 20, 300),
|
|
105
|
+
]);
|
|
106
|
+
if (!ipOk || !emailOk) return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
|
|
107
|
+
|
|
108
|
+
const { data: allow, error: allowErr } = await admin
|
|
109
|
+
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
110
|
+
if (allowErr) return fail(500, 'allowlist_lookup_failed', allowErr.message);
|
|
111
|
+
if (!allow) return fail(403, 'not_authorized', 'Not authorized.');
|
|
112
|
+
|
|
113
|
+
// === Body ===
|
|
114
|
+
let raw: unknown;
|
|
115
|
+
try { raw = await req.json(); } catch { return fail(400, 'invalid_json', 'Body was not valid JSON.'); }
|
|
116
|
+
const parsed = Body.safeParse(raw);
|
|
117
|
+
if (!parsed.success) {
|
|
118
|
+
return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
|
|
119
|
+
}
|
|
120
|
+
const {
|
|
121
|
+
room_id, start_at, end_at, total_price_cents, security_deposit_cents,
|
|
122
|
+
client, event_name, hold_days, notes,
|
|
123
|
+
} = parsed.data;
|
|
124
|
+
|
|
125
|
+
// === Room + tier ===
|
|
126
|
+
const { data: room, error: rErr } = await admin
|
|
127
|
+
.from('rooms')
|
|
128
|
+
.select('id,name,slug,booking_mode,active')
|
|
129
|
+
.eq('id', room_id)
|
|
130
|
+
.maybeSingle();
|
|
131
|
+
if (rErr) return fail(500, 'load_room_failed', rErr.message);
|
|
132
|
+
if (!room) return fail(404, 'room_not_found', 'Room not found.');
|
|
133
|
+
|
|
134
|
+
const { data: tier, error: tErr } = await admin
|
|
135
|
+
.rpc('resolve_room_contract_tier', { p_room_id: room_id });
|
|
136
|
+
if (tErr) return fail(500, 'tier_lookup_failed', tErr.message);
|
|
137
|
+
if (Number(tier) !== 3) {
|
|
138
|
+
return fail(409, 'not_tier3', 'This room is not a tier-3 (contract + deposit) room.');
|
|
139
|
+
}
|
|
140
|
+
// Commons moved from `quote` to self-serve `day_block`; this gate would
|
|
141
|
+
// otherwise 409 every staff-created Commons event. This function prices from
|
|
142
|
+
// the staff-supplied total and reads neither business_hours nor any dynamic
|
|
143
|
+
// rule, so widening the accepted modes is the whole change needed here.
|
|
144
|
+
if (!['quote', 'day_block'].includes(room.booking_mode) || room.active !== true) {
|
|
145
|
+
return fail(409, 'room_inactive', 'Room must be an active quote-mode or day-block room.');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// === Window ===
|
|
149
|
+
const startMs = Date.parse(start_at);
|
|
150
|
+
const endMs = Date.parse(end_at);
|
|
151
|
+
const nowMs = Date.now();
|
|
152
|
+
if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) {
|
|
153
|
+
return fail(400, 'invalid_window', 'Arrival and checkout must be valid timestamps.');
|
|
154
|
+
}
|
|
155
|
+
if (startMs >= endMs) return fail(400, 'invalid_window', 'Checkout must be after arrival.');
|
|
156
|
+
if (startMs <= nowMs) return fail(400, 'invalid_window', 'Arrival must be in the future.');
|
|
157
|
+
if (endMs - startMs > MAX_WINDOW_MS) {
|
|
158
|
+
return fail(400, 'invalid_window', 'Event window cannot exceed 14 days.');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// === Price ===
|
|
162
|
+
if (total_price_cents % 100 !== 0) {
|
|
163
|
+
return fail(400, 'invalid_price', 'Total must be a whole-dollar amount (no cents) so the 50% split is exact.');
|
|
164
|
+
}
|
|
165
|
+
if (total_price_cents < 10000 || total_price_cents > 10000000) {
|
|
166
|
+
return fail(400, 'invalid_price', 'Total must be between $100 and $100,000.');
|
|
167
|
+
}
|
|
168
|
+
if (security_deposit_cents < 0 || security_deposit_cents > total_price_cents) {
|
|
169
|
+
return fail(400, 'invalid_price', 'Security deposit must be between $0 and the event total.');
|
|
170
|
+
}
|
|
171
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(client.email)) {
|
|
172
|
+
return fail(400, 'invalid_client', 'Client email is not valid.');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const depositCents = total_price_cents / 2;
|
|
176
|
+
|
|
177
|
+
// Hold: min(now + hold_days, arrival). Default 14 days, clamped to 60.
|
|
178
|
+
const holdDays = Math.min(Math.max(hold_days ?? 14, 1), 60);
|
|
179
|
+
const holdMs = Math.min(nowMs + holdDays * 24 * 60 * 60 * 1000, startMs);
|
|
180
|
+
const holdExpiresAt = new Date(holdMs).toISOString();
|
|
181
|
+
|
|
182
|
+
const rangeLiteral = `[${new Date(startMs).toISOString()},${new Date(endMs).toISOString()})`;
|
|
183
|
+
|
|
184
|
+
// NOTE: `charged_amount_cents` is left NULL, not 0. The existing
|
|
185
|
+
// `bookings_amount_math_check` constraint requires
|
|
186
|
+
// list - dynamic_discount - credit - discount = charged whenever charged is
|
|
187
|
+
// NOT NULL, so a literal 0 alongside a non-zero list would be rejected.
|
|
188
|
+
// NULL is the schema's existing "nothing captured yet" state.
|
|
189
|
+
const insertRow: Record<string, unknown> = {
|
|
190
|
+
room_id,
|
|
191
|
+
during: rangeLiteral,
|
|
192
|
+
status: 'pending',
|
|
193
|
+
list_amount_cents: total_price_cents,
|
|
194
|
+
charged_amount_cents: null,
|
|
195
|
+
deposit_amount_cents: depositCents,
|
|
196
|
+
credit_applied_cents: EVENT_PACKAGE_CREDIT_APPLIED_CENTS,
|
|
197
|
+
discount_applied_cents: 0,
|
|
198
|
+
payment_source: 'stripe',
|
|
199
|
+
contact_email: client.email.toLowerCase(),
|
|
200
|
+
contact_name: client.contact_name,
|
|
201
|
+
contact_phone: client.phone ?? null,
|
|
202
|
+
hold_expires_at: holdExpiresAt,
|
|
203
|
+
created_by: callerEmail,
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const { data: inserted, error: iErr } = await admin
|
|
207
|
+
.from('bookings')
|
|
208
|
+
.insert(insertRow)
|
|
209
|
+
.select('id')
|
|
210
|
+
.single();
|
|
211
|
+
if (iErr) {
|
|
212
|
+
// deno-lint-ignore no-explicit-any
|
|
213
|
+
const code = (iErr as any).code;
|
|
214
|
+
if (code === '23P01') {
|
|
215
|
+
return fail(409, 'overlap', 'Another booking already holds part of that window.');
|
|
216
|
+
}
|
|
217
|
+
return fail(500, 'insert_failed', iErr.message);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const booking_id = inserted.id as string;
|
|
221
|
+
|
|
222
|
+
// `event_name`, `client.legal_name` and `notes` have no column on `bookings`
|
|
223
|
+
// today — they are recorded on the ops event for traceability only and will
|
|
224
|
+
// move onto `booking_agreements` when the tier-3 contract stage lands.
|
|
225
|
+
await logOps(admin, 'commons_event_booking_created', {
|
|
226
|
+
booking_id,
|
|
227
|
+
room_id,
|
|
228
|
+
actor: callerEmail,
|
|
229
|
+
client_legal_name: client.legal_name,
|
|
230
|
+
event_name: event_name ?? null,
|
|
231
|
+
notes: notes ?? null,
|
|
232
|
+
list_amount_cents: total_price_cents,
|
|
233
|
+
deposit_amount_cents: depositCents,
|
|
234
|
+
security_deposit_cents,
|
|
235
|
+
}, { severity: 'info', bookingId: booking_id }).catch(() => {});
|
|
236
|
+
|
|
237
|
+
return json(200, {
|
|
238
|
+
ok: true,
|
|
239
|
+
booking_id,
|
|
240
|
+
list_amount_cents: total_price_cents,
|
|
241
|
+
deposit_amount_cents: depositCents,
|
|
242
|
+
hold_expires_at: holdExpiresAt,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// supabase/functions/admin-debug-boldsign-doc/index.ts
|
|
2
|
+
//
|
|
3
|
+
// Read-only diagnostic: fetch a BoldSign document's field geometry (and
|
|
4
|
+
// optionally the rendered PDF as base64) so staff/Claude can inspect field
|
|
5
|
+
// placement without needing BOLDSIGN_API_KEY client-side. GET-only against
|
|
6
|
+
// BoldSign, no writes anywhere.
|
|
7
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
8
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
9
|
+
|
|
10
|
+
const corsHeaders = {
|
|
11
|
+
'Access-Control-Allow-Origin': '*',
|
|
12
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
13
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
17
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
18
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
19
|
+
function getJwks(supabaseUrl: string) {
|
|
20
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
21
|
+
return jwksCache;
|
|
22
|
+
}
|
|
23
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
24
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
25
|
+
const token = authHeader.slice(7).trim();
|
|
26
|
+
try {
|
|
27
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
28
|
+
const claims = payload as unknown as CallerClaims;
|
|
29
|
+
if (!claims.sub) return null;
|
|
30
|
+
return claims;
|
|
31
|
+
} catch { return null; }
|
|
32
|
+
}
|
|
33
|
+
function json(status: number, body: unknown) {
|
|
34
|
+
return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function handle(req: Request): Promise<Response> {
|
|
38
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
39
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
40
|
+
|
|
41
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
42
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
43
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
44
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
45
|
+
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
46
|
+
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
47
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
48
|
+
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
49
|
+
|
|
50
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
|
|
51
|
+
const { data: allow } = await admin.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
52
|
+
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
53
|
+
|
|
54
|
+
let body: { document_id?: string; include_pdf_base64?: boolean };
|
|
55
|
+
try { body = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
|
|
56
|
+
const documentId = (body.document_id ?? '').trim();
|
|
57
|
+
if (!documentId) return json(400, { ok: false, error: 'document_id_required' });
|
|
58
|
+
|
|
59
|
+
const apiKey = Deno.env.get('BOLDSIGN_API_KEY');
|
|
60
|
+
if (!apiKey) return json(500, { ok: false, error: 'boldsign_not_configured' });
|
|
61
|
+
|
|
62
|
+
const propsRes = await fetch(`https://api.boldsign.com/v1/document/properties?documentId=${encodeURIComponent(documentId)}`, {
|
|
63
|
+
headers: { 'X-API-KEY': apiKey, accept: 'application/json' },
|
|
64
|
+
});
|
|
65
|
+
const propsText = await propsRes.text();
|
|
66
|
+
if (!propsRes.ok) return json(502, { ok: false, error: 'boldsign_properties_failed', status: propsRes.status, detail: propsText.slice(0, 500) });
|
|
67
|
+
let props: unknown;
|
|
68
|
+
try { props = JSON.parse(propsText); } catch { return json(502, { ok: false, error: 'boldsign_properties_bad_json' }); }
|
|
69
|
+
|
|
70
|
+
let debug_pdf_path: string | null = null;
|
|
71
|
+
let pdf_debug: Record<string, unknown> = {};
|
|
72
|
+
if (body.include_pdf_base64) {
|
|
73
|
+
const dlRes = await fetch(`https://api.boldsign.com/v1/document/download?documentId=${encodeURIComponent(documentId)}`, {
|
|
74
|
+
headers: { 'X-API-KEY': apiKey },
|
|
75
|
+
});
|
|
76
|
+
pdf_debug.download_status = dlRes.status;
|
|
77
|
+
if (dlRes.ok) {
|
|
78
|
+
const buf = new Uint8Array(await dlRes.arrayBuffer());
|
|
79
|
+
pdf_debug.byte_length = buf.length;
|
|
80
|
+
const path = `debug/${documentId}.pdf`;
|
|
81
|
+
const up = await admin.storage.from('contract-templates').upload(path, buf, {
|
|
82
|
+
contentType: 'application/pdf',
|
|
83
|
+
upsert: true,
|
|
84
|
+
});
|
|
85
|
+
if (!up.error) debug_pdf_path = path;
|
|
86
|
+
else pdf_debug.upload_error = up.error.message;
|
|
87
|
+
} else {
|
|
88
|
+
pdf_debug.download_body = (await dlRes.text()).slice(0, 300);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return json(200, { ok: true, properties: props, debug_pdf_path, pdf_debug });
|
|
93
|
+
}
|
|
@@ -0,0 +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
|
+
}
|