@simplelayer/graniteer-core 0.3.27 → 0.3.28

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.
@@ -14,6 +14,7 @@ import { laWallToUtc } from '../availability.js';
14
14
  import { resolveContractTier, loadTier1Terms } from '../tier1Agreement.js';
15
15
  import { logOps } from '../ops.js';
16
16
  import { verifyRetellSignature } from '../retellSignature.js';
17
+ import { checkPolicyAcceptance, POLICY_NOT_ACCEPTED_ERROR, policyTextSha256, } from '../policyAcknowledgment.js';
17
18
  const Body = z.object({
18
19
  room_slug: z.string().min(1).max(120),
19
20
  date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
@@ -25,6 +26,9 @@ const Body = z.object({
25
26
  // Optional replay guard for the voice agent: a dropped call can make it
26
27
  // resend the same request. Omitting it behaves exactly as before.
27
28
  idempotency_key: z.string().min(1).max(200).optional(),
29
+ // Spoken acceptance of rooms.checkout_agreement_text. Absent or false is
30
+ // not acceptance — never coerce this to true.
31
+ room_rules_accepted: z.boolean().optional(),
28
32
  });
29
33
  // How long a stored response is replayed. Older rows are treated as a miss and
30
34
  // simply overwritten by the next write (most recent write wins, no GC job).
@@ -35,7 +39,12 @@ const json = (status, body) => new Response(JSON.stringify(body), {
35
39
  });
36
40
  // Business-logic failures always return HTTP 200 so the caller reliably gets
37
41
  // JSON back; only a malformed request body is a non-200.
38
- const GENERIC_ERROR = 'Sorry — that booking could not be completed.';
42
+ const GENERIC_ERROR = 'Sorry, that booking could not be completed.';
43
+ // Codes that may be logged or returned. Upstream sentences never qualify.
44
+ const SAFE_CODE = /^[a-z0-9_]{1,64}$/;
45
+ function safeCode(value) {
46
+ return typeof value === 'string' && SAFE_CODE.test(value) ? value : 'unknown_error';
47
+ }
39
48
  const GHL_BASE = 'https://services.leadconnectorhq.com';
40
49
  const GHL_VERSION = '2021-07-28';
41
50
  const GHL_LOCATION_ID = 'BDI8NHA4nkHnQGJ8g3hV';
@@ -180,7 +189,7 @@ export async function handle(req, config) {
180
189
  const parsed = Body.safeParse(raw);
181
190
  if (!parsed.success)
182
191
  return json(400, { ok: false, error: 'invalid_request' });
183
- const { room_slug, date, start_time, duration_minutes, contact_name, contact_email, contact_phone, idempotency_key, } = parsed.data;
192
+ const { room_slug, date, start_time, duration_minutes, contact_name, contact_email, contact_phone, idempotency_key, room_rules_accepted, } = parsed.data;
184
193
  const supabaseUrl = Deno.env.get('SUPABASE_URL');
185
194
  const serviceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
186
195
  const supabase = createClient(supabaseUrl, serviceKey);
@@ -222,13 +231,13 @@ export async function handle(req, config) {
222
231
  // Not cached: rate limiting is transient and must stay retryable.
223
232
  return json(200, {
224
233
  ok: false,
225
- error: 'Too many booking attempts — please try again in a few minutes.',
234
+ error: 'Too many booking attempts - please try again in a few minutes.',
226
235
  });
227
236
  }
228
237
  // Slug -> id only. `create-booking` owns the active=true check and its 404.
229
238
  const { data: room, error: rErr } = await supabase
230
239
  .from('rooms')
231
- .select('id,name')
240
+ .select('id,name,checkout_agreement_text')
232
241
  .eq('slug', room_slug)
233
242
  .maybeSingle();
234
243
  if (rErr)
@@ -248,13 +257,25 @@ export async function handle(req, config) {
248
257
  if (contractTier === 2) {
249
258
  return await finish({
250
259
  ok: false,
251
- error: "That room needs a signed use agreement. Give us your email and we'll send the agreement over to sign — once it's signed we'll send a payment link to confirm the booking.",
260
+ error: "That room needs a signed use agreement. Give us your email and we'll send the agreement over to sign - once it's signed we'll send a payment link to confirm the booking.",
252
261
  });
253
262
  }
254
263
  if (contractTier !== 1) {
255
264
  return await finish({
256
265
  ok: false,
257
- error: `Please complete this booking on ${config.bookingSiteDomain} to review and accept the room agreement — it only takes a minute, and the room stays available while you do it.`,
266
+ error: `Please complete this booking on ${config.bookingSiteDomain} to review and accept the room agreement - it only takes a minute, and the room stays available while you do it.`,
267
+ });
268
+ }
269
+ // Per-room checkout policy (separate from the Tier 1 terms below). A room
270
+ // with non-empty checkout_agreement_text is gated on an explicit true.
271
+ // Checked before terms load so a terms outage cannot hide this debug_code.
272
+ const policyText = room.checkout_agreement_text ?? null;
273
+ const policy = checkPolicyAcceptance({ checkout_agreement_text: policyText }, room_rules_accepted);
274
+ if (!policy.ok) {
275
+ return json(200, {
276
+ ok: false,
277
+ error: GENERIC_ERROR,
278
+ debug_code: safeCode('room_rules_not_accepted'),
258
279
  });
259
280
  }
260
281
  // Tier 1 terms: the version is resolved server-side (never client-declared),
@@ -291,6 +312,9 @@ export async function handle(req, config) {
291
312
  },
292
313
  policy_accepted: true,
293
314
  agreement,
315
+ // Only an explicit true. Omitting the field is what create-booking
316
+ // treats as "not accepted" for a gated room; never send false or a default.
317
+ ...(room_rules_accepted === true ? { agreementAccepted: true } : {}),
294
318
  }),
295
319
  });
