@simplelayer/graniteer-core 0.4.3 → 0.5.0-rc.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 (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 +280 -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 +24 -1
  58. package/dist/functions/manage-booking.js +151 -16
  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 +183 -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/ops.js +4 -3
  97. package/dist/outbox.d.ts +64 -0
  98. package/dist/outbox.js +70 -0
  99. package/dist/pricing.d.ts +10 -2
  100. package/dist/pricing.js +14 -9
  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
@@ -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,29 @@ 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;
43
+ /** Optional override for the best-effort Google Calendar event delete on
44
+ * cancel. When provided it replaces the built-in service-account delete
45
+ * (which reads GOOGLE_SA_* env + rooms.google_calendar_id). Same
46
+ * best-effort contract: `ok: true` clears bookings.google_event_id; a
47
+ * non-ok result or a throw never rolls back the cancel/credit. */
48
+ deleteCalendarEvent?: (booking: {
49
+ id: string;
50
+ google_event_id: string | null;
51
+ rooms: {
52
+ google_calendar_id: string | null;
53
+ } | null;
54
+ }) => Promise<{
55
+ ok: boolean;
56
+ detail?: string;
57
+ }>;
36
58
  }
37
59
  declare function parseTstzRange(range: string): {
38
60
  startISO: string;
@@ -66,6 +88,7 @@ declare function bookingViewForCustomer(b: BookingRow, operator: {
66
88
  }>;
67
89
  export declare function handle(req: Request, operator: {
68
90
  operatorName: string;
91
+ googleCalendarWriteback?: boolean | null;
69
92
  }, deps: ManageBookingDeps): Promise<Response>;
70
93
  export declare const _test: {
71
94
  bookingViewForCustomer: typeof bookingViewForCustomer;
@@ -1,11 +1,15 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
- import { JWT } from 'google-auth-library';
2
+ import { getEnv } from '../runtime/env.js';
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)
@@ -41,14 +113,15 @@ function googleCalendarUrl(startISO, endISO, title, details, location) {
41
113
  return `https://calendar.google.com/calendar/render?${params}`;
42
114
  }
43
115
  async function deleteCalendarEvent(booking) {
44
- const clientEmail = Deno.env.get('GOOGLE_SA_CLIENT_EMAIL');
45
- const rawKey = Deno.env.get('GOOGLE_SA_PRIVATE_KEY');
116
+ const clientEmail = getEnv('GOOGLE_SA_CLIENT_EMAIL');
117
+ const rawKey = getEnv('GOOGLE_SA_PRIVATE_KEY');
46
118
  if (!clientEmail || !rawKey)
47
119
  return { ok: false, detail: 'not_configured' };
48
120
  if (!booking.google_event_id || !booking.rooms?.google_calendar_id)
49
121
  return { ok: false, detail: 'no_event_or_calendar' };
50
122
  const privateKey = rawKey.replace(/\\n/g, '\n');
51
123
  try {
124
+ const { JWT } = await import('google-auth-library');
52
125
  const jwt = new JWT({ email: clientEmail, key: privateKey, scopes: ['https://www.googleapis.com/auth/calendar.events'] });
53
126
  const tok = await jwt.getAccessToken();
54
127
  if (!tok?.token)
@@ -66,7 +139,7 @@ async function deleteCalendarEvent(booking) {
66
139
  }
67
140
  }
68
141
  async function addGhlNote(ghlContactId, message) {
69
- const apiKey = Deno.env.get('GHL_API_KEY');
142
+ const apiKey = getEnv('GHL_API_KEY');
70
143
  if (!apiKey || !ghlContactId)
71
144
  return;
72
145
  try {
@@ -101,7 +174,7 @@ async function bookingViewForCustomer(b, operator) {
101
174
  // confirmed. A cancelled booking needs no extra handling: ftw-middleware
102
175
  // only ever validates against currently live/paid bookings.
103
176
  let reservationWifiCode = null;
104
- const wifiSecret = Deno.env.get('RESERVATION_WIFI_CODE_SECRET');
177
+ const wifiSecret = getEnv('RESERVATION_WIFI_CODE_SECRET');
105
178
  if (isPaid && wifiSecret && isReservationWifiRoom(b.rooms?.slug)) {
106
179
  reservationWifiCode = await deriveReservationWifiCode(wifiSecret, b.id);
107
180
  }
@@ -132,14 +205,15 @@ async function bookingViewForCustomer(b, operator) {
132
205
  export async function handle(req, operator, deps) {
133
206
  if (req.method === 'OPTIONS')
134
207
  return new Response('ok', { headers: corsHeaders });
135
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
136
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
137
- const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
208
+ const SUPABASE_URL = getEnv('SUPABASE_URL');
209
+ const SERVICE_ROLE_KEY = getEnv('SUPABASE_SERVICE_ROLE_KEY');
210
+ const secret = getEnv('MANAGE_TOKEN_SECRET');
138
211
  if (!secret)
139
212
  return json(500, { error: 'not_configured' });
140
213
  const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
141
214
  auth: { persistSession: false, autoRefreshToken: false },
142
215
  });
216
+ const busBase = deps.busBase ?? getEventAccessBusBase();
143
217
  // Rate-limit BEFORE any DB work.
144
218
  const ip = clientIp(req);
145
219
  const [ipOk] = await Promise.all([
@@ -217,7 +291,7 @@ export async function handle(req, operator, deps) {
217
291
  if (b.status !== 'paid' || endMs <= Date.now()) {
218
292
  return json(404, { error: 'no_credential' });
219
293
  }
220
- const busSecret = Deno.env.get('BUS_HMAC_SECRET');
294
+ const busSecret = getEnv('BUS_HMAC_SECRET');
221
295
  const slug = b.rooms?.slug ?? null;
222
296
  if (!busSecret || !slug || !parsedRange) {
223
297
  return json(404, { error: 'no_credential' });
@@ -228,11 +302,7 @@ export async function handle(req, operator, deps) {
228
302
  const ts = Math.floor(Date.now() / 1000);
229
303
  const sig = await deps.signBus('credential', b.id, slug, startUtc, endUtc, busSecret, ts);
230
304
  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()}`, {
305
+ const res = await fetch(`${busBase}/bookings/credential?${qs.toString()}`, {
236
306
  method: 'GET',
237
307
  headers: { 'X-GC-Signature': sig, 'X-GC-Timestamp': String(ts) },
238
308
  signal: AbortSignal.timeout(10000),
@@ -261,6 +331,52 @@ export async function handle(req, operator, deps) {
261
331
  return json(404, { error: 'no_credential' });
262
332
  }
263
333
  }
334
+ // Two-pin organizer credential (D35 follow-up): unlike 'credential' above,
335
+ // this table lives in this SAME Supabase project, so it's read directly
336
+ // via `admin` -- no HTTP call out to the ftw-middleware droplet at all. A
337
+ // booking may have EITHER a legacy single-pin credential (above) OR a
338
+ // two-pin grant (below), never assumed to be exclusive. Returns
339
+ // 404 { error: 'no_credential' } until the (separate, later) PIN-capture
340
+ // provisioning code actually writes unlock_pin/relock_pin.
341
+ if (action === 'two_pin_credential') {
342
+ const parsedRange = parseTstzRange(b.during);
343
+ const endMs = parsedRange ? new Date(parsedRange.endISO).getTime() : 0;
344
+ if (b.status !== 'paid' || endMs <= Date.now()) {
345
+ return json(404, { error: 'no_credential' });
346
+ }
347
+ try {
348
+ const { data, error } = await admin
349
+ .from('booking_access_grants')
350
+ .select('id,unlock_pin,relock_pin,access_start,access_end,status')
351
+ .eq('booking_id', b.id).eq('status', 'active')
352
+ .order('created_at', { ascending: false }).limit(1).maybeSingle();
353
+ if (error || !data)
354
+ return json(404, { error: 'no_credential' });
355
+ const grant = data;
356
+ if (!grant.unlock_pin && !grant.relock_pin)
357
+ return json(404, { error: 'no_credential' });
358
+ // Organizer early-manual-lock/unlock link (D35 follow-up): only attempt
359
+ // the mint while the grant itself is still within its active window —
360
+ // no point minting a link for a grant that's already over. Never blocks
361
+ // or alters the PIN response: a failed/skipped mint is just a null url.
362
+ let organizerLinkUrl = null;
363
+ const grantEndMs = grant.access_end ? new Date(grant.access_end).getTime() : NaN;
364
+ const grantWithinWindow = !Number.isFinite(grantEndMs) || grantEndMs > Date.now();
365
+ if (grant.id && grantWithinWindow) {
366
+ organizerLinkUrl = await mintOrganizerLinkUrl(admin, `customer:${authedEmail}`, grant.id, b.id, busBase);
367
+ }
368
+ return json(200, {
369
+ unlock_pin: grant.unlock_pin ?? null,
370
+ relock_pin: grant.relock_pin ?? null,
371
+ valid_from_utc: grant.access_start ?? null,
372
+ valid_to_utc: grant.access_end ?? null,
373
+ organizer_link_url: organizerLinkUrl,
374
+ });
375
+ }
376
+ catch {
377
+ return json(404, { error: 'no_credential' });
378
+ }
379
+ }
264
380
  if (action !== 'cancel')
265
381
  return json(400, { error: 'invalid_action' });
266
382
  // Idempotent: if already cancelled, just return the current view.
@@ -286,6 +402,7 @@ export async function handle(req, operator, deps) {
286
402
  .update({ status: newStatus })
287
403
  .eq('id', b.id)
288
404
  .eq('status', 'paid')
405
+ .is('access_revoke_required_at', null)
289
406
  .select('id');
290
407
  if (updErr)
291
408
  return json(500, { error: 'update_failed' });
@@ -293,9 +410,14 @@ export async function handle(req, operator, deps) {
293
410
  // Someone else flipped it in-between — return current view.
294
411
  const { data: fresh } = await admin
295
412
  .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)')
413
+ .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
414
  .eq('id', b.id)
298
415
  .maybeSingle();
416
+ if (fresh && fresh.status === 'paid' && fresh.access_revoke_required_at) {
417
+ // Webhook flagged this booking (Connect full refund / dispute): no
418
+ // self-service cancel, hence no credit.
419
+ return json(409, { error: 'booking_flagged_contact_support' });
420
+ }
299
421
  if (fresh) {
300
422
  return json(200, {
301
423
  ...await bookingViewForCustomer(fresh, operator),
@@ -303,6 +425,8 @@ export async function handle(req, operator, deps) {
303
425
  outcome: fresh.status,
304
426
  });
305
427
  }
428
+ // Re-read failed: fail closed, never fall through to the credit grant.
429
+ return json(409, { error: 'already_changed' });
306
430
  }
307
431
  // Credit ledger row(s): split cash-funded (1yr) vs credit-funded (capped at
308
432
  // the ORIGINAL credit's own expiry) so a cancellation can never launder a
@@ -354,9 +478,11 @@ export async function handle(req, operator, deps) {
354
478
  catch (e) {
355
479
  await logOps(admin, 'coupon_reverse_on_cancel_failed', { message: String(e) }, { severity: 'error', bookingId: b.id });
356
480
  }
481
+ // Opt-in, fail-soft: remove the write-back event (deterministic id; no stored id needed).
482
+ await writebackBookingCancelled(operator, b.rooms?.google_calendar_id, b.id);
357
483
  // Best-effort: delete Google Calendar event.
358
484
  try {
359
- const cal = await deleteCalendarEvent(b);
485
+ const cal = await (deps.deleteCalendarEvent ?? deleteCalendarEvent)(b);
360
486
  if (cal.ok) {
361
487
  await admin.from('bookings').update({ google_event_id: null }).eq('id', b.id);
362
488
  }
@@ -389,6 +515,15 @@ export async function handle(req, operator, deps) {
389
515
  }
390
516
  }
391
517
  catch { /* never break the response */ }
518
+ // Best-effort: revoke organizer door grants (O3b). Must not block cancel.
519
+ try {
520
+ await revokeBookingOrganizerAccessGrants(admin, {
521
+ bookingId: b.id,
522
+ actingUserId: `customer:booking:${b.id}`,
523
+ reason: 'booking_cancelled',
524
+ });
525
+ }
526
+ catch { /* revokeBookingOrganizerAccessGrants never throws; belt-and-suspenders */ }
392
527
  const { data: fresh } = await admin
393
528
  .from('bookings')
394
529
  .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 {};