@simplelayer/graniteer-core 0.3.19 → 0.3.21-referral.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/bookingSource.d.ts +2 -0
  2. package/dist/bookingSource.js +11 -0
  3. package/dist/businessHours.d.ts +11 -0
  4. package/dist/businessHours.js +55 -0
  5. package/dist/connectBookingCharge.d.ts +49 -0
  6. package/dist/connectBookingCharge.js +68 -0
  7. package/dist/functions/admin-create-booking.d.ts +3 -0
  8. package/dist/functions/admin-create-booking.js +15 -2
  9. package/dist/functions/admin-mark-booking-paid.d.ts +6 -1
  10. package/dist/functions/admin-mark-booking-paid.js +27 -3
  11. package/dist/functions/booking-access-revoke-backstop.d.ts +11 -0
  12. package/dist/functions/booking-access-revoke-backstop.js +121 -0
  13. package/dist/functions/booking-access-revoke-door-state.d.ts +22 -0
  14. package/dist/functions/booking-access-revoke-door-state.js +61 -0
  15. package/dist/functions/booking-access-revoke.d.ts +35 -0
  16. package/dist/functions/booking-access-revoke.js +279 -0
  17. package/dist/functions/booking-availability.d.ts +2 -1
  18. package/dist/functions/booking-availability.js +14 -5
  19. package/dist/functions/create-booking.d.ts +5 -0
  20. package/dist/functions/create-booking.js +22 -4
  21. package/dist/functions/create-subscription-checkout.js +4 -1
  22. package/dist/functions/manage-booking.d.ts +6 -0
  23. package/dist/functions/manage-booking.js +36 -13
  24. package/dist/functions/reschedule-booking.d.ts +5 -0
  25. package/dist/functions/reschedule-booking.js +39 -2
  26. package/dist/functions/space-availability-range.d.ts +2 -1
  27. package/dist/functions/space-availability-range.js +8 -1
  28. package/dist/functions/stripe-webhook.d.ts +4 -0
  29. package/dist/functions/stripe-webhook.js +200 -16
  30. package/dist/functions/sync-gcal-blackouts.js +1 -1
  31. package/dist/gcalBookingEvents.d.ts +59 -0
  32. package/dist/gcalBookingEvents.js +182 -0
  33. package/dist/gcalSync.d.ts +1 -0
  34. package/dist/gcalSync.js +5 -0
  35. package/dist/pricing.d.ts +10 -2
  36. package/dist/pricing.js +14 -9
  37. package/dist/referralCodeLookup.d.ts +1 -0
  38. package/dist/referralCodeLookup.js +3 -0
  39. package/dist/referralCredits.d.ts +5 -0
  40. package/dist/referralCredits.js +5 -0
  41. package/dist/referralGrant.d.ts +4 -31
  42. package/dist/referralGrant.js +14 -234
  43. package/dist/stripeConnectEvents.d.ts +11 -0
  44. package/dist/stripeConnectEvents.js +37 -0
  45. package/dist/tenant-config.d.ts +8 -0
  46. package/dist/tenant-config.js +24 -0
  47. package/package.json +26 -2