296
320
  const payload = await res.json().catch(() => null);
@@ -304,6 +328,18 @@ export async function handle(req, config) {
304
328
  method: 'phone_verbal',
305
329
  consented_at: new Date().toISOString(),
306
330
  }, { severity: 'info', bookingId: payload.booking_id });
331
+ if (policy.required && room_rules_accepted === true) {
332
+ const rulesDetail = {
333
+ booking_id: payload.booking_id,
334
+ call_id: callId,
335
+ method: 'phone_verbal',
336
+ consented_at: new Date().toISOString(),
337
+ };
338
+ if (typeof policyText === 'string' && policyText.trim().length > 0) {
339
+ rulesDetail.agreement_text_sha256 = await policyTextSha256(policyText);
340
+ }
341
+ await logOps(supabase, 'voice_booking_room_rules_consent', rulesDetail, { severity: 'info', bookingId: payload.booking_id });
342
+ }
307
343
  const roomName = room.name || room_slug;
308
344
  if (payload.fully_covered === true) {
309
345
  const smsSent = await runSmsWithBudget(sendVoiceBookingSms({
@@ -343,6 +379,22 @@ export async function handle(req, config) {
343
379
  });
344
380
  }
345
381
  }
382
+ // Status and a safe error code only. Upstream text (sentences, punctuation,
383
+ // over-long values) is never stored or returned as a code.
384
+ const rawError = typeof payload?.error === 'string' ? payload.error : 'invalid_body';
385
+ const errorCode = rawError === POLICY_NOT_ACCEPTED_ERROR
386
+ ? safeCode('room_rules_not_accepted')
387
+ : safeCode(rawError);
388
+ if (!res.ok) {
389
+ await logOps(supabase, 'voice_booking_create_failed', { status: res.status, error_code: errorCode }, { severity: 'error' });
390
+ }
391
+ if (payload?.error === POLICY_NOT_ACCEPTED_ERROR) {
392
+ return json(200, {
393
+ ok: false,
394
+ error: GENERIC_ERROR,
395
+ debug_code: safeCode('room_rules_not_accepted'),
396
+ });
397
+ }
346
398
  // 409 is the one caller-safe passthrough — it is already a clean, actionable
347
399
  // sentence ("That time was just booked — please choose another slot.").
348
400
  if (res.status === 409 && typeof payload?.error === 'string') {
@@ -350,7 +402,7 @@ export async function handle(req, config) {
350
402
  }
351
403
  // Everything else (400 zod flatten, 404, 429, 500, unparseable body) is
352
404
  // logged but never leaked to the caller.
353
- console.error('[voice-booking] create-booking failed', res.status, JSON.stringify(payload));
405
+ console.error('[voice-booking] create-booking failed', res.status, errorCode);
354
406
  return json(200, { ok: false, error: GENERIC_ERROR });
355
407
  }
356
408
  catch (e) {
@@ -0,0 +1,13 @@
1
+ export declare const HUMAN_POLICY: Readonly<{
2
+ readonly allowOffline: true;
3
+ readonly allowCredit: true;
4
+ readonly allowMembershipAttach: true;
5
+ readonly allowSkipDynamicDiscount: true;
6
+ readonly settlePaid: true;
7
+ readonly failClosedRateLimit: false;
8
+ readonly requireIdempotencyKey: false;
9
+ readonly minNetCents: 0;
10
+ readonly allowedTiers: "any";
11
+ readonly refuseQuoteMode: false;
12
+ readonly refuseAgreementText: false;
13
+ }>;
@@ -0,0 +1,13 @@
1
+ export const HUMAN_POLICY = Object.freeze({
2
+ allowOffline: true,
3
+ allowCredit: true,
4
+ allowMembershipAttach: true,
5
+ allowSkipDynamicDiscount: true,
6
+ settlePaid: true,
7
+ failClosedRateLimit: false,
8
+ requireIdempotencyKey: false,
9
+ minNetCents: 0,
10
+ allowedTiers: 'any',
11
+ refuseQuoteMode: false,
12
+ refuseAgreementText: false,
13
+ });
@@ -1,11 +1,18 @@
1
1
  import type { SupabaseClient } from '@supabase/supabase-js';
2
2
  type SupabaseLike = SupabaseClient<any, 'public', any>;
3
3
  export type PaymentLinkEmailResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
4
- export declare function sendPaymentLinkEmail(supabase: SupabaseLike, { email, name, checkoutUrl, officeNumber }: {
4
+ export declare function sendPaymentLinkEmail(supabase: SupabaseLike, { email, name, checkoutUrl, officeNumber, variant, booking }: {
5
5
  email: string;
6
6
  name?: string | null;
7
7
  checkoutUrl: string;
8
8
  officeNumber?: string | null;
9
+ /** Omitted => the original office-agreement copy, byte-identical. */
10
+ variant?: 'office_agreement' | 'agent_booking';
11
+ booking?: {
12
+ roomName: string;
13
+ when: string;
14
+ expiresAtIso: string;
15
+ } | null;
9
16
  }, operator: {
10
17
  name: string;
11
18
  shortName: string;
@@ -26,7 +26,11 @@ function classifyError(e) {
26
26
  }
27
27
  return 'failed_permanent';
28
28
  }
29
- export async function sendPaymentLinkEmail(supabase, { email, name, checkoutUrl, officeNumber }, operator) {
29
+ /** Strip Checkout URLs and cap length so GHL error bodies cannot leak a payable link into logs. */
30
+ function redactErrorMessage(msg) {
31
+ return msg.replace(/https:\/\/checkout\.stripe\.com\/\S+/g, '[redacted-url]').slice(0, 120);
32
+ }
33
+ export async function sendPaymentLinkEmail(supabase, { email, name, checkoutUrl, officeNumber, variant, booking }, operator) {
30
34
  try {
31
35
  const apiKey = Deno.env.get('GHL_API_KEY');
32
36
  const locationId = Deno.env.get('GHL_LOCATION_ID');
@@ -51,14 +55,21 @@ export async function sendPaymentLinkEmail(supabase, { email, name, checkoutUrl,
51
55
  crmName.firstName = parts[0];
52
56
  if (parts.length > 1)
53
57
  crmName.lastName = parts.slice(1).join(' ');
58
+ const isAgentVariant = variant === 'agent_booking';
54
59
  const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
55
60
  method: 'POST', headers,
56
61
  signal: AbortSignal.timeout(8000),
57
- body: JSON.stringify({
58
- locationId, ...crmName, email,
59
- source: `${operator.shortName} Website — Office Agreement`,
60
- tags: ['Office Agreement', operator.domain],
61
- }),
62
+ body: JSON.stringify(isAgentVariant
63
+ ? {
64
+ locationId, email,
65
+ source: `${operator.shortName} - Agent booking payment link`,
66
+ tags: ['Agent Booking Link', operator.domain],
67
+ }
68
+ : {
69
+ locationId, ...crmName, email,
70
+ source: `${operator.shortName} Website — Office Agreement`,
71
+ tags: ['Office Agreement', operator.domain],
72
+ }),
62
73
  });
63
74
  if (!upRes.ok)
64
75
  throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
@@ -69,7 +80,20 @@ export async function sendPaymentLinkEmail(supabase, { email, name, checkoutUrl,
69
80
  const p = (t) => `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
70
81
  const office = (officeNumber || '').trim();
71
82
  const officeClause = office ? ` for office ${esc(office)}` : '';
72
- const html = `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
83
+ const isAgent = isAgentVariant;
84
+ const subject = isAgent
85
+ ? `Complete your ${operator.shortName} room booking — payment link`
86
+ : `Your ${operator.shortName} office agreement is signed — set up payment`;
87
+ const html = isAgent
88
+ ? `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
89
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Complete your ${esc(operator.shortName)} room booking</h2>
90
+ ${p(`Hi ${esc(greetingName)},`)}
91
+ ${p(`A booking was requested for you at ${esc(operator.name)}${booking ? `: ${esc(booking.roomName)}, ${esc(booking.when)}` : ''}. It is held for you until you pay.`)}
92
+ ${p(`<a href="${esc(checkoutUrl)}" style="color:#C98A5E">Review the terms and pay →</a>`)}
93
+ ${p(`${booking ? `This link expires ${esc(booking.expiresAtIso)}. ` : ''}It is unique to this booking, so please don't forward it. If you did not expect this email, ignore it and nothing will be charged.`)}
94
+ ${p(`Questions? Reply to this email or reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
95
+ </td></tr></table></td></tr></table></div>`
96
+ : `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
73
97
  <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Your ${operator.shortName} office agreement is signed — set up payment</h2>
74
98
  ${p(`Hi ${esc(greetingName)},`)}
75
99
  ${p(`Thanks for signing your ${operator.name} office agreement${officeClause} — you're one step from locked in.`)}
@@ -85,7 +109,7 @@ ${p(`Welcome aboard,<br />The ${operator.name} team`)}
85
109
  body: JSON.stringify({
86
110
  type: 'Email',
87
111
  contactId,
88
- subject: `Your ${operator.shortName} office agreement is signed — set up payment`,
112
+ subject,
89
113
  html,
90
114
  }),
91
115
  });
@@ -96,7 +120,7 @@ ${p(`Welcome aboard,<br />The ${operator.name} team`)}
96
120
  }
97
121
  catch (e) {
98
122
  const classification = classifyError(e);
99
- await logOps(supabase, 'payment_link_email_failed', { email, message: e instanceof Error ? e.message : String(e) }, { severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => { });
123
+ await logOps(supabase, 'payment_link_email_failed', { email, message: redactErrorMessage(e instanceof Error ? e.message : String(e)) }, { severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => { });
100
124
  return classification;
101
125
  }
102
126
  }
package/dist/pricing.js CHANGED
@@ -57,7 +57,8 @@ export function formatHumanTime(startUtc, endUtc) {
57
57
  const timeFmt = new Intl.DateTimeFormat('en-US', {
58
58
  timeZone: 'America/Los_Angeles', hour: 'numeric', minute: '2-digit', hour12: true,
59
59
  });
60
- return `${dateFmt.format(startUtc)}, ${timeFmt.format(startUtc)}–${timeFmt.format(endUtc)} PT`;
60
+ const t = (d) => timeFmt.format(d).replace(/[\u202F\u00A0]/g, ' ');
61
+ return `${dateFmt.format(startUtc)}, ${t(startUtc)}–${t(endUtc)} PT`;
61
62
  }
62
63
  async function getHours(supabase, roomId, wd) {
63
64
  const { data, error } = await supabase
@@ -24,4 +24,11 @@ export declare function manageBookingClientIp(req: Request): string;
24
24
  export declare function checkRateLimit(supabase: SupabaseLike, bucket: string, identifier: string, max: number, windowSeconds: number, opts?: {
25
25
  failClosed?: boolean;
26
26
  }): Promise<boolean>;
27
+ export type RateLimitDetailed = 'ok' | 'limited' | 'error';
28
+ /**
29
+ * Additive sibling of checkRateLimit for callers that must distinguish "over
30
+ * the limit" from "the limiter itself failed" (fail-closed callers answer 503
31
+ * on 'error', 429 on 'limited'). checkRateLimit is deliberately untouched.
32
+ */
33
+ export declare function checkRateLimitDetailed(supabase: SupabaseLike, bucket: string, identifier: string, max: number, windowSeconds: number): Promise<RateLimitDetailed>;
27
34
  export {};
package/dist/rateLimit.js CHANGED
@@ -80,3 +80,31 @@ opts = {}) {
80
80
  return !opts.failClosed;
81
81
  }
82
82
  }
83
+ /**
84
+ * Additive sibling of checkRateLimit for callers that must distinguish "over
85
+ * the limit" from "the limiter itself failed" (fail-closed callers answer 503
86
+ * on 'error', 429 on 'limited'). checkRateLimit is deliberately untouched.
87
+ */
88
+ export async function checkRateLimitDetailed(supabase, bucket, identifier, max, windowSeconds) {
89
+ try {
90
+ const { data, error } = await supabase.rpc('check_rate_limit', {
91
+ p_bucket: bucket,
92
+ p_identifier: identifier,
93
+ p_max: max,
94
+ p_window_seconds: windowSeconds,
95
+ });
96
+ if (error) {
97
+ await logOps(supabase, 'rate_limit_check_failed', { bucket, identifier: identifier.slice(0, 64), message: error.message }, { severity: 'warning' }).catch(() => { });
98
+ return 'error';
99
+ }
100
+ if (data === true)
101
+ return 'ok';
102
+ if (data === false)
103
+ return 'limited';
104
+ return 'error';
105
+ }
106
+ catch (e) {
107
+ await logOps(supabase, 'rate_limit_check_failed', { bucket, identifier: identifier.slice(0, 64), message: String(e) }, { severity: 'warning' }).catch(() => { });
108
+ return 'error';
109
+ }
110
+ }
@@ -39,6 +39,10 @@ declare class FakeQuery implements PromiseLike<DbResult> {
39
39
  gt(...args: unknown[]): this;
40
40
  gte(...args: unknown[]): this;
41
41
  lt(...args: unknown[]): this;
42
+ lte(...args: unknown[]): this;
43
+ ilike(...args: unknown[]): this;
44
+ or(...args: unknown[]): this;
45
+ filter(...args: unknown[]): this;
42
46
  order(...args: unknown[]): this;
43
47
  limit(...args: unknown[]): this;
44
48
  maybeSingle(): Promise<DbResult>;
@@ -46,7 +50,33 @@ declare class FakeQuery implements PromiseLike<DbResult> {
46
50
  then<R1 = DbResult, R2 = never>(onOk?: ((v: DbResult) => R1 | PromiseLike<R1>) | null, onErr?: ((e: unknown) => R2 | PromiseLike<R2>) | null): PromiseLike<R1 | R2>;
47
51
  private resolve;
48
52
  }
53
+ /**
54
+ * One entry of the shared, strictly ordered call log. Both the fake Supabase
55
+ * client and the recording Stripe fake can append to the same array, so a test
56
+ * can pin the exact interleaving of DB writes, RPCs and Stripe calls.
57
+ */
58
+ export type OrderedCall = {
59
+ kind: 'db';
60
+ table: string;
61
+ op: RecordedDbCall['op'];
62
+ columns?: string;
63
+ payload?: unknown;
64
+ filters: RecordedDbCall['filters'];
65
+ terminal: string;
66
+ } | {
67
+ kind: 'rpc';
68
+ fn: string;
69
+ args: unknown;
70
+ } | {
71
+ kind: 'stripe';
72
+ op: 'create' | 'expire' | 'retrieve';
73
+ id?: string;
74
+ params?: unknown;
75
+ options?: unknown;
76
+ };
49
77
  export interface FakeSupabase {
78
+ /** Every db + rpc call in the order it happened (also mirrored into opts.log). */
79
+ readonly calls: OrderedCall[];
50
80
  from(table: string): FakeQuery;
51
81
  rpc(fn: string, args?: unknown): Promise<DbResult>;
52
82
  /** Every PostgREST call made, in order. */
@@ -61,7 +91,37 @@ export interface FakeSupabase {
61
91
  export declare function makeFakeSupabase(opts?: {
62
92
  db?: DbResponder;
63
93
  rpc?: RpcResponder;
94
+ /** Optional shared ordered log (see OrderedCall). */
95
+ log?: OrderedCall[];
64
96
  }): FakeSupabase;
65
97
  /** Reads the value an `update` payload set for one column, or `undefined`. */
66
98
  export declare function updatedValue(call: RecordedDbCall, column: string): unknown;
99
+ export interface RecordedStripeCall {
100
+ op: 'create' | 'expire' | 'retrieve';
101
+ id?: string;
102
+ params?: unknown;
103
+ options?: unknown;
104
+ }
105
+ export interface RecordingStripe {
106
+ checkout: {
107
+ sessions: {
108
+ create(params: unknown, options?: unknown): Promise<Record<string, unknown>>;
109
+ expire(id: string, params?: unknown, options?: unknown): Promise<Record<string, unknown>>;
110
+ retrieve(id: string, params?: unknown, options?: unknown): Promise<Record<string, unknown>>;
111
+ };
112
+ };
113
+ /** Exact arguments of every checkout.sessions.* call, in order. */
114
+ readonly calls: RecordedStripeCall[];
115
+ }
116
+ /**
117
+ * TEST-ONLY recording Stripe fake. Captures the exact params/options handed to
118
+ * checkout.sessions.create/expire/retrieve; no transport. A responder may
119
+ * return a session object or throw to simulate a Stripe failure.
120
+ */
121
+ export declare function makeRecordingStripe(opts?: {
122
+ create?: (params: unknown, options?: unknown) => Record<string, unknown>;
123
+ expire?: (id: string) => Record<string, unknown>;
124
+ retrieve?: (id: string) => Record<string, unknown>;
125
+ log?: OrderedCall[];
126
+ }): RecordingStripe;
67
127
  export {};
@@ -35,6 +35,10 @@ class FakeQuery {
35
35
  gt(...args) { this.rec.filters.push({ kind: 'gt', args }); return this; }
36
36
  gte(...args) { this.rec.filters.push({ kind: 'gte', args }); return this; }
37
37
  lt(...args) { this.rec.filters.push({ kind: 'lt', args }); return this; }
38
+ lte(...args) { this.rec.filters.push({ kind: 'lte', args }); return this; }
39
+ ilike(...args) { this.rec.filters.push({ kind: 'ilike', args }); return this; }
40
+ or(...args) { this.rec.filters.push({ kind: 'or', args }); return this; }
41
+ filter(...args) { this.rec.filters.push({ kind: 'filter', args }); return this; }
38
42
  order(...args) { this.rec.filters.push({ kind: 'order', args }); return this; }
39
43
  limit(...args) { this.rec.filters.push({ kind: 'limit', args }); return this; }
40
44
  maybeSingle() { this.rec.terminal = 'maybeSingle'; return this.resolve(); }
@@ -60,17 +64,34 @@ class FakeQuery {
60
64
  export function makeFakeSupabase(opts = {}) {
61
65
  const dbCalls = [];
62
66
  const rpcCalls = [];
67
+ const calls = [];
63
68
  const db = opts.db ?? (() => OK);
64
69
  const rpc = opts.rpc ?? (() => OK);
70
+ const record = (c) => { calls.push(c); opts.log?.push(c); };
71
+ // The query records itself into `dbCalls` when it is awaited; mirror that
72
+ // moment into the ordered log by observing pushes.
73
+ const observedDbCalls = new Proxy(dbCalls, {
74
+ get(target, prop, receiver) {
75
+ if (prop === 'push') {
76
+ return (rec) => {
77
+ record({ kind: 'db', table: rec.table, op: rec.op, columns: rec.columns, payload: rec.payload, filters: rec.filters, terminal: rec.terminal });
78
+ return target.push(rec);
79
+ };
80
+ }
81
+ return Reflect.get(target, prop, receiver);
82
+ },
83
+ });
65
84
  return {
66
85
  dbCalls,
67
86
  rpcCalls,
87
+ calls,
68
88
  from(table) {
69
- return new FakeQuery({ table, op: 'none', filters: [], terminal: 'await' }, db, dbCalls);
89
+ return new FakeQuery({ table, op: 'none', filters: [], terminal: 'await' }, db, observedDbCalls);
70
90
  },
71
91
  rpc(fn, args) {
72
92
  const call = { fn, args };
73
93
  rpcCalls.push(call);
94
+ record({ kind: 'rpc', fn, args });
74
95
  return Promise.resolve(rpc(call) ?? OK);
75
96
  },
76
97
  callsTo(table) { return dbCalls.filter((c) => c.table === table); },
@@ -83,3 +104,49 @@ export function makeFakeSupabase(opts = {}) {
83
104
  export function updatedValue(call, column) {
84
105
  return call.payload?.[column];
85
106
  }
107
+ /**
108
+ * TEST-ONLY recording Stripe fake. Captures the exact params/options handed to
109
+ * checkout.sessions.create/expire/retrieve; no transport. A responder may
110
+ * return a session object or throw to simulate a Stripe failure.
111
+ */
112
+ export function makeRecordingStripe(opts = {}) {
113
+ const calls = [];
114
+ const record = (c) => {
115
+ calls.push(c);
116
+ opts.log?.push({ kind: 'stripe', ...c });
117
+ };
118
+ return {
119
+ calls,
120
+ checkout: {
121
+ sessions: {
122
+ create(params, options) {
123
+ record({ op: 'create', params, options });
124
+ try {
125
+ return Promise.resolve(opts.create?.(params, options) ?? { id: 'cs_fake_1', url: 'https://checkout.stripe.test/cs_fake_1' });
126
+ }
127
+ catch (e) {
128
+ return Promise.reject(e);
129
+ }
130
+ },
131
+ expire(id, params, options) {
132
+ record({ op: 'expire', id, params, options });
133
+ try {
134
+ return Promise.resolve(opts.expire?.(id) ?? { id, status: 'expired' });
135
+ }
136
+ catch (e) {
137
+ return Promise.reject(e);
138
+ }
139
+ },
140
+ retrieve(id, params, options) {
141
+ record({ op: 'retrieve', id, params, options });
142
+ try {
143
+ return Promise.resolve(opts.retrieve?.(id) ?? { id, status: 'open' });
144
+ }
145
+ catch (e) {
146
+ return Promise.reject(e);
147
+ }
148
+ },
149
+ },
150
+ },
151
+ };
152
+ }
@@ -28,11 +28,19 @@ export declare function loadTier1Terms(supabase: SupabaseLike, declaredVersion:
28
28
  error: 'terms_unavailable' | 'terms_version_stale';
29
29
  current_version?: string;
30
30
  }>;
31
+ /** Loads a SPECIFIC published Tier-1 version (what a Checkout customer saw), hashing its exact bytes. */
32
+ export declare function loadTier1TermsVersion(supabase: SupabaseLike, version: string): Promise<{
33
+ ok: true;
34
+ terms: Tier1Terms;
35
+ } | {
36
+ ok: false;
37
+ error: 'terms_unavailable' | 'terms_version_invalid' | 'terms_version_missing';
38
+ }>;
31
39
  export interface Tier1AgreementInput {
32
40
  bookingId: string;
33
41
  roomSlug: string | null;
34
42
  terms: Tier1Terms;
35
- method?: 'click_through' | 'phone_verbal';
43
+ method?: 'click_through' | 'phone_verbal' | 'stripe_checkout_tos';
36
44
  signerName: string | null;
37
45
  signerEmail: string | null;
38
46
  signerIp: string | null;
@@ -46,6 +46,31 @@ export async function loadTier1Terms(supabase, declaredVersion) {
46
46
  const bytes = new Uint8Array(await docRes.data.arrayBuffer());
47
47
  return { ok: true, terms: { version: current, path, content_sha256: await sha256Hex(bytes) } };
48
48
  }
49
+ function isStorageNotFound(err) {
50
+ if (!err || typeof err !== 'object')
51
+ return false;
52
+ const e = err;
53
+ const msg = typeof e.message === 'string' ? e.message.trim() : '';
54
+ if (/^object not found$/i.test(msg))
55
+ return true;
56
+ const is404 = Number(e.status) === 404 || Number(e.statusCode) === 404;
57
+ return is404 && /object not found/i.test(msg) && !/bucket/i.test(msg);
58
+ }
59
+ /** Loads a SPECIFIC published Tier-1 version (what a Checkout customer saw), hashing its exact bytes. */
60
+ export async function loadTier1TermsVersion(supabase, version) {
61
+ if (typeof version !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(version)) {
62
+ return { ok: false, error: 'terms_version_invalid' };
63
+ }
64
+ const path = `${TIER1_TERMS_DIR}/${version}.md`;
65
+ const docRes = await supabase.storage.from(TERMS_BUCKET).download(path);
66
+ if (docRes.error) {
67
+ return { ok: false, error: isStorageNotFound(docRes.error) ? 'terms_version_missing' : 'terms_unavailable' };
68
+ }
69
+ if (!docRes.data)
70
+ return { ok: false, error: 'terms_unavailable' };
71
+ const bytes = new Uint8Array(await docRes.data.arrayBuffer());
72
+ return { ok: true, terms: { version, path, content_sha256: await sha256Hex(bytes) } };
73
+ }
49
74
  /**
50
75
  * Records the Tier 1 acceptance. `booking_agreements.booking_id` is
51
76
  * UNIQUE, so a duplicate insert (retry / reschedule re-entry) is a no-op.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.27",
3
+ "version": "0.3.28",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -21,6 +21,14 @@
21
21
  "types": "./dist/adminBookingCredit.d.ts",
22
22
  "default": "./dist/adminBookingCredit.js"
23
23
  },
24
+ "./agentBooking": {
25
+ "types": "./dist/agentBooking.d.ts",
26
+ "default": "./dist/agentBooking.js"
27
+ },
28
+ "./agentPolicy": {
29
+ "types": "./dist/agentPolicy.d.ts",
30
+ "default": "./dist/agentPolicy.js"
31
+ },
24
32
  "./agreementCheckout": {
25
33
  "types": "./dist/agreementCheckout.d.ts",
26
34
  "default": "./dist/agreementCheckout.js"
@@ -125,6 +133,10 @@
125
133
  "types": "./dist/conductorAdmin.d.ts",
126
134
  "default": "./dist/conductorAdmin.js"
127
135
  },
136
+ "./createBookingCore": {
137
+ "types": "./dist/createBookingCore.d.ts",
138
+ "default": "./dist/createBookingCore.js"
139
+ },
128
140
  "./entitlements": {
129
141
  "types": "./dist/entitlements.d.ts",
130
142
  "default": "./dist/entitlements.js"
@@ -409,6 +421,10 @@
409
421
  "types": "./dist/functions/admin-wall-photo-write.d.ts",
410
422
  "default": "./dist/functions/admin-wall-photo-write.js"
411
423
  },
424
+ "./functions/agent-create-booking": {
425
+ "types": "./dist/functions/agent-create-booking.d.ts",
426
+ "default": "./dist/functions/agent-create-booking.js"
427
+ },
412
428
  "./functions/auth-email-hook": {
413
429
  "types": "./dist/functions/auth-email-hook.d.ts",
414
430
  "default": "./dist/functions/auth-email-hook.js"