@simplelayer/graniteer-core 0.4.2 → 0.5.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/LICENSE +4 -0
  2. package/dist/bookingAgreementEmail.d.ts +34 -3
  3. package/dist/bookingAgreementEmail.js +100 -1
  4. package/dist/bookingEffects.d.ts +3 -1
  5. package/dist/bookingEffects.js +4 -3
  6. package/dist/bookingSource.d.ts +2 -0
  7. package/dist/bookingSource.js +11 -0
  8. package/dist/businessHours.d.ts +11 -0
  9. package/dist/businessHours.js +55 -0
  10. package/dist/checkoutSessionParams.d.ts +33 -0
  11. package/dist/checkoutSessionParams.js +71 -0
  12. package/dist/commonsSignedUnpaidCancellation.d.ts +154 -0
  13. package/dist/commonsSignedUnpaidCancellation.js +650 -0
  14. package/dist/connectBookingCharge.d.ts +49 -0
  15. package/dist/connectBookingCharge.js +72 -0
  16. package/dist/entitlements.d.ts +1 -1
  17. package/dist/entitlements.js +6 -1
  18. package/dist/functions/admin-acknowledge-contract-violation.d.ts +1 -0
  19. package/dist/functions/admin-acknowledge-contract-violation.js +120 -0
  20. package/dist/functions/admin-cancel-membership.js +109 -13
  21. package/dist/functions/admin-change-membership-plan.js +74 -18
  22. package/dist/functions/admin-charge-guest-print.d.ts +3 -1
  23. package/dist/functions/admin-charge-guest-print.js +8 -1
  24. package/dist/functions/admin-create-booking.d.ts +8 -3
  25. package/dist/functions/admin-create-booking.js +15 -2
  26. package/dist/functions/admin-create-commons-event.d.ts +3 -1
  27. package/dist/functions/admin-create-commons-event.js +8 -1
  28. package/dist/functions/admin-door-write.d.ts +3 -1
  29. package/dist/functions/admin-door-write.js +8 -1
  30. package/dist/functions/admin-issue-day-pass.d.ts +1 -0
  31. package/dist/functions/admin-issue-day-pass.js +8 -1
  32. package/dist/functions/admin-mark-booking-paid.d.ts +6 -1
  33. package/dist/functions/admin-mark-booking-paid.js +27 -3
  34. package/dist/functions/admin-request-trial.js +22 -1
  35. package/dist/functions/auth-email-hook.js +42 -2
  36. package/dist/functions/booking-access-revoke-backstop.d.ts +11 -0
  37. package/dist/functions/booking-access-revoke-backstop.js +121 -0
  38. package/dist/functions/booking-access-revoke-door-state.d.ts +22 -0
  39. package/dist/functions/booking-access-revoke-door-state.js +61 -0
  40. package/dist/functions/booking-access-revoke.d.ts +35 -0
  41. package/dist/functions/booking-access-revoke.js +279 -0
  42. package/dist/functions/booking-availability.d.ts +2 -1
  43. package/dist/functions/booking-availability.js +14 -5
  44. package/dist/functions/conductor.js +39 -16
  45. package/dist/functions/create-booking.d.ts +10 -3
  46. package/dist/functions/create-booking.js +22 -4
  47. package/dist/functions/create-day-pass-checkout.d.ts +1 -0
  48. package/dist/functions/create-day-pass-checkout.js +6 -0
  49. package/dist/functions/create-subscription-checkout.js +7 -2
  50. package/dist/functions/event-access-admin.d.ts +1 -0
  51. package/dist/functions/event-access-admin.js +23 -1
  52. package/dist/functions/event-access-store.js +18 -0
  53. package/dist/functions/guest-print-setup-confirm.d.ts +3 -1
  54. package/dist/functions/guest-print-setup-confirm.js +8 -1
  55. package/dist/functions/guest-print-submit.d.ts +3 -1
  56. package/dist/functions/guest-print-submit.js +8 -1
  57. package/dist/functions/manage-booking.d.ts +9 -1
  58. package/dist/functions/manage-booking.js +140 -6
  59. package/dist/functions/mcp.d.ts +2 -2
  60. package/dist/functions/mcp.js +2 -2
  61. package/dist/functions/member-door-action.d.ts +3 -1
  62. package/dist/functions/member-door-action.js +9 -2
  63. package/dist/functions/membership-door-sync.d.ts +18 -0
  64. package/dist/functions/membership-door-sync.js +76 -6
  65. package/dist/functions/office-assignment-end.d.ts +3 -1
  66. package/dist/functions/office-assignment-end.js +8 -1
  67. package/dist/functions/portal-submit-event.d.ts +1 -0
  68. package/dist/functions/portal-submit-event.js +4 -0
  69. package/dist/functions/reschedule-booking.d.ts +11 -4
  70. package/dist/functions/reschedule-booking.js +39 -2
  71. package/dist/functions/review-ratings.js +1 -1
  72. package/dist/functions/space-availability-range.d.ts +2 -1
  73. package/dist/functions/space-availability-range.js +8 -1
  74. package/dist/functions/stripe-db-reconcile.js +8 -1
  75. package/dist/functions/stripe-webhook.d.ts +4 -0
  76. package/dist/functions/stripe-webhook.js +328 -17
  77. package/dist/functions/sync-gcal-blackouts.js +1 -1
  78. package/dist/functions/timetable-event-register.d.ts +3 -1
  79. package/dist/functions/timetable-event-register.js +8 -1
  80. package/dist/functions/touch-pass-signup.d.ts +3 -1
  81. package/dist/functions/touch-pass-signup.js +9 -2
  82. package/dist/functions/voice-booking.d.ts +1 -1
  83. package/dist/functions/voice-day-pass.d.ts +2 -1
  84. package/dist/functions/voice-day-pass.js +4 -0
  85. package/dist/functions/voice-inquiry.d.ts +3 -1
  86. package/dist/functions/voice-inquiry.js +9 -2
  87. package/dist/functions/voice-membership-signup.d.ts +2 -2
  88. package/dist/functions/voice-tour-booking.d.ts +1 -1
  89. package/dist/gcalBookingEvents.d.ts +59 -0
  90. package/dist/gcalBookingEvents.js +182 -0
  91. package/dist/gcalSync.d.ts +1 -0
  92. package/dist/gcalSync.js +5 -0
  93. package/dist/membershipSubscriptionItems.d.ts +87 -0
  94. package/dist/membershipSubscriptionItems.js +71 -0
  95. package/dist/membershipWelcome.d.ts +1 -1
  96. package/dist/outbox.d.ts +64 -0
  97. package/dist/outbox.js +70 -0
  98. package/dist/pricing.d.ts +10 -2
  99. package/dist/pricing.js +14 -9
  100. package/dist/printBilling.js +47 -47
  101. package/dist/referralCodeLookup.d.ts +13 -0
  102. package/dist/referralCodeLookup.js +17 -0
  103. package/dist/referralCredits.d.ts +5 -0
  104. package/dist/referralCredits.js +5 -0
  105. package/dist/referralGrant.d.ts +4 -31
  106. package/dist/referralGrant.js +14 -234
  107. package/dist/runtime/env.d.ts +7 -0
  108. package/dist/runtime/env.js +32 -0
  109. package/dist/runtime/fs.d.ts +5 -0
  110. package/dist/runtime/fs.js +16 -0
  111. package/dist/runtime/serve.d.ts +8 -0
  112. package/dist/runtime/serve.js +12 -0
  113. package/dist/stripeConnectEvents.d.ts +11 -0
  114. package/dist/stripeConnectEvents.js +37 -0
  115. package/dist/supabaseTestFakes.js +7 -1
  116. package/dist/tenant-config.d.ts +8 -0
  117. package/dist/tenant-config.js +25 -0
  118. package/dist/tenantManifest.d.ts +85 -0
  119. package/dist/tenantManifest.js +43 -0
  120. package/package.json +59 -3
