@simplelayer/graniteer-core 0.3.24 → 0.3.27

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.
@@ -81,6 +81,13 @@ export type NotifyGhlConfig = {
81
81
  /** Absolute origin the signed manage-booking link is built against. */
82
82
  manageUrlBase: string;
83
83
  customFieldNames: BookingCustomFieldNames;
84
+ /**
85
+ * Optional. Room slugs whose standard confirmation email gets an extra line
86
+ * saying door access details arrive the day before the event. Core does not
87
+ * hardcode any slug; the consuming wrapper supplies them. Absent/empty = no
88
+ * change to the email.
89
+ */
90
+ doorAccessEmailRoomSlugs?: readonly string[];
84
91
  };
85
92
  export declare function notifyGhl(supabase: SupabaseLike, booking: BookingRow, config: NotifyGhlConfig, doorAccess?: BookingDoorAccess | null): Promise<void>;
86
93
  export {};
@@ -12,7 +12,7 @@
12
12
  // That whole door/calendar-signing group is deferred to a later phase gated on
13
13
  // a dedicated security review, so createCalendarEvent stays in gc-connect,
14
14
  // untouched, and imports isDepositOnly/parseTstzRange/formatDollars from here.
15
- import { buildManageUrl } from './manageToken.js';
15
+ import { buildManageUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE } from './manageToken.js';
16
16
  import { deriveReservationWifiCode, isReservationWifiRoom } from './reservationWifiCode.js';
17
17
  const LA_TZ = 'America/Los_Angeles';
18
18
  const GHL_BASE = 'https://services.leadconnectorhq.com';
