@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,99 +1,99 @@
1
- // Member-portal invoice list. Thin read-only wrapper around Stripe's invoice
2
- // list, needed because the Stripe secret key must never reach the browser.
3
- //
4
- // Auth is the SAME portal-session mode already added to manage-booking /
5
- // reschedule-booking: `Authorization: Bearer <supabase jwt>` verified with
6
- // `_shared/portalSession.ts`. No new secret is introduced — it reuses the
7
- // existing STRIPE_SECRET_KEY.
8
- import { createClient } from 'npm:@supabase/supabase-js@2';
9
- import Stripe from 'npm:stripe@17.5.0';
10
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
11
- import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
12
-
13
- const corsHeaders = {
14
- 'Access-Control-Allow-Origin': '*',
15
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
16
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
17
- };
18
-
19
- function json(status: number, body: unknown) {
20
- return new Response(JSON.stringify(body), {
21
- status,
22
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
23
- });
24
- }
25
-
26
- export async function handle(req: Request): Promise<Response> {
27
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
28
- if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
29
-
30
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
31
- if (!stripeKey) return json(500, { error: 'not_configured' });
32
-
33
- const admin = createClient(
34
- Deno.env.get('SUPABASE_URL')!,
35
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
36
- { auth: { persistSession: false, autoRefreshToken: false } },
37
- );
38
-
39
- const ipOk = await checkRateLimit(admin, 'portal-invoices-ip', clientIp(req), 60, 300);
40
- if (!ipOk) return json(429, { error: 'rate_limited' });
41
-
42
- const session = await resolvePortalSession(req, admin);
43
- if (!session) return json(401, { error: 'unauthorized' });
44
- const email = session.email;
45
-
46
- const emailLower = email.toLowerCase();
47
-
48
- // Step A: identity match on the linked auth user id.
49
- const { data: byIdRows, error: byIdErr } = await admin
50
- .from('memberships')
51
- .select('stripe_customer_id,email')
52
- .eq('auth_user_id', session.id)
53
- .not('stripe_customer_id', 'is', null)
54
- .order('created_at', { ascending: false });
55
- if (byIdErr) return json(500, { error: 'lookup_failed' });
56
- let membership: { stripe_customer_id: string; email: string } | undefined = (byIdRows ?? [])[0];
57
-
58
- // Step B (transition): case-insensitive DB round-trip, then an exact JS match
59
- // so a session email containing LIKE wildcards (_ or %) can never select
60
- // another member's row. Restricted to still-unlinked rows.
61
- if (!membership) {
62
- const { data: membershipRows, error: membershipErr } = await admin
63
- .from('memberships')
64
- .select('stripe_customer_id,email')
65
- .ilike('email', emailLower)
66
- .is('auth_user_id', null)
67
- .not('stripe_customer_id', 'is', null)
68
- .order('created_at', { ascending: false });
69
- if (membershipErr) return json(500, { error: 'lookup_failed' });
70
- membership = (membershipRows ?? []).find(
71
- (r) => (r.email ?? '').toLowerCase() === emailLower,
72
- );
73
- }
74
-
75
- const customer = membership?.stripe_customer_id;
76
- // No Stripe customer on file is a normal state (booking-only customer).
77
- if (!customer) return json(200, { invoices: [] });
78
-
79
- try {
80
- const stripe = new Stripe(stripeKey, {
81
- apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion,
82
- });
83
- const list = await stripe.invoices.list({ customer, limit: 20 });
84
- const invoices = list.data.map((inv) => ({
85
- id: inv.id,
86
- number: inv.number ?? null,
87
- created: new Date(inv.created * 1000).toISOString(),
88
- amount_due_cents: inv.amount_due ?? 0,
89
- amount_paid_cents: inv.amount_paid ?? 0,
90
- status: inv.status ?? null,
91
- hosted_invoice_url: inv.hosted_invoice_url ?? null,
92
- invoice_pdf: inv.invoice_pdf ?? null,
93
- }));
94
- return json(200, { invoices });
95
- } catch (e) {
96
- console.error('[portal-list-invoices] stripe list failed', e);
97
- return json(502, { error: 'invoices_unavailable' });
98
- }
99
- }
1
+ // Member-portal invoice list. Thin read-only wrapper around Stripe's invoice
2
+ // list, needed because the Stripe secret key must never reach the browser.
3
+ //
4
+ // Auth is the SAME portal-session mode already added to manage-booking /
5
+ // reschedule-booking: `Authorization: Bearer <supabase jwt>` verified with
6
+ // `_shared/portalSession.ts`. No new secret is introduced — it reuses the
7
+ // existing STRIPE_SECRET_KEY.
8
+ import { createClient } from 'npm:@supabase/supabase-js@2';
9
+ import Stripe from 'npm:stripe@17.5.0';
10
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
11
+ import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
12
+
13
+ const corsHeaders = {
14
+ 'Access-Control-Allow-Origin': '*',
15
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
16
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
17
+ };
18
+
19
+ function json(status: number, body: unknown) {
20
+ return new Response(JSON.stringify(body), {
21
+ status,
22
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
23
+ });
24
+ }
25
+
26
+ export async function handle(req: Request): Promise<Response> {
27
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
28
+ if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
29
+
30
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
31
+ if (!stripeKey) return json(500, { error: 'not_configured' });
32
+
33
+ const admin = createClient(
34
+ Deno.env.get('SUPABASE_URL')!,
35
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
36
+ { auth: { persistSession: false, autoRefreshToken: false } },
37
+ );
38
+
39
+ const ipOk = await checkRateLimit(admin, 'portal-invoices-ip', clientIp(req), 60, 300);
40
+ if (!ipOk) return json(429, { error: 'rate_limited' });
41
+
42
+ const session = await resolvePortalSession(req, admin);
43
+ if (!session) return json(401, { error: 'unauthorized' });
44
+ const email = session.email;
45
+
46
+ const emailLower = email.toLowerCase();
47
+
48
+ // Step A: identity match on the linked auth user id.
49
+ const { data: byIdRows, error: byIdErr } = await admin
50
+ .from('memberships')
51
+ .select('stripe_customer_id,email')
52
+ .eq('auth_user_id', session.id)
53
+ .not('stripe_customer_id', 'is', null)
54
+ .order('created_at', { ascending: false });
55
+ if (byIdErr) return json(500, { error: 'lookup_failed' });
56
+ let membership: { stripe_customer_id: string; email: string } | undefined = (byIdRows ?? [])[0];
57
+
58
+ // Step B (transition): case-insensitive DB round-trip, then an exact JS match
59
+ // so a session email containing LIKE wildcards (_ or %) can never select
60
+ // another member's row. Restricted to still-unlinked rows.
61
+ if (!membership) {
62
+ const { data: membershipRows, error: membershipErr } = await admin
63
+ .from('memberships')
64
+ .select('stripe_customer_id,email')
65
+ .ilike('email', emailLower)
66
+ .is('auth_user_id', null)
67
+ .not('stripe_customer_id', 'is', null)
68
+ .order('created_at', { ascending: false });
69
+ if (membershipErr) return json(500, { error: 'lookup_failed' });
70
+ membership = (membershipRows ?? []).find(
71
+ (r) => (r.email ?? '').toLowerCase() === emailLower,
72
+ );
73
+ }
74
+
75
+ const customer = membership?.stripe_customer_id;
76
+ // No Stripe customer on file is a normal state (booking-only customer).
77
+ if (!customer) return json(200, { invoices: [] });
78
+
79
+ try {
80
+ const stripe = new Stripe(stripeKey, {
81
+ apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion,
82
+ });
83
+ const list = await stripe.invoices.list({ customer, limit: 20 });
84
+ const invoices = list.data.map((inv) => ({
85
+ id: inv.id,
86
+ number: inv.number ?? null,
87
+ created: new Date(inv.created * 1000).toISOString(),
88
+ amount_due_cents: inv.amount_due ?? 0,
89
+ amount_paid_cents: inv.amount_paid ?? 0,
90
+ status: inv.status ?? null,
91
+ hosted_invoice_url: inv.hosted_invoice_url ?? null,
92
+ invoice_pdf: inv.invoice_pdf ?? null,
93
+ }));
94
+ return json(200, { invoices });
95
+ } catch (e) {
96
+ console.error('[portal-list-invoices] stripe list failed', e);
97
+ return json(502, { error: 'invoices_unavailable' });
98
+ }
99
+ }
@@ -1,192 +1,219 @@
1
- // Member-portal magic-link request.
2
- //
3
- // The browser never calls signInWithOtp directly — it posts here so the send
4
- // is rate-limited server-side (per IP and per email) using the same
5
- // check_rate_limit helper the booking functions use. Project-level signup is
6
- // disabled (deliberate, do not widen), and shouldCreateUser:true does NOT
7
- // override it for the anon client — so we pre-create the auth user with the
8
- // service-role admin API first, then send a plain magic link to an
9
- // already-existing user, which the signup gate never blocks.
10
- //
11
- // This does NOT touch the existing HMAC manage-link flow.
12
- import { createClient } from 'npm:@supabase/supabase-js@2';
13
- import { z } from 'npm:zod@3.23.8';
14
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
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
- const Body = z.object({
23
- email: z.string().email().max(320),
24
- redirect_to: z.string().url().optional(),
25
- });
26
-
27
- function json(status: number, body: unknown) {
28
- return new Response(JSON.stringify(body), {
29
- status,
30
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
31
- });
32
- }
33
-
34
- export interface PortalRequestLoginConfig {
35
- /** Bare tenant site domain, e.g. "example.com". The redirect allowlist
36
- * is this domain, its www subdomain, plus localhost/127.0.0.1 for dev.
37
- * The fallback redirect is `https://${rootDomain}/portal`. */
38
- rootDomain: string;
39
- }
40
-
41
- export function createPortalRequestLoginHandler(
42
- config: PortalRequestLoginConfig,
43
- ): (req: Request) => Promise<Response> {
44
- const ROOT_DOMAIN = config.rootDomain.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/+$/, '');
45
-
46
- // Only ever redirect back to hosts we control.
47
- function safeRedirect(raw: string | undefined): string {
48
- const fallback = `https://${ROOT_DOMAIN}/portal`;
49
- if (!raw) return fallback;
50
- try {
51
- const u = new URL(raw);
52
- const h = u.hostname;
53
- const ok =
54
- h === ROOT_DOMAIN ||
55
- h === `www.${ROOT_DOMAIN}` ||
56
- h === 'localhost' ||
57
- h === '127.0.0.1';
58
- if (!ok) return fallback;
59
- // Preserve only known internal destinations (portal pages, and the MCP
60
- // OAuth consent screen so a client authorization survives sign-in).
61
- const path = u.pathname + u.search;
62
- const allowedPath =
63
- path === '/portal' ||
64
- path.startsWith('/portal/') ||
65
- path.startsWith('/.lovable/oauth/consent');
66
- return allowedPath ? `${u.origin}${path}` : `${u.origin}/portal`;
67
- } catch {
68
- return fallback;
69
- }
70
- }
71
-
72
- return async (req) => {
73
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
74
- if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
75
-
76
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
77
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
78
- const ANON_KEY = Deno.env.get('SUPABASE_ANON_KEY')!;
79
-
80
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
81
- auth: { persistSession: false, autoRefreshToken: false },
82
- });
83
-
84
- const raw = await req.json().catch(() => ({}));
85
- const parsed = Body.safeParse(raw);
86
- if (!parsed.success) return json(400, { error: parsed.error.flatten() });
87
- const email = parsed.data.email.trim().toLowerCase();
88
-
89
- const ip = clientIp(req);
90
- const [ipOk, emailOk] = await Promise.all([
91
- checkRateLimit(admin, 'portal-login-ip', ip, 15, 300),
92
- checkRateLimit(admin, 'portal-login-email', email, 5, 900),
93
- ]);
94
- if (!ipOk || !emailOk) return json(429, { error: 'rate_limited' });
95
-
96
- // Gate the account-creation + email-send side effects on the address being a
97
- // known member, booking contact, day-pass guest, guest-print submitter, or
98
- // admin/staff account. Response shape is identical either way so the
99
- // endpoint never enumerates.
100
- // Emails are stored lowercase (S2 fix), so a case-insensitive match here is
101
- // exact.
102
- const [mRes, bRes, dRes, aRes, gRes] = await Promise.all([
103
- admin.from('memberships').select('id', { count: 'exact', head: true }).ilike('email', email),
104
- admin.from('bookings').select('id', { count: 'exact', head: true }).ilike('contact_email', email),
105
- // Day-pass guests get a portal account too (Kyle, 2026-08-20), so they must
106
- // count as a known contact or their login request would silently no-op.
107
- admin.from('day_pass_purchases').select('id', { count: 'exact', head: true }).ilike('email', email),
108
- // Admin/staff accounts have no row in any of the above three tables, so
109
- // without this an admin_users-only address was silently told "sent" with
110
- // no email ever going out (real lockout, confirmed 2026-09-09).
111
- // NOTE: admin_users has NO `id` column (email is the PK). Selecting 'id'
112
- // here returned PostgREST 42703 with an empty message on a HEAD request,
113
- // which tripped the error branch below and silently swallowed every
114
- // admin-only login request (confirmed 2026-09-10).
115
- admin.from('admin_users').select('email', { count: 'exact', head: true }).ilike('email', email),
116
- // D5 (GATE-0194 option B): a guest print-job submission is itself the
117
- // "known contact" qualifying event -- no prior day-pass/booking purchase
118
- // required first. Any row counts regardless of status (mirrors
119
- // day_pass_purchases above): the qualifying act is submitting the job,
120
- // not the card succeeding or the job being charged yet.
121
- //
122
- // OPEN PRODUCT QUESTION, flagged by D5's adversarial review (round 1 S1,
123
- // round 2 confirmed): guest-print-submit is PUBLIC and unauthenticated,
124
- // so counting ANY row (including 'pending_card', before the guest has
125
- // touched a card form at all) means one POST with an arbitrary email
126
- // creates a permanent "known contact" record and triggers a real
127
- // Supabase auth-user creation + magic-link email to that address. Both
128
- // reviewers independently recommended `status <> 'pending_card'` as the
129
- // reading that still implements GATE-0194(B) ("showing up to print
130
- // qualifies you") while requiring the guest to have actually reached a
131
- // card step -- but this is Kyle's product call to ratify, not a silent
132
- // patch. See the D5 build report. NOT changed pending that decision.
133
- admin.from('print_guest_submissions').select('id', { count: 'exact', head: true }).ilike('email', email),
134
- ]);
135
- if (mRes.error || bRes.error || dRes.error || aRes.error || gRes.error) {
136
- console.error('[portal-request-login] known-contact lookup failed', {
137
- memberships: mRes.error?.message, bookings: bRes.error?.message,
138
- day_passes: dRes.error?.message, admin_users: aRes.error?.message,
139
- guest_print: gRes.error?.message,
140
- });
141
- // A real lookup failure must not masquerade as the "unknown email"
142
- // success response — that pattern hid the admin_users column bug.
143
- // This happens before any email-existence check, so it never reveals
144
- // whether an address is known.
145
- return json(500, { error: 'lookup_failed' });
146
- }
147
- if (
148
- (mRes.count ?? 0) === 0 && (bRes.count ?? 0) === 0 && (dRes.count ?? 0) === 0 &&
149
- (aRes.count ?? 0) === 0 && (gRes.count ?? 0) === 0
150
- ) {
151
- return json(200, { ok: true });
152
- }
153
-
154
- const anon = createClient(SUPABASE_URL, ANON_KEY, {
155
- auth: { persistSession: false, autoRefreshToken: false },
156
- });
157
-
158
- // Ensure the auth user exists (service role bypasses disable_signup).
159
- // "already registered" is the expected happy path for returning members.
160
- const { error: createErr } = await admin.auth.admin.createUser({
161
- email,
162
- email_confirm: true,
163
- });
164
- if (createErr) {
165
- const msg = (createErr.message || '').toLowerCase();
166
- const alreadyExists =
167
- msg.includes('already been registered') ||
168
- msg.includes('already registered') ||
169
- msg.includes('already exists') ||
170
- createErr.code === 'email_exists' ||
171
- createErr.status === 422;
172
- if (!alreadyExists) {
173
- console.error('[portal-request-login] create user failed', { email, error: createErr.message });
174
- return json(500, { error: 'send_failed' });
175
- }
176
- }
177
-
178
- const { error } = await anon.auth.signInWithOtp({
179
- email,
180
- options: {
181
- emailRedirectTo: safeRedirect(parsed.data.redirect_to),
182
- },
183
- });
184
- if (error) {
185
- console.error('[portal-request-login] otp send failed', { email, error: error.message });
186
- return json(500, { error: 'send_failed' });
187
- }
188
-
189
- // Generic response — never reveals whether the address is known.
190
- return json(200, { ok: true });
191
- };
192
- }
1
+ // Member-portal magic-link request.
2
+ //
3
+ // The browser never calls signInWithOtp directly — it posts here so the send
4
+ // is rate-limited server-side (per IP and per email) using the same
5
+ // check_rate_limit helper the booking functions use. Project-level signup is
6
+ // disabled (deliberate, do not widen), and shouldCreateUser:true does NOT
7
+ // override it for the anon client — so we pre-create the auth user with the
8
+ // service-role admin API first, then send a plain magic link to an
9
+ // already-existing user, which the signup gate never blocks.
10
+ //
11
+ // This does NOT touch the existing HMAC manage-link flow.
12
+ import { createClient } from 'npm:@supabase/supabase-js@2';
13
+ import { z } from 'npm:zod@3.23.8';
14
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
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
+ const Body = z.object({
23
+ email: z.string().email().max(320),
24
+ redirect_to: z.string().url().optional(),
25
+ });
26
+
27
+ function json(status: number, body: unknown) {
28
+ return new Response(JSON.stringify(body), {
29
+ status,
30
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
31
+ });
32
+ }
33
+
34
+ export interface PortalRequestLoginConfig {
35
+ /** Bare tenant site domain, e.g. "example.com". The redirect allowlist
36
+ * is this domain, its www subdomain, plus localhost/127.0.0.1 for dev.
37
+ * The fallback redirect is `https://${rootDomain}/portal`. */
38
+ rootDomain: string;
39
+ }
40
+
41
+ export function createPortalRequestLoginHandler(
42
+ config: PortalRequestLoginConfig,
43
+ ): (req: Request) => Promise<Response> {
44
+ const ROOT_DOMAIN = config.rootDomain.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/+$/, '');
45
+
46
+ // Only ever redirect back to hosts we control.
47
+ function safeRedirect(raw: string | undefined): string {
48
+ const fallback = `https://${ROOT_DOMAIN}/portal`;
49
+ if (!raw) return fallback;
50
+ try {
51
+ const u = new URL(raw);
52
+ const h = u.hostname;
53
+ const ok =
54
+ h === ROOT_DOMAIN ||
55
+ h === `www.${ROOT_DOMAIN}` ||
56
+ h === 'localhost' ||
57
+ h === '127.0.0.1';
58
+ if (!ok) return fallback;
59
+ // Preserve only known internal destinations (portal pages, and the MCP
60
+ // OAuth consent screen so a client authorization survives sign-in).
61
+ const path = u.pathname + u.search;
62
+ const allowedPath =
63
+ path === '/portal' ||
64
+ path.startsWith('/portal/') ||
65
+ path.startsWith('/.lovable/oauth/consent');
66
+ return allowedPath ? `${u.origin}${path}` : `${u.origin}/portal`;
67
+ } catch {
68
+ return fallback;
69
+ }
70
+ }
71
+
72
+ return async (req) => {
73
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
74
+ if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
75
+
76
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
77
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
78
+ const ANON_KEY = Deno.env.get('SUPABASE_ANON_KEY')!;
79
+
80
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
81
+ auth: { persistSession: false, autoRefreshToken: false },
82
+ });
83
+
84
+ const raw = await req.json().catch(() => ({}));
85
+ const parsed = Body.safeParse(raw);
86
+ if (!parsed.success) return json(400, { error: parsed.error.flatten() });
87
+ const email = parsed.data.email.trim().toLowerCase();
88
+
89
+ const ip = clientIp(req);
90
+ const [ipOk, emailOk] = await Promise.all([
91
+ checkRateLimit(admin, 'portal-login-ip', ip, 15, 300),
92
+ checkRateLimit(admin, 'portal-login-email', email, 5, 900),
93
+ ]);
94
+ if (!ipOk || !emailOk) return json(429, { error: 'rate_limited' });
95
+
96
+ // Gate the account-creation + email-send side effects on the address being a
97
+ // known member, booking contact, day-pass guest, guest-print submitter, or
98
+ // admin/staff account. Response shape is identical either way so the
99
+ // endpoint never enumerates.
100
+ // Emails are stored lowercase (S2 fix), so a case-insensitive match here is
101
+ // exact.
102
+ const [mRes, bRes, dRes, aRes, gRes] = await Promise.all([
103
+ admin.from('memberships').select('id', { count: 'exact', head: true }).ilike('email', email),
104
+ admin.from('bookings').select('id', { count: 'exact', head: true }).ilike('contact_email', email),
105
+ // Day-pass guests get a portal account too (Kyle, 2026-08-20), so they must
106
+ // count as a known contact or their login request would silently no-op.
107
+ admin.from('day_pass_purchases').select('id', { count: 'exact', head: true }).ilike('email', email),
108
+ // Admin/staff accounts have no row in any of the above three tables, so
109
+ // without this an admin_users-only address was silently told "sent" with
110
+ // no email ever going out (real lockout, confirmed 2026-09-09).
111
+ // NOTE: admin_users has NO `id` column (email is the PK). Selecting 'id'
112
+ // here returned PostgREST 42703 with an empty message on a HEAD request,
113
+ // which tripped the error branch below and silently swallowed every
114
+ // admin-only login request (confirmed 2026-09-10).
115
+ admin.from('admin_users').select('email', { count: 'exact', head: true }).ilike('email', email),
116
+ // D5 (GATE-0194 option B): a guest print-job submission is itself the
117
+ // "known contact" qualifying event -- no prior day-pass/booking purchase
118
+ // required first. Any row counts regardless of status (mirrors
119
+ // day_pass_purchases above): the qualifying act is submitting the job,
120
+ // not the card succeeding or the job being charged yet.
121
+ //
122
+ // OPEN PRODUCT QUESTION, flagged by D5's adversarial review (round 1 S1,
123
+ // round 2 confirmed): guest-print-submit is PUBLIC and unauthenticated,
124
+ // so counting ANY row (including 'pending_card', before the guest has
125
+ // touched a card form at all) means one POST with an arbitrary email
126
+ // creates a permanent "known contact" record and triggers a real
127
+ // Supabase auth-user creation + magic-link email to that address. Both
128
+ // reviewers independently recommended `status <> 'pending_card'` as the
129
+ // reading that still implements GATE-0194(B) ("showing up to print
130
+ // qualifies you") while requiring the guest to have actually reached a
131
+ // card step -- but this is Kyle's product call to ratify, not a silent
132
+ // patch. See the D5 build report. NOT changed pending that decision.
133
+ admin.from('print_guest_submissions').select('id', { count: 'exact', head: true }).ilike('email', email),
134
+ ]);
135
+
136
+ // A table this tenant hasn't provisioned yet (e.g. the guest-print feature
137
+ // isn't migrated for every tenant) must not take down every login on this
138
+ // endpoint — confirmed live 2026-09-16: print_guest_submissions missing on
139
+ // a real tenant's DB made this branch 500 on every single request,
140
+ // regardless of email, before the email-send step was ever reached. Only
141
+ // "relation does not exist" (Postgres 42P01) degrades gracefully to "no
142
+ // match from this channel"; any OTHER error still hard-fails exactly as
143
+ // before, preserving the original intent (don't let a real lookup failure
144
+ // — e.g. the past admin_users column bug — masquerade as "unknown email").
145
+ function isMissingTable(err: { code?: string; message?: string } | null | undefined): boolean {
146
+ if (!err) return false;
147
+ if (err.code === '42P01') return true;
148
+ return /relation .* does not exist/i.test(err.message ?? '');
149
+ }
150
+
151
+ const lookups = {
152
+ memberships: mRes, bookings: bRes, day_passes: dRes, admin_users: aRes, guest_print: gRes,
153
+ } as const;
154
+ const hardFailures = Object.entries(lookups).filter(([, r]) => r.error && !isMissingTable(r.error));
155
+ if (hardFailures.length > 0) {
156
+ console.error('[portal-request-login] known-contact lookup failed', {
157
+ memberships: mRes.error?.message, bookings: bRes.error?.message,
158
+ day_passes: dRes.error?.message, admin_users: aRes.error?.message,
159
+ guest_print: gRes.error?.message,
160
+ });
161
+ // A real lookup failure must not masquerade as the "unknown email"
162
+ // success response — that pattern hid the admin_users column bug.
163
+ // This happens before any email-existence check, so it never reveals
164
+ // whether an address is known.
165
+ return json(500, { error: 'lookup_failed' });
166
+ }
167
+ for (const [key, r] of Object.entries(lookups)) {
168
+ if (r.error) {
169
+ console.warn(`[portal-request-login] ${key} table not provisioned for this tenant — treating as no match`, r.error.message);
170
+ }
171
+ }
172
+ const mCount = mRes.error ? 0 : (mRes.count ?? 0);
173
+ const bCount = bRes.error ? 0 : (bRes.count ?? 0);
174
+ const dCount = dRes.error ? 0 : (dRes.count ?? 0);
175
+ const aCount = aRes.error ? 0 : (aRes.count ?? 0);
176
+ const gCount = gRes.error ? 0 : (gRes.count ?? 0);
177
+ if (mCount === 0 && bCount === 0 && dCount === 0 && aCount === 0 && gCount === 0) {
178
+ return json(200, { ok: true });
179
+ }
180
+
181
+ const anon = createClient(SUPABASE_URL, ANON_KEY, {
182
+ auth: { persistSession: false, autoRefreshToken: false },
183
+ });
184
+
185
+ // Ensure the auth user exists (service role bypasses disable_signup).
186
+ // "already registered" is the expected happy path for returning members.
187
+ const { error: createErr } = await admin.auth.admin.createUser({
188
+ email,
189
+ email_confirm: true,
190
+ });
191
+ if (createErr) {
192
+ const msg = (createErr.message || '').toLowerCase();
193
+ const alreadyExists =
194
+ msg.includes('already been registered') ||
195
+ msg.includes('already registered') ||
196
+ msg.includes('already exists') ||
197
+ createErr.code === 'email_exists' ||
198
+ createErr.status === 422;
199
+ if (!alreadyExists) {
200
+ console.error('[portal-request-login] create user failed', { email, error: createErr.message });
201
+ return json(500, { error: 'send_failed' });
202
+ }
203
+ }
204
+
205
+ const { error } = await anon.auth.signInWithOtp({
206
+ email,
207
+ options: {
208
+ emailRedirectTo: safeRedirect(parsed.data.redirect_to),
209
+ },
210
+ });
211
+ if (error) {
212
+ console.error('[portal-request-login] otp send failed', { email, error: error.message });
213
+ return json(500, { error: 'send_failed' });
214
+ }
215
+
216
+ // Generic response — never reveals whether the address is known.
217
+ return json(200, { ok: true });
218
+ };
219
+ }