@simplelayer/graniteer-core 0.0.1 → 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.
Files changed (100) hide show
  1. package/index.js +2 -2
  2. package/package.json +98 -15
  3. package/src/adminBookingCredit.test.ts +451 -0
  4. package/src/adminBookingCredit.ts +239 -0
  5. package/src/availability.test.ts +25 -0
  6. package/src/availability.ts +201 -0
  7. package/src/bookingHoldReclaim.ts +94 -0
  8. package/src/checkoutSessionParams.ts +56 -0
  9. package/src/commonsContract.ts +175 -0
  10. package/src/conductorAdmin.ts +141 -0
  11. package/src/email-templates/email-change.tsx +92 -0
  12. package/src/email-templates/invite.tsx +79 -0
  13. package/src/email-templates/reauthentication.tsx +60 -0
  14. package/src/functions/admin-cancel-membership.ts +311 -0
  15. package/src/functions/admin-change-membership-plan.ts +308 -0
  16. package/src/functions/admin-charge-guest-print.ts +229 -0
  17. package/src/functions/admin-correct-booking.ts +333 -0
  18. package/src/functions/admin-create-commons-event.ts +244 -0
  19. package/src/functions/admin-debug-boldsign-doc.ts +93 -0
  20. package/src/functions/admin-door-write.ts +272 -0
  21. package/src/functions/admin-mark-booking-paid.ts +203 -0
  22. package/src/functions/admin-photo-upload.ts +128 -0
  23. package/src/functions/admin-remove-team-member.ts +150 -0
  24. package/src/functions/admin-reset-mfa.ts +138 -0
  25. package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
  26. package/src/functions/admin-send-commons-agreement.ts +214 -0
  27. package/src/functions/admin-set-credit-amount.ts +123 -0
  28. package/src/functions/admin-skip-commons-contract.ts +165 -0
  29. package/src/functions/admin-undo-membership-cancel.ts +144 -0
  30. package/src/functions/admin-wall-photo-write.ts +141 -0
  31. package/src/functions/boldsign-sender-identity.ts +114 -0
  32. package/src/functions/booking-availability.ts +419 -0
  33. package/src/functions/booking-member-preview.ts +136 -0
  34. package/src/functions/day-pass-status.ts +89 -0
  35. package/src/functions/dayStatus.ts +71 -0
  36. package/src/functions/diag-webpush-test.ts +45 -0
  37. package/src/functions/event-access-store.ts +309 -0
  38. package/src/functions/ezeep-print-webhook.ts +213 -0
  39. package/src/functions/ezeep-usage-reconcile.ts +299 -0
  40. package/src/functions/get-signing-link.ts +211 -0
  41. package/src/functions/guest-print-setup-confirm.ts +128 -0
  42. package/src/functions/guest-print-submit.ts +149 -0
  43. package/src/functions/luma-webhook.ts +165 -0
  44. package/src/functions/migration-collision-alert.copy.ts +232 -0
  45. package/src/functions/migration-collision-alert.test.ts +349 -0
  46. package/src/functions/migration-collision-alert.ts +232 -0
  47. package/src/functions/office-assignment-end.ts +146 -0
  48. package/src/functions/portal-booking-access.ts +95 -0
  49. package/src/functions/portal-list-invoices.ts +99 -0
  50. package/src/functions/print-billing-recover.ts +97 -0
  51. package/src/functions/print-billing-run.ts +183 -0
  52. package/src/functions/public-facts.ts +168 -0
  53. package/src/functions/space-availability-range.acceptance.test.ts +161 -0
  54. package/src/functions/space-availability-range.ts +142 -0
  55. package/src/functions/sync-gcal-blackouts.ts +298 -0
  56. package/src/functions/timetable-event-register.ts +162 -0
  57. package/src/functions/timetable-event-status.ts +90 -0
  58. package/src/functions/timetable-spaces.ts +219 -0
  59. package/src/functions/touch-pass-reconciler.ts +689 -0
  60. package/src/functions/virtual-onboarding-purge.ts +134 -0
  61. package/src/functions/virtual-onboarding-submit.ts +315 -0
  62. package/src/functions/voice-inquiry.test.ts +301 -0
  63. package/src/functions/voice-inquiry.ts +198 -0
  64. package/src/functions/voice-tour-availability.ts +204 -0
  65. package/src/gcalSync.ts +142 -0
  66. package/src/ghlNote.ts +34 -0
  67. package/src/ghlTask.ts +48 -0
  68. package/src/ghlVoiceInquiry.ts +90 -0
  69. package/src/guestPrintCapture.test.ts +722 -0
  70. package/src/guestPrintCapture.ts +538 -0
  71. package/src/lumaGhl.ts +195 -0
  72. package/src/membership.ts +109 -0
  73. package/src/money.ts +36 -0
  74. package/src/ops.ts +97 -0
  75. package/src/pacificDate.ts +34 -0
  76. package/src/policyAcknowledgment.test.ts +50 -0
  77. package/src/policyAcknowledgment.ts +96 -0
  78. package/src/portalSession.ts +46 -0
  79. package/src/pricing.test.ts +660 -0
  80. package/src/pricing.ts +1025 -0
  81. package/src/printBilling.test.ts +750 -0
  82. package/src/printBilling.ts +891 -0
  83. package/src/printBillingAdapters.ts +169 -0
  84. package/src/printCorrections.test.ts +348 -0
  85. package/src/printCorrections.ts +496 -0
  86. package/src/rateLimit.ts +82 -0
  87. package/src/referralCredits.test.ts +31 -0
  88. package/src/referralCredits.ts +34 -0
  89. package/src/referralGrant.ts +321 -0
  90. package/src/rescheduleCredit.test.ts +521 -0
  91. package/src/rescheduleCredit.ts +337 -0
  92. package/src/reservationWifiCode.test.ts +69 -0
  93. package/src/reservationWifiCode.ts +81 -0
  94. package/src/retellCallAnalyzed.test.ts +167 -0
  95. package/src/retellCallAnalyzed.ts +113 -0
  96. package/src/retellSignature.test.ts +137 -0
  97. package/src/retellSignature.ts +82 -0
  98. package/src/slackAlert.ts +38 -0
  99. package/src/supabaseTestFakes.ts +131 -0
  100. package/src/tier1Agreement.ts +125 -0
