@simplelayer/graniteer-core 0.4.3 → 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 (119) 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/referralCodeLookup.d.ts +13 -0
  101. package/dist/referralCodeLookup.js +17 -0
  102. package/dist/referralCredits.d.ts +5 -0
  103. package/dist/referralCredits.js +5 -0
  104. package/dist/referralGrant.d.ts +4 -31
  105. package/dist/referralGrant.js +14 -234
  106. package/dist/runtime/env.d.ts +7 -0
  107. package/dist/runtime/env.js +32 -0
  108. package/dist/runtime/fs.d.ts +5 -0
  109. package/dist/runtime/fs.js +16 -0
  110. package/dist/runtime/serve.d.ts +8 -0
  111. package/dist/runtime/serve.js +12 -0
  112. package/dist/stripeConnectEvents.d.ts +11 -0
  113. package/dist/stripeConnectEvents.js +37 -0
  114. package/dist/supabaseTestFakes.js +7 -1
  115. package/dist/tenant-config.d.ts +8 -0
  116. package/dist/tenant-config.js +25 -0
  117. package/dist/tenantManifest.d.ts +85 -0
  118. package/dist/tenantManifest.js +43 -0
  119. package/package.json +59 -3
@@ -11,12 +11,31 @@ import { jwtVerify, createRemoteJWKSet } from 'jose';
11
11
  import { clientIp, checkRateLimit } from '../rateLimit.js';
12
12
  import { logOps } from '../ops.js';
13
13
  import { sha256Hex, signBusMessage } from '../busSignature.js';
14
+ import { hasEntitlement } from '../entitlements.js';
14
15
  const corsHeaders = {
15
16
  'Access-Control-Allow-Origin': '*',
16
17
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
17
18
  'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
18
19
  };
19
20
  const TIMEOUT_MS = 20_000;
21
+ // D32 item #3 (2026-09-23): a two-pin grant's UniFi collision-retry logic
22
+ // can, in the corrected worst case, take up to ~65-70s inside ftw-middleware
23
+ // alone (one wall-clock-budget-gated retry attempt can itself make up to 3
24
+ // UniFi calls before the budget check ever gets a chance to abort it -- see
25
+ // event_access.py's _TWO_PIN_PROVISION_BUDGET_SEC comment for the full
26
+ // derivation). The original 20s TIMEOUT_MS fired long before the middleware
27
+ // could ever return a real (success or definitive-failure) response for a
28
+ // grant, forcing staff to see a spurious 502 middleware_unreachable while
29
+ // the middleware kept working in the background -- wasting a minted PIN and
30
+ // requiring a manual Revoke+Grant. GRANT_TIMEOUT_MS gives grant-only
31
+ // headroom (95s) that sits comfortably above ftw-middleware's own
32
+ // _GRANT_HANDLER_TIMEOUT_SEC (85s, itself raised in the same pass to clear
33
+ // the corrected worst case) while staying under the Cloudflare Tunnel
34
+ // edge's own ~100s proxied-HTTP limit for the FTW middleware's origin -- past that,
35
+ // Cloudflare cuts the connection with a 524 regardless of what this signal
36
+ // says, so there is no point setting this any higher. door/revoke keep the
37
+ // original 20s: neither has a retry loop and both should fail fast.
38
+ const GRANT_TIMEOUT_MS = 95_000;
20
39
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
21
40
  const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
22
41
  let jwksCache = null;
@@ -101,6 +120,9 @@ export function createEventAccessAdminHandler(config) {
101
120
  return json(500, { ok: false, error: 'authz_lookup_failed' });
102
121
  if (!allowRes.data && !doorOpsRes.data)
103
122
  return json(403, { ok: false, error: 'not_authorized' });
123
+ if (!hasEntitlement(config, 'access_control')) {
124
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'access_control' });
125
+ }
104
126
  let body;
105
127
  try {
106
128
  body = await req.json();
@@ -226,7 +248,7 @@ export function createEventAccessAdminHandler(config) {
226
248
  'X-Event-Access-Timestamp': ts,
227
249
  },
228
250
  body: rawBody,
229
- signal: AbortSignal.timeout(TIMEOUT_MS),
251
+ signal: AbortSignal.timeout(action === 'grant' ? GRANT_TIMEOUT_MS : TIMEOUT_MS),
230
252
  });
231
253
  }