@@ -163,15 +163,18 @@ export async function notifyGhl(supabase, booking, config, doorAccess) {
163
163
  const gcalDetails = `Your booking at ${operator.name}.\nRoom: ${roomName}\nWhen: ${whenStr}\nBooking ID: ${booking.id}`;
164
164
  const gcalLocation = booking.rooms?.address || operator.name;
165
165
  const gcalUrl = googleCalendarUrl(startISO, endISO, gcalTitle, gcalDetails, gcalLocation);
166
- const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET') ?? '';
166
+ const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET');
167
167
  let manageUrl = '';
168
- if (manageSecret) {
168
+ if (!isManageTokenSecretUsable(manageSecret)) {
169
+ console.error('[bookingEffects]', MANAGE_TOKEN_UNAVAILABLE_CODE);
170
+ }
171
+ else {
169
172
  try {
170
173
  const exp = Math.floor(new Date(endISO).getTime() / 1000) + 30 * 24 * 60 * 60;
171
174
  manageUrl = await buildManageUrl(config.manageUrlBase, { bid: booking.id, eml: (booking.contact_email || '').toLowerCase(), exp }, manageSecret);
172
175
  }
173
- catch (e) {
174
- console.warn('[bookingEffects] manage url build failed', e);
176
+ catch {
177
+ console.error('[bookingEffects]', MANAGE_TOKEN_UNAVAILABLE_CODE);
175
178
  }
176
179
  }
177
180
  const headers = ghlHeaders(apiKey);
@@ -265,7 +268,7 @@ export async function notifyGhl(supabase, booking, config, doorAccess) {
265
268
  const address = booking.rooms.address || operator.name;
266
269
  const manageParagraph = manageUrl
267
270
  ? `<p>Need to change plans? <a href='${manageUrl}' style='color:#C98A5E'>Manage your booking</a> — free cancellation with credit up to 48 hours before your start time.</p>`
268
- : '';
271
+ : `<p>Need to change plans? Reply to this email to manage your booking — a manage link is not available for this confirmation.</p>`;
269
272
  let doorSection = '';
270
273
  if (doorAccess?.pin) {
271
274
  const activeLine = (doorAccess.validFromUtc && doorAccess.validToUtc)
@@ -291,7 +294,13 @@ export async function notifyGhl(supabase, booking, config, doorAccess) {
291
294
  if (typeof usageInstructions === 'string' && usageInstructions.trim().length > 0) {
292
295
  instructionsSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>About this room</h3>${textToHtmlParagraphs(usageInstructions)}</div>`;
293
296
  }
294
- const confirmationHtml = `<div style='font-family:Inter,Arial,sans-serif;max-width:560px;margin:0 auto;color:#22263B'><h2 style='color:#22263B'>Your booking is confirmed</h2><p>Hi ${firstName},</p><p>Thanks for booking with ${operator.name}. Here are your details:</p><table style='border-collapse:collapse;width:100%'><tr><td style='padding:6px 0;color:#5f6c5d;width:110px'>Room</td><td style='padding:6px 0'><strong>${roomName}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>When</td><td style='padding:6px 0'><strong>${whenStr}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>Amount</td><td style='padding:6px 0'><strong>${amountStr}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>Address</td><td style='padding:6px 0'>${address}</td></tr></table><p style='margin:20px 0'><a href='${gcalUrl}' style='background:#748272;color:#F6F6F6;padding:10px 18px;text-decoration:none;border-radius:6px;display:inline-block'>Add to Google Calendar</a></p>${doorSection}${wifiSection}${instructionsSection}${manageParagraph}<p style='color:#5f6c5d;font-size:13px;margin-top:28px'>${operator.name} · ${address}</p></div>`;
297
+ const doorAccessSlugs = Array.isArray(config.doorAccessEmailRoomSlugs) ? config.doorAccessEmailRoomSlugs : [];
298
+ // The external day-before sender only fires for starts at least ~20h out, so a booking made inside 24h must not be promised the email.
299
+ const doorAccessLaterRow = typeof booking.rooms.slug === 'string' && doorAccessSlugs.includes(booking.rooms.slug) && !doorAccess?.pin
300
+ && new Date(startISO).getTime() - Date.now() > 24 * 60 * 60 * 1000
301
+ ? `<tr><td colspan='2' style='padding:2px 0 8px 0;color:#5f6c5d;font-size:13px'>We'll email your door access details the day before your event.</td></tr>`
302
+ : '';
303
+ const confirmationHtml = `<div style='font-family:Inter,Arial,sans-serif;max-width:560px;margin:0 auto;color:#22263B'><h2 style='color:#22263B'>Your booking is confirmed</h2><p>Hi ${firstName},</p><p>Thanks for booking with ${operator.name}. Here are your details:</p><table style='border-collapse:collapse;width:100%'><tr><td style='padding:6px 0;color:#5f6c5d;width:110px'>Room</td><td style='padding:6px 0'><strong>${roomName}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>When</td><td style='padding:6px 0'><strong>${whenStr}</strong></td></tr>${doorAccessLaterRow}<tr><td style='padding:6px 0;color:#5f6c5d'>Amount</td><td style='padding:6px 0'><strong>${amountStr}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>Address</td><td style='padding:6px 0'>${address}</td></tr></table><p style='margin:20px 0'><a href='${gcalUrl}' style='background:#748272;color:#F6F6F6;padding:10px 18px;text-decoration:none;border-radius:6px;display:inline-block'>Add to Google Calendar</a></p>${doorSection}${wifiSection}${instructionsSection}${manageParagraph}<p style='color:#5f6c5d;font-size:13px;margin-top:28px'>${operator.name} · ${address}</p></div>`;
295
304
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
296
305
  method: 'POST', headers,
297
306
  body: JSON.stringify({
@@ -130,6 +130,7 @@ export function buildDayPassSessionParams(input) {
130
130
  : { receipt_email: input.receiptEmail };
131
131
  return {
132
132
  mode: 'payment',
133
+ payment_method_types: ['card'],
133
134
  customer: input.customerId,
134
135
  line_items: [{ price: input.priceId, quantity: 1 }],
135
136
  ...(input.stripeCouponId
@@ -191,7 +191,7 @@ export function sendCommonsDepositReceiptEmail(supabase, { email, name, eventDat
191
191
  contractUrl
192
192
  ? p(`<a href="${esc(contractUrl)}" style="color:#C98A5E">View your signed agreement →</a>`)
193
193
  : p(`A copy of your signed agreement was emailed to you when signing completed.`),
194
- p(`We'll be in touch before your date to confirm setup, timing and access details.`),
194
+ p(`We'll be in touch before your date to confirm setup and timing. Once your balance is paid, we'll email your door access details the day before your event.`),
195
195
  p(`Questions? Reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`),
196
196
  p(`— The ${operator.name} team`),
197
197
  ].join(''),
@@ -44,6 +44,14 @@ type SessionCreator = {
44
44
  };
45
45
  };
46
46
  };
47
+ /**
48
+ * Single choke point for booking Checkout sessions. Both branches force
49
+ * payment_method_types ['card']: delayed-notification methods (e.g. ACH debit)
50
+ * are excluded so a completed session always means money moved, which the
51
+ * stripe-webhook paid guard (payment_status 'paid' / 'no_payment_required')
52
+ * relies on. Connect sessions additionally go to the connected account with
53
+ * the application fee.
54
+ */
47
55
  export declare function createBookingCheckoutSession(stripe: SessionCreator, params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Promise<Stripe.Checkout.Session>;
48
56
  export declare const CONNECT_MISCONFIGURED_MESSAGE = "Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.";
49
57
  export {};
@@ -57,12 +57,21 @@ export function applyConnectToSessionParams(params, plan) {
57
57
  export function stripeAccountRequestOptions(accountId) {
58
58
  return accountId ? { stripeAccount: accountId } : undefined;
59
59
  }
60
+ /**
61
+ * Single choke point for booking Checkout sessions. Both branches force
62
+ * payment_method_types ['card']: delayed-notification methods (e.g. ACH debit)
63
+ * are excluded so a completed session always means money moved, which the
64
+ * stripe-webhook paid guard (payment_status 'paid' / 'no_payment_required')
65
+ * relies on. Connect sessions additionally go to the connected account with
66
+ * the application fee.
67
+ */
60
68
  export function createBookingCheckoutSession(stripe, params, plan) {
61
69
  if ('error' in plan) {
62
70
  return Promise.reject(new Error(`booking checkout refused: ${plan.error}`));
63
71
  }
64
- if (!plan.connected)
65
- return stripe.checkout.sessions.create(params);
72
+ if (!plan.connected) {
73
+ return stripe.checkout.sessions.create({ ...params, payment_method_types: ['card'] });
74
+ }
66
75
  return stripe.checkout.sessions.create({ ...applyConnectToSessionParams(params, plan), payment_method_types: ['card'] }, { stripeAccount: plan.accountId });
67
76
  }
68
77
  export const CONNECT_MISCONFIGURED_MESSAGE = 'Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.';
@@ -136,6 +136,7 @@ operator, deps) {
136
136
  const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
137
137
  const session = await stripe.checkout.sessions.create({
138
138
  mode: 'payment',
139
+ payment_method_types: ['card'],
139
140
  customer: customerId,
140
141
  line_items: [{ price: plan.stripe_price_id, quantity: 1 }],
141
142
  allow_promotion_codes: true,
@@ -2,7 +2,7 @@
2
2
  // signature_documents row. Read-only against the DB; reuses MANAGE_TOKEN_SECRET
3
3
  // and the same buildAgreementPortalUrl helper as create-agreement.
4
4
  import { createClient } from '@supabase/supabase-js';
5
- import { buildAgreementPortalUrl } from '../manageToken.js';
5
+ import { buildAgreementPortalUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, } from '../manageToken.js';
6
6
  const corsHeaders = {
7
7
  'Access-Control-Allow-Origin': '*',
8
8
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -32,6 +32,10 @@ export async function handle(req, operator) {
32
32
  return json(400, { ok: false, error: 'invalid_signature_document_id' });
33
33
  if (!email)
34
34
  return json(400, { ok: false, error: 'invalid_signer_email' });
35
+ const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
36
+ if (!isManageTokenSecretUsable(secret)) {
37
+ return json(503, { ok: false, error: MANAGE_TOKEN_UNAVAILABLE_CODE });
38
+ }
35
39
  const admin = createClient(Deno.env.get('SUPABASE_URL'), Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'), { auth: { persistSession: false, autoRefreshToken: false } });
36
40
  const { data: row, error } = await admin
37
41
  .from('signature_documents')
@@ -46,9 +50,6 @@ export async function handle(req, operator) {
46
50
  if (!rowEmail || rowEmail !== email.toLowerCase()) {
47
51
  return json(404, { ok: false, error: 'not_found' });
48
52
  }
49
- const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
50
- if (!secret)
51
- return json(500, { ok: false, error: 'not_configured' });
52
53
  const url = await buildAgreementPortalUrl(`https://${operator.domain}`, String(row.id), rowEmail, secret);
53
54
  return json(200, { ok: true, url });
54
55
  }
@@ -1,7 +1,7 @@
1
1
  import { corsHeaders } from '@supabase/supabase-js/cors';
2
2
  import { createClient } from '@supabase/supabase-js';
3
3
  import { z } from 'zod';
4
- import { buildManageUrl, verifyManageToken } from '../manageToken.js';
4
+ import { buildManageUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyManageToken, } from '../manageToken.js';
5
5
  // Auth model: this endpoint is unauthenticated but MUST NOT return PII for a
6
6
  // bare booking UUID (that was an IDOR). Callers must supply either:
7
7
  // - session_id: the Stripe Checkout Session id (unguessable, only known to
@@ -51,11 +51,12 @@ export async function handle(req, operator) {
51
51
  // Resolve to a booking id via the caller's chosen credential.
52
52
  let bookingId = null;
53
53
  let tokenBoundEmail = null;
54
- const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET') ?? '';
54
+ const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET');
55
55
  if (parsed.data.token) {
56
- if (!manageSecret) {
57
- return new Response(JSON.stringify({ error: 'not_configured' }), {
58
- status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
56
+ if (!isManageTokenSecretUsable(manageSecret)) {
57
+ console.error('booking-status', MANAGE_TOKEN_UNAVAILABLE_CODE);
58
+ return new Response(JSON.stringify({ error: MANAGE_TOKEN_UNAVAILABLE_CODE }), {
59
+ status: 503, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
59
60
  });
60
61
  }
61
62
  const claims = await verifyManageToken(parsed.data.token, manageSecret);
@@ -111,9 +112,17 @@ export async function handle(req, operator) {
111
112
  const room = data.rooms;
112
113
  // Build a manage-booking magic link the confirmation page can surface.
113
114
  let manageUrl = null;
114
- if (manageSecret && range?.end && data.contact_email) {
115
- const exp = Math.floor(new Date(range.end).getTime() / 1000) + 30 * 24 * 60 * 60;
116
- manageUrl = await buildManageUrl(`https://${operator.domain}`, { bid: data.id, eml: data.contact_email.toLowerCase(), exp }, manageSecret);
115
+ if (isManageTokenSecretUsable(manageSecret) && range?.end && data.contact_email) {
116
+ try {
117
+ const exp = Math.floor(new Date(range.end).getTime() / 1000) + 30 * 24 * 60 * 60;
118
+ manageUrl = await buildManageUrl(`https://${operator.domain}`, { bid: data.id, eml: data.contact_email.toLowerCase(), exp }, manageSecret);
119
+ }
120
+ catch {
121
+ console.error('booking-status', MANAGE_TOKEN_UNAVAILABLE_CODE);
122
+ }
123
+ }
124
+ else if (!isManageTokenSecretUsable(manageSecret)) {
125
+ console.error('booking-status', MANAGE_TOKEN_UNAVAILABLE_CODE);
117
126
  }
118
127
  return new Response(JSON.stringify({
119
128
  room_name: room?.name ?? null,
@@ -130,9 +139,9 @@ export async function handle(req, operator) {
130
139
  manage_url: manageUrl,
131
140
  }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
132
141
  }
133
- catch (e) {
134
- console.error('booking-status error', e);
135
- return new Response(JSON.stringify({ error: e instanceof Error ? e.message : String(e) }), {
142
+ catch {
143
+ console.error('booking-status', 'internal_error');
144
+ return new Response(JSON.stringify({ error: 'internal_error' }), {
136
145
  status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
137
146
  });
138
147
  }
@@ -1,3 +1,9 @@
1
+ /**
2
+ * Mint an agreement-portal URL, or return null when MANAGE_TOKEN_SECRET is
3
+ * missing/under 32 UTF-8 bytes. Fail closed: never produces a weak URL, never
4
+ * logs the secret or its length.
5
+ */
6
+ export declare function issueAgreementPortalUrl(base: string, signatureDocumentId: string, signerEmail: string, secret: string | undefined | null): Promise<string | null>;
1
7
  export declare function handle(req: Request, operator: {
2
8
  operatorName: string;
3
9
  operatorShortName: string;
@@ -4,7 +4,7 @@ import JSZip from 'jszip';
4
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
5
  import { centsFrom } from '../agreementCheckout.js';
6
6
  import { parseRetainerConfig } from '../money.js';
7
- import { buildAgreementPortalUrl } from '../manageToken.js';
7
+ import { buildAgreementPortalUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, } from '../manageToken.js';
8
8
  import { sendAgreementPortalEmail } from '../agreementPortalEmail.js';
9
9
  import { logOps } from '../ops.js';
10
10
  const corsHeaders = {
@@ -182,6 +182,18 @@ function validateAgreementBillability(v) {
182
182
  return retainer.code === 'service_retainer_absent' ? 'service_retainer_must_be_positive' : retainer.code;
183
183
  return null;
184
184
  }
185
+ /**
186
+ * Mint an agreement-portal URL, or return null when MANAGE_TOKEN_SECRET is
187
+ * missing/under 32 UTF-8 bytes. Fail closed: never produces a weak URL, never
188
+ * logs the secret or its length.
189
+ */
190
+ export async function issueAgreementPortalUrl(base, signatureDocumentId, signerEmail, secret) {
191
+ if (!isManageTokenSecretUsable(secret)) {
192
+ console.error('[create-agreement]', MANAGE_TOKEN_UNAVAILABLE_CODE);
193
+ return null;
194
+ }
195
+ return buildAgreementPortalUrl(base, signatureDocumentId, signerEmail, secret);
196
+ }
185
197
  export async function handle(req, operator) {
186
198
  if (req.method === 'OPTIONS')
187
199
  return new Response('ok', { headers: corsHeaders });
@@ -461,9 +473,8 @@ export async function handle(req, operator) {
461
473
  // own native signing email is unaffected and still goes out either way.
462
474
  if (tpl.fires_stripe) {
463
475
  try {
464
- const tokenSecret = Deno.env.get('MANAGE_TOKEN_SECRET');
465
- if (tokenSecret) {
466
- const portalUrl = await buildAgreementPortalUrl(`https://${operator.domain}`, docId, row.signer_email, tokenSecret);
476
+ const portalUrl = await issueAgreementPortalUrl(`https://${operator.domain}`, docId, row.signer_email, Deno.env.get('MANAGE_TOKEN_SECRET'));
477
+ if (portalUrl) {
467
478
  const emailResult = await sendAgreementPortalEmail(admin, {
468
479
  email: row.signer_email, name: row.signer_name, portalUrl, officeNumber: String(v.office_number ?? '') || undefined,
469
480
  }, {
@@ -476,9 +487,6 @@ export async function handle(req, operator) {
476
487
  if (emailResult !== 'sent')
477
488
  console.warn('[create-agreement] portal email not sent:', emailResult);
478
489
  }
479
- else {
480
- console.error('[create-agreement] MANAGE_TOKEN_SECRET not configured -- portal email not sent');
481
- }
482
490
  }
483
491
  catch (e) {
484
492
  console.error('[create-agreement] portal email dispatch failed (non-fatal)', e);
@@ -1,7 +1,7 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import Stripe from 'stripe';
3
3
  import { clientIp, checkRateLimit } from '../rateLimit.js';
4
- import { verifyMemberToken } from '../manageToken.js';
4
+ import { isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyMemberToken, } from '../manageToken.js';
5
5
  import { resolvePortalSession } from '../portalSession.js';
6
6
  import { logOps } from '../ops.js';
7
7
  import { getOrCreateCoworkingPortalConfig } from '../stripeCoworkingPortal.js';
@@ -25,7 +25,9 @@ export async function handle(req, operator) {
25
25
  const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
26
26
  const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
27
27
  const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
28
- if (!secret || !stripeKey)
28
+ if (!isManageTokenSecretUsable(secret))
29
+ return json(503, { error: MANAGE_TOKEN_UNAVAILABLE_CODE });
30
+ if (!stripeKey)
29
31
  return json(500, { error: 'not_configured' });
30
32
  const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
31
33
  auth: { persistSession: false, autoRefreshToken: false },
@@ -13,6 +13,7 @@ interface BookingRow {
13
13
  dynamic_discount_cents: number | null;
14
14
  credit_applied_cents: number | null;
15
15
  google_event_id: string | null;
16
+ access_revoke_required_at: string | null;
16
17
  rooms: {
17
18
  id: string;
18
19
  name: string;
@@ -1,8 +1,8 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import { JWT } from 'google-auth-library';
3
3
  import { writebackBookingCancelled } from '../gcalBookingEvents.js';
4
- import { clientIp, checkRateLimit } from '../rateLimit.js';
5
- import { verifyManageToken } from '../manageToken.js';
4
+ import { manageBookingClientIp, checkRateLimit } from '../rateLimit.js';
5
+ import { isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyManageToken } from '../manageToken.js';
6
6
  import { resolvePortalSessionEmail } from '../portalSession.js';
7
7
  import { logOps } from '../ops.js';
8
8
  import { deriveReservationWifiCode, isReservationWifiRoom } from '../reservationWifiCode.js';
@@ -91,6 +91,14 @@ async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId, bus
91
91
  return await fail('exception', { message: String(e) });
92
92
  }
93
93
  }
94
+ /** Grant is usable only while access_start <= now < access_end. Missing/unparseable bounds fail closed. */
95
+ function grantWindowContainsNow(grant, nowMs = Date.now()) {
96
+ const startMs = grant.access_start ? new Date(grant.access_start).getTime() : NaN;
97
+ const endMs = grant.access_end ? new Date(grant.access_end).getTime() : NaN;
98
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs))
99
+ return false;
100
+ return startMs <= nowMs && nowMs < endMs;
101
+ }
94
102
  function parseTstzRange(range) {
95
103
  const m = range.match(/[[(]"?([^",)]+)"?,"?([^",)]+)"?[\])]/);
96
104
  if (!m)
@@ -207,17 +215,17 @@ export async function handle(req, operator, deps) {
207
215
  const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
208
216
  const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
209
217
  const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
210
- if (!secret)
211
- return json(500, { error: 'not_configured' });
218
+ if (!isManageTokenSecretUsable(secret)) {
219
+ return json(503, { error: MANAGE_TOKEN_UNAVAILABLE_CODE });
220
+ }
212
221
  const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
213
222
  auth: { persistSession: false, autoRefreshToken: false },
214
223
  });
215
224
  const busBase = deps.busBase ?? getEventAccessBusBase();
216
- // Rate-limit BEFORE any DB work.
217
- const ip = clientIp(req);
218
- const [ipOk] = await Promise.all([
219
- checkRateLimit(admin, 'manage-booking-ip', ip, 30, 300),
220
- ]);
225
+ // Rate-limit BEFORE any DB work. failClosed: a limiter outage must not
226
+ // become an unthrottled PIN/token oracle.
227
+ const ip = manageBookingClientIp(req);
228
+ const ipOk = await checkRateLimit(admin, 'manage-booking-ip', ip, 30, 300, { failClosed: true });
221
229
  if (!ipOk)
222
230
  return json(429, { error: 'rate_limited' });
223
231
  // Extract token + action.
@@ -263,12 +271,12 @@ export async function handle(req, operator, deps) {
263
271
  authedEmail = sessionEmail;
264
272
  }
265
273
  // Rate-limit per booking id to cap abuse of a single link/session.
266
- const bidOk = await checkRateLimit(admin, 'manage-booking-bid', bookingId, 30, 300);
274
+ const bidOk = await checkRateLimit(admin, 'manage-booking-bid', bookingId, 30, 300, { failClosed: true });
267
275
  if (!bidOk)
268
276
  return json(429, { error: 'rate_limited' });
269
277
  const { data: booking, error: bErr } = await admin
270
278
  .from('bookings')
271
- .select('id,status,contact_email,contact_name,contact_phone,ghl_contact_id,during,charged_amount_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents,google_event_id,rooms(id,name,address,google_calendar_id,slug,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes)')
279
+ .select('id,status,contact_email,contact_name,contact_phone,ghl_contact_id,during,charged_amount_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents,google_event_id,access_revoke_required_at,rooms(id,name,address,google_calendar_id,slug,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes)')
272
280
  .eq('id', bookingId)
273
281
  .maybeSingle();
274
282
  if (bErr)
@@ -340,7 +348,7 @@ export async function handle(req, operator, deps) {
340
348
  if (action === 'two_pin_credential') {
341
349
  const parsedRange = parseTstzRange(b.during);
342
350
  const endMs = parsedRange ? new Date(parsedRange.endISO).getTime() : 0;
343
- if (b.status !== 'paid' || endMs <= Date.now()) {
351
+ if (b.status !== 'paid' || endMs <= Date.now() || b.access_revoke_required_at) {
344
352
  return json(404, { error: 'no_credential' });
345
353
  }
346
354
  try {
@@ -354,14 +362,13 @@ export async function handle(req, operator, deps) {
354
362
  const grant = data;
355
363
  if (!grant.unlock_pin && !grant.relock_pin)
356
364
  return json(404, { error: 'no_credential' });
357
- // Organizer early-manual-lock/unlock link (D35 follow-up): only attempt
358
- // the mint while the grant itself is still within its active window —
359
- // no point minting a link for a grant that's already over. Never blocks
360
- // or alters the PIN response: a failed/skipped mint is just a null url.
365
+ if (!grantWindowContainsNow(grant))
366
+ return json(404, { error: 'no_credential' });
367
+ // Organizer early-manual-lock/unlock link (D35 follow-up): only reached
368
+ // while the grant is inside its active window. Never blocks or alters
369
+ // the PIN response: a failed mint is just a null url.
361
370
  let organizerLinkUrl = null;
362
- const grantEndMs = grant.access_end ? new Date(grant.access_end).getTime() : NaN;
363
- const grantWithinWindow = !Number.isFinite(grantEndMs) || grantEndMs > Date.now();
364
- if (grant.id && grantWithinWindow) {
371
+ if (grant.id) {
365
372
  organizerLinkUrl = await mintOrganizerLinkUrl(admin, `customer:${authedEmail}`, grant.id, b.id, busBase);
366
373
  }
367
374
  return json(200, {
@@ -2,7 +2,7 @@ import { createClient } from '@supabase/supabase-js';
2
2
  import { z } from 'zod';
3
3
  import { clientIp, checkRateLimit } from '../rateLimit.js';
4
4
  import { logOps } from '../ops.js';
5
- import { buildMemberManageUrl } from '../manageToken.js';
5
+ import { buildMemberManageUrl, isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, } from '../manageToken.js';
6
6
  const corsHeaders = {
7
7
  'Access-Control-Allow-Origin': '*',
8
8
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -115,14 +115,13 @@ export async function handle(req, operator) {
115
115
  return new Response('ok', { headers: corsHeaders });
116
116
  if (req.method !== 'POST')
117
117
  return json(405, { error: 'method_not_allowed' });
118
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
119
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
120
118
  const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
121
- // Missing secret should never happen in prod; fail closed to generic OK so
122
- // callers can't distinguish this from "no membership found".
123
- if (!secret) {
124
- console.warn('[request-portal-link] MANAGE_TOKEN_SECRET not configured');
119
+ if (!isManageTokenSecretUsable(secret)) {
120
+ console.warn('[request-portal-link]', MANAGE_TOKEN_UNAVAILABLE_CODE);
121
+ return json(503, { error: MANAGE_TOKEN_UNAVAILABLE_CODE });
125
122
  }
123
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
124
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
126
125
  const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
127
126
  auth: { persistSession: false, autoRefreshToken: false },
128
127
  });
@@ -163,7 +162,7 @@ export async function handle(req, operator) {
163
162
  return json(200, GENERIC_OK);
164
163
  }
165
164
  const membership = (membershipRows ?? [])[0];
166
- if (!membership || !secret) {
165
+ if (!membership) {
167
166
  // Same shape/timing as the found path (no existence leak).
168
167
  return json(200, GENERIC_OK);
169
168
  }
@@ -2,7 +2,7 @@ import { createClient } from '@supabase/supabase-js';
2
2
  import Stripe from 'stripe';
3
3
  import { z } from 'zod';
4
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
- import { verifyManageToken } from '../manageToken.js';
5
+ import { isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyManageToken, } from '../manageToken.js';
6
6
  import { resolvePortalSessionEmail } from '../portalSession.js';
7
7
  import { logOps } from '../ops.js';
8
8
  import { reclaimStaleHoldsExceptCompletedTier3 } from '../bookingHoldReclaim.js';
@@ -60,8 +60,9 @@ export async function handle(req, operator, deps) {
60
60
  const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
61
61
  const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
62
62
  const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
63
- if (!secret)
64
- return json(500, { error: 'not_configured' });
63
+ if (!isManageTokenSecretUsable(secret)) {
64
+ return json(503, { error: MANAGE_TOKEN_UNAVAILABLE_CODE });
65
+ }
65
66
  const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
66
67
  auth: { persistSession: false, autoRefreshToken: false },
67
68
  });
@@ -1546,6 +1546,18 @@ function buildStripeWebhookHandler(config, connect) {
1546
1546
  const session = event.data.object;
1547
1547
  // Day Pass one-time checkout — record the purchase, no booking / no membership.
1548
1548
  if (session.metadata?.checkout_type === 'day_pass') {
1549
+ // Fail-closed payment guard: a completed session that has not moved
1550
+ // money (e.g. 'unpaid' from a delayed-notification method such as ACH
1551
+ // debit) must never grant door access, email, or create anything.
1552
+ if (session.payment_status !== 'paid' && session.payment_status !== 'no_payment_required') {
1553
+ await logOps(supabase, 'day_pass_session_completed_unpaid', {
1554
+ session_id: session.id,
1555
+ payment_status: session.payment_status ?? null,
1556
+ amount_total: session.amount_total ?? null,
1557
+ day_pass_id: session.metadata?.day_pass_id ?? session.metadata?.booking_id ?? null,
1558
+ }, { severity: 'error', dedupeKey: `day_pass_session_completed_unpaid:${session.id}` });
1559
+ break;
1560
+ }
1549
1561
  const email = session.customer_details?.email ?? session.customer_email ?? null;
1550
1562
  const customerId = typeof session.customer === 'string'
1551
1563
  ? session.customer
@@ -1807,9 +1819,12 @@ function buildStripeWebhookHandler(config, connect) {
1807
1819
  // else-if branch further down -- which handles the actual
1808
1820
  // cancelled_* case -- can reuse it without recomputing.
1809
1821
  const bkIsCancelled = bkStatus.startsWith('cancelled_');
1810
- // Connect-only: non-Connect (GC) completions keep the legacy behavior.
1811
- const sessionIsPaid = !connect ||
1812
- session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
1822
+ // Universal paid guard: a completed session whose payment_status is
1823
+ // not 'paid' / 'no_payment_required' (e.g. 'unpaid' from a
1824
+ // delayed-notification method such as ACH debit) has not moved any
1825
+ // money, so it must never flip a booking to paid or provision access,
1826
+ // for Connect and non-Connect operators alike.
1827
+ const sessionIsPaid = session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
1813
1828
  if (booking &&
1814
1829
  !sessionIsPaid &&
1815
1830
  bkStatus !== 'paid' &&
@@ -1824,7 +1839,7 @@ function buildStripeWebhookHandler(config, connect) {
1824
1839
  booking_status: bkStatus,
1825
1840
  amount_total: session.amount_total ?? null,
1826
1841
  }, {
1827
- severity: 'warning',
1842
+ severity: 'error',
1828
1843
  bookingId: booking.id,
1829
1844
  dedupeKey: `booking_session_completed_unpaid:${booking.id}:${session.id}`,
1830
1845
  });
@@ -3,6 +3,13 @@ export interface ManageTokenPayload {
3
3
  eml: string;
4
4
  exp: number;
5
5
  }
6
+ /** Allowlisted handler/error code when the HMAC key is missing or too short. */
7
+ export declare const MANAGE_TOKEN_UNAVAILABLE_CODE = "manage_token_unavailable";
8
+ /**
9
+ * M2(a): MANAGE_TOKEN_SECRET must be present and at least 32 UTF-8 bytes.
10
+ * Never log, throw, or return the secret value or its length.
11
+ */
12
+ export declare function isManageTokenSecretUsable(secret: string | undefined | null): secret is string;
6
13
  export declare function signManageToken(payload: ManageTokenPayload, secret: string): Promise<string>;
7
14
  export declare function verifyManageToken(token: string, secret: string): Promise<ManageTokenPayload | null>;
8
15
  /**
@@ -1,6 +1,24 @@
1
1
  // HMAC-SHA256 signed token for self-serve booking management. Payload is a
2
2
  // small JSON object identifying the booking and the customer email, plus an
3
3
  // expiry. Never accept a bare booking UUID for PII — the token is the only key.
4
+ /** Allowlisted handler/error code when the HMAC key is missing or too short. */
5
+ export const MANAGE_TOKEN_UNAVAILABLE_CODE = 'manage_token_unavailable';
6
+ const MANAGE_TOKEN_UNAVAILABLE_MESSAGE = 'manage token unavailable';
7
+ const MIN_MANAGE_TOKEN_SECRET_BYTES = 32;
8
+ /**
9
+ * M2(a): MANAGE_TOKEN_SECRET must be present and at least 32 UTF-8 bytes.
10
+ * Never log, throw, or return the secret value or its length.
11
+ */
12
+ export function isManageTokenSecretUsable(secret) {
13
+ if (typeof secret !== 'string')
14
+ return false;
15
+ return new TextEncoder().encode(secret).byteLength >= MIN_MANAGE_TOKEN_SECRET_BYTES;
16
+ }
17
+ function requireManageTokenSecret(secret) {
18
+ if (!isManageTokenSecretUsable(secret)) {
19
+ throw new Error(MANAGE_TOKEN_UNAVAILABLE_MESSAGE);
20
+ }
21
+ }
4
22
  function b64urlEncode(bytes) {
5
23
  const s = btoa(String.fromCharCode(...bytes));
6
24
  return s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
@@ -25,12 +43,15 @@ function timingSafeEqual(a, b) {
25
43
  return diff === 0;
26
44
  }
27
45
  export async function signManageToken(payload, secret) {
46
+ requireManageTokenSecret(secret);
28
47
  const key = await getKey(secret);
29
48
  const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
30
49
  const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes));
31
50
  return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
32
51
  }
33
52
  export async function verifyManageToken(token, secret) {
53
+ if (!isManageTokenSecretUsable(secret))
54
+ return null;
34
55
  const parts = token.split('.');
35
56
  if (parts.length !== 2)
36
57
  return null;
@@ -74,12 +95,15 @@ export async function buildManageUrl(base, payload, secret) {
74
95
  return `${base.replace(/\/+$/, '')}/manage-booking?token=${encodeURIComponent(token)}`;
75
96
  }
76
97
  export async function signMemberToken(payload, secret) {
98
+ requireManageTokenSecret(secret);
77
99
  const key = await getKey(secret);
78
100
  const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
79
101
  const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes));
80
102
  return `${b64urlEncode(payloadBytes)}.${b64urlEncode(sig)}`;
81
103
  }
82
104
  export async function verifyMemberToken(token, secret) {
105
+ if (!isManageTokenSecretUsable(secret))
106
+ return null;
83
107
  const parts = token.split('.');
84
108
  if (parts.length !== 2)
85
109
  return null;
@@ -117,6 +141,7 @@ export async function buildMemberManageUrl(base, payload, secret) {
117
141
  return `${base.replace(/\/+$/, '')}/membership/manage?token=${encodeURIComponent(token)}`;
118
142
  }
119
143
  export async function signAgreementPortalToken(payload, secret) {
144
+ requireManageTokenSecret(secret);
120
145
  const key = await getKey(secret);
121
146
  const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
122
147
  const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes));
@@ -128,6 +153,8 @@ export async function signAgreementPortalToken(payload, secret) {
128
153
  * verifies again without any separate un-revoke step.
129
154
  */
130
155
  export async function verifyAgreementPortalToken(token, secret, revokedAtIso) {
156
+ if (!isManageTokenSecretUsable(secret))
157
+ return null;
131
158
  const parts = token.split('.');
132
159
  if (parts.length !== 2)
133
160
  return null;
@@ -190,6 +217,7 @@ export async function buildAgreementPortalUrl(base, signatureDocumentId, signerE
190
217
  */
191
218
  export const MIGRATION_CHECKOUT_TOKEN_TTL_SECONDS = 60 * 24 * 3600;
192
219
  export async function signMigrationCheckoutToken(payload, secret) {
220
+ requireManageTokenSecret(secret);
193
221
  const key = await getKey(secret);
194
222
  const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
195
223
  const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, payloadBytes));
@@ -197,6 +225,8 @@ export async function signMigrationCheckoutToken(payload, secret) {
197
225
  }
198
226
  /** Phase 1: decode + HMAC + shape + expiry. Pure — no DB, no revocation check. */
199
227
  export async function verifyMigrationCheckoutToken(token, secret) {
228
+ if (!isManageTokenSecretUsable(secret))
229
+ return null;
200
230
  const parts = token.split('.');
201
231
  if (parts.length !== 2)
202
232
  return null;
@@ -19,7 +19,7 @@
19
19
  // remains exclusively stripe-webhook's job, unmodified.
20
20
  import { createClient } from '@supabase/supabase-js';
21
21
  import Stripe from 'stripe';
22
- import { verifyMigrationCheckoutToken, migrationCheckoutTokenIsRevoked, } from './manageToken.js';
22
+ import { isManageTokenSecretUsable, MANAGE_TOKEN_UNAVAILABLE_CODE, verifyMigrationCheckoutToken, migrationCheckoutTokenIsRevoked, } from './manageToken.js';
23
23
  export const MIGRATION_CONFIRM_PATH = '/functions/v1/migration-checkout-confirm';
24
24
  export const MIGRATION_REDIRECT_PATH = '/functions/v1/migration-checkout-redirect';
25
25
  export function resolveDeps(req, defaultBaseUrl) {
@@ -70,8 +70,12 @@ export const EXISTING_MEMBERSHIP_STATUSES = [
70
70
  */
71
71
  export async function loadTokenStateAndPlan(deps, token) {
72
72
  // --- step 1 ---
73
- if (!token || !deps.tokenSecret)
73
+ if (!token)
74
74
  return { kind: 'token_error' };
75
+ if (!isManageTokenSecretUsable(deps.tokenSecret)) {
76
+ console.error('[migrationCheckout]', MANAGE_TOKEN_UNAVAILABLE_CODE);
77
+ return { kind: 'token_error' };
78
+ }
75
79
  const payload = await verifyMigrationCheckoutToken(token, deps.tokenSecret);
76
80
  if (!payload)
77
81
  return { kind: 'token_error' };
@@ -16,6 +16,10 @@ export async function resolvePortalSession(req, admin) {
16
16
  const { data, error } = await admin.auth.getUser(jwt);
17
17
  if (error || !data?.user?.email)
18
18
  return null;
19
+ // A session JWT is not enough: the address must be confirmed so an
20
+ // unconfirmed signup cannot present as that email on manage-booking.
21
+ if (!data.user.email_confirmed_at)
22
+ return null;
19
23
  return { id: data.user.id, email: data.user.email.toLowerCase() };
20
24
  }
21
25
  catch (e) {
@@ -14,6 +14,13 @@ export declare const RETELL_ALLOWLISTED_IP = "100.20.5.228";
14
14
  */
15
15
  export declare const RETELL_EXEMPT_BUCKETS: Set<string>;
16
16
  export declare function clientIp(req: Request): string;
17
+ /**
18
+ * Manage-booking IP buckets only. Uses Cloudflare's cf-connecting-ip and
19
+ * ignores client-supplied X-Forwarded-For. Missing CF header shares the
20
+ * same `'unknown'` sentinel clientIp() uses, rather than a fresh bucket
21
+ * per spoofed hop.
22
+ */
23
+ export declare function manageBookingClientIp(req: Request): string;
17
24
  export declare function checkRateLimit(supabase: SupabaseLike, bucket: string, identifier: string, max: number, windowSeconds: number, opts?: {
18
25
  failClosed?: boolean;
19
26
  }): Promise<boolean>;
package/dist/rateLimit.js CHANGED
@@ -30,6 +30,18 @@ export function clientIp(req) {
30
30
  return cf.trim();
31
31
  return 'unknown';
32
32
  }
33
+ /**
34
+ * Manage-booking IP buckets only. Uses Cloudflare's cf-connecting-ip and
35
+ * ignores client-supplied X-Forwarded-For. Missing CF header shares the
36
+ * same `'unknown'` sentinel clientIp() uses, rather than a fresh bucket
37
+ * per spoofed hop.
38
+ */
39
+ export function manageBookingClientIp(req) {
40
+ const cf = req.headers.get('cf-connecting-ip')?.trim();
41
+ if (cf)
42
+ return cf;
43
+ return 'unknown';
44
+ }
33
45
  export async function checkRateLimit(supabase, bucket, identifier, max, windowSeconds,
34
46
  // Should-fix S2 (adversarial review, round 1): the shared default here is
35
47
  // fail-OPEN on an RPC error/throw -- deliberately, since most callers of
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.24",
3
+ "version": "0.3.27",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",