@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,231 +1,231 @@
|
|
|
1
|
-
// supabase/functions/admin-issue-day-pass/index.ts
|
|
2
|
-
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
3
|
-
import Stripe from 'npm:stripe@17.5.0';
|
|
4
|
-
import { z } from 'npm:zod@3.23.8';
|
|
5
|
-
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
6
|
-
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
7
|
-
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
8
|
-
|
|
9
|
-
const corsHeaders = {
|
|
10
|
-
'Access-Control-Allow-Origin': '*',
|
|
11
|
-
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
12
|
-
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
const DAY_PASS_SLUG = 'day-pass';
|
|
16
|
-
|
|
17
|
-
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
18
|
-
|
|
19
|
-
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
20
|
-
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
21
|
-
function getJwks(supabaseUrl: string) {
|
|
22
|
-
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
23
|
-
return jwksCache;
|
|
24
|
-
}
|
|
25
|
-
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
26
|
-
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
27
|
-
const token = authHeader.slice(7).trim();
|
|
28
|
-
try {
|
|
29
|
-
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
30
|
-
const claims = payload as unknown as CallerClaims;
|
|
31
|
-
if (!claims.sub) return null;
|
|
32
|
-
return claims;
|
|
33
|
-
} catch { return null; }
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function json(status: number, body: unknown) {
|
|
37
|
-
return new Response(JSON.stringify(body), {
|
|
38
|
-
status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function todayLA(): string {
|
|
43
|
-
return new Intl.DateTimeFormat('en-CA', {
|
|
44
|
-
timeZone: 'America/Los_Angeles',
|
|
45
|
-
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
46
|
-
}).format(new Date());
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
const Body = z.object({
|
|
50
|
-
guest_name: z.string().trim().min(1).max(200),
|
|
51
|
-
guest_email: z.string().trim().email().max(255),
|
|
52
|
-
visit_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
53
|
-
issue_mode: z.enum(['payment_link', 'paid_offline', 'comp']),
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
export interface AdminIssueDayPassDeps {
|
|
57
|
-
provisionDayPass: (
|
|
58
|
-
admin: ReturnType<typeof createClient>,
|
|
59
|
-
dayPassId: string,
|
|
60
|
-
visitDate: string,
|
|
61
|
-
email: string,
|
|
62
|
-
guestName: string,
|
|
63
|
-
) => Promise<{
|
|
64
|
-
status: 'provisioned' | 'dry_run' | 'disabled' | 'failed';
|
|
65
|
-
credentialStatus: string | null;
|
|
66
|
-
wifiCode: string | null;
|
|
67
|
-
wifiValidFromIso: string | null;
|
|
68
|
-
wifiValidToIso: string | null;
|
|
69
|
-
error: string | null;
|
|
70
|
-
}>;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export async function handle(req: Request, operator: { domain: string }, deps: AdminIssueDayPassDeps): Promise<Response> {
|
|
74
|
-
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
75
|
-
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
76
|
-
|
|
77
|
-
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
78
|
-
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
79
|
-
|
|
80
|
-
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
81
|
-
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
82
|
-
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
83
|
-
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
84
|
-
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
85
|
-
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
86
|
-
|
|
87
|
-
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
88
|
-
auth: { persistSession: false, autoRefreshToken: false },
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
const [ipOk, emailOk] = await Promise.all([
|
|
92
|
-
checkRateLimit(admin, 'admin-issue-day-pass-ip', clientIp(req), 30, 300),
|
|
93
|
-
checkRateLimit(admin, 'admin-issue-day-pass-email', callerEmail, 20, 300),
|
|
94
|
-
]);
|
|
95
|
-
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
96
|
-
|
|
97
|
-
const { data: allow, error: allowErr } = await admin
|
|
98
|
-
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
99
|
-
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
100
|
-
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
101
|
-
|
|
102
|
-
let raw: unknown;
|
|
103
|
-
try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
|
|
104
|
-
const parsed = Body.safeParse(raw);
|
|
105
|
-
if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
|
|
106
|
-
const { guest_name, guest_email, visit_date, issue_mode } = parsed.data;
|
|
107
|
-
const emailKey = guest_email.toLowerCase();
|
|
108
|
-
|
|
109
|
-
if (visit_date < todayLA()) return json(400, { ok: false, error: 'visit_date_in_past' });
|
|
110
|
-
|
|
111
|
-
const { data: plan, error: pErr } = await admin
|
|
112
|
-
.from('membership_plans')
|
|
113
|
-
.select('id,slug,name,active,billable,billing_interval,stripe_price_id,price_cents')
|
|
114
|
-
.eq('slug', DAY_PASS_SLUG)
|
|
115
|
-
.maybeSingle();
|
|
116
|
-
if (pErr) return json(500, { ok: false, error: 'load_plan_failed', detail: pErr.message });
|
|
117
|
-
if (!plan || plan.active !== true || plan.billable !== true || plan.billing_interval === 'month') {
|
|
118
|
-
return json(400, { ok: false, error: 'day_pass_plan_unavailable' });
|
|
119
|
-
}
|
|
120
|
-
const planPriceCents = plan.price_cents ?? 0;
|
|
121
|
-
|
|
122
|
-
try {
|
|
123
|
-
if (issue_mode === 'payment_link') {
|
|
124
|
-
if (!plan.stripe_price_id) return json(400, { ok: false, error: 'day_pass_price_not_configured' });
|
|
125
|
-
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
126
|
-
if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
|
|
127
|
-
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
|
|
128
|
-
|
|
129
|
-
let customerId: string | null = null;
|
|
130
|
-
try {
|
|
131
|
-
const listed = await stripe.customers.list({ email: emailKey, limit: 1 });
|
|
132
|
-
if (listed.data.length > 0) customerId = listed.data[0].id;
|
|
133
|
-
} catch (e) {
|
|
134
|
-
console.warn('[admin-issue-day-pass] customers.list failed', e);
|
|
135
|
-
}
|
|
136
|
-
if (!customerId) customerId = (await stripe.customers.create({ email: emailKey, name: guest_name })).id;
|
|
137
|
-
|
|
138
|
-
const origin = req.headers.get('origin');
|
|
139
|
-
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
140
|
-
|
|
141
|
-
const session = await stripe.checkout.sessions.create({
|
|
142
|
-
mode: 'payment',
|
|
143
|
-
customer: customerId,
|
|
144
|
-
line_items: [{ price: plan.stripe_price_id, quantity: 1 }],
|
|
145
|
-
allow_promotion_codes: true,
|
|
146
|
-
metadata: {
|
|
147
|
-
checkout_type: 'day_pass',
|
|
148
|
-
plan_slug: plan.slug,
|
|
149
|
-
plan_id: plan.id,
|
|
150
|
-
visit_date,
|
|
151
|
-
issued_by: callerEmail,
|
|
152
|
-
},
|
|
153
|
-
payment_intent_data: { receipt_email: emailKey },
|
|
154
|
-
success_url: `${base}/day-pass/success?session_id={CHECKOUT_SESSION_ID}`,
|
|
155
|
-
cancel_url: `${base}/pricing`,
|
|
156
|
-
});
|
|
157
|
-
|
|
158
|
-
return json(200, {
|
|
159
|
-
ok: true, issue_mode, url: session.url, session_id: session.id,
|
|
160
|
-
amount_cents: planPriceCents,
|
|
161
|
-
});
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
const source = issue_mode === 'comp' ? 'comp' : 'offline';
|
|
165
|
-
const amountCents = issue_mode === 'comp' ? 0 : planPriceCents;
|
|
166
|
-
const localRef = `${source}_${crypto.randomUUID()}`;
|
|
167
|
-
|
|
168
|
-
const { data: row, error: insErr } = await admin
|
|
169
|
-
.from('day_pass_purchases')
|
|
170
|
-
.insert({
|
|
171
|
-
email: emailKey,
|
|
172
|
-
customer_name: guest_name,
|
|
173
|
-
stripe_checkout_session_id: localRef,
|
|
174
|
-
plan_id: plan.id,
|
|
175
|
-
amount_cents: amountCents,
|
|
176
|
-
visit_date,
|
|
177
|
-
payment_source: source,
|
|
178
|
-
created_by: callerEmail,
|
|
179
|
-
})
|
|
180
|
-
.select('id')
|
|
181
|
-
.single();
|
|
182
|
-
if (insErr) return json(500, { ok: false, error: 'insert_failed', detail: insErr.message });
|
|
183
|
-
|
|
184
|
-
let provisioningStatus: "provisioned" | "dry_run" | "disabled" | "failed" = "failed";
|
|
185
|
-
let wifiCode: string | null = null;
|
|
186
|
-
try {
|
|
187
|
-
const outcome = await deps.provisionDayPass(admin, row.id, visit_date, emailKey, guest_name);
|
|
188
|
-
provisioningStatus = outcome.status;
|
|
189
|
-
wifiCode = outcome.wifiCode;
|
|
190
|
-
const { error: provWriteErr } = await admin
|
|
191
|
-
.from('day_pass_purchases')
|
|
192
|
-
.update({
|
|
193
|
-
provisioning_status: outcome.status,
|
|
194
|
-
credential_status: outcome.credentialStatus,
|
|
195
|
-
wifi_code: outcome.wifiCode,
|
|
196
|
-
wifi_valid_from: outcome.wifiValidFromIso,
|
|
197
|
-
wifi_valid_to: outcome.wifiValidToIso,
|
|
198
|
-
provisioned_at: (outcome.status === 'provisioned' || outcome.status === 'dry_run')
|
|
199
|
-
? new Date().toISOString()
|
|
200
|
-
: null,
|
|
201
|
-
provision_error: outcome.error,
|
|
202
|
-
})
|
|
203
|
-
.eq('id', row.id);
|
|
204
|
-
if (provWriteErr) {
|
|
205
|
-
console.error('[admin-issue-day-pass] provisioning-status write failed', provWriteErr);
|
|
206
|
-
await logOps(admin, 'day_pass_provision_status_write_failed',
|
|
207
|
-
{ day_pass_id: row.id, message: provWriteErr.message, pg_code: (provWriteErr as { code?: string }).code },
|
|
208
|
-
{ severity: 'error' }).catch(() => {});
|
|
209
|
-
}
|
|
210
|
-
} catch (e) {
|
|
211
|
-
console.error('[admin-issue-day-pass] provisioning threw', e);
|
|
212
|
-
await logOps(admin, 'day_pass_provision_threw',
|
|
213
|
-
{ day_pass_id: row.id, message: e instanceof Error ? e.message : String(e) },
|
|
214
|
-
{ severity: 'error' }).catch(() => {});
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
return json(200, {
|
|
218
|
-
ok: true, issue_mode, day_pass_id: row.id, amount_cents: amountCents,
|
|
219
|
-
provisioning_status: provisioningStatus,
|
|
220
|
-
wifi_code: wifiCode,
|
|
221
|
-
});
|
|
222
|
-
} catch (e) {
|
|
223
|
-
console.error('admin-issue-day-pass error', e);
|
|
224
|
-
try {
|
|
225
|
-
await logOps(admin, 'admin_issue_day_pass_error',
|
|
226
|
-
{ message: e instanceof Error ? e.message : String(e), issue_mode, actor: callerEmail },
|
|
227
|
-
{ severity: 'error' });
|
|
228
|
-
} catch { /* ignore */ }
|
|
229
|
-
return json(500, { ok: false, error: 'unexpected_error' });
|
|
230
|
-
}
|
|
231
|
-
}
|
|
1
|
+
// supabase/functions/admin-issue-day-pass/index.ts
|
|
2
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
3
|
+
import Stripe from 'npm:stripe@17.5.0';
|
|
4
|
+
import { z } from 'npm:zod@3.23.8';
|
|
5
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
6
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
7
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
8
|
+
|
|
9
|
+
const corsHeaders = {
|
|
10
|
+
'Access-Control-Allow-Origin': '*',
|
|
11
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
12
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const DAY_PASS_SLUG = 'day-pass';
|
|
16
|
+
|
|
17
|
+
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
18
|
+
|
|
19
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
20
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
21
|
+
function getJwks(supabaseUrl: string) {
|
|
22
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
23
|
+
return jwksCache;
|
|
24
|
+
}
|
|
25
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
26
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
27
|
+
const token = authHeader.slice(7).trim();
|
|
28
|
+
try {
|
|
29
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
30
|
+
const claims = payload as unknown as CallerClaims;
|
|
31
|
+
if (!claims.sub) return null;
|
|
32
|
+
return claims;
|
|
33
|
+
} catch { return null; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function json(status: number, body: unknown) {
|
|
37
|
+
return new Response(JSON.stringify(body), {
|
|
38
|
+
status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function todayLA(): string {
|
|
43
|
+
return new Intl.DateTimeFormat('en-CA', {
|
|
44
|
+
timeZone: 'America/Los_Angeles',
|
|
45
|
+
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
46
|
+
}).format(new Date());
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const Body = z.object({
|
|
50
|
+
guest_name: z.string().trim().min(1).max(200),
|
|
51
|
+
guest_email: z.string().trim().email().max(255),
|
|
52
|
+
visit_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
53
|
+
issue_mode: z.enum(['payment_link', 'paid_offline', 'comp']),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
export interface AdminIssueDayPassDeps {
|
|
57
|
+
provisionDayPass: (
|
|
58
|
+
admin: ReturnType<typeof createClient>,
|
|
59
|
+
dayPassId: string,
|
|
60
|
+
visitDate: string,
|
|
61
|
+
email: string,
|
|
62
|
+
guestName: string,
|
|
63
|
+
) => Promise<{
|
|
64
|
+
status: 'provisioned' | 'dry_run' | 'disabled' | 'failed';
|
|
65
|
+
credentialStatus: string | null;
|
|
66
|
+
wifiCode: string | null;
|
|
67
|
+
wifiValidFromIso: string | null;
|
|
68
|
+
wifiValidToIso: string | null;
|
|
69
|
+
error: string | null;
|
|
70
|
+
}>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function handle(req: Request, operator: { domain: string }, deps: AdminIssueDayPassDeps): Promise<Response> {
|
|
74
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
75
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
76
|
+
|
|
77
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
78
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
79
|
+
|
|
80
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
81
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
82
|
+
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
83
|
+
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
84
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
85
|
+
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
86
|
+
|
|
87
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
88
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
92
|
+
checkRateLimit(admin, 'admin-issue-day-pass-ip', clientIp(req), 30, 300),
|
|
93
|
+
checkRateLimit(admin, 'admin-issue-day-pass-email', callerEmail, 20, 300),
|
|
94
|
+
]);
|
|
95
|
+
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
96
|
+
|
|
97
|
+
const { data: allow, error: allowErr } = await admin
|
|
98
|
+
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
99
|
+
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
100
|
+
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
101
|
+
|
|
102
|
+
let raw: unknown;
|
|
103
|
+
try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
|
|
104
|
+
const parsed = Body.safeParse(raw);
|
|
105
|
+
if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
|
|
106
|
+
const { guest_name, guest_email, visit_date, issue_mode } = parsed.data;
|
|
107
|
+
const emailKey = guest_email.toLowerCase();
|
|
108
|
+
|
|
109
|
+
if (visit_date < todayLA()) return json(400, { ok: false, error: 'visit_date_in_past' });
|
|
110
|
+
|
|
111
|
+
const { data: plan, error: pErr } = await admin
|
|
112
|
+
.from('membership_plans')
|
|
113
|
+
.select('id,slug,name,active,billable,billing_interval,stripe_price_id,price_cents')
|
|
114
|
+
.eq('slug', DAY_PASS_SLUG)
|
|
115
|
+
.maybeSingle();
|
|
116
|
+
if (pErr) return json(500, { ok: false, error: 'load_plan_failed', detail: pErr.message });
|
|
117
|
+
if (!plan || plan.active !== true || plan.billable !== true || plan.billing_interval === 'month') {
|
|
118
|
+
return json(400, { ok: false, error: 'day_pass_plan_unavailable' });
|
|
119
|
+
}
|
|
120
|
+
const planPriceCents = plan.price_cents ?? 0;
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
if (issue_mode === 'payment_link') {
|
|
124
|
+
if (!plan.stripe_price_id) return json(400, { ok: false, error: 'day_pass_price_not_configured' });
|
|
125
|
+
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
126
|
+
if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
|
|
127
|
+
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
|
|
128
|
+
|
|
129
|
+
let customerId: string | null = null;
|
|
130
|
+
try {
|
|
131
|
+
const listed = await stripe.customers.list({ email: emailKey, limit: 1 });
|
|
132
|
+
if (listed.data.length > 0) customerId = listed.data[0].id;
|
|
133
|
+
} catch (e) {
|
|
134
|
+
console.warn('[admin-issue-day-pass] customers.list failed', e);
|
|
135
|
+
}
|
|
136
|
+
if (!customerId) customerId = (await stripe.customers.create({ email: emailKey, name: guest_name })).id;
|
|
137
|
+
|
|
138
|
+
const origin = req.headers.get('origin');
|
|
139
|
+
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
140
|
+
|
|
141
|
+
const session = await stripe.checkout.sessions.create({
|
|
142
|
+
mode: 'payment',
|
|
143
|
+
customer: customerId,
|
|
144
|
+
line_items: [{ price: plan.stripe_price_id, quantity: 1 }],
|
|
145
|
+
allow_promotion_codes: true,
|
|
146
|
+
metadata: {
|
|
147
|
+
checkout_type: 'day_pass',
|
|
148
|
+
plan_slug: plan.slug,
|
|
149
|
+
plan_id: plan.id,
|
|
150
|
+
visit_date,
|
|
151
|
+
issued_by: callerEmail,
|
|
152
|
+
},
|
|
153
|
+
payment_intent_data: { receipt_email: emailKey },
|
|
154
|
+
success_url: `${base}/day-pass/success?session_id={CHECKOUT_SESSION_ID}`,
|
|
155
|
+
cancel_url: `${base}/pricing`,
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
return json(200, {
|
|
159
|
+
ok: true, issue_mode, url: session.url, session_id: session.id,
|
|
160
|
+
amount_cents: planPriceCents,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const source = issue_mode === 'comp' ? 'comp' : 'offline';
|
|
165
|
+
const amountCents = issue_mode === 'comp' ? 0 : planPriceCents;
|
|
166
|
+
const localRef = `${source}_${crypto.randomUUID()}`;
|
|
167
|
+
|
|
168
|
+
const { data: row, error: insErr } = await admin
|
|
169
|
+
.from('day_pass_purchases')
|
|
170
|
+
.insert({
|
|
171
|
+
email: emailKey,
|
|
172
|
+
customer_name: guest_name,
|
|
173
|
+
stripe_checkout_session_id: localRef,
|
|
174
|
+
plan_id: plan.id,
|
|
175
|
+
amount_cents: amountCents,
|
|
176
|
+
visit_date,
|
|
177
|
+
payment_source: source,
|
|
178
|
+
created_by: callerEmail,
|
|
179
|
+
})
|
|
180
|
+
.select('id')
|
|
181
|
+
.single();
|
|
182
|
+
if (insErr) return json(500, { ok: false, error: 'insert_failed', detail: insErr.message });
|
|
183
|
+
|
|
184
|
+
let provisioningStatus: "provisioned" | "dry_run" | "disabled" | "failed" = "failed";
|
|
185
|
+
let wifiCode: string | null = null;
|
|
186
|
+
try {
|
|
187
|
+
const outcome = await deps.provisionDayPass(admin, row.id, visit_date, emailKey, guest_name);
|
|
188
|
+
provisioningStatus = outcome.status;
|
|
189
|
+
wifiCode = outcome.wifiCode;
|
|
190
|
+
const { error: provWriteErr } = await admin
|
|
191
|
+
.from('day_pass_purchases')
|
|
192
|
+
.update({
|
|
193
|
+
provisioning_status: outcome.status,
|
|
194
|
+
credential_status: outcome.credentialStatus,
|
|
195
|
+
wifi_code: outcome.wifiCode,
|
|
196
|
+
wifi_valid_from: outcome.wifiValidFromIso,
|
|
197
|
+
wifi_valid_to: outcome.wifiValidToIso,
|
|
198
|
+
provisioned_at: (outcome.status === 'provisioned' || outcome.status === 'dry_run')
|
|
199
|
+
? new Date().toISOString()
|
|
200
|
+
: null,
|
|
201
|
+
provision_error: outcome.error,
|
|
202
|
+
})
|
|
203
|
+
.eq('id', row.id);
|
|
204
|
+
if (provWriteErr) {
|
|
205
|
+
console.error('[admin-issue-day-pass] provisioning-status write failed', provWriteErr);
|
|
206
|
+
await logOps(admin, 'day_pass_provision_status_write_failed',
|
|
207
|
+
{ day_pass_id: row.id, message: provWriteErr.message, pg_code: (provWriteErr as { code?: string }).code },
|
|
208
|
+
{ severity: 'error' }).catch(() => {});
|
|
209
|
+
}
|
|
210
|
+
} catch (e) {
|
|
211
|
+
console.error('[admin-issue-day-pass] provisioning threw', e);
|
|
212
|
+
await logOps(admin, 'day_pass_provision_threw',
|
|
213
|
+
{ day_pass_id: row.id, message: e instanceof Error ? e.message : String(e) },
|
|
214
|
+
{ severity: 'error' }).catch(() => {});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return json(200, {
|
|
218
|
+
ok: true, issue_mode, day_pass_id: row.id, amount_cents: amountCents,
|
|
219
|
+
provisioning_status: provisioningStatus,
|
|
220
|
+
wifi_code: wifiCode,
|
|
221
|
+
});
|
|
222
|
+
} catch (e) {
|
|
223
|
+
console.error('admin-issue-day-pass error', e);
|
|
224
|
+
try {
|
|
225
|
+
await logOps(admin, 'admin_issue_day_pass_error',
|
|
226
|
+
{ message: e instanceof Error ? e.message : String(e), issue_mode, actor: callerEmail },
|
|
227
|
+
{ severity: 'error' });
|
|
228
|
+
} catch { /* ignore */ }
|
|
229
|
+
return json(500, { ok: false, error: 'unexpected_error' });
|
|
230
|
+
}
|
|
231
|
+
}
|