232
254
  catch (e) {
@@ -174,6 +174,16 @@ export async function handle(req) {
174
174
  extra.unlock_visitor_id = unlockVisitorId;
175
175
  if (relockVisitorId)
176
176
  extra.relock_visitor_id = relockVisitorId;
177
+ // D35 follow-up (PIN storage): unlock_pin/relock_pin are the plaintext
178
+ // PINs UniFi mints at visitor-creation time and never returns again --
179
+ // captured here, once, so a later read-back has somewhere to find them.
180
+ // Same optional/omitted-stays-untouched treatment as the visitor ids.
181
+ const unlockPin = str(args.unlock_pin);
182
+ const relockPin = str(args.relock_pin);
183
+ if (unlockPin)
184
+ extra.unlock_pin = unlockPin;
185
+ if (relockPin)
186
+ extra.relock_pin = relockPin;
177
187
  const r = await cas(grantId, 'pending', 'active', extra);
178
188
  if ('err' in r)
179
189
  return await fail('db_error', { message: r.err });
@@ -226,6 +236,14 @@ export async function handle(req) {
226
236
  patch.unlock_visitor_id = unlockVisitorId;
227
237
  if (relockVisitorId)
228
238
  patch.relock_visitor_id = relockVisitorId;
239
+ // PIN-storage follow-up: same COALESCE-on-presence semantics -- a
240
+ // revoke-failed row must not silently blank out a PIN already stored.
241
+ const unlockPin = str(args.unlock_pin);
242
+ const relockPin = str(args.relock_pin);
243
+ if (unlockPin)
244
+ patch.unlock_pin = unlockPin;
245
+ if (relockPin)
246
+ patch.relock_pin = relockPin;
229
247
  const { data, error } = await supabase
230
248
  .from('booking_access_grants').update(patch).eq('id', grantId).select('*').maybeSingle();
231
249
  if (error)
@@ -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>;
@@ -8,6 +8,7 @@ import Stripe from 'stripe';
8
8
  import { z } from 'zod';
9
9
  import { clientIp, checkRateLimit } from '../rateLimit.js';
10
10
  import { logOps } from '../ops.js';
11
+ import { hasEntitlement } from '../entitlements.js';
11
12
  import { confirmGuestPrintSetup, } from '../guestPrintCapture.js';
12
13
  const Body = z.object({
13
14
  submission_id: z.string().uuid(),
@@ -18,7 +19,10 @@ function json(status, body) {
18
19
  status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
19
20
  });
20
21
  }
21
- export async function handle(req) {
22
+ export async function handle(req,
23
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
24
+ // full-featured legacy plan, so every existing caller is unaffected.
25
+ operator = {}) {
22
26
  if (req.method === 'OPTIONS')
23
27
  return new Response('ok', { headers: corsHeaders });
24
28
  if (req.method !== 'POST')
@@ -43,6 +47,9 @@ export async function handle(req) {
43
47
  const ipOk = await checkRateLimit(supabase, 'guest-print-setup-confirm-ip', ip, 30, 600);
44
48
  if (!ipOk)
45
49
  return json(429, { ok: false, error: 'rate_limited' });
50
+ if (!hasEntitlement(operator, 'guest_print')) {
51
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'guest_print' });
52
+ }
46
53
  // Ownership check BEFORE touching Stripe: the submission_id + setup_intent_id
47
54
  // pair must belong to the same row, or a guessed submission_id + an
48
55
  // attacker's own real setup_intent_id could mark someone else's row
@@ -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>;
@@ -12,6 +12,7 @@ import Stripe from 'stripe';
12
12
  import { z } from 'zod';
13
13
  import { clientIp, checkRateLimit } from '../rateLimit.js';
14
14
  import { logOps } from '../ops.js';
15
+ import { hasEntitlement } from '../entitlements.js';
15
16
  import { generateGuestBillingCode, submitGuestPrintJob, } from '../guestPrintCapture.js';
16
17
  const Body = z.object({
17
18
  email: z.string().trim().email().max(255),
@@ -22,7 +23,10 @@ function json(status, body) {
22
23
  status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
23
24
  });
24
25
  }
25
- export async function handle(req) {
26
+ export async function handle(req,
27
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
28
+ // full-featured legacy plan, so every existing caller is unaffected.
29
+ operator = {}) {
26
30
  if (req.method === 'OPTIONS')
27
31
  return new Response('ok', { headers: corsHeaders });
28
32
  if (req.method !== 'POST')
@@ -51,6 +55,9 @@ export async function handle(req) {
51
55
  ]);
52
56
  if (!ipOk || !emailOk)
53
57
  return json(429, { ok: false, error: 'rate_limited' });
58
+ if (!hasEntitlement(operator, 'guest_print')) {
59
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'guest_print' });
60
+ }
54
61
  const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
55
62
  if (!stripeKey)
56
63
  return json(500, { ok: false, error: 'stripe_not_configured' });
@@ -1,3 +1,5 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ type SupabaseLike = SupabaseClient<any, any, any>;
1
3
  interface BookingRow {
2
4
  id: string;
3
5
  status: string;
@@ -30,9 +32,14 @@ export interface ManageBookingDeps {
30
32
  roomKey: string;
31
33
  startUtc: string;
32
34
  endUtc: string;
33
- }, admin: unknown) => Promise<unknown>;
35
+ }, admin: SupabaseLike) => Promise<unknown>;
34
36
  signBus: (verb: string, bookingId: string, roomKey: string, startUtc: string, endUtc: string, secret: string, ts: number) => Promise<string>;
35
37
  toBusUtc: (iso: string) => string;
38
+ /** Override for this tenant's event-access middleware origin. Defaults to
39
+ * tenant-config.ts's getEventAccessBusBase() (EVENT_ACCESS_BUS_BASE env
40
+ * var) when omitted -- same opts-override pattern as
41
+ * booking-access-revoke.ts's revokeBookingOrganizerAccessGrants. */
42
+ busBase?: string;
36
43
  }