@@ -0,0 +1,2 @@
1
+ export declare const MAX_BOOKING_SOURCE_LENGTH = 40;
2
+ export declare function sanitizeBookingSource(raw: unknown): string | null;
@@ -0,0 +1,11 @@
1
+ export const MAX_BOOKING_SOURCE_LENGTH = 40;
2
+ export function sanitizeBookingSource(raw) {
3
+ if (typeof raw !== 'string')
4
+ return null;
5
+ const v = raw.trim().toLowerCase();
6
+ if (v.length === 0 || v.length > MAX_BOOKING_SOURCE_LENGTH)
7
+ return null;
8
+ if (!/^[a-z0-9_-]+$/.test(v))
9
+ return null;
10
+ return v;
11
+ }
@@ -0,0 +1,11 @@
1
+ export declare const DEFAULT_MIN_NOTICE_MS: number;
2
+ export interface NoticeConfig {
3
+ minNoticeBusinessHours?: number | null;
4
+ holidays?: string[] | null;
5
+ }
6
+ export declare function addBusinessHours(fromUtc: Date, hours: number, holidays?: readonly string[]): Date;
7
+ export declare function hasBusinessHoursNotice(cfg?: NoticeConfig | null): cfg is NoticeConfig & {
8
+ minNoticeBusinessHours: number;
9
+ };
10
+ export declare function earliestBookingStartMs(nowMs: number, cfg?: NoticeConfig | null): number;
11
+ export declare function minNoticeErrorMessage(nowMs: number, cfg?: NoticeConfig | null): string;
@@ -0,0 +1,55 @@
1
+ import { laMidnightUtc } from './gcalSync.js';
2
+ import { addDaysStr, pacificDateStr } from './pacificDate.js';
3
+ export const DEFAULT_MIN_NOTICE_MS = 15 * 60 * 1000;
4
+ const HOUR_MS = 60 * 60 * 1000;
5
+ const MAX_DAYS_WALKED = 3700;
6
+ function isBusinessDay(dateStr, holidays) {
7
+ if (holidays.has(dateStr))
8
+ return false;
9
+ const [y, m, d] = dateStr.split('-').map(Number);
10
+ const wd = new Date(Date.UTC(y, m - 1, d, 12)).getUTCDay();
11
+ return wd >= 1 && wd <= 5;
12
+ }
13
+ export function addBusinessHours(fromUtc, hours, holidays = []) {
14
+ if (!Number.isFinite(hours) || hours <= 0)
15
+ return new Date(fromUtc.getTime());
16
+ const holidaySet = new Set(holidays);
17
+ let remaining = hours * HOUR_MS;
18
+ let cursor = fromUtc.getTime();
19
+ let day = pacificDateStr(new Date(cursor));
20
+ for (let i = 0; i < MAX_DAYS_WALKED; i++) {
21
+ const nextDay = addDaysStr(day, 1);
22
+ const nextMidnight = laMidnightUtc(nextDay).getTime();
23
+ if (isBusinessDay(day, holidaySet)) {
24
+ const available = nextMidnight - cursor;
25
+ if (remaining <= available)
26
+ return new Date(cursor + remaining);
27
+ remaining -= available;
28
+ }
29
+ cursor = nextMidnight;
30
+ day = nextDay;
31
+ }
32
+ return new Date(cursor + remaining);
33
+ }
34
+ export function hasBusinessHoursNotice(cfg) {
35
+ return typeof cfg?.minNoticeBusinessHours === 'number' &&
36
+ Number.isFinite(cfg.minNoticeBusinessHours) && cfg.minNoticeBusinessHours > 0;
37
+ }
38
+ export function earliestBookingStartMs(nowMs, cfg) {
39
+ const floor = nowMs + DEFAULT_MIN_NOTICE_MS;
40
+ if (!hasBusinessHoursNotice(cfg))
41
+ return floor;
42
+ const bh = addBusinessHours(new Date(nowMs), cfg.minNoticeBusinessHours, cfg.holidays ?? []).getTime();
43
+ return Math.max(floor, bh);
44
+ }
45
+ export function minNoticeErrorMessage(nowMs, cfg) {
46
+ if (!hasBusinessHoursNotice(cfg)) {
47
+ return 'Bookings need at least 15 minutes notice — please choose a later start time.';
48
+ }
49
+ const earliest = new Intl.DateTimeFormat('en-US', {
50
+ timeZone: 'America/Los_Angeles',
51
+ weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit',
52
+ }).format(new Date(earliestBookingStartMs(nowMs, cfg)));
53
+ return `Bookings need at least ${cfg.minNoticeBusinessHours} business hours notice ` +
54
+ `(Monday–Friday, excluding holidays). The earliest available start is ${earliest} Pacific time.`;
55
+ }
@@ -0,0 +1,49 @@
1
+ import type Stripe from 'stripe';
2
+ export interface ConnectBookingOperator {
3
+ stripeConnectedAccountId?: string | null;
4
+ stripeApplicationFeePercent?: number | null;
5
+ }
6
+ export declare const CONNECTED_ACCOUNT_ID_RE: RegExp;
7
+ export type ConnectConfigError = 'connect_account_invalid' | 'connect_fee_invalid' | 'connect_charge_invalid' | 'connect_fee_exceeds_charge';
8
+ export type ConnectedAccountResolution = {
9
+ ok: true;
10
+ accountId: string | null;
11
+ } | {
12
+ ok: false;
13
+ error: 'connect_account_invalid';
14
+ };
15
+ export type BookingChargePlan = {
16
+ ok: true;
17
+ connected: false;
18
+ } | {
19
+ ok: true;
20
+ connected: true;
21
+ accountId: string;
22
+ applicationFeeCents: number;
23
+ } | {
24
+ ok: false;
25
+ error: ConnectConfigError;
26
+ };
27
+ export declare function isValidConnectedAccountId(v: unknown): v is string;
28
+ export interface ConnectTenantEnv {
29
+ connectTenant: boolean;
30
+ }
31
+ export declare function defaultConnectTenantEnv(): ConnectTenantEnv;
32
+ export declare function resolveConnectedAccount(operator: ConnectBookingOperator | null | undefined, env?: ConnectTenantEnv): ConnectedAccountResolution;
33
+ export declare function planBookingCharge(operator: ConnectBookingOperator | null | undefined, chargeCents: number, env?: ConnectTenantEnv): BookingChargePlan;
34
+ export declare function applyConnectToSessionParams(params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Stripe.Checkout.SessionCreateParams;
35
+ export declare function stripeAccountRequestOptions(accountId: string | null | undefined): {
36
+ stripeAccount: string;
37
+ } | undefined;
38
+ type SessionCreator = {
39
+ checkout: {
40
+ sessions: {
41
+ create: (params: Stripe.Checkout.SessionCreateParams, options?: {
42
+ stripeAccount: string;
43
+ }) => Promise<Stripe.Checkout.Session>;
44
+ };
45
+ };
46
+ };
47
+ export declare function createBookingCheckoutSession(stripe: SessionCreator, params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Promise<Stripe.Checkout.Session>;
48
+ export declare const CONNECT_MISCONFIGURED_MESSAGE = "Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.";
49
+ export {};
@@ -0,0 +1,68 @@
1
+ // Stripe Connect DIRECT charges for room bookings. Opt-in per operator: with no
2
+ // `stripeConnectedAccountId` (undefined/null) every helper here is a no-op and
3
+ // the caller's Stripe request is byte-identical to the pre-Connect one.
4
+ import { computeApplicationFeeCents } from './checkoutSessionParams.js';
5
+ export const CONNECTED_ACCOUNT_ID_RE = /^acct_[A-Za-z0-9]+$/;
6
+ export function isValidConnectedAccountId(v) {
7
+ return typeof v === 'string' && CONNECTED_ACCOUNT_ID_RE.test(v);
8
+ }
9
+ // A project that has STRIPE_CONNECT_WEBHOOK_SECRET set is a Connect tenant:
10
+ // an omitted account id there is a wiring bug and must never fall back to the
11
+ // platform account. GC never sets that secret, so its behavior is unchanged.
12
+ export function defaultConnectTenantEnv() {
13
+ return { connectTenant: !!Deno.env.get('STRIPE_CONNECT_WEBHOOK_SECRET') };
14
+ }
15
+ export function resolveConnectedAccount(operator, env = defaultConnectTenantEnv()) {
16
+ const raw = operator?.stripeConnectedAccountId;
17
+ if (raw === undefined || raw === null) {
18
+ return env.connectTenant ? { ok: false, error: 'connect_account_invalid' } : { ok: true, accountId: null };
19
+ }
20
+ if (!isValidConnectedAccountId(raw))
21
+ return { ok: false, error: 'connect_account_invalid' };
22
+ return { ok: true, accountId: raw };
23
+ }
24
+ export function planBookingCharge(operator, chargeCents, env = defaultConnectTenantEnv()) {
25
+ const account = resolveConnectedAccount(operator, env);
26
+ if ('error' in account)
27
+ return { ok: false, error: account.error };
28
+ if (account.accountId === null)
29
+ return { ok: true, connected: false };
30
+ const pct = operator?.stripeApplicationFeePercent;
31
+ const hasFee = !(pct === undefined || pct === null || pct === 0);
32
+ // Exclusive upper bound: a 100% fee would leave the connected account paying
33
+ // Stripe's processing fee on every booking.
34
+ if (hasFee && (typeof pct !== 'number' || !Number.isFinite(pct) || pct <= 0 || pct >= 100)) {
35
+ return { ok: false, error: 'connect_fee_invalid' };
36
+ }
37
+ if (!Number.isSafeInteger(chargeCents) || chargeCents <= 0) {
38
+ return { ok: false, error: 'connect_charge_invalid' };
39
+ }
40
+ const fee = hasFee ? computeApplicationFeeCents(chargeCents, pct) : 0;
41
+ if (!Number.isSafeInteger(fee) || fee < 0 || fee > chargeCents) {
42
+ return { ok: false, error: 'connect_fee_exceeds_charge' };
43
+ }
44
+ return { ok: true, connected: true, accountId: account.accountId, applicationFeeCents: fee };
45
+ }
46
+ export function applyConnectToSessionParams(params, plan) {
47
+ if (!plan.ok || !plan.connected || plan.applicationFeeCents <= 0)
48
+ return params;
49
+ return {
50
+ ...params,
51
+ payment_intent_data: {
52
+ ...(params.payment_intent_data ?? {}),
53
+ application_fee_amount: plan.applicationFeeCents,
54
+ },
55
+ };
56
+ }
57
+ export function stripeAccountRequestOptions(accountId) {
58
+ return accountId ? { stripeAccount: accountId } : undefined;
59
+ }
60
+ export function createBookingCheckoutSession(stripe, params, plan) {
61
+ if ('error' in plan) {
62
+ return Promise.reject(new Error(`booking checkout refused: ${plan.error}`));
63
+ }
64
+ if (!plan.connected)
65
+ return stripe.checkout.sessions.create(params);
66
+ return stripe.checkout.sessions.create({ ...applyConnectToSessionParams(params, plan), payment_method_types: ['card'] }, { stripeAccount: plan.accountId });
67
+ }
68
+ export const CONNECT_MISCONFIGURED_MESSAGE = 'Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.';
@@ -41,5 +41,8 @@ export interface AdminCreateBookingDeps {
41
41
  }
42
42
  export declare function handle(req: Request, operator: {
43
43
  domain: string;
44
+ googleCalendarWriteback?: boolean | null;
45
+ stripeConnectedAccountId?: string | null;
46
+ stripeApplicationFeePercent?: number | null;
44
47
  }, deps: AdminCreateBookingDeps): Promise<Response>;
45
48
  export {};
@@ -19,7 +19,9 @@ import { logOps } from '../ops.js';
19
19
  import { reclaimStaleHoldsExceptCompletedTier3 } from '../bookingHoldReclaim.js';
20
20
  import { validateAndPriceForRoom, formatHumanTime, } from '../pricing.js';
21
21
  import { resolveIsMember, computeEntitlement } from '../membership.js';
22
+ import { writebackBookingCreated } from '../gcalBookingEvents.js';
22
23
  import { buildAdminCheckoutSessionParams, consumeMemberCredit, holdMemberCredit, loadMembershipById, releaseMemberCredit, resolveRoomContractTier, splitCharge, } from '../adminBookingCredit.js';
24
+ import { createBookingCheckoutSession, planBookingCharge } from '../connectBookingCharge.js';
23
25
  const corsHeaders = {
24
26
  'Access-Control-Allow-Origin': '*',
25
27
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -306,6 +308,7 @@ export async function handle(req, operator, deps) {
306
308
  catch (e) {
307
309
  console.warn('[admin-create-booking] gcal failed', e);
308
310
  }
311
+ await writebackBookingCreated(operator, eff);
309
312
  };
310
313
  // Finalizes a booking that needs no Stripe payment: consume the held credit,
311
314
  // flip the row to paid, then run the paid side effects.
@@ -399,11 +402,21 @@ export async function handle(req, operator, deps) {
399
402
  await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
400
403
  return json(500, { ok: false, error: 'stripe_not_configured' });
401
404
  }
405
+ const chargePlan = planBookingCharge(operator, charged);
406
+ if ('error' in chargePlan) {
407
+ await releaseHeldCredit('payments_misconfigured');
408
+ await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
409
+ try {
410
+ await logOps(admin, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'admin-create-booking', booking_id, actor: callerEmail }, { severity: 'error', bookingId: booking_id });
411
+ }
412
+ catch { /* ignore */ }
413
+ return json(500, { ok: false, error: 'payments_misconfigured' });
414
+ }
402
415
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
403
416
  const origin = req.headers.get('origin');
404
417
  const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
405
418
  try {
406
- const session = await stripe.checkout.sessions.create(buildAdminCheckoutSessionParams({
419
+ const session = await createBookingCheckoutSession(stripe, buildAdminCheckoutSessionParams({
407
420
  roomName: room.name,
408
421
  roomSlug: room.slug ?? null,
409
422
  human,
@@ -411,7 +424,7 @@ export async function handle(req, operator, deps) {
411
424
  bookingId: booking_id,
412
425
  amountCents: charged,
413
426
  base,
414
- }));
427
+ }), chargePlan);
415
428
  await admin.from('bookings').update({ stripe_session_id: session.id }).eq('id', booking_id);
416
429
  try {
417
430
  await logOps(admin, 'admin_payment_link_created', { booking_id, room: room.name, actor: callerEmail, amount_cents: net,
@@ -1 +1,6 @@
1
- export declare function handle(req: Request): Promise<Response>;
1
+ export declare function handle(req: Request, operator?: {
2
+ stripeConnectedAccountId?: string | null;
3
+ }): Promise<Response>;
4
+ export declare function createAdminMarkBookingPaidHandler(operator: {
5
+ stripeConnectedAccountId?: string | null;
6
+ }): (req: Request) => Promise<Response>;
@@ -12,6 +12,7 @@ import { jwtVerify, createRemoteJWKSet } from 'jose';
12
12
  import Stripe from 'stripe';
13
13
  import { clientIp, checkRateLimit } from '../rateLimit.js';
14
14
  import { logOps } from '../ops.js';
15
+ import { resolveConnectedAccount } from '../connectBookingCharge.js';
15
16
  const corsHeaders = {
16
17
  'Access-Control-Allow-Origin': '*',
17
18
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -56,7 +57,7 @@ const Body = z.object({
56
57
  // value added later (e.g. a dispute/chargeback state) should default to
57
58
  // NOT payable until someone explicitly decides otherwise.
58
59
  const PAYABLE_STATUSES = new Set(['pending', 'deposit_paid']);
59
- export async function handle(req) {
60
+ export async function handle(req, operator) {
60
61
  if (req.method === 'OPTIONS')
61
62
  return new Response('ok', { headers: corsHeaders });
62
63
  if (req.method !== 'POST')
@@ -141,11 +142,28 @@ export async function handle(req) {
141
142
  if (!stripeKey) {
142
143
  return fail(500, 'stripe_not_configured', 'STRIPE_SECRET_KEY is not set; cannot safely void the outstanding deposit link.');
143
144
  }
145
+ const connectAccount = resolveConnectedAccount(operator);
146
+ if ('error' in connectAccount) {
147
+ return fail(500, 'stripe_connect_misconfigured', 'The Stripe connected account for this location is misconfigured; cannot safely void the outstanding payment link.');
148
+ }
144
149
  try {
145
150
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
146
- const session = await stripe.checkout.sessions.retrieve(String(booking.stripe_session_id));
151
+ const connectedAccountId = connectAccount.accountId;
152
+ const session = connectedAccountId
153
+ ? await stripe.checkout.sessions.retrieve(String(booking.stripe_session_id), {}, { stripeAccount: connectedAccountId })
154
+ : await stripe.checkout.sessions.retrieve(String(booking.stripe_session_id));
155
+ if (session.status === 'complete') {
156
+ // The customer already paid online (the webhook may not have landed yet).
157
+ // Marking it paid offline too would double-charge them silently.
158
+ return fail(409, 'already_paid_online', 'The customer already completed payment online for this booking; do not mark it paid manually. Wait for the payment to be recorded, or check the Stripe dashboard.');
159
+ }
147
160
  if (session.status === 'open') {
148
- await stripe.checkout.sessions.expire(String(booking.stripe_session_id));
161
+ if (connectedAccountId) {
162
+ await stripe.checkout.sessions.expire(String(booking.stripe_session_id), {}, { stripeAccount: connectedAccountId });
163
+ }
164
+ else {
165
+ await stripe.checkout.sessions.expire(String(booking.stripe_session_id));
166
+ }
149
167
  }
150
168
  }
151
169
  catch (e) {
@@ -200,3 +218,9 @@ export async function handle(req) {
200
218
  }, { severity: 'warning', bookingId: booking_id }).catch(() => { });
201
219
  return json(200, { ok: true, booking_id, status: 'paid', charged_amount_cents: netCents });
202
220
  }
221
+ // Binds the operator so a Connect tenant never relies on a positional second
222
+ // argument (Deno.serve passes its ServeHandlerInfo there). Extra args from the
223
+ // runtime are ignored.
224
+ export function createAdminMarkBookingPaidHandler(operator) {
225
+ return (req) => handle(req, operator);
226
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Bookings whose organizer grants the backstop may revoke via terminal booking.status.
3
+ * Refund/dispute paths keep status `paid`; those bookings are selected via access_revoke_required_at.
4
+ */
5
+ export declare const BACKSTOP_BOOKING_STATUSES: readonly ["cancelled_credited", "cancelled_forfeited", "cancelled_refunded"];
6
+ export declare function bookingStatusRequiresBackstopRevoke(status: string): boolean;
7
+ export declare function bookingRowRequiresBackstopRevoke(booking: {
8
+ status?: string;
9
+ access_revoke_required_at?: string | null;
10
+ }): boolean;
11
+ export declare function handle(req: Request): Promise<Response>;
@@ -0,0 +1,121 @@
1
+ // SCHEDULED backstop (C6 code-side): pg_cron → HTTP POST when wired. Not scheduled in-repo.
2
+ //
3
+ // gc-connect wiring (out of this repo):
4
+ // - Set verify_jwt=false on this function ONLY together with the constant-time secret
5
+ // check below (never an open POST).
6
+ // - Store BOOKING_GRANT_REVOKE_BACKSTOP_SECRET in Vault; inject into the edge runtime.
7
+ // Do not embed the secret in cron SQL text — reference the Vault secret from the job config.
8
+ //
9
+ // pg_cron jobs typically POST with an empty body (no next_cursor). Selection orders by
10
+ // revoke_backstop_last_attempt_at (never-attempted first) so stuck grants do not starve the queue.
11
+ import { createClient } from '@supabase/supabase-js';
12
+ import { logOps } from '../ops.js';
13
+ import { isBookingGrantRevokeEnabled, revokeBookingOrganizerAccessGrants } from './booking-access-revoke.js';
14
+ const REVOCABLE_STATUSES = ['active', 'pending', 'reconciling', 'revoke_failed'];
15
+ const MAX_GRANTS_PER_TICK = 5;
16
+ /**
17
+ * Bookings whose organizer grants the backstop may revoke via terminal booking.status.
18
+ * Refund/dispute paths keep status `paid`; those bookings are selected via access_revoke_required_at.
19
+ */
20
+ export const BACKSTOP_BOOKING_STATUSES = [
21
+ 'cancelled_credited',
22
+ 'cancelled_forfeited',
23
+ 'cancelled_refunded',
24
+ ];
25
+ export function bookingStatusRequiresBackstopRevoke(status) {
26
+ return BACKSTOP_BOOKING_STATUSES.includes(status);
27
+ }
28
+ export function bookingRowRequiresBackstopRevoke(booking) {
29
+ if (booking.access_revoke_required_at)
30
+ return true;
31
+ return bookingStatusRequiresBackstopRevoke(String(booking.status ?? ''));
32
+ }
33
+ function safeEqual(a, b) {
34
+ const enc = new TextEncoder();
35
+ const ab = enc.encode(a), bb = enc.encode(b);
36
+ if (ab.length !== bb.length)
37
+ return false;
38
+ let diff = 0;
39
+ for (let i = 0; i < ab.length; i++)
40
+ diff |= ab[i] ^ bb[i];
41
+ return diff === 0;
42
+ }
43
+ function envSecret(name) {
44
+ const v = Deno.env.get(name);
45
+ return v && v.length > 0 ? v : null;
46
+ }
47
+ function bookingFromJoin(row) {
48
+ const b = row.bookings;
49
+ if (Array.isArray(b))
50
+ return b[0] ?? { status: '' };
51
+ return b ?? { status: '' };
52
+ }
53
+ export async function handle(req) {
54
+ if (req.method !== 'POST')
55
+ return new Response('Method not allowed', { status: 405 });
56
+ const provided = req.headers.get('x-booking-access-revoke-backstop-secret');
57
+ const expected = envSecret('BOOKING_GRANT_REVOKE_BACKSTOP_SECRET');
58
+ if (!provided || !expected || !safeEqual(provided, expected)) {
59
+ return new Response('Unauthorized', { status: 401 });
60
+ }
61
+ if (!isBookingGrantRevokeEnabled()) {
62
+ return new Response(JSON.stringify({ ok: true, skipped: 'revoke_disabled' }), {
63
+ status: 200,
64
+ headers: { 'Content-Type': 'application/json' },
65
+ });
66
+ }
67
+ const supabase = createClient(Deno.env.get('SUPABASE_URL'), Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'), { auth: { persistSession: false, autoRefreshToken: false } });
68
+ const terminalStatuses = BACKSTOP_BOOKING_STATUSES.join(',');
69
+ const { data: grantRows, error: grantErr } = await supabase
70
+ .from('booking_access_grants')
71
+ .select('id, booking_id, revoke_backstop_last_attempt_at, bookings!inner(status, access_revoke_required_at)')
72
+ .in('status', [...REVOCABLE_STATUSES])
73
+ .or(`status.in.(${terminalStatuses}),access_revoke_required_at.not.is.null`, { foreignTable: 'bookings' })
74
+ .order('revoke_backstop_last_attempt_at', { ascending: true, nullsFirst: true })
75
+ .order('id', { ascending: true })
76
+ .limit(MAX_GRANTS_PER_TICK);
77
+ if (grantErr) {
78
+ await logOps(supabase, 'booking_access_revoke_backstop_list_failed', {
79
+ error_code: grantErr.code ?? 'unknown',
80
+ }, { severity: 'error' });
81
+ return new Response(JSON.stringify({ ok: false }), { status: 500 });
82
+ }
83
+ const candidates = (grantRows ?? []);
84
+ let processed = 0;
85
+ for (const row of candidates) {
86
+ if (!row.booking_id || !row.id)
87
+ continue;
88
+ const booking = bookingFromJoin(row);
89
+ if (!bookingRowRequiresBackstopRevoke(booking))
90
+ continue;
91
+ const attemptAt = new Date().toISOString();
92
+ const { error: attemptErr } = await supabase
93
+ .from('booking_access_grants')
94
+ .update({ revoke_backstop_last_attempt_at: attemptAt })
95
+ .eq('id', row.id);
96
+ if (attemptErr) {
97
+ await logOps(supabase, 'booking_access_revoke_backstop_attempt_stamp_failed', {
98
+ grant_id: row.id,
99
+ error_code: attemptErr.code ?? 'unknown',
100
+ }, { severity: 'error', bookingId: row.booking_id });
101
+ }
102
+ processed += 1;
103
+ try {
104
+ await revokeBookingOrganizerAccessGrants(supabase, {
105
+ bookingId: row.booking_id,
106
+ actingUserId: 'system:booking-access-revoke-backstop',
107
+ reason: 'scheduled_backstop',
108
+ });
109
+ }
110
+ catch (e) {
111
+ await logOps(supabase, 'booking_access_revoke_backstop_revoke_failed', {
112
+ grant_id: row.id,
113
+ error_name: e instanceof Error ? e.name : 'Error',
114
+ }, { severity: 'error', bookingId: row.booking_id });
115
+ }
116
+ }
117
+ return new Response(JSON.stringify({ ok: true, processed }), {
118
+ status: 200,
119
+ headers: { 'Content-Type': 'application/json' },
120
+ });
121
+ }
@@ -0,0 +1,22 @@
1
+ export type MiddlewareRevokeBody = {
2
+ error?: unknown;
3
+ door_read?: unknown;
4
+ lock_rule?: unknown;
5
+ staff_lockdown?: unknown;
6
+ custom_unlock_ends_at?: unknown;
7
+ /** Required when lock_rule is `custom` (organizer-marked timed unlock). */
8
+ organizer_marked_custom?: unknown;
9
+ };
10
+ /** R3: only these door_read values may be copied into ops_events detail. */
11
+ export declare const OPS_LOGGABLE_DOOR_READS: Set<string>;
12
+ export declare function doorReadForOpsLog(read: unknown): string | undefined;
13
+ /**
14
+ * C6 ruling (10/8 3:25 PM): grant_not_revocable or already-revoked counts as complete
15
+ * only if a read shows the door is not left unlocked by this grant — lock_rule is idle
16
+ * (including UniFi's present empty string `""`), intentional staff lockdown applies, or an organizer-marked
17
+ * timed custom has already expired. keep_unlock, or custom with time remaining, is incomplete.
18
+ *
19
+ * Fail-closed (F1): missing, null, or non-string lock_rule is incomplete unless door_read is
20
+ * relocked/staff_lockdown or staff_lockdown is true. A present `lock_rule: ""` is UniFi idle (complete).
21
+ */
22
+ export declare function isDoorStateCompleteForGrantRevoke(body: MiddlewareRevokeBody | null, nowMs?: number): boolean;
@@ -0,0 +1,61 @@
1
+ // C6 ruling (10/8 3:25 PM): middleware revoke responses must be interpreted before
2
+ // treating grant_not_revocable / already-revoked as complete.
3
+ /** R3: only these door_read values may be copied into ops_events detail. */
4
+ export const OPS_LOGGABLE_DOOR_READS = new Set([
5
+ 'relocked',
6
+ 'staff_lockdown',
7
+ 'keep_unlock',
8
+ 'unlocked',
9
+ 'idle',
10
+ 'custom',
11
+ ]);
12
+ export function doorReadForOpsLog(read) {
13
+ if (typeof read !== 'string')
14
+ return undefined;
15
+ return OPS_LOGGABLE_DOOR_READS.has(read) ? read : undefined;
16
+ }
17
+ /**
18
+ * C6 ruling (10/8 3:25 PM): grant_not_revocable or already-revoked counts as complete
19
+ * only if a read shows the door is not left unlocked by this grant — lock_rule is idle
20
+ * (including UniFi's present empty string `""`), intentional staff lockdown applies, or an organizer-marked
21
+ * timed custom has already expired. keep_unlock, or custom with time remaining, is incomplete.
22
+ *
23
+ * Fail-closed (F1): missing, null, or non-string lock_rule is incomplete unless door_read is
24
+ * relocked/staff_lockdown or staff_lockdown is true. A present `lock_rule: ""` is UniFi idle (complete).
25
+ */
26
+ export function isDoorStateCompleteForGrantRevoke(body, nowMs = Date.now()) {
27
+ if (!body)
28
+ return false;
29
+ if (body.staff_lockdown === true)
30
+ return true;
31
+ const doorRead = typeof body.door_read === 'string' ? body.door_read : '';
32
+ if (doorRead === 'relocked' || doorRead === 'staff_lockdown')
33
+ return true;
34
+ if (doorRead === 'keep_unlock' || doorRead === 'unlocked')
35
+ return false;
36
+ if (!('lock_rule' in body) || typeof body.lock_rule !== 'string') {
37
+ return false;
38
+ }
39
+ if (body.lock_rule === '')
40
+ return true;
41
+ const lockRule = body.lock_rule.trim();
42
+ if (lockRule === '')
43
+ return false;
44
+ if (lockRule === 'keep_unlock')
45
+ return false;
46
+ if (lockRule === 'idle')
47
+ return true;
48
+ if (lockRule === 'custom') {
49
+ if (body.organizer_marked_custom !== true)
50
+ return false;
51
+ const endRaw = body.custom_unlock_ends_at;
52
+ if (typeof endRaw === 'string' && Number.isFinite(Date.parse(endRaw))) {
53
+ return Date.parse(endRaw) <= nowMs;
54
+ }
55
+ return false;
56
+ }
57
+ if (doorRead === 'custom') {
58
+ return false;
59
+ }
60
+ return false;
61
+ }
@@ -0,0 +1,35 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ export type SupabaseLike = SupabaseClient<any, any, any>;
3
+ /** @deprecated Granite City's literal default, kept for import compatibility.
4
+ * The actual default is resolved at call time from tenant-config.ts's
5
+ * getEventAccessBusBase(), which reads the EVENT_ACCESS_BUS_BASE env var. */
6
+ export declare const DEFAULT_EVENT_ACCESS_BUS_BASE = "https://ftw.granitecity.io";
7
+ /** C6 code-side: revoke calls must stay at or below 8s. */
8
+ export declare const REVOKE_TIMEOUT_MS = 8000;
9
+ /** Hardening: cap in-process sweep batches (20 × 5 grants max per edge invocation). */
10
+ export declare const MAX_REVOKE_SWEEP_BATCHES = 20;
11
+ export declare const BOOKING_GRANT_REVOKE_ENABLED_ENV = "BOOKING_GRANT_REVOKE_ENABLED";
12
+ export declare function setForceRevokeThrowForTest(enabled: boolean): void;
13
+ /** Fail-closed: only the exact string 'true' arms revoke work. */
14
+ export declare function isBookingGrantRevokeEnabled(): boolean;
15
+ export declare function errorNameFromUnknown(e: unknown): string;
16
+ /**
17
+ * CS-GM product decision (O3b / PR #21): partial refunds must NOT revoke organizer door access.
18
+ * The guest keeps a valid paid booking; grants remain until the booking window ends.
19
+ *
20
+ * Stripe emits `charge.refunded` on every refund leg, but `charge.refunded` is only `true` once
21
+ * the charge is fully refunded — that is the sole gate for organizer grant revoke on refund.
22
+ */
23
+ export declare function shouldRevokeOrganizerGrantsOnStripeChargeRefunded(charge: {
24
+ refunded: boolean;
25
+ }): boolean;
26
+ /**
27
+ * Revoke every active or upcoming organizer access grant for `bookingId`.
28
+ * Safe to call multiple times (cancel replay, Stripe redelivery after revoke).
29
+ */
30
+ export declare function revokeBookingOrganizerAccessGrants(admin: SupabaseLike, opts: {
31
+ bookingId: string;
32
+ actingUserId: string;
33
+ reason: string;
34
+ busBase?: string;
35
+ }): Promise<void>;