@simplelayer/graniteer-core 0.0.2 → 0.2.0
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/package.json +169 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/agreementCheckout.ts +250 -0
- package/src/agreementPortalEmail.ts +128 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/billingPortalLinkEmail.ts +117 -0
- package/src/bookingAgreementEmail.ts +149 -0
- package/src/bookingEffects.ts +388 -0
- package/src/bookingHoldReclaim.ts +94 -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/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/commonsDeposit.ts +298 -0
- package/src/commonsDepositWebhook.ts +237 -0
- package/src/conductorAdmin.ts +141 -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/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/magic-link.tsx +59 -0
- package/src/email-templates/reauthentication.tsx +60 -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 -0
- package/src/functions/admin-change-membership-plan.ts +312 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-booking.ts +460 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-issue-day-pass.ts +231 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- 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 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- 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 -0
- 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 -0
- package/src/functions/admin-revoke-agreement.ts +467 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/auth-email-hook.ts +259 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- 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 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-admin.ts +277 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- 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 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- 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 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- 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 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- 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 -0
- package/src/functions/space-availability-range.ts +142 -0
- 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 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- 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 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- 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 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-membership-signup.ts +355 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/functions/voice-tour-booking.ts +429 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlEventInquiry.ts +143 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/mailArrivalEmail.ts +121 -0
- package/src/manageToken.ts +363 -0
- package/src/membership.ts +109 -0
- package/src/membershipBusClient.ts +537 -0
- package/src/membershipWelcome.ts +683 -0
- package/src/migrationCheckout.ts +366 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +88 -0
- package/src/paymentLinkEmail.ts +123 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/signedUnpaidReminderEmail.test.ts +246 -0
- package/src/signedUnpaidReminderEmail.ts +132 -0
- package/src/slackAlert.ts +38 -0
- package/src/stripeCoworkingPortal.ts +91 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/supportTicketEmail.ts +119 -0
- package/src/tier1Agreement.ts +125 -0
- package/src/unifiAccessPolicies.ts +228 -0
- package/src/unifiGroups.ts +129 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Member-portal event submission -> gc-events-hub member-submit route.
|
|
2
|
+
//
|
|
3
|
+
// Trust boundary: this function signs the submitter's identity (email + name)
|
|
4
|
+
// server-side from the portal session, then forwards it to gc-events-hub's
|
|
5
|
+
// authenticated /submit/member route via a shared-secret HMAC. gc-events-hub
|
|
6
|
+
// still lands every submission `pending` for staff review -- the signature
|
|
7
|
+
// only proves "this came from a real member session", it never auto-approves
|
|
8
|
+
// anything.
|
|
9
|
+
//
|
|
10
|
+
// Signature scheme MUST match gc-events-hub's verifyMemberSignature exactly:
|
|
11
|
+
// Member-Signature: t=<unix_seconds>,kid=<1|2>,v1=<hex hmac>
|
|
12
|
+
// HMAC-SHA256 over `${t}.${method}.${path}.${rawBody}`, hex-encoded.
|
|
13
|
+
// This is a fourth, byte-distinct HMAC construction alongside busClient's v1
|
|
14
|
+
// (b64url) and portal-resend-invite's r1 (b64url) -- do not merge or reuse
|
|
15
|
+
// their helpers; the receiver (gc-events-hub, a separate Cloudflare
|
|
16
|
+
// Worker/D1 codebase) expects hex, not base64url.
|
|
17
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
18
|
+
import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
|
|
19
|
+
import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
20
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
21
|
+
|
|
22
|
+
const corsHeaders = {
|
|
23
|
+
'Access-Control-Allow-Origin': '*',
|
|
24
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
25
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const SUBMIT_PATH = '/submit/member';
|
|
29
|
+
const TIMEOUT_MS = 10_000;
|
|
30
|
+
|
|
31
|
+
export interface PortalSubmitEventConfig {
|
|
32
|
+
eventsHubBase: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function json(status: number, body: unknown) {
|
|
36
|
+
return new Response(JSON.stringify(body), {
|
|
37
|
+
status,
|
|
38
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function toHex(buf: ArrayBuffer): string {
|
|
43
|
+
return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function signMemberSubmit(
|
|
47
|
+
method: string, path: string, rawBody: string, secret: string, ts: number,
|
|
48
|
+
): Promise<string> {
|
|
49
|
+
const payload = `${ts}.${method}.${path}.${rawBody}`;
|
|
50
|
+
const key = await crypto.subtle.importKey(
|
|
51
|
+
'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
|
|
52
|
+
);
|
|
53
|
+
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(payload));
|
|
54
|
+
return toHex(sig);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function handle(req: Request, config: PortalSubmitEventConfig): Promise<Response> {
|
|
58
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
59
|
+
if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
|
|
60
|
+
|
|
61
|
+
const admin = createClient(
|
|
62
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
63
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
64
|
+
{ auth: { persistSession: false, autoRefreshToken: false } },
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
const session = await resolvePortalSession(req, admin);
|
|
69
|
+
if (!session) return json(401, { error: 'unauthorized' });
|
|
70
|
+
const email = session.email.toLowerCase();
|
|
71
|
+
|
|
72
|
+
const ok = await checkRateLimit(admin, 'portal-submit-event', email, 10, 3600);
|
|
73
|
+
if (!ok) return json(429, { error: 'rate_limited' });
|
|
74
|
+
|
|
75
|
+
let body: Record<string, unknown>;
|
|
76
|
+
try {
|
|
77
|
+
body = await req.json();
|
|
78
|
+
} catch {
|
|
79
|
+
return json(400, { error: 'invalid_json' });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const title = typeof body.title === 'string' ? body.title.trim() : '';
|
|
83
|
+
const startAt = typeof body.start_at === 'string' ? body.start_at.trim() : '';
|
|
84
|
+
if (!title || !startAt) return json(400, { error: 'missing_required_fields' });
|
|
85
|
+
if (isNaN(Date.parse(startAt))) return json(400, { error: 'invalid_start_at' });
|
|
86
|
+
|
|
87
|
+
const description = typeof body.description === 'string' ? body.description.slice(0, 2000) : '';
|
|
88
|
+
const endAt = typeof body.end_at === 'string' && !isNaN(Date.parse(body.end_at)) ? body.end_at : undefined;
|
|
89
|
+
const locationText = typeof body.location_text === 'string' ? body.location_text.slice(0, 200) : '';
|
|
90
|
+
const sourceUrl = typeof body.source_url === 'string' ? body.source_url.slice(0, 500) : '';
|
|
91
|
+
|
|
92
|
+
// Name/email are NEVER taken from the request body -- always the verified
|
|
93
|
+
// portal session, matching portal-resend-invite's identity model.
|
|
94
|
+
// PLURALITY: never .maybeSingle() here -- supabase-js returns data:null when
|
|
95
|
+
// >1 row matches, so a member with two memberships would silently lose their
|
|
96
|
+
// display name and submit as a bare email. Oldest-first + limit(1), matching
|
|
97
|
+
// _shared/membership.ts's "THE OLDEST ENTITLED MEMBERSHIP PAYS" intent.
|
|
98
|
+
const { data: membershipRows, error: membershipErr } = await admin
|
|
99
|
+
.from('memberships')
|
|
100
|
+
.select('customer_name')
|
|
101
|
+
.eq('auth_user_id', session.id)
|
|
102
|
+
.order('created_at', { ascending: true })
|
|
103
|
+
.limit(1);
|
|
104
|
+
if (membershipErr) {
|
|
105
|
+
await logOps(admin, 'portal_submit_event_membership_lookup_failed',
|
|
106
|
+
{ email, message: membershipErr.message }, { severity: 'warning' });
|
|
107
|
+
}
|
|
108
|
+
const membership = (membershipRows ?? [])[0];
|
|
109
|
+
const submitterName = (membership?.customer_name as string | null)?.trim() || email;
|
|
110
|
+
|
|
111
|
+
const secret = Deno.env.get('MEMBER_EVENTS_HUB_SECRET');
|
|
112
|
+
if (!secret) {
|
|
113
|
+
await logOps(admin, 'portal_submit_event_not_configured', {}, { severity: 'error' });
|
|
114
|
+
return json(503, { error: 'not_configured' });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const payload: Record<string, unknown> = {
|
|
118
|
+
title,
|
|
119
|
+
description,
|
|
120
|
+
start_at: startAt,
|
|
121
|
+
submitter_email: email,
|
|
122
|
+
submitter_name: submitterName,
|
|
123
|
+
};
|
|
124
|
+
if (endAt) payload.end_at = endAt;
|
|
125
|
+
if (locationText) payload.location_text = locationText;
|
|
126
|
+
if (sourceUrl) payload.source_url = sourceUrl;
|
|
127
|
+
|
|
128
|
+
const rawBody = JSON.stringify(payload);
|
|
129
|
+
const ts = Math.floor(Date.now() / 1000);
|
|
130
|
+
const sig = await signMemberSubmit('POST', SUBMIT_PATH, rawBody, secret, ts);
|
|
131
|
+
|
|
132
|
+
const res = await fetch(`${config.eventsHubBase}${SUBMIT_PATH}`, {
|
|
133
|
+
method: 'POST',
|
|
134
|
+
headers: {
|
|
135
|
+
'Content-Type': 'application/json',
|
|
136
|
+
'Member-Signature': `t=${ts},kid=1,v1=${sig}`,
|
|
137
|
+
},
|
|
138
|
+
body: rawBody,
|
|
139
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const text = await res.text();
|
|
143
|
+
let parsed: Record<string, unknown> = {};
|
|
144
|
+
try { parsed = text ? JSON.parse(text) : {}; } catch { parsed = {}; }
|
|
145
|
+
|
|
146
|
+
if (!res.ok) {
|
|
147
|
+
await logOps(admin, 'portal_submit_event_upstream_failed', {
|
|
148
|
+
status: res.status, detail: text.slice(0, 300),
|
|
149
|
+
}, { severity: 'error' });
|
|
150
|
+
return json(502, { error: 'submit_failed' });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return json(200, {
|
|
154
|
+
ok: true,
|
|
155
|
+
id: typeof parsed.id === 'string' ? parsed.id : undefined,
|
|
156
|
+
message: typeof parsed.message === 'string'
|
|
157
|
+
? parsed.message
|
|
158
|
+
: "Thanks — our team reviews submissions before they go on the calendar.",
|
|
159
|
+
});
|
|
160
|
+
} catch (e) {
|
|
161
|
+
try {
|
|
162
|
+
await logOps(admin, 'portal_submit_event_error', {
|
|
163
|
+
message: e instanceof Error ? e.message : String(e),
|
|
164
|
+
}, { severity: 'error' });
|
|
165
|
+
} catch { /* ignore */ }
|
|
166
|
+
return json(502, { error: 'submit_failed' });
|
|
167
|
+
}
|
|
168
|
+
}
|