37
44
  declare function parseTstzRange(range: string): {
38
45
  startISO: string;
@@ -66,6 +73,7 @@ declare function bookingViewForCustomer(b: BookingRow, operator: {
66
73
  }>;
67
74
  export declare function handle(req: Request, operator: {
68
75
  operatorName: string;
76
+ googleCalendarWriteback?: boolean | null;
69
77
  }, deps: ManageBookingDeps): Promise<Response>;
70
78
  export declare const _test: {
71
79
  bookingViewForCustomer: typeof bookingViewForCustomer;
@@ -1,11 +1,15 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import { JWT } from 'google-auth-library';
3
+ import { writebackBookingCancelled } from '../gcalBookingEvents.js';
3
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
4
5
  import { verifyManageToken } from '../manageToken.js';
5
6
  import { resolvePortalSessionEmail } from '../portalSession.js';
6
7
  import { logOps } from '../ops.js';
7
8
  import { deriveReservationWifiCode, isReservationWifiRoom } from '../reservationWifiCode.js';
8
9
  import { buildCancellationCreditGrants } from '../rescheduleCredit.js';
10
+ import { sha256Hex, signBusMessage } from '../busSignature.js';
11
+ import { getEventAccessBusBase } from '../tenant-config.js';
12
+ import { revokeBookingOrganizerAccessGrants } from './booking-access-revoke.js';
9
13
  const corsHeaders = {
10
14
  'Access-Control-Allow-Origin': '*',
11
15
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -19,6 +23,74 @@ function json(status, body) {
19
23
  headers: { ...corsHeaders, 'Content-Type': 'application/json' },
20
24
  });
21
25
  }
26
+ // Same "e1" HMAC scheme as event-access-admin.ts's signE1 (identical secret,
27
+ // signing helper, and msg shape) — see that file's own PINNED CROSS-REPO
28
+ // CONTRACT note. Duplicated rather than imported: event-access-admin.ts's
29
+ // version is a module-private function, not exported.
30
+ async function signOrganizerLinkE1(secret, verb, ts, bodyHashHex) {
31
+ const msg = ['e1', verb, ts, bodyHashHex].join('\n');
32
+ return signBusMessage(msg, secret);
33
+ }
34
+ async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId, busBase) {
35
+ // Every failure path logs a breadcrumb (severity 'warning', same as the
36
+ // sibling credential branch's manage_credential_unauthorized) so a broken
37
+ // contract is visible in ops_events/Slack, even though the customer-facing
38
+ // response never surfaces it -- it just gets a null url.
39
+ const fail = async (reason, detail = {}) => {
40
+ await logOps(admin, 'manage_organizer_link_mint_failed', { reason, grant_id: grantId, ...detail }, { severity: 'warning', bookingId });
41
+ return null;
42
+ };
43
+ try {
44
+ const { data: secretRaw, error: secretErr } = await admin.rpc('get_event_access_hmac_secret');
45
+ const secret = typeof secretRaw === 'string' ? secretRaw : null;
46
+ if (secretErr || !secret)
47
+ return await fail('missing_secret');
48
+ const outbound = { acting_user_id: actingUserId, grant_id: grantId };
49
+ const rawBody = JSON.stringify(outbound);
50
+ const bodyHash = await sha256Hex(rawBody);
51
+ const ts = String(Math.floor(Date.now() / 1000));
52
+ const signature = await signOrganizerLinkE1(secret, 'organizer_link', ts, bodyHash);
53
+ const res = await fetch(`${busBase}/admin/event-access/organizer-link`, {
54
+ method: 'POST',
55
+ headers: {
56
+ 'Content-Type': 'application/json',
57
+ 'X-Event-Access-Signature': signature,
58
+ 'X-Event-Access-Timestamp': ts,
59
+ },
60
+ body: rawBody,
61
+ signal: AbortSignal.timeout(10000),
62
+ });
63
+ if (!res.ok)
64
+ return await fail('http_error', { status: res.status });
65
+ const j = await res.json().catch(() => null);
66
+ if (!j?.ok || typeof j.url !== 'string' || j.url.length === 0)
67
+ return await fail('invalid_response');
68
+ // The response isn't otherwise authenticated (no signature on the reply),
69
+ // so a compromised/misconfigured middleware could hand back an
70
+ // attacker-controlled URL. Reject anything not on the expected (this
71
+ // tenant's own busBase) origin rather than trusting it blindly.
72
+ let origin;
73
+ let expectedOrigin;
74
+ try {
75
+ origin = new URL(j.url).origin;
76
+ }
77
+ catch {
78
+ origin = null;
79
+ }
80
+ try {
81
+ expectedOrigin = new URL(busBase).origin;
82
+ }
83
+ catch {
84
+ expectedOrigin = null;
85
+ }
86
+ if (!expectedOrigin || origin !== expectedOrigin)
87
+ return await fail('origin_mismatch', { origin });
88
+ return j.url;
89
+ }
90
+ catch (e) {
91
+ return await fail('exception', { message: String(e) });
92
+ }
93
+ }
22
94
  function parseTstzRange(range) {
23
95
  const m = range.match(/[[(]"?([^",)]+)"?,"?([^",)]+)"?[\])]/);
24
96
  if (!m)
@@ -140,6 +212,7 @@ export async function handle(req, operator, deps) {
140
212
  const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
141
213
  auth: { persistSession: false, autoRefreshToken: false },
142
214
  });