@@ -0,0 +1,203 @@
1
+ // supabase/functions/admin-mark-booking-paid/index.ts
2
+ //
3
+ // Manual "mark fully paid" admin action, for payments collected outside the
4
+ // normal Stripe checkout flow -- cash, a Mercury wire/ACH, a sponsorship, or
5
+ // anything else staff need to record by hand. Works on any booking tier; the
6
+ // Commons (tier-3) contract flow is the main consumer since its remaining
7
+ // balance is explicitly collected by check/ACH per the contract, never
8
+ // through Stripe.
9
+ import { createClient } from 'npm:@supabase/supabase-js@2';
10
+ import { z } from 'npm:zod@3.23.8';
11
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
12
+ import Stripe from 'npm:stripe@17.5.0';
13
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
14
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
15
+
16
+ const corsHeaders = {
17
+ 'Access-Control-Allow-Origin': '*',
18
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
19
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
20
+ };
21
+
22
+ interface CallerClaims { sub: string; email?: string; aal?: string }
23
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
24
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
25
+ function getJwks(supabaseUrl: string) {
26
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
27
+ return jwksCache;
28
+ }
29
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
30
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
31
+ const token = authHeader.slice(7).trim();
32
+ try {
33
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
34
+ const claims = payload as unknown as CallerClaims;
35
+ if (!claims.sub) return null;
36
+ return claims;
37
+ } catch { return null; }
38
+ }
39
+ function json(status: number, body: unknown) {
40
+ return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
41
+ }
42
+ function fail(status: number, code: string, error: string, extra?: Record<string, unknown>) {
43
+ return json(status, { ok: false, status, code, error, ...(extra ?? {}) });
44
+ }
45
+
46
+ const PAYMENT_METHODS = ['cash', 'stripe', 'mercury', 'sponsored', 'other'] as const;
47
+ const Body = z.object({
48
+ booking_id: z.string().uuid(),
49
+ payment_method: z.enum(PAYMENT_METHODS),
50
+ notes: z.string().trim().max(500).optional(),
51
+ }).refine(
52
+ (b) => b.payment_method !== 'stripe' || !!b.notes?.trim(),
53
+ { message: 'notes (e.g. the Stripe payment/charge ID) are required when payment_method is "stripe" -- this action does not itself touch Stripe.', path: ['notes'] },
54
+ );
55
+
56
+ // Only a live, still-collectible booking can be marked paid. Deliberately an
57
+ // allowlist, not a denylist of terminal statuses -- a new booking_status
58
+ // value added later (e.g. a dispute/chargeback state) should default to
59
+ // NOT payable until someone explicitly decides otherwise.
60
+ const PAYABLE_STATUSES = new Set(['pending', 'deposit_paid']);
61
+
62
+ export async function handle(req: Request): Promise<Response> {
63
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
64
+ if (req.method !== 'POST') return fail(405, 'method_not_allowed', 'Method not allowed.');
65
+
66
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
67
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
68
+
69
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
70
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
71
+ if (!caller) return fail(401, 'unauthenticated', 'Not signed in.');
72
+ if (caller.aal !== 'aal2') return fail(403, 'mfa_required', 'Two-factor authentication is required.');
73
+ const callerEmail = (caller.email ?? '').toLowerCase();
74
+ if (!callerEmail) return fail(403, 'no_email', 'Caller has no email claim.');
75
+
76
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
77
+
78
+ const [ipOk, emailOk] = await Promise.all([
79
+ checkRateLimit(admin, 'admin-mark-booking-paid-ip', clientIp(req), 20, 300),
80
+ checkRateLimit(admin, 'admin-mark-booking-paid-email', callerEmail, 20, 300),
81
+ ]);
82
+ if (!ipOk || !emailOk) return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
83
+
84
+ const { data: allow, error: allowErr } = await admin.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
85
+ if (allowErr) return fail(500, 'allowlist_lookup_failed', allowErr.message);
86
+ if (!allow) return fail(403, 'not_authorized', 'Not authorized.');
87
+
88
+ let raw: unknown;
89
+ try { raw = await req.json(); } catch { return fail(400, 'invalid_json', 'Body was not valid JSON.'); }
90
+ const parsed = Body.safeParse(raw);
91
+ if (!parsed.success) return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
92
+ const { booking_id, payment_method, notes } = parsed.data;
93
+
94
+ const { data: booking, error: bErr } = await admin
95
+ .from('bookings')
96
+ .select('id,status,list_amount_cents,dynamic_discount_cents,credit_applied_cents,discount_applied_cents,charged_amount_cents,paid_method,stripe_session_id,hold_expires_at,deposit_paid_at,payment_source,paid_notes,paid_marked_by_email,paid_marked_at')
97
+ .eq('id', booking_id)
98
+ .maybeSingle();
99
+ if (bErr) return fail(500, 'booking_lookup_failed', bErr.message);
100
+ if (!booking) return fail(404, 'booking_not_found', 'Booking not found.');
101
+ const priorStatus = String(booking.status);
102
+ if (!PAYABLE_STATUSES.has(priorStatus)) {
103
+ return fail(409, 'not_payable', `Booking status is "${priorStatus}"; nothing to mark paid.`);
104
+ }
105
+
106
+ // Never guess an amount -- a null list price means the booking isn't
107
+ // priced yet. (Number(null ?? 0) would silently treat that as $0 and a
108
+ // Postgres CHECK constraint passes on a NULL comparison, so nothing else
109
+ // would have caught this.)
110
+ if (booking.list_amount_cents == null) {
111
+ return fail(409, 'missing_list_amount', 'This booking has no list amount set; fix the booking before marking it paid.');
112
+ }
113
+
114
+ const grossCents = Number(booking.list_amount_cents)
115
+ - Number(booking.dynamic_discount_cents ?? 0)
116
+ - Number(booking.credit_applied_cents ?? 0)
117
+ - Number(booking.discount_applied_cents ?? 0);
118
+
119
+ // 'sponsored' means the venue comped it -- $0 actually changed hands, so
120
+ // charged_amount_cents must be $0. We fold the remainder into
121
+ // discount_applied_cents so bookings_amount_math_check is satisfied
122
+ // truthfully instead of recording full list revenue for a comped event.
123
+ const isSponsored = payment_method === 'sponsored';
124
+ const netCents = isSponsored ? 0 : grossCents;
125
+ if (!isSponsored && netCents <= 0) {
126
+ return fail(409, 'invalid_amount', `Computed amount is $${(netCents / 100).toFixed(2)}, which isn't a valid amount to mark paid. Check the booking's discounts/credits.`);
127
+ }
128
+ const extraDiscountForSponsored = isSponsored ? grossCents : 0;
129
+
130
+ // If there's still a live, unpaid Stripe checkout session on this booking
131
+ // (the deposit link emailed on contract signature), void it before
132
+ // recording an out-of-band payment. The real deposit-paid webhook is
133
+ // CAS-guarded on status='pending' so it can no longer corrupt this row
134
+ // once we flip to 'paid' below -- but Stripe would still capture real
135
+ // money if the customer clicks that live link later, which is the actual
136
+ // harm this guards against.
137
+ if (booking.stripe_session_id && priorStatus === 'pending') {
138
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
139
+ if (!stripeKey) {
140
+ return fail(500, 'stripe_not_configured', 'STRIPE_SECRET_KEY is not set; cannot safely void the outstanding deposit link.');
141
+ }
142
+ try {
143
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
144
+ const session = await stripe.checkout.sessions.retrieve(String(booking.stripe_session_id));
145
+ if (session.status === 'open') {
146
+ await stripe.checkout.sessions.expire(String(booking.stripe_session_id));
147
+ }
148
+ } catch (e) {
149
+ return fail(502, 'stripe_session_expire_failed',
150
+ `Could not void the outstanding Stripe deposit link (${e instanceof Error ? e.message : String(e)}). Void it manually in the Stripe dashboard, then retry.`);
151
+ }
152
+ }
153
+
154
+ const markedAt = new Date().toISOString();
155
+
156
+ const { data: updated, error: updErr } = await admin
157
+ .from('bookings')
158
+ .update({
159
+ status: 'paid',
160
+ charged_amount_cents: netCents,
161
+ discount_applied_cents: Number(booking.discount_applied_cents ?? 0) + extraDiscountForSponsored,
162
+ paid_method: payment_method,
163
+ payment_source: payment_method === 'stripe' ? 'stripe' : 'offline',
164
+ paid_notes: notes ?? null,
165
+ paid_marked_by_email: callerEmail,
166
+ paid_marked_at: markedAt,
167
+ hold_expires_at: null,
168
+ })
169
+ .eq('id', booking_id)
170
+ .eq('status', priorStatus) // CAS -- refuse a stale double-click racing a real webhook
171
+ .select('id')
172
+ .maybeSingle();
173
+ if (updErr) return fail(500, 'update_failed', updErr.message);
174
+ if (!updated) return fail(409, 'status_changed', "This booking's status changed before the update landed — reload and try again.");
175
+
176
+ await logOps(admin, 'booking_marked_fully_paid', {
177
+ booking_id, actor: callerEmail, actor_user_id: caller.sub, payment_method, notes: notes ?? null,
178
+ prior_status: priorStatus, charged_amount_cents: netCents,
179
+ // mark_event_at ties this exact log row to the exact row mutation it
180
+ // describes -- admin-correct-booking matches on this instead of trusting
181
+ // "most recent row of this kind," which a swallowed insert error (or a
182
+ // second mark-paid/undo cycle) could otherwise make stale-but-present.
183
+ mark_event_at: markedAt,
184
+ // Full "before" snapshot of every column this action mutates AND every
185
+ // column bookings_amount_math_check depends on, so admin-correct-booking
186
+ // can both revert this exact row and detect drift instead of guessing.
187
+ prior_charged_amount_cents: booking.charged_amount_cents ?? null,
188
+ prior_discount_applied_cents: Number(booking.discount_applied_cents ?? 0),
189
+ prior_list_amount_cents: Number(booking.list_amount_cents),
190
+ prior_dynamic_discount_cents: Number(booking.dynamic_discount_cents ?? 0),
191
+ prior_credit_applied_cents: Number(booking.credit_applied_cents ?? 0),
192
+ prior_paid_method: booking.paid_method ?? null,
193
+ prior_payment_source: booking.payment_source ?? null,
194
+ prior_paid_notes: booking.paid_notes ?? null,
195
+ prior_paid_marked_by_email: booking.paid_marked_by_email ?? null,
196
+ prior_paid_marked_at: booking.paid_marked_at ?? null,
197
+ prior_hold_expires_at: booking.hold_expires_at ?? null,
198
+ prior_deposit_paid_at: booking.deposit_paid_at ?? null,
199
+ }, { severity: 'warning', bookingId: booking_id }).catch(() => {});
200
+
201
+
202
+ return json(200, { ok: true, booking_id, status: 'paid', charged_amount_cents: netCents });
203
+ }
@@ -0,0 +1,128 @@
1
+ // Server-to-server room photo upload. Same effect as the admin UI's upload in
2
+ // src/pages/admin/AdminRoomEdit.tsx (handleUpload): pushes the file into the
3
+ // "room-photos" Storage bucket and appends { path, alt, url } onto that room's
4
+ // rooms.images jsonb array. Auth here is a single shared-secret header
5
+ // (x-upload-key) instead of a logged-in browser session, since this is meant
6
+ // to be called machine-to-machine over plain HTTPS.
7
+ import { createClient } from 'npm:@supabase/supabase-js@2';
8
+
9
+ const corsHeaders = {
10
+ 'Access-Control-Allow-Origin': '*',
11
+ 'Access-Control-Allow-Headers': 'content-type,x-upload-key',
12
+ 'Access-Control-Allow-Methods': 'POST,OPTIONS',
13
+ };
14
+
15
+ function json(status: number, body: unknown) {
16
+ return new Response(JSON.stringify(body), {
17
+ status,
18
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
19
+ });
20
+ }
21
+
22
+ // Constant-time-ish string compare so a mismatching key doesn't leak timing
23
+ // info about how many leading characters matched.
24
+ function safeEqual(a: string, b: string): boolean {
25
+ if (a.length !== b.length) return false;
26
+ let diff = 0;
27
+ for (let i = 0; i < a.length; i++) {
28
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
29
+ }
30
+ return diff === 0;
31
+ }
32
+
33
+ interface UploadBody {
34
+ room_id?: unknown;
35
+ filename?: unknown;
36
+ content_type?: unknown;
37
+ image_base64?: unknown;
38
+ alt?: unknown;
39
+ }
40
+
41
+ interface ImageRef {
42
+ path: string;
43
+ alt: string;
44
+ url: string;
45
+ }
46
+
47
+ export async function handle(req: Request): Promise<Response> {
48
+ try {
49
+ if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders });
50
+ if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
51
+
52
+ const expectedKey = Deno.env.get('PHOTO_UPLOAD_KEY');
53
+ const providedKey = req.headers.get('x-upload-key');
54
+ if (!expectedKey || !providedKey || !safeEqual(providedKey, expectedKey)) {
55
+ return json(401, { error: 'unauthorized' });
56
+ }
57
+
58
+ let body: UploadBody;
59
+ try {
60
+ body = await req.json();
61
+ } catch {
62
+ return json(400, { error: 'invalid_json' });
63
+ }
64
+
65
+ const roomId = typeof body.room_id === 'string' ? body.room_id.trim() : '';
66
+ if (!roomId) return json(400, { error: 'invalid_field', field: 'room_id' });
67
+
68
+ const filename = typeof body.filename === 'string' ? body.filename.trim() : '';
69
+ if (!filename) return json(400, { error: 'invalid_field', field: 'filename' });
70
+
71
+ const contentType = typeof body.content_type === 'string' ? body.content_type.trim() : '';
72
+ if (!contentType) return json(400, { error: 'invalid_field', field: 'content_type' });
73
+
74
+ const imageBase64 = typeof body.image_base64 === 'string' ? body.image_base64 : '';
75
+ if (!imageBase64) return json(400, { error: 'invalid_field', field: 'image_base64' });
76
+
77
+ const alt = typeof body.alt === 'string' ? body.alt : '';
78
+
79
+ let bytes: Uint8Array;
80
+ try {
81
+ bytes = Uint8Array.from(atob(imageBase64.replace(/\s/g, '')), (c) => c.charCodeAt(0));
82
+ } catch {
83
+ return json(400, { error: 'invalid_field', field: 'image_base64' });
84
+ }
85
+
86
+ const admin = createClient(
87
+ Deno.env.get('SUPABASE_URL')!,
88
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
89
+ { auth: { persistSession: false, autoRefreshToken: false } },
90
+ );
91
+
92
+ // Same sanitize + path convention as AdminRoomEdit.tsx's handleUpload, so
93
+ // files from both paths coexist cleanly in the same bucket/folder.
94
+ const safeFilename = filename.replace(/[^a-zA-Z0-9._-]/g, '_');
95
+ const path = `${roomId}/${Date.now()}-${safeFilename}`;
96
+
97
+ const { error: upErr } = await admin.storage
98
+ .from('room-photos')
99
+ .upload(path, bytes, { upsert: false, contentType });
100
+ if (upErr) return json(500, { error: upErr.message });
101
+
102
+ const url = admin.storage.from('room-photos').getPublicUrl(path).data.publicUrl;
103
+
104
+ const { data: room, error: roomErr } = await admin
105
+ .from('rooms')
106
+ .select('images')
107
+ .eq('id', roomId)
108
+ .single();
109
+ if (roomErr) {
110
+ if (roomErr.code === 'PGRST116') return json(404, { error: 'room_not_found' });
111
+ return json(500, { error: roomErr.message });
112
+ }
113
+ if (!room) return json(404, { error: 'room_not_found' });
114
+
115
+ const existing = Array.isArray((room as { images: unknown }).images)
116
+ ? ((room as { images: ImageRef[] }).images)
117
+ : [];
118
+ const image: ImageRef = { path, alt, url };
119
+ const next = [...existing, image];
120
+
121
+ const { error: updErr } = await admin.from('rooms').update({ images: next }).eq('id', roomId);
122
+ if (updErr) return json(500, { error: updErr.message });
123
+
124
+ return json(200, { ok: true, image, images_count: next.length });
125
+ } catch (e) {
126
+ return json(500, { error: String(e) });
127
+ }
128
+ }
@@ -0,0 +1,150 @@
1
+ // Remove a sponsored "team member" (Company member) seat.
2
+ //
3
+ // Scope: seats with NO Stripe subscription of their own. Anyone holding a real
4
+ // subscription must go through admin-cancel-membership instead.
5
+ //
6
+ // Auth/audit scaffold copied from admin-cancel-membership (minus its Stripe
7
+ // pre-flight, which does not apply 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 {
21
+ sub: string;
22
+ email?: string;
23
+ aal?: string;
24
+ }
25
+
26
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
27
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
28
+ function getJwks(supabaseUrl: string) {
29
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
30
+ return jwksCache;
31
+ }
32
+
33
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
34
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
35
+ const token = authHeader.slice(7).trim();
36
+ try {
37
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
38
+ const claims = payload as unknown as CallerClaims;
39
+ if (!claims.sub) return null;
40
+ return claims;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ function json(status: number, body: unknown) {
47
+ return new Response(JSON.stringify(body), {
48
+ status,
49
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
50
+ });
51
+ }
52
+
53
+ const SEAT_COLUMNS = 'id,email,customer_name,status,stripe_subscription_id,sponsor_membership_id,membership_ended_at';
54
+
55
+ export async function handle(req: Request): Promise<Response> {
56
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
57
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
58
+
59
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
60
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
61
+
62
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
63
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
64
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
65
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
66
+ const callerEmail = (caller.email ?? '').toLowerCase();
67
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
68
+
69
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
70
+ auth: { persistSession: false, autoRefreshToken: false },
71
+ });
72
+
73
+ const [ipOk, emailOk] = await Promise.all([
74
+ checkRateLimit(admin, 'admin-remove-team-member-ip', clientIp(req), 30, 300),
75
+ checkRateLimit(admin, 'admin-remove-team-member-email', callerEmail, 20, 300),
76
+ ]);
77
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
78
+
79
+ const { data: allow, error: allowErr } = await admin
80
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
81
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
82
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
83
+
84
+ let body: { membership_id?: string; idempotency_key?: string; reason?: string };
85
+ try {
86
+ body = await req.json();
87
+ } catch {
88
+ return json(400, { ok: false, error: 'invalid_json' });
89
+ }
90
+
91
+ const membershipId = (body.membership_id ?? '').trim();
92
+ if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
93
+ return json(400, { ok: false, error: 'invalid_membership_id' });
94
+ }
95
+ const idempotencyKey = (body.idempotency_key ?? '').trim();
96
+ if (!idempotencyKey || idempotencyKey.length > 100) {
97
+ return json(400, { ok: false, error: 'invalid_idempotency_key' });
98
+ }
99
+ const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
100
+
101
+ const { data: seat, error: sErr } = await admin
102
+ .from('memberships').select(SEAT_COLUMNS).eq('id', membershipId).maybeSingle();
103
+ if (sErr) return json(500, { ok: false, error: 'lookup_failed', detail: sErr.message });
104
+ if (!seat) return json(404, { ok: false, error: 'membership_not_found' });
105
+ if (seat.stripe_subscription_id) {
106
+ return json(400, { ok: false, error: 'has_stripe_subscription' });
107
+ }
108
+
109
+ // Audit first, with the idempotency key. A duplicate means this removal
110
+ // already ran — report the row's actual current state, not a bare flag.
111
+ const { error: insErr } = await admin.from('membership_admin_actions').insert({
112
+ membership_id: membershipId,
113
+ action: 'sponsor_removed',
114
+ actor_email: callerEmail,
115
+ idempotency_key: idempotencyKey,
116
+ reason: reasonInput,
117
+ effective_at: new Date().toISOString(),
118
+ } as never);
119
+ if (insErr) {
120
+ if ((insErr as { code?: string }).code === '23505') {
121
+ const { data: current } = await admin
122
+ .from('memberships').select(SEAT_COLUMNS).eq('id', membershipId).maybeSingle();
123
+ return json(200, { ok: true, duplicate: true, membership: current ?? null });
124
+ }
125
+ return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
126
+ }
127
+
128
+ // Explicit column allowlist. door_managed is deliberately left as-is: door
129
+ // revocation is handled downstream, not by flipping this flag here.
130
+ const { error: updErr } = await admin
131
+ .from('memberships')
132
+ .update({
133
+ status: 'canceled',
134
+ membership_ended_at: new Date().toISOString(),
135
+ sponsor_membership_id: null,
136
+ } as never)
137
+ .eq('id', membershipId);
138
+ if (updErr) {
139
+ await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
140
+ await logOps(admin, 'team_member_remove_failed', {
141
+ membership_id: membershipId, actor: callerEmail, message: updErr.message,
142
+ }, { severity: 'error' }).catch(() => {});
143
+ return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
144
+ }
145
+
146
+ const { data: finalRow } = await admin
147
+ .from('memberships').select(SEAT_COLUMNS).eq('id', membershipId).maybeSingle();
148
+
149
+ return json(200, { ok: true, membership: finalRow ?? null });
150
+ }
@@ -0,0 +1,138 @@
1
+ import { createClient } from "npm:@supabase/supabase-js@2.45.0";
2
+ import { jwtVerify, createRemoteJWKSet } from "npm:jose@5.9.6";
3
+
4
+ const corsHeaders = {
5
+ "Access-Control-Allow-Origin": "*",
6
+ "Access-Control-Allow-Headers":
7
+ "authorization, x-client-info, apikey, content-type",
8
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
9
+ };
10
+
11
+ /**
12
+ * Admin-assisted MFA reset. Removes every MFA factor from a target
13
+ * allowlisted admin, signs them out globally, and forces re-enrollment on
14
+ * next magic-link login. Never trusts client claims; verifies the caller JWT
15
+ * via JWKS and re-checks the allowlist server-side with the service role.
16
+ */
17
+
18
+ function json(status: number, body: unknown) {
19
+ return new Response(JSON.stringify(body), {
20
+ status,
21
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
22
+ });
23
+ }
24
+
25
+ interface CallerClaims {
26
+ sub: string;
27
+ email?: string;
28
+ aal?: string;
29
+ }
30
+
31
+ const SUPABASE_URL = Deno.env.get("SUPABASE_URL")!;
32
+ const SERVICE_ROLE_KEY = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
33
+ const JWKS_URL = `${SUPABASE_URL}/auth/v1/.well-known/jwks.json`;
34
+ const jwks = createRemoteJWKSet(new URL(JWKS_URL));
35
+
36
+ async function verifyCaller(authHeader: string | null): Promise<CallerClaims | null> {
37
+ if (!authHeader?.toLowerCase().startsWith("bearer ")) return null;
38
+ const token = authHeader.slice(7).trim();
39
+ try {
40
+ const { payload } = await jwtVerify(token, jwks);
41
+ const claims = payload as unknown as CallerClaims;
42
+ if (!claims.sub) return null;
43
+ return claims;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ export async function handle(req: Request): Promise<Response> {
50
+ if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });
51
+ if (req.method !== "POST") return json(405, { ok: false, error: "method_not_allowed" });
52
+
53
+ const caller = await verifyCaller(req.headers.get("authorization"));
54
+ if (!caller) return json(401, { ok: false, error: "unauthenticated" });
55
+
56
+ if (caller.aal !== "aal2") {
57
+ return json(403, { ok: false, error: "mfa_required" });
58
+ }
59
+
60
+ const callerEmail = (caller.email ?? "").toLowerCase();
61
+ if (!callerEmail) return json(403, { ok: false, error: "no_email" });
62
+
63
+ let body: { target_email?: string; reason?: string };
64
+ try {
65
+ body = await req.json();
66
+ } catch {
67
+ return json(400, { ok: false, error: "invalid_json" });
68
+ }
69
+
70
+ const targetEmail = (body.target_email ?? "").trim().toLowerCase();
71
+ const reason = (body.reason ?? "").trim().slice(0, 500) || null;
72
+ if (!targetEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(targetEmail)) {
73
+ return json(400, { ok: false, error: "invalid_target_email" });
74
+ }
75
+ if (targetEmail === callerEmail) {
76
+ return json(403, { ok: false, error: "cannot_reset_self" });
77
+ }
78
+
79
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
80
+ auth: { persistSession: false, autoRefreshToken: false },
81
+ });
82
+
83
+ const { data: callerAllow, error: callerAllowErr } = await admin
84
+ .from("admin_users")
85
+ .select("email")
86
+ .eq("email", callerEmail)
87
+ .maybeSingle();
88
+ if (callerAllowErr) return json(500, { ok: false, error: "allowlist_lookup_failed" });
89
+ if (!callerAllow) return json(403, { ok: false, error: "caller_not_allowlisted" });
90
+
91
+ const { data: targetAllow, error: targetAllowErr } = await admin
92
+ .from("admin_users")
93
+ .select("email")
94
+ .eq("email", targetEmail)
95
+ .maybeSingle();
96
+ if (targetAllowErr) return json(500, { ok: false, error: "allowlist_lookup_failed" });
97
+ if (!targetAllow) return json(403, { ok: false, error: "target_not_allowlisted" });
98
+
99
+ // Locate target auth user. There are only three admins today, so page 1 is
100
+ // sufficient; we loop defensively in case that grows.
101
+ let targetUserId: string | null = null;
102
+ for (let page = 1; page <= 5 && !targetUserId; page++) {
103
+ const { data, error } = await admin.auth.admin.listUsers({ page, perPage: 200 });
104
+ if (error) return json(500, { ok: false, error: "list_users_failed", detail: error.message });
105
+ const found = data.users.find((u) => (u.email ?? "").toLowerCase() === targetEmail);
106
+ if (found) targetUserId = found.id;
107
+ if (data.users.length < 200) break;
108
+ }
109
+ if (!targetUserId) return json(404, { ok: false, error: "target_user_not_found" });
110
+
111
+ const { data: factorList, error: factorListErr } = await admin.auth.admin.mfa.listFactors({
112
+ userId: targetUserId,
113
+ });
114
+ if (factorListErr) return json(500, { ok: false, error: "list_factors_failed", detail: factorListErr.message });
115
+
116
+ let removed = 0;
117
+ for (const f of factorList.factors ?? []) {
118
+ const { error: delErr } = await admin.auth.admin.mfa.deleteFactor({
119
+ userId: targetUserId,
120
+ id: f.id,
121
+ });
122
+ if (delErr) return json(500, { ok: false, error: "delete_factor_failed", detail: delErr.message });
123
+ removed += 1;
124
+ }
125
+
126
+ await admin.auth.admin.signOut(targetUserId, "global");
127
+
128
+ await admin.from("mfa_reset_audit").insert({
129
+ actor_email: callerEmail,
130
+ actor_uid: caller.sub,
131
+ target_email: targetEmail,
132
+ target_uid: targetUserId,
133
+ factors_removed: removed,
134
+ reason,
135
+ });
136
+
137
+ return json(200, { ok: true, factors_removed: removed });
138
+ }