@simplelayer/graniteer-core 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +2 -2
- package/package.json +1 -1
- package/src/agreementCheckout.ts +250 -250
- package/src/agreementPortalEmail.ts +128 -128
- package/src/billingPortalLinkEmail.ts +117 -117
- package/src/bookingAgreementEmail.ts +149 -149
- package/src/bookingEffects.ts +388 -388
- package/src/busClient.ts +268 -268
- package/src/busSignature.ts +71 -71
- package/src/checkoutCoupon.test.ts +675 -675
- package/src/checkoutCoupon.ts +455 -455
- package/src/commonsDeposit.ts +298 -298
- package/src/commonsDepositWebhook.ts +237 -237
- package/src/dayPassConfirmation.ts +230 -230
- package/src/dunningEmails.test.ts +263 -263
- package/src/dunningEmails.ts +203 -203
- package/src/email-templates/brand.ts +93 -93
- package/src/email-templates/magic-link.tsx +59 -59
- package/src/email-templates/recovery.tsx +59 -59
- package/src/email-templates/signup.tsx +67 -67
- package/src/functions/admin-cancel-membership.ts +311 -311
- package/src/functions/admin-change-membership-plan.ts +312 -312
- package/src/functions/admin-charge-guest-print.ts +229 -229
- package/src/functions/admin-correct-booking.ts +333 -333
- package/src/functions/admin-create-booking.ts +460 -460
- package/src/functions/admin-create-commons-event.ts +244 -244
- package/src/functions/admin-debug-boldsign-doc.ts +93 -93
- package/src/functions/admin-door-write.ts +272 -272
- package/src/functions/admin-issue-day-pass.ts +231 -231
- package/src/functions/admin-mark-booking-paid.ts +203 -203
- package/src/functions/admin-mint-billing-portal-link.ts +168 -168
- package/src/functions/admin-mint-portal-link.ts +62 -62
- package/src/functions/admin-photo-upload.ts +128 -128
- package/src/functions/admin-remove-team-member.ts +150 -150
- package/src/functions/admin-request-trial.ts +366 -366
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
- package/src/functions/admin-reset-mfa.ts +138 -138
- package/src/functions/admin-retry-invoice-payment.ts +333 -333
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
- package/src/functions/admin-revoke-agreement.ts +467 -467
- package/src/functions/admin-send-commons-agreement.ts +214 -214
- package/src/functions/admin-set-credit-amount.ts +123 -123
- package/src/functions/admin-skip-commons-contract.ts +165 -165
- package/src/functions/admin-undo-membership-cancel.ts +144 -144
- package/src/functions/admin-wall-photo-write.ts +141 -141
- package/src/functions/auth-email-hook.ts +259 -259
- package/src/functions/boldsign-sender-identity.ts +114 -114
- package/src/functions/booking-availability.ts +419 -419
- package/src/functions/booking-member-preview.ts +136 -136
- package/src/functions/booking-status.ts +149 -149
- package/src/functions/create-booking.ts +648 -648
- package/src/functions/create-day-pass-checkout.ts +218 -218
- package/src/functions/create-portal-session.ts +142 -142
- package/src/functions/create-subscription-checkout.test.ts +222 -222
- package/src/functions/create-subscription-checkout.ts +440 -440
- package/src/functions/day-pass-status.ts +89 -89
- package/src/functions/diag-webpush-test.ts +45 -45
- package/src/functions/event-access-admin.ts +277 -277
- package/src/functions/event-access-store.ts +334 -334
- package/src/functions/ezeep-print-webhook.ts +213 -213
- package/src/functions/ezeep-usage-reconcile.ts +299 -299
- package/src/functions/fetch-avatar-original.ts +457 -457
- package/src/functions/get-provider-sign-link.ts +155 -155
- package/src/functions/get-signing-link.ts +211 -211
- package/src/functions/guest-print-setup-confirm.ts +128 -128
- package/src/functions/guest-print-submit.ts +149 -149
- package/src/functions/luma-webhook.ts +165 -165
- package/src/functions/mcp.ts +67 -67
- package/src/functions/member-door-action.test.ts +1248 -1248
- package/src/functions/member-door-action.ts +863 -863
- package/src/functions/member-unifi-mapping.test.ts +516 -516
- package/src/functions/member-unifi-mapping.ts +206 -206
- package/src/functions/membership-door-sync.ts +956 -956
- package/src/functions/migration-collision-alert.copy.ts +232 -232
- package/src/functions/migration-collision-alert.test.ts +349 -349
- package/src/functions/migration-collision-alert.ts +232 -232
- package/src/functions/office-assignment-end.ts +146 -146
- package/src/functions/portal-booking-access.ts +217 -217
- package/src/functions/portal-list-invoices.ts +99 -99
- package/src/functions/portal-request-login.ts +219 -192
- package/src/functions/portal-resend-invite.ts +248 -248
- package/src/functions/portal-submit-event.ts +168 -168
- package/src/functions/print-billing-recover.ts +97 -97
- package/src/functions/print-billing-run.ts +183 -183
- package/src/functions/public-facts.ts +168 -168
- package/src/functions/push-send.ts +348 -348
- package/src/functions/push-test.ts +234 -234
- package/src/functions/request-portal-link.ts +211 -211
- package/src/functions/review-ratings.ts +113 -113
- package/src/functions/space-availability-range.acceptance.test.ts +161 -161
- package/src/functions/space-availability-range.ts +142 -142
- package/src/functions/stripe-db-reconcile.ts +319 -319
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
- package/src/functions/stripe-webhook.ts +2595 -2595
- package/src/functions/sync-gcal-blackouts.ts +298 -298
- package/src/functions/timetable-event-register.ts +162 -162
- package/src/functions/timetable-event-status.ts +90 -90
- package/src/functions/timetable-spaces.ts +219 -219
- package/src/functions/touch-pass-reconciler.ts +689 -689
- package/src/functions/touch-pass-signup.ts +478 -478
- package/src/functions/upload-booking-display-image.ts +179 -179
- package/src/functions/virtual-onboarding-purge.ts +134 -134
- package/src/functions/virtual-onboarding-submit.ts +315 -315
- package/src/functions/voice-booking.ts +453 -453
- package/src/functions/voice-day-pass.ts +346 -346
- package/src/functions/voice-inquiry.test.ts +301 -301
- package/src/functions/voice-inquiry.ts +198 -198
- package/src/functions/voice-membership-signup.ts +355 -355
- package/src/functions/voice-tour-availability.ts +204 -204
- package/src/functions/voice-tour-booking.ts +429 -429
- package/src/ghlEventInquiry.ts +143 -143
- package/src/mailArrivalEmail.ts +121 -121
- package/src/manageToken.ts +363 -363
- package/src/membershipBusClient.ts +537 -537
- package/src/membershipWelcome.ts +683 -683
- package/src/migrationCheckout.ts +366 -366
- package/src/paymentLinkEmail.ts +123 -123
- package/src/signedUnpaidReminderEmail.test.ts +246 -246
- package/src/signedUnpaidReminderEmail.ts +132 -132
- package/src/stripeCoworkingPortal.ts +91 -91
- package/src/supabaseTestFakes.ts +131 -131
- package/src/supportTicketEmail.ts +119 -119
- package/src/unifiAccessPolicies.ts +228 -228
- package/src/unifiGroups.ts +129 -129
|
@@ -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
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
email
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
},
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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
|
+
}
|