215
+ const busBase = deps.busBase ?? getEventAccessBusBase();
143
216
  // Rate-limit BEFORE any DB work.
144
217
  const ip = clientIp(req);
145
218
  const [ipOk] = await Promise.all([
@@ -228,11 +301,7 @@ export async function handle(req, operator, deps) {
228
301
  const ts = Math.floor(Date.now() / 1000);
229
302
  const sig = await deps.signBus('credential', b.id, slug, startUtc, endUtc, busSecret, ts);
230
303
  const qs = new URLSearchParams({ source: 'gc-connect', booking_id: b.id });
231
- // FTW membership-bus base URL: same GC-hardcoded infra as
232
- // _shared/busClient.ts's own BUS_BASE, tracked for the later "make the
233
- // bus pluggable" phase of this project, not this identity-parameterization
234
- // phase.
235
- const res = await fetch(`https://ftw.granitecity.io/bookings/credential?${qs.toString()}`, {
304
+ const res = await fetch(`${busBase}/bookings/credential?${qs.toString()}`, {
236
305
  method: 'GET',
237
306
  headers: { 'X-GC-Signature': sig, 'X-GC-Timestamp': String(ts) },
238
307
  signal: AbortSignal.timeout(10000),
@@ -261,6 +330,52 @@ export async function handle(req, operator, deps) {
261
330
  return json(404, { error: 'no_credential' });
262
331
  }
263
332
  }
333
+ // Two-pin organizer credential (D35 follow-up): unlike 'credential' above,
334
+ // this table lives in this SAME Supabase project, so it's read directly
335
+ // via `admin` -- no HTTP call out to the ftw-middleware droplet at all. A
336
+ // booking may have EITHER a legacy single-pin credential (above) OR a
337
+ // two-pin grant (below), never assumed to be exclusive. Returns
338
+ // 404 { error: 'no_credential' } until the (separate, later) PIN-capture
339
+ // provisioning code actually writes unlock_pin/relock_pin.
340
+ if (action === 'two_pin_credential') {
341
+ const parsedRange = parseTstzRange(b.during);
342
+ const endMs = parsedRange ? new Date(parsedRange.endISO).getTime() : 0;
343
+ if (b.status !== 'paid' || endMs <= Date.now()) {
344
+ return json(404, { error: 'no_credential' });
345
+ }
346
+ try {
347
+ const { data, error } = await admin
348
+ .from('booking_access_grants')
349
+ .select('id,unlock_pin,relock_pin,access_start,access_end,status')
350
+ .eq('booking_id', b.id).eq('status', 'active')
351
+ .order('created_at', { ascending: false }).limit(1).maybeSingle();
352
+ if (error || !data)
353
+ return json(404, { error: 'no_credential' });
354
+ const grant = data;
355
+ if (!grant.unlock_pin && !grant.relock_pin)
356
+ return json(404, { error: 'no_credential' });
357
+ // Organizer early-manual-lock/unlock link (D35 follow-up): only attempt
358
+ // the mint while the grant itself is still within its active window —
359
+ // no point minting a link for a grant that's already over. Never blocks
360
+ // or alters the PIN response: a failed/skipped mint is just a null url.
361
+ let organizerLinkUrl = null;
362
+ const grantEndMs = grant.access_end ? new Date(grant.access_end).getTime() : NaN;
363
+ const grantWithinWindow = !Number.isFinite(grantEndMs) || grantEndMs > Date.now();
364
+ if (grant.id && grantWithinWindow) {
365
+ organizerLinkUrl = await mintOrganizerLinkUrl(admin, `customer:${authedEmail}`, grant.id, b.id, busBase);
366
+ }
367
+ return json(200, {
368
+ unlock_pin: grant.unlock_pin ?? null,
369
+ relock_pin: grant.relock_pin ?? null,
370
+ valid_from_utc: grant.access_start ?? null,
371
+ valid_to_utc: grant.access_end ?? null,
372
+ organizer_link_url: organizerLinkUrl,
373
+ });
374
+ }
375
+ catch {
376
+ return json(404, { error: 'no_credential' });
377
+ }
378
+ }
264
379
  if (action !== 'cancel')
265
380
  return json(400, { error: 'invalid_action' });
266
381
  // Idempotent: if already cancelled, just return the current view.
@@ -286,6 +401,7 @@ export async function handle(req, operator, deps) {
286
401
  .update({ status: newStatus })
287
402
  .eq('id', b.id)
288
403
  .eq('status', 'paid')
404
+ .is('access_revoke_required_at', null)
289
405
  .select('id');
290
406
  if (updErr)
291
407
  return json(500, { error: 'update_failed' });
@@ -293,9 +409,14 @@ export async function handle(req, operator, deps) {
293
409
  // Someone else flipped it in-between — return current view.
294
410
  const { data: fresh } = await admin
295
411
  .from('bookings')
296
- .select('id,status,contact_email,contact_name,contact_phone,ghl_contact_id,during,charged_amount_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents,google_event_id,rooms(id,name,address,google_calendar_id,slug,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes)')
412
+ .select('access_revoke_required_at,id,status,contact_email,contact_name,contact_phone,ghl_contact_id,during,charged_amount_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents,google_event_id,rooms(id,name,address,google_calendar_id,slug,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes)')
297
413
  .eq('id', b.id)
298
414
  .maybeSingle();
415
+ if (fresh && fresh.status === 'paid' && fresh.access_revoke_required_at) {
416
+ // Webhook flagged this booking (Connect full refund / dispute): no
417
+ // self-service cancel, hence no credit.
418
+ return json(409, { error: 'booking_flagged_contact_support' });
419
+ }
299
420
  if (fresh) {
300
421
  return json(200, {
301
422
  ...await bookingViewForCustomer(fresh, operator),
@@ -303,6 +424,8 @@ export async function handle(req, operator, deps) {
303
424
  outcome: fresh.status,
304
425
  });
305
426
  }
427
+ // Re-read failed: fail closed, never fall through to the credit grant.
428
+ return json(409, { error: 'already_changed' });
306
429
  }
307
430
  // Credit ledger row(s): split cash-funded (1yr) vs credit-funded (capped at
308
431
  // the ORIGINAL credit's own expiry) so a cancellation can never launder a
@@ -354,6 +477,8 @@ export async function handle(req, operator, deps) {
354
477
  catch (e) {
355
478
  await logOps(admin, 'coupon_reverse_on_cancel_failed', { message: String(e) }, { severity: 'error', bookingId: b.id });
356
479
  }
480
+ // Opt-in, fail-soft: remove the write-back event (deterministic id; no stored id needed).
481
+ await writebackBookingCancelled(operator, b.rooms?.google_calendar_id, b.id);
357
482
  // Best-effort: delete Google Calendar event.
358
483
  try {
359
484
  const cal = await deleteCalendarEvent(b);
@@ -389,6 +514,15 @@ export async function handle(req, operator, deps) {
389
514
  }
390
515
  }
391
516
  catch { /* never break the response */ }
517
+ // Best-effort: revoke organizer door grants (O3b). Must not block cancel.
518
+ try {
519
+ await revokeBookingOrganizerAccessGrants(admin, {
520
+ bookingId: b.id,
521
+ actingUserId: `customer:booking:${b.id}`,
522
+ reason: 'booking_cancelled',
523
+ });
524
+ }
525
+ catch { /* revokeBookingOrganizerAccessGrants never throws; belt-and-suspenders */ }
392
526
  const { data: fresh } = await admin
393
527
  .from('bookings')
394
528
  .select('id,status,contact_email,contact_name,contact_phone,ghl_contact_id,during,charged_amount_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents,google_event_id,rooms(id,name,address,google_calendar_id,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes)')
@@ -1,7 +1,7 @@
1
1
  export interface McpBrandConfig {
2
- /** Public-facing operator name, e.g. "Granite City Workspaces". */
2
+ /** Public-facing operator name, e.g. "Acme Coworking". */
3
3
  brandName: string;
4
- /** Site origin, no trailing slash, e.g. "https://granitecity.io". */
4
+ /** Site origin, no trailing slash, e.g. "https://acme-coworking.example". */
5
5
  siteBase: string;
6
6
  }
7
7
  export declare function meetingRoomUrl(config: McpBrandConfig, slug: string): string;
@@ -4,8 +4,8 @@
4
4
  // stay in the tenant repo -- this module only supplies the generic
5
5
  // text-construction logic behind the brand name / site URL literals that
6
6
  // appear in tool descriptions and generated links, so those strings are
7
- // parameterized instead of hardcoding "Granite City Workspaces" /
8
- // "granitecity.io" in nine separate places.
7
+ // parameterized instead of hardcoding a single tenant's brand name / site
8
+ // domain in nine separate places.
9
9
  function bareDomain(siteBase) {
10
10
  return siteBase.replace(/^https?:\/\//, '');
11
11
  }
@@ -57,4 +57,6 @@ export declare function parseEnabled(raw: string | undefined): {
57
57
  * An EMPTY allowlist denies everyone — not "no filter applied".
58
58
  */
59
59
  export declare function parseAllowlist(raw: string | undefined): Set<string>;
60
- export declare function handleMemberDoorAction(req: Request): Promise<Response>;
60
+ export declare function handleMemberDoorAction(req: Request, operator?: {
61
+ planId?: string | null;
62
+ }): Promise<Response>;
@@ -82,6 +82,7 @@ import { clientIp, checkRateLimit } from '../rateLimit.js';
82
82
  import { resolvePortalSession } from '../portalSession.js';
83
83
  import { computeEntitlement } from '../membership.js';
84
84
  import { logOps } from '../ops.js';
85
+ import { hasEntitlement } from '../entitlements.js';
85
86
  const corsHeaders = {
86
87
  'Access-Control-Allow-Origin': '*',
87
88
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -107,7 +108,7 @@ const corsHeaders = {
107
108
  // keyIsolationViolations() enforces it)
108
109
  //
109
110
  // No hardcoded live host. Every other tenant-app -> middleware caller in this repo
110
- // hardcodes `https://ftw.granitecity.io`; this one does not, so the function is
111
+ // hardcodes the FTW middleware's live origin; this one does not, so the function is
111
112
  // inert (503 not_configured) until an operator sets the base URL as a secret.
112
113
  // That also keeps a mis-deployed member-facing door route from ever reaching the
113
114
  // real middleware by default.
@@ -379,7 +380,10 @@ function doorGateOk(notBefore, now) {
379
380
  return false;
380
381
  return t <= now;
381
382
  }
382
- export async function handleMemberDoorAction(req) {
383
+ export async function handleMemberDoorAction(req,
384
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
385
+ // full-featured legacy plan, so every existing caller is unaffected.
386
+ operator = {}) {
383
387
  if (req.method === 'OPTIONS')
384
388
  return new Response('ok', { headers: corsHeaders });
385
389
  if (req.method !== 'POST')
@@ -446,6 +450,9 @@ export async function handleMemberDoorAction(req) {
446
450
  }, { severity: 'warning' });
447
451
  return denied();
448
452
  }
453
+ if (!hasEntitlement(operator, 'access_control')) {
454
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'access_control' });
455
+ }
449
456
  // ---- Step 5: the tenant app's half of the dual authorization check ---------------
450
457
  // Requires a real auth_user_id linkage. Deliberately NO email fallback for
451
458
  // still-unlinked rows (portal-resend-invite has one): an email-matched,
@@ -10,5 +10,23 @@ export interface MembershipDoorSyncConfig {
10
10
  membershipBusEnforce: (members: MembershipSnapshotMember[], supabase: SupabaseLike) => Promise<Record<string, unknown> | null>;
11
11
  membershipBusRevoke: (members: MembershipSnapshotMember[], generatedAt: string, supabase: SupabaseLike) => Promise<Record<string, unknown> | null>;
12
12
  }
13
+ /**
14
+ * Loads membership_id -> add-on UniFi group ids for LIVE subscriptions to
15
+ * grants_access add-ons. Throws on any read error so the tick aborts before
16
+ * any Phase 2/3/4 call: falling back to "no add-on groups" could make the
17
+ * revoke phase strip real access.
18
+ */
19
+ export declare function loadAddonGroupIds(supabase: SupabaseClient): Promise<Map<string, string[]>>;
20
+ /**
21
+ * Desired UniFi group ids = union of entitled rows' plan groups and those
22
+ * same rows' live add-on groups. Not entitled (no entitled rows) => [].
23
+ * Sorted + de-duplicated; empty/null ids ignored.
24
+ */
25
+ export declare function computeDesiredGroupIds(entitledRows: Array<{
26
+ id: string;
27
+ membership_plans: {
28
+ unifi_group_ids: string[] | null;
29
+ } | null;
30
+ }>, addonGroupsByMembership: Map<string, string[]>): string[];
13
31
  export declare function createMembershipDoorSyncHandler(config: MembershipDoorSyncConfig): (req: Request) => Promise<Response>;
14
32
  export {};
@@ -83,6 +83,80 @@ function stateEquals(a, b) {
83
83
  }
84
84
  return true;
85
85
  }
86
+ const LIVE_ADDON_STATUSES = ['active', 'past_due', 'pending_removal'];
87
+ function assertNotTruncated(table, res) {
88
+ const data = res.data ?? [];
89
+ const count = res.count;
90
+ if (typeof count !== 'number' || count !== data.length) {
91
+ throw new Error(`${table} read truncated: got ${data.length} of ${count} -- aborting tick before any Phase 2/3/4 call`);
92
+ }
93
+ }
94
+ /**
95
+ * Loads membership_id -> add-on UniFi group ids for LIVE subscriptions to
96
+ * grants_access add-ons. Throws on any read error so the tick aborts before
97
+ * any Phase 2/3/4 call: falling back to "no add-on groups" could make the
98
+ * revoke phase strip real access.
99
+ */
100
+ export async function loadAddonGroupIds(supabase) {
101
+ const result = new Map();
102
+ const subsRes = (await supabase
103
+ .from('member_addon_subscriptions')
104
+ .select('membership_id,addon_id,status', { count: 'exact' })
105
+ .in('status', LIVE_ADDON_STATUSES)
106
+ .order('id'));
107
+ if (subsRes.error)
108
+ throw new Error('member_addon_subscriptions read failed: ' + subsRes.error.message);
109
+ assertNotTruncated('member_addon_subscriptions', subsRes);
110
+ // Re-check status locally so correctness never depends solely on the filter.
111
+ const subs = (subsRes.data ?? [])
112
+ .filter((s) => s.membership_id && s.addon_id && LIVE_ADDON_STATUSES.includes(s.status));
113
+ if (subs.length === 0)
114
+ return result;
115
+ const addonIds = Array.from(new Set(subs.map((s) => s.addon_id)));
116
+ const addonsRes = (await supabase
117
+ .from('member_addons')
118
+ .select('id,unifi_group_ids,grants_access', { count: 'exact' })
119
+ .in('id', addonIds)
120
+ .eq('grants_access', true)
121
+ .order('id'));
122
+ if (addonsRes.error)
123
+ throw new Error('member_addons read failed: ' + addonsRes.error.message);
124
+ assertNotTruncated('member_addons', addonsRes);
125
+ const groupsByAddon = new Map();
126
+ for (const a of (addonsRes.data ?? [])) {
127
+ if (a.grants_access !== true)
128
+ continue;
129
+ groupsByAddon.set(a.id, a.unifi_group_ids ?? []);
130
+ }
131
+ for (const s of subs) {
132
+ const gids = groupsByAddon.get(s.addon_id);
133
+ if (!gids)
134
+ continue;
135
+ const list = result.get(s.membership_id) ?? [];
136
+ for (const g of gids)
137
+ if (g)
138
+ list.push(g);
139
+ result.set(s.membership_id, list);
140
+ }
141
+ return result;
142
+ }
143
+ /**
144
+ * Desired UniFi group ids = union of entitled rows' plan groups and those
145
+ * same rows' live add-on groups. Not entitled (no entitled rows) => [].
146
+ * Sorted + de-duplicated; empty/null ids ignored.
147
+ */
148
+ export function computeDesiredGroupIds(entitledRows, addonGroupsByMembership) {
149
+ const set = new Set();
150
+ for (const r of entitledRows) {
151
+ for (const g of r.membership_plans?.unifi_group_ids ?? [])
152
+ if (g)
153
+ set.add(g);
154
+ for (const g of addonGroupsByMembership.get(r.id) ?? [])
155
+ if (g)
156
+ set.add(g);
157
+ }
158
+ return Array.from(set).sort();
159
+ }
86
160
  /**
87
161
  * Door-access start-date gate, separate from (and layered AFTER) pricing
88
162
  * entitlement. An UNGATED row (door_access_not_before === null) is never
@@ -134,6 +208,7 @@ export function createMembershipDoorSyncHandler(config) {
134
208
  if (rows.length > 0 && !('door_access_not_before' in rows[0])) {
135
209
  throw new Error('shape_guard_failed: door_access_not_before missing from memberships select result -- aborting tick before any Phase 2/3/4 call');
136
210
  }
211
+ const addonGroupsByMembership = await loadAddonGroupIds(supabase);
137
212
  // Group by lowercased email. Rows with no email are ignored (nothing to
138
213
  // key door/WiFi state to). resolveIsMember() likewise treats "" as "not
139
214
  // a member" — keep that behavior aligned.
@@ -184,16 +259,11 @@ export function createMembershipDoorSyncHandler(config) {
184
259
  let groupIds = [];
185
260
  let wifiEnabled = false;
186
261
  if (entitled) {
187
- const set = new Set();
188
262
  for (const r of entitledRows) {
189
- const gids = r.membership_plans?.unifi_group_ids ?? [];
190
- for (const g of gids)
191
- if (g)
192
- set.add(g);
193
263
  if (r.membership_plans?.wifi_enabled === true)
194
264
  wifiEnabled = true;
195
265
  }
196
- groupIds = Array.from(set).sort();
266
+ groupIds = computeDesiredGroupIds(entitledRows, addonGroupsByMembership);
197
267
  }
198
268
  const desired = { entitled, group_ids: groupIds, wifi_enabled: wifiEnabled };
199
269
  // Every managed, non-protected email goes into the snapshot -- entitled or not.
@@ -9,4 +9,6 @@
9
9
  * Auth scaffold mirrors create-agreement: JWKS verify -> aal2 -> rate limit ->
10
10
  * admin_users allowlist.
11
11
  */
12
- export declare function handle(req: Request): Promise<Response>;
12
+ export declare function handle(req: Request, operator?: {
13
+ planId?: string | null;
14
+ }): Promise<Response>;
@@ -2,6 +2,7 @@ import { createClient } from '@supabase/supabase-js';
2
2
  import { jwtVerify, createRemoteJWKSet } from 'jose';
3
3
  import { clientIp, checkRateLimit } from '../rateLimit.js';
4
4
  import { logOps } from '../ops.js';
5
+ import { hasEntitlement } from '../entitlements.js';
5
6
  const corsHeaders = {
6
7
  'Access-Control-Allow-Origin': '*',
7
8
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -46,7 +47,10 @@ function json(status, body) {
46
47
  * Auth scaffold mirrors create-agreement: JWKS verify -> aal2 -> rate limit ->
47
48
  * admin_users allowlist.
48
49
  */
49
- export async function handle(req) {
50
+ export async function handle(req,
51
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
52
+ // full-featured legacy plan, so every existing caller is unaffected.
53
+ operator = {}) {
50
54
  if (req.method === 'OPTIONS')
51
55
  return new Response('ok', { headers: corsHeaders });
52
56
  if (req.method !== 'POST')
@@ -77,6 +81,9 @@ export async function handle(req) {
77
81
  return json(500, { ok: false, error: 'allowlist_lookup_failed' });
78
82
  if (!allow)
79
83
  return json(403, { ok: false, error: 'not_authorized' });
84
+ if (!hasEntitlement(operator, 'office_assignment')) {
85
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'office_assignment' });
86
+ }
80
87
  let body;
81
88
  try {
82
89
  body = await req.json();
@@ -1,4 +1,5 @@
1
1
  export interface PortalSubmitEventConfig {
2
2
  eventsHubBase: string;
3
+ planId?: string | null;
3
4
  }
4
5
  export declare function handle(req: Request, config: PortalSubmitEventConfig): Promise<Response>;