@@ -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,3 @@
1
- export declare function handle(req: Request): Promise<Response>;
1
+ export declare function handle(req: Request, operator?: {
2
+ planId?: string | null;
3
+ }): Promise<Response>;
@@ -17,6 +17,7 @@ import { z } from 'zod';
17
17
  import { jwtVerify, createRemoteJWKSet } from 'jose';
18
18
  import { clientIp, checkRateLimit } from '../rateLimit.js';
19
19
  import { logOps } from '../ops.js';
20
+ import { hasEntitlement } from '../entitlements.js';
20
21
  const corsHeaders = {
21
22
  'Access-Control-Allow-Origin': '*',
22
23
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -76,7 +77,10 @@ const MAX_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
76
77
  // credit_consume) only ever applies to hourly/day-rate room bookings in
77
78
  // create-booking. Never wire this up without a deliberate product call.
78
79
  const EVENT_PACKAGE_CREDIT_APPLIED_CENTS = 0;
79
- export async function handle(req) {
80
+ export async function handle(req,
81
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
82
+ // full-featured legacy plan, so every existing caller is unaffected.
83
+ operator = {}) {
80
84
  if (req.method === 'OPTIONS')
81
85
  return new Response('ok', { headers: corsHeaders });
82
86
  if (req.method !== 'POST')
@@ -108,6 +112,9 @@ export async function handle(req) {
108
112
  return fail(500, 'allowlist_lookup_failed', allowErr.message);
109
113
  if (!allow)
110
114
  return fail(403, 'not_authorized', 'Not authorized.');
115
+ if (!hasEntitlement(operator, 'events')) {
116
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'events' });
117
+ }
111
118
  // === Body ===
112
119
  let raw;
113
120
  try {
@@ -1 +1,3 @@
1
- export declare function handle(req: Request): Promise<Response>;
1
+ export declare function handle(req: Request, operator?: {
2
+ planId?: string | null;
3
+ }): Promise<Response>;
@@ -9,6 +9,7 @@ import { createClient } from '@supabase/supabase-js';
9
9
  import { jwtVerify, createRemoteJWKSet } from 'jose';
10
10
  import { clientIp, checkRateLimit } from '../rateLimit.js';
11
11
  import { logOps } from '../ops.js';
12
+ import { hasEntitlement } from '../entitlements.js';
12
13
  const corsHeaders = {
13
14
  'Access-Control-Allow-Origin': '*',
14
15
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -68,7 +69,10 @@ function diff(before, after) {
68
69
  }
69
70
  return out;
70
71
  }
71
- export async function handle(req) {
72
+ export async function handle(req,
73
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
74
+ // full-featured legacy plan, so every existing caller is unaffected.
75
+ operator = {}) {
72
76
  if (req.method === 'OPTIONS')
73
77
  return new Response('ok', { headers: corsHeaders });
74
78
  if (req.method !== 'POST')
@@ -98,6 +102,9 @@ export async function handle(req) {
98
102
  return json(500, { ok: false, error: 'allowlist_lookup_failed' });
99
103
  if (!allow)
100
104
  return json(403, { ok: false, error: 'not_authorized' });
105
+ if (!hasEntitlement(operator, 'access_control')) {
106
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'access_control' });
107
+ }
101
108
  let body;
102
109
  try {
103
110
  body = await req.json();
@@ -11,4 +11,5 @@ export interface AdminIssueDayPassDeps {
11
11
  }
12
12
  export declare function handle(req: Request, operator: {
13
13
  domain: string;
14
+ planId?: string | null;
14
15
  }, deps: AdminIssueDayPassDeps): Promise<Response>;
@@ -5,6 +5,7 @@ import { z } from 'zod';
5
5
  import { jwtVerify, createRemoteJWKSet } from 'jose';
6
6
  import { clientIp, checkRateLimit } from '../rateLimit.js';
7
7
  import { logOps } from '../ops.js';
8
+ import { hasEntitlement } from '../entitlements.js';
8
9
  const corsHeaders = {
9
10
  'Access-Control-Allow-Origin': '*',
10
11
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -50,7 +51,10 @@ const Body = z.object({
50
51
  visit_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
51
52
  issue_mode: z.enum(['payment_link', 'paid_offline', 'comp']),
52
53
  });
53
- export async function handle(req, operator, deps) {
54
+ export async function handle(req,
55
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
56
+ // full-featured legacy plan, so every existing caller is unaffected.
57
+ operator, deps) {
54
58
  if (req.method === 'OPTIONS')
55
59
  return new Response('ok', { headers: corsHeaders });
56
60
  if (req.method !== 'POST')
@@ -81,6 +85,9 @@ export async function handle(req, operator, deps) {
81
85
  return json(500, { ok: false, error: 'allowlist_lookup_failed' });
82
86
  if (!allow)
83
87
  return json(403, { ok: false, error: 'not_authorized' });
88
+ if (!hasEntitlement(operator, 'day_pass')) {
89
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'day_pass' });
90
+ }
84
91
  let raw;
85
92
  try {
86
93
  raw = await req.json();
@@ -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
+ }
@@ -10,7 +10,7 @@ const corsHeaders = {
10
10
  };
11
11
  const LA_TZ = 'America/Los_Angeles';
12
12
  const TRIAL_DAYS = 7;
13
- const TIMEOUT_MS = 20_000;
13
+ const TIMEOUT_MS = 45_000;
14
14
  const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
15
15
  let jwksCache = null;
16
16
  function getJwks(supabaseUrl) {
@@ -207,6 +207,10 @@ export async function handle(req, config) {
207
207
  let provisionOk = false;
208
208
  let provisionUnifiUserId;
209
209
  let provisionPin;
210
+ // WiFi voucher minted by ftw-middleware (best-effort; absent when guest WiFi
211
+ // is disabled or the mint failed). Before 0.3.14 this was dropped here, so
212
+ // the voucher existed in UniFi but was never recorded or surfaced.
213
+ let wifiVoucher;
210
214
  let provisionErrorCode;
211
215
  const trialHmacSecret = Deno.env.get('TRIAL_HMAC_SECRET');
212
216
  if (!trialHmacSecret) {
@@ -270,6 +274,14 @@ export async function handle(req, config) {
270
274
  ? provisionParsed.unifi_user_id : undefined;
271
275
  const cred = provisionParsed?.credential;
272
276
  provisionPin = cred && typeof cred.pin === 'string' ? cred.pin : undefined;
277
+ const wv = provisionParsed?.wifi_voucher;
278
+ if (wv && typeof wv.code_display === 'string' && wv.code_display) {
279
+ wifiVoucher = {
280
+ id: typeof wv.id === 'string' ? wv.id : '',
281
+ code_display: wv.code_display,
282
+ expires_minutes: typeof wv.expires_minutes === 'number' ? wv.expires_minutes : 0,
283
+ };
284
+ }
273
285
  }
274
286
  }
275
287
  }
@@ -286,6 +298,12 @@ export async function handle(req, config) {
286
298
  else {
287
299
  updatePayload.notes = 'Provisioned without a PIN — mint/set failed on ftw-middleware.';
288
300
  }
301
+ if (wifiVoucher) {
302
+ if (wifiVoucher.id)
303
+ updatePayload.wifi_voucher_id = wifiVoucher.id;
304
+ // The voucher is scoped to the trial window; record the window end.
305
+ updatePayload.wifi_expires_at = grant.trial_end_at;
306
+ }
289
307
  const { error: statusUpdateErr } = await admin.from('trial_grants').update(updatePayload).eq('id', grant.id);
290
308
  if (statusUpdateErr) {
291
309
  await logOps(admin, 'admin_request_trial_status_update_failed', { grant_id: grant.id, message: statusUpdateErr.message }, { severity: 'error' });
@@ -335,6 +353,9 @@ export async function handle(req, config) {
335
353
  trial_end_at: grant.trial_end_at,
336
354
  status: finalStatus,
337
355
  ...(credential ? { credential } : {}),
356
+ ...(wifiVoucher && provisionOk
357
+ ? { wifi_voucher: { code_display: wifiVoucher.code_display, expires_minutes: wifiVoucher.expires_minutes } }
358
+ : {}),
338
359
  ...(provisioningErrorForResponse ? { provisioning_error: provisioningErrorForResponse } : {}),
339
360
  });
340
361
  }
@@ -6,7 +6,7 @@
6
6
  // DELIVERABILITY-CRITICAL. `senderDomain` and `fromDomain` are the values the
7
7
  // sending backend signs and stamps on real password-reset / magic-link mail.
8
8
  // They are supplied per tenant by the caller and are NOT interchangeable:
9
- // today Granite City's sender/from domain (mail.notify.*) differs from its
9
+ // today the current production tenant's sender/from domain (mail.notify.*) differs from its
10
10
  // rootDomain (notify.*). Never collapse them into one field, and never
11
11
  // default them.
12
12
  import * as React from 'react';
@@ -22,6 +22,43 @@ const corsHeaders = {
22
22
  'Access-Control-Allow-Origin': '*',
23
23
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, x-lovable-signature, x-lovable-timestamp, x-supabase-client-platform, x-supabase-client-platform-version, x-supabase-client-runtime, x-supabase-client-runtime-version',
24
24
  };
25
+ // `data.url` for magiclink (and recovery) arrives as Supabase's own
26
+ // `{SUPABASE_URL}/auth/v1/verify?token=<hash>&type=<type>&redirect_to=<dest>`
27
+ // action link. That link performs the OTP verification on a plain GET, so an
28
+ // email-scanner prefetch (M365 Safe Links, etc.) silently burns the token
29
+ // before the real recipient ever clicks -- confirmed live 2026-09-23 against
30
+ // kyle+qatest@simplelayer.io (M365-hosted inbox): the link arrived, was
31
+ // pre-fetched, and the user's own click then hit an already-consumed token
32
+ // (otp_expired).
33
+ //
34
+ // Fix (magiclink only, for now): rewrite the emailed link to point at our own
35
+ // /portal/confirm page instead, carrying the same token/type/redirect_to as
36
+ // query params. That page does nothing on load -- it renders a "Continue to
37
+ // sign in" button and only calls supabase.auth.verifyOtp({token_hash, type})
38
+ // on an actual click, so a scanner's GET can no longer consume the token.
39
+ //
40
+ // Fails open: if the URL doesn't parse or is missing an expected param
41
+ // (Supabase changes the link shape, a non-magiclink call site reuses this),
42
+ // return the original link unchanged rather than break the login/reset flow.
43
+ function toClickToContinueUrl(rawUrl) {
44
+ try {
45
+ const u = new URL(rawUrl);
46
+ const token = u.searchParams.get('token');
47
+ const type = u.searchParams.get('type');
48
+ const redirectTo = u.searchParams.get('redirect_to');
49
+ if (!token || !type || !redirectTo)
50
+ return rawUrl;
51
+ const dest = new URL(redirectTo);
52
+ const confirm = new URL('/portal/confirm', dest.origin);
53
+ confirm.searchParams.set('token_hash', token);
54
+ confirm.searchParams.set('type', type);
55
+ confirm.searchParams.set('redirect_to', redirectTo);
56
+ return confirm.toString();
57
+ }
58
+ catch {
59
+ return rawUrl;
60
+ }
61
+ }
25
62
  // Template mapping for preview mode
26
63
  const EMAIL_TEMPLATES = {
27
64
  signup: SignupEmail,
@@ -164,7 +201,10 @@ export function createAuthEmailHook(config) {
164
201
  subject: 'Your login link',
165
202
  render: (data) => React.createElement(MagicLinkEmail, {
166
203
  siteName: SITE_NAME,
167
- confirmationUrl: data.url,
204
+ // Click-to-continue (2026-09-23): route through our own confirm
205
+ // page instead of Supabase's direct, scanner-vulnerable /verify
206
+ // GET link. See toClickToContinueUrl() above.
207
+ confirmationUrl: toClickToContinueUrl(data.url),
168
208
  colors: BRAND_COLORS,
169
209
  footerLine: FOOTER_LINE,
170
210
  }),
@@ -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>;