@simplelayer/graniteer-core 0.2.0 → 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 -309
  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 -95
  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,128 +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
- }
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
+ }
@@ -1,150 +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
- }
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
+ }