@simplelayer/graniteer-core 0.1.2 → 0.2.1
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 +73 -2
- package/src/agreementCheckout.ts +250 -0
- package/src/agreementPortalEmail.ts +128 -0
- package/src/billingPortalLinkEmail.ts +117 -0
- package/src/bookingAgreementEmail.ts +149 -0
- package/src/bookingEffects.ts +388 -0
- package/src/busClient.ts +268 -0
- package/src/busSignature.ts +71 -0
- package/src/checkoutCoupon.test.ts +675 -0
- package/src/checkoutCoupon.ts +455 -0
- package/src/commonsDeposit.ts +298 -0
- package/src/commonsDepositWebhook.ts +237 -0
- package/src/dayPassConfirmation.ts +230 -0
- package/src/dunningEmails.test.ts +263 -0
- package/src/dunningEmails.ts +203 -0
- package/src/email-templates/brand.ts +93 -0
- package/src/email-templates/magic-link.tsx +59 -0
- package/src/email-templates/recovery.tsx +59 -0
- package/src/email-templates/signup.tsx +67 -0
- package/src/functions/admin-cancel-membership.ts +311 -311
- package/src/functions/admin-change-membership-plan.ts +312 -308
- 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 -0
- 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 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -203
- package/src/functions/admin-mint-billing-portal-link.ts +168 -0
- package/src/functions/admin-mint-portal-link.ts +62 -0
- 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 -0
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
- package/src/functions/admin-reset-mfa.ts +138 -138
- package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
- package/src/functions/admin-retry-invoice-payment.ts +333 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
- package/src/functions/admin-revoke-agreement.ts +467 -0
- 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 -0
- 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 -0
- package/src/functions/conductor.ts +505 -0
- package/src/functions/create-agreement.ts +537 -0
- package/src/functions/create-booking.ts +648 -0
- package/src/functions/create-day-pass-checkout.ts +218 -0
- package/src/functions/create-portal-session.ts +142 -0
- package/src/functions/create-subscription-checkout.test.ts +222 -0
- package/src/functions/create-subscription-checkout.ts +440 -0
- 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 -0
- package/src/functions/event-access-store.ts +334 -309
- 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 -0
- package/src/functions/get-provider-sign-link.ts +155 -0
- 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/manage-booking.ts +472 -0
- package/src/functions/mcp.ts +67 -0
- package/src/functions/member-door-action.test.ts +1248 -0
- package/src/functions/member-door-action.ts +863 -0
- package/src/functions/member-unifi-mapping.test.ts +516 -0
- package/src/functions/member-unifi-mapping.ts +206 -0
- package/src/functions/membership-door-sync.ts +956 -0
- 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 -95
- package/src/functions/portal-list-invoices.ts +99 -99
- package/src/functions/portal-request-login.ts +192 -0
- package/src/functions/portal-resend-invite.ts +248 -0
- package/src/functions/portal-submit-event.ts +168 -0
- 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 -0
- package/src/functions/push-test.ts +234 -0
- package/src/functions/request-portal-link.ts +211 -0
- package/src/functions/reschedule-booking.ts +649 -0
- package/src/functions/review-ratings.ts +113 -0
- 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 -0
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
- package/src/functions/stripe-webhook.ts +2595 -0
- 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 -0
- package/src/functions/upload-booking-display-image.ts +179 -0
- 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 -0
- package/src/functions/voice-day-pass.ts +346 -0
- 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 -0
- package/src/functions/voice-tour-availability.ts +204 -204
- package/src/functions/voice-tour-booking.ts +429 -0
- package/src/ghlEventInquiry.ts +143 -0
- package/src/mailArrivalEmail.ts +121 -0
- package/src/manageToken.ts +363 -0
- package/src/membershipBusClient.ts +537 -0
- package/src/membershipWelcome.ts +683 -0
- package/src/migrationCheckout.ts +366 -0
- package/src/pacificDate.ts +54 -0
- package/src/paymentLinkEmail.ts +123 -0
- package/src/signedUnpaidReminderEmail.test.ts +246 -0
- package/src/signedUnpaidReminderEmail.ts +132 -0
- package/src/stripeCoworkingPortal.ts +91 -0
- package/src/supabaseTestFakes.ts +131 -131
- package/src/supportTicketEmail.ts +119 -0
- package/src/unifiAccessPolicies.ts +228 -0
- package/src/unifiGroups.ts +129 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,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
|
+
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
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// THIRD SIBLING HMAC SCHEME. busClient.ts signs "v1" bookings under
|
|
2
|
+
// BUS_HMAC_SECRET; membershipBusClient.ts signs "m1" membership snapshots
|
|
3
|
+
// under BUS_HMAC_SECRET_MEMBERSHIP. This signs "r1" single-member resend
|
|
4
|
+
// requests under BUS_HMAC_SECRET_RESEND and posts to
|
|
5
|
+
// /membership/resend-invite. The three constructions are byte-distinct and
|
|
6
|
+
// must never be merged or generalized.
|
|
7
|
+
//
|
|
8
|
+
// Canonical message -- 7 lines joined with "\n", no trailing newline:
|
|
9
|
+
// r1
|
|
10
|
+
// {source} trim().toLowerCase()
|
|
11
|
+
// {event} trim().toLowerCase()
|
|
12
|
+
// {request_id} trim().toLowerCase()
|
|
13
|
+
// {requested_at} trim() only, verbatim
|
|
14
|
+
// {email} trim().toLowerCase()
|
|
15
|
+
// {unifi_user_id} trim() ONLY -- Access ids are CASE-SENSITIVE
|
|
16
|
+
//
|
|
17
|
+
// Auth is the portal bearer session ONLY. The email and unifi_user_id are
|
|
18
|
+
// resolved server-side from the caller's own memberships row; nothing from the
|
|
19
|
+
// request body is ever read. That scoping is the entire security model here.
|
|
20
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
21
|
+
import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
22
|
+
import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
|
|
23
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
24
|
+
|
|
25
|
+
const corsHeaders = {
|
|
26
|
+
'Access-Control-Allow-Origin': '*',
|
|
27
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
28
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const CONTRACT = 'v0.3';
|
|
32
|
+
const EVENT = 'membership.resend_invite';
|
|
33
|
+
const TIMEOUT_MS = 10_000;
|
|
34
|
+
|
|
35
|
+
export interface PortalResendInviteConfig {
|
|
36
|
+
busBase: string;
|
|
37
|
+
source: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function json(status: number, body: unknown) {
|
|
41
|
+
return new Response(JSON.stringify(body), {
|
|
42
|
+
status,
|
|
43
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function b64urlNoPad(bytes: Uint8Array): string {
|
|
48
|
+
let s = '';
|
|
49
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
50
|
+
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function canonicalResendMessage(
|
|
54
|
+
source: string,
|
|
55
|
+
event: string,
|
|
56
|
+
requestId: string,
|
|
57
|
+
requestedAt: string,
|
|
58
|
+
email: string,
|
|
59
|
+
unifiUserId: string,
|
|
60
|
+
): string {
|
|
61
|
+
return [
|
|
62
|
+
'r1',
|
|
63
|
+
(source ?? '').trim().toLowerCase(),
|
|
64
|
+
(event ?? '').trim().toLowerCase(),
|
|
65
|
+
(requestId ?? '').trim().toLowerCase(),
|
|
66
|
+
(requestedAt ?? '').trim(),
|
|
67
|
+
(email ?? '').trim().toLowerCase(),
|
|
68
|
+
// NEVER case-fold: UniFi Access user ids are case-sensitive.
|
|
69
|
+
(unifiUserId ?? '').trim(),
|
|
70
|
+
].join('\n');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function signResend(msg: string, secret: string): Promise<string> {
|
|
74
|
+
const key = await crypto.subtle.importKey(
|
|
75
|
+
'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
|
|
76
|
+
);
|
|
77
|
+
const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(msg)));
|
|
78
|
+
return b64urlNoPad(sig);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function handle(req: Request, config: PortalResendInviteConfig): Promise<Response> {
|
|
82
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
83
|
+
if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
|
|
84
|
+
|
|
85
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
86
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
87
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
88
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
const session = await resolvePortalSession(req, admin);
|
|
93
|
+
if (!session) return json(401, { error: 'unauthorized' });
|
|
94
|
+
const email = session.email.toLowerCase();
|
|
95
|
+
|
|
96
|
+
// Per-email (not per-IP) app-level limit: a shared office IP must not
|
|
97
|
+
// throttle other members. Defense-in-depth on top of the middleware's own
|
|
98
|
+
// 300s per-email cooldown, not a substitute for it.
|
|
99
|
+
const ok = await checkRateLimit(admin, 'portal-resend-invite', email, 5, 300);
|
|
100
|
+
if (!ok) return json(429, { error: 'rate_limited' });
|
|
101
|
+
|
|
102
|
+
// Step A: linked identity match. Step B (transition): email match limited
|
|
103
|
+
// to still-unlinked rows.
|
|
104
|
+
// PLURALITY: never .maybeSingle() here -- supabase-js returns data:null when
|
|
105
|
+
// >1 row matches, which would break resend for exactly the member holding
|
|
106
|
+
// two memberships. Oldest-first + limit(1), matching
|
|
107
|
+
// _shared/membership.ts's "THE OLDEST ENTITLED MEMBERSHIP PAYS" intent.
|
|
108
|
+
const { data: byIdRows, error: byIdErr } = await admin
|
|
109
|
+
.from('memberships')
|
|
110
|
+
.select('id,email,unifi_access_user_id')
|
|
111
|
+
.eq('auth_user_id', session.id)
|
|
112
|
+
.order('created_at', { ascending: true })
|
|
113
|
+
.limit(1);
|
|
114
|
+
if (byIdErr) return json(500, { error: 'lookup_failed' });
|
|
115
|
+
let membership = (byIdRows ?? [])[0];
|
|
116
|
+
if (!membership) {
|
|
117
|
+
const { data: byEmailRows, error: byEmailErr } = await admin
|
|
118
|
+
.from('memberships')
|
|
119
|
+
.select('id,email,unifi_access_user_id')
|
|
120
|
+
.eq('email', email)
|
|
121
|
+
.is('auth_user_id', null)
|
|
122
|
+
.order('created_at', { ascending: true })
|
|
123
|
+
.limit(1);
|
|
124
|
+
if (byEmailErr) return json(500, { error: 'lookup_failed' });
|
|
125
|
+
membership = (byEmailRows ?? [])[0];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const unifiUserId = (membership?.unifi_access_user_id as string | null | undefined)?.trim() ?? '';
|
|
129
|
+
if (!membership || !unifiUserId) {
|
|
130
|
+
return json(400, { error: 'not_invited_yet' });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const secret = Deno.env.get('BUS_HMAC_SECRET_RESEND');
|
|
134
|
+
if (!secret) {
|
|
135
|
+
console.log('[portal-resend-invite] BUS_HMAC_SECRET_RESEND unset; skip');
|
|
136
|
+
return json(503, { error: 'not_configured' });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const requestId = crypto.randomUUID();
|
|
140
|
+
const requestedAt = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
141
|
+
const hmac = await signResend(
|
|
142
|
+
canonicalResendMessage(config.source, EVENT, requestId, requestedAt, email, unifiUserId),
|
|
143
|
+
secret,
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
const body = {
|
|
147
|
+
schema: 1,
|
|
148
|
+
contract: CONTRACT,
|
|
149
|
+
event: EVENT,
|
|
150
|
+
source: config.source,
|
|
151
|
+
request_id: requestId,
|
|
152
|
+
requested_at: requestedAt,
|
|
153
|
+
email,
|
|
154
|
+
unifi_user_id: unifiUserId,
|
|
155
|
+
hmac,
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const res = await fetch(`${config.busBase}/membership/resend-invite`, {
|
|
159
|
+
method: 'POST',
|
|
160
|
+
headers: { 'Content-Type': 'application/json' },
|
|
161
|
+
body: JSON.stringify(body),
|
|
162
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
// Own-shape passthrough (same convention as membershipBusEnforce): any
|
|
166
|
+
// parsed JSON carrying `ok`/`error`/`contract` is this endpoint's own
|
|
167
|
+
// documented response -- success OR refusal -- and is handed back with its
|
|
168
|
+
// own status. Only a body that is not this shape at all is a transport fault.
|
|
169
|
+
const rawText = await res.text();
|
|
170
|
+
let parsed: Record<string, unknown> | null = null;
|
|
171
|
+
if (rawText.length > 0) {
|
|
172
|
+
try {
|
|
173
|
+
const candidate = JSON.parse(rawText);
|
|
174
|
+
if (candidate && typeof candidate === 'object') parsed = candidate as Record<string, unknown>;
|
|
175
|
+
} catch {
|
|
176
|
+
parsed = null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const isOwnShape = parsed !== null &&
|
|
180
|
+
('contract' in parsed || 'error' in parsed || 'ok' in parsed);
|
|
181
|
+
if (isOwnShape) {
|
|
182
|
+
// Mirror membership-door-sync's T8 identity-status write-back: the
|
|
183
|
+
// literal string 'sent' is the only value that means an invite actually
|
|
184
|
+
// reached the member. 'dry_run' and every error/refusal shape must never
|
|
185
|
+
// stamp this column. A failed stamp write must never mask the original
|
|
186
|
+
// middleware response to the caller -- log and fall through regardless.
|
|
187
|
+
if (parsed?.result === 'sent') {
|
|
188
|
+
// identity_invited_at is a per-person fact, not a per-membership one
|
|
189
|
+
// (same reasoning as membership-door-sync's T8 identity-status
|
|
190
|
+
// write-back): a member holding more than one membership row must
|
|
191
|
+
// have every row sharing their email stamped, not just whichever one
|
|
192
|
+
// `membership` above happened to resolve to. Re-query by the SAME
|
|
193
|
+
// `email` used to resolve `membership` and batch the write with
|
|
194
|
+
// .in('id', ids) so one member never ends up with a stale unstamped
|
|
195
|
+
// sibling row.
|
|
196
|
+
const { data: emailRows, error: emailLookupErr } = await admin
|
|
197
|
+
.from('memberships')
|
|
198
|
+
.select('id')
|
|
199
|
+
.eq('email', email);
|
|
200
|
+
if (emailLookupErr) {
|
|
201
|
+
await logOps(admin, 'resend_invite_stamp_failed', {
|
|
202
|
+
event: EVENT,
|
|
203
|
+
contract: CONTRACT,
|
|
204
|
+
request_id: requestId,
|
|
205
|
+
membership_id: membership.id,
|
|
206
|
+
error: emailLookupErr.message,
|
|
207
|
+
}, { severity: 'error' });
|
|
208
|
+
} else {
|
|
209
|
+
const ids = (emailRows ?? []).map((r) => r.id as string);
|
|
210
|
+
if (ids.length > 0) {
|
|
211
|
+
const { error: stampErr } = await admin
|
|
212
|
+
.from('memberships')
|
|
213
|
+
.update({ identity_invited_at: new Date().toISOString() })
|
|
214
|
+
.in('id', ids);
|
|
215
|
+
if (stampErr) {
|
|
216
|
+
await logOps(admin, 'resend_invite_stamp_failed', {
|
|
217
|
+
event: EVENT,
|
|
218
|
+
contract: CONTRACT,
|
|
219
|
+
request_id: requestId,
|
|
220
|
+
membership_id: membership.id,
|
|
221
|
+
error: stampErr.message,
|
|
222
|
+
}, { severity: 'error' });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return json(res.status, parsed);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
await logOps(admin, 'resend_invite_bus_call_error', {
|
|
231
|
+
event: EVENT,
|
|
232
|
+
contract: CONTRACT,
|
|
233
|
+
request_id: requestId,
|
|
234
|
+
status: res.status,
|
|
235
|
+
detail: rawText.slice(0, 300),
|
|
236
|
+
}, { severity: 'error' });
|
|
237
|
+
return json(502, { error: 'bus_unreachable' });
|
|
238
|
+
} catch (e) {
|
|
239
|
+
try {
|
|
240
|
+
await logOps(admin, 'resend_invite_bus_call_error', {
|
|
241
|
+
event: EVENT,
|
|
242
|
+
contract: CONTRACT,
|
|
243
|
+
message: e instanceof Error ? e.message : String(e),
|
|
244
|
+
}, { severity: 'error' });
|
|
245
|
+
} catch { /* ignore */ }
|
|
246
|
+
return json(502, { error: 'bus_unreachable' });
|
|
247
|
+
}
|
|
248
|
+
}
|