@simplelayer/graniteer-core 0.3.18 → 0.3.19

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 (41) hide show
  1. package/dist/functions/admin-create-booking.d.ts +0 -3
  2. package/dist/functions/admin-create-booking.js +2 -15
  3. package/dist/functions/admin-mark-booking-paid.d.ts +1 -6
  4. package/dist/functions/admin-mark-booking-paid.js +3 -27
  5. package/dist/functions/admin-request-trial.js +1 -1
  6. package/dist/functions/booking-availability.d.ts +1 -2
  7. package/dist/functions/booking-availability.js +5 -14
  8. package/dist/functions/create-booking.d.ts +0 -5
  9. package/dist/functions/create-booking.js +4 -22
  10. package/dist/functions/manage-booking.d.ts +0 -6
  11. package/dist/functions/manage-booking.js +12 -29
  12. package/dist/functions/reschedule-booking.d.ts +0 -5
  13. package/dist/functions/reschedule-booking.js +2 -28
  14. package/dist/functions/space-availability-range.d.ts +1 -2
  15. package/dist/functions/space-availability-range.js +1 -8
  16. package/dist/functions/stripe-webhook.d.ts +0 -4
  17. package/dist/functions/stripe-webhook.js +2 -168
  18. package/dist/functions/sync-gcal-blackouts.js +1 -1
  19. package/dist/gcalSync.d.ts +0 -1
  20. package/dist/gcalSync.js +0 -5
  21. package/dist/pricing.d.ts +2 -10
  22. package/dist/pricing.js +9 -14
  23. package/package.json +2 -26
  24. package/dist/bookingSource.d.ts +0 -2
  25. package/dist/bookingSource.js +0 -11
  26. package/dist/businessHours.d.ts +0 -11
  27. package/dist/businessHours.js +0 -55
  28. package/dist/connectBookingCharge.d.ts +0 -49
  29. package/dist/connectBookingCharge.js +0 -68
  30. package/dist/functions/booking-access-revoke-backstop.d.ts +0 -11
  31. package/dist/functions/booking-access-revoke-backstop.js +0 -121
  32. package/dist/functions/booking-access-revoke-door-state.d.ts +0 -22
  33. package/dist/functions/booking-access-revoke-door-state.js +0 -61
  34. package/dist/functions/booking-access-revoke.d.ts +0 -35
  35. package/dist/functions/booking-access-revoke.js +0 -279
  36. package/dist/gcalBookingEvents.d.ts +0 -59
  37. package/dist/gcalBookingEvents.js +0 -182
  38. package/dist/stripeConnectEvents.d.ts +0 -11
  39. package/dist/stripeConnectEvents.js +0 -37
  40. package/dist/tenant-config.d.ts +0 -8
  41. package/dist/tenant-config.js +0 -24
@@ -1,121 +0,0 @@
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
- }
@@ -1,22 +0,0 @@
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;
@@ -1,61 +0,0 @@
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
- }
@@ -1,35 +0,0 @@
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>;
@@ -1,279 +0,0 @@
1
- // Best-effort revoke of a booking's organizer door grants via the tenant
2
- // middleware's signed /admin/event-access/revoke path (same e1 HMAC contract
3
- // as event-access-admin.ts). Never throws; failures are ops-logged only.
4
- import { logOps } from '../ops.js';
5
- import { sha256Hex, signBusMessage } from '../busSignature.js';
6
- import { getEventAccessBusBase } from '../tenant-config.js';
7
- import { doorReadForOpsLog, isDoorStateCompleteForGrantRevoke, } from './booking-access-revoke-door-state.js';
8
- /** @deprecated Granite City's literal default, kept for import compatibility.
9
- * The actual default is resolved at call time from tenant-config.ts's
10
- * getEventAccessBusBase(), which reads the EVENT_ACCESS_BUS_BASE env var. */
11
- export const DEFAULT_EVENT_ACCESS_BUS_BASE = 'https://ftw.granitecity.io';
12
- /** C6 code-side: revoke calls must stay at or below 8s. */
13
- export const REVOKE_TIMEOUT_MS = 8_000;
14
- const MAX_GRANTS_PER_BATCH = 5;
15
- /** Hardening: cap in-process sweep batches (20 × 5 grants max per edge invocation). */
16
- export const MAX_REVOKE_SWEEP_BATCHES = 20;
17
- const REVOCABLE_STATUSES = ['active', 'pending', 'reconciling', 'revoke_failed'];
18
- const SAFE_ERROR_CODE = /^[a-z_]{1,64}$/;
19
- export const BOOKING_GRANT_REVOKE_ENABLED_ENV = 'BOOKING_GRANT_REVOKE_ENABLED';
20
- /** Tests only: next revoke call throws (W1 marker-failed + revoke throw path). */
21
- let forceRevokeThrowForTest = false;
22
- export function setForceRevokeThrowForTest(enabled) {
23
- forceRevokeThrowForTest = enabled;
24
- }
25
- /** Fail-closed: only the exact string 'true' arms revoke work. */
26
- export function isBookingGrantRevokeEnabled() {
27
- return Deno.env.get(BOOKING_GRANT_REVOKE_ENABLED_ENV) === 'true';
28
- }
29
- export function errorNameFromUnknown(e) {
30
- if (e instanceof Error && e.name)
31
- return e.name;
32
- return 'Error';
33
- }
34
- /**
35
- * CS-GM product decision (O3b / PR #21): partial refunds must NOT revoke organizer door access.
36
- * The guest keeps a valid paid booking; grants remain until the booking window ends.
37
- *
38
- * Stripe emits `charge.refunded` on every refund leg, but `charge.refunded` is only `true` once
39
- * the charge is fully refunded — that is the sole gate for organizer grant revoke on refund.
40
- */
41
- export function shouldRevokeOrganizerGrantsOnStripeChargeRefunded(charge) {
42
- return charge.refunded === true;
43
- }
44
- function parseMiddlewareBody(text) {
45
- if (!text)
46
- return null;
47
- try {
48
- const parsed = JSON.parse(text);
49
- return parsed && typeof parsed === 'object' ? parsed : null;
50
- }
51
- catch {
52
- return null;
53
- }
54
- }
55
- function middlewareErrorCode(parsed) {
56
- const err = parsed?.error;
57
- if (typeof err !== 'string' || !SAFE_ERROR_CODE.test(err))
58
- return undefined;
59
- return err;
60
- }
61
- function opsDoorReadDetail(parsed) {
62
- const doorRead = doorReadForOpsLog(parsed?.door_read);
63
- return doorRead ? { door_read: doorRead } : {};
64
- }
65
- async function signRevokeE1(secret, verb, ts, bodyHashHex) {
66
- const msg = ['e1', verb, ts, bodyHashHex].join('\n');
67
- return signBusMessage(msg, secret);
68
- }
69
- async function postRevoke(admin, opts) {
70
- const outbound = { acting_user_id: opts.actingUserId, grant_id: opts.grantId };
71
- const rawBody = JSON.stringify(outbound);
72
- const bodyHash = await sha256Hex(rawBody);
73
- const ts = String(Math.floor(Date.now() / 1000));
74
- const signature = await signRevokeE1(opts.secret, 'revoke', ts, bodyHash);
75
- let res;
76
- try {
77
- res = await fetch(`${opts.busBase}/admin/event-access/revoke`, {
78
- method: 'POST',
79
- headers: {
80
- 'Content-Type': 'application/json',
81
- 'X-Event-Access-Signature': signature,
82
- 'X-Event-Access-Timestamp': ts,
83
- },
84
- body: rawBody,
85
- signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS),
86
- });
87
- }
88
- catch (e) {
89
- await logOps(admin, 'booking_access_revoke_call_error', {
90
- reason: opts.reason,
91
- grant_id: opts.grantId,
92
- error_name: errorNameFromUnknown(e),
93
- }, { severity: 'error', bookingId: opts.bookingId });
94
- return;
95
- }
96
- const text = await res.text();
97
- const parsed = parseMiddlewareBody(text);
98
- if (res.ok) {
99
- // C5 (flag-on): waits on O3(a) middleware — HTTP 200 must satisfy the C6 ruling read.
100
- if (!isDoorStateCompleteForGrantRevoke(parsed)) {
101
- await logOps(admin, 'booking_access_revoke_door_not_secured', {
102
- reason: opts.reason,
103
- grant_id: opts.grantId,
104
- status: res.status,
105
- ...opsDoorReadDetail(parsed),
106
- }, { severity: 'error', bookingId: opts.bookingId });
107
- }
108
- return;
109
- }
110
- const errCode = middlewareErrorCode(parsed);
111
- if (errCode === 'grant_not_found') {
112
- return;
113
- }
114
- if (errCode === 'grant_not_revocable' || errCode === 'grant_already_revoked' || errCode === 'already_revoked') {
115
- if (isDoorStateCompleteForGrantRevoke(parsed)) {
116
- return;
117
- }
118
- // R1: not-revocable without a secured door is an error, not a warning.
119
- await logOps(admin, 'booking_access_revoke_not_revocable', {
120
- reason: opts.reason,
121
- grant_id: opts.grantId,
122
- status: res.status,
123
- error_code: errCode,
124
- ...opsDoorReadDetail(parsed),
125
- }, { severity: 'error', bookingId: opts.bookingId });
126
- return;
127
- }
128
- const detail = {
129
- reason: opts.reason,
130
- grant_id: opts.grantId,
131
- status: res.status,
132
- };
133
- if (errCode)
134
- detail.error_code = errCode;
135
- await logOps(admin, 'booking_access_revoke_call_failed', detail, { severity: 'error', bookingId: opts.bookingId });
136
- }
137
- /**
138
- * Revoke every active or upcoming organizer access grant for `bookingId`.
139
- * Safe to call multiple times (cancel replay, Stripe redelivery after revoke).
140
- */
141
- export async function revokeBookingOrganizerAccessGrants(admin, opts) {
142
- if (!isBookingGrantRevokeEnabled()) {
143
- await logOps(admin, 'booking_access_revoke_skipped_disabled', {
144
- reason: opts.reason,
145
- }, { severity: 'info', bookingId: opts.bookingId });
146
- return;
147
- }
148
- if (forceRevokeThrowForTest) {
149
- forceRevokeThrowForTest = false;
150
- throw new Error('forced revoke throw for test');
151
- }
152
- const busBase = opts.busBase ?? getEventAccessBusBase();
153
- const triedGrantIds = new Set();
154
- try {
155
- const listRevocable = async () => {
156
- const { data: grants, error: listErr } = await admin
157
- .from('booking_access_grants')
158
- .select('id,status,access_end')
159
- .eq('booking_id', opts.bookingId)
160
- .in('status', [...REVOCABLE_STATUSES]);
161
- if (listErr) {
162
- const code = listErr.code;
163
- await logOps(admin, 'booking_access_revoke_lookup_failed', {
164
- reason: opts.reason,
165
- ...(typeof code === 'string' ? { error_code: code } : {}),
166
- }, { severity: 'error', bookingId: opts.bookingId });
167
- return null;
168
- }
169
- const rows = (grants ?? []);
170
- // Hardening: stable ordering before batching.
171
- return rows.filter((row) => row.id).sort((a, b) => a.id.localeCompare(b.id));
172
- };
173
- const clearAccessRevokeMarkerIfDone = async (knownNoRevocableGrants = false) => {
174
- if (!knownNoRevocableGrants) {
175
- const remaining = await listRevocable();
176
- if (remaining === null || remaining.length > 0)
177
- return;
178
- }
179
- await admin.from('bookings')
180
- .update({ access_revoke_required_at: null })
181
- .eq('id', opts.bookingId)
182
- .not('access_revoke_required_at', 'is', null);
183
- };
184
- const initial = await listRevocable();
185
- if (initial === null)
186
- return;
187
- if (initial.length === 0) {
188
- await clearAccessRevokeMarkerIfDone(true);
189
- return;
190
- }
191
- if (initial.length > MAX_GRANTS_PER_BATCH) {
192
- await logOps(admin, 'booking_access_revoke_truncated', {
193
- reason: opts.reason,
194
- count: initial.length,
195
- }, { severity: 'error', bookingId: opts.bookingId });
196
- }
197
- const { data: secretRaw, error: secretErr } = await admin.rpc('get_event_access_hmac_secret');
198
- const secret = typeof secretRaw === 'string' ? secretRaw : null;
199
- if (secretErr || !secret) {
200
- await logOps(admin, 'booking_access_revoke_secret_missing', {
201
- reason: opts.reason,
202
- }, { severity: 'error', bookingId: opts.bookingId });
203
- return;
204
- }
205
- // C6 code-side: Promise.allSettled batches (≤5) until done, stalled, or hardening cap.
206
- let batches = 0;
207
- let truncatedSweepLogged = false;
208
- while (batches < MAX_REVOKE_SWEEP_BATCHES) {
209
- const rows = batches === 0 ? initial : await listRevocable();
210
- if (rows === null)
211
- return;
212
- if (rows.length === 0) {
213
- await clearAccessRevokeMarkerIfDone(true);
214
- break;
215
- }
216
- const pending = rows.filter((row) => !triedGrantIds.has(row.id));
217
- if (pending.length === 0) {
218
- await logOps(admin, 'booking_access_revoke_sweep_no_progress', {
219
- reason: opts.reason,
220
- grant_ids: rows.map((r) => r.id),
221
- }, { severity: 'error', bookingId: opts.bookingId });
222
- break;
223
- }
224
- if (batches > 0 && rows.length > MAX_GRANTS_PER_BATCH && !truncatedSweepLogged) {
225
- await logOps(admin, 'booking_access_revoke_sweep_continued', {
226
- reason: opts.reason,
227
- count: rows.length,
228
- batch: batches + 1,
229
- }, { severity: 'info', bookingId: opts.bookingId });
230
- truncatedSweepLogged = true;
231
- }
232
- const idsBefore = new Set(rows.map((r) => r.id));
233
- const targets = pending.slice(0, MAX_GRANTS_PER_BATCH);
234
- for (const row of targets)
235
- triedGrantIds.add(row.id);
236
- await Promise.allSettled(targets.map((row) => postRevoke(admin, {
237
- busBase,
238
- secret,
239
- actingUserId: opts.actingUserId,
240
- grantId: row.id,
241
- bookingId: opts.bookingId,
242
- reason: opts.reason,
243
- })));
244
- batches += 1;
245
- const afterRows = await listRevocable();
246
- if (afterRows === null)
247
- return;
248
- const idsAfter = new Set(afterRows.map((r) => r.id));
249
- const removedCount = [...idsBefore].filter((id) => !idsAfter.has(id)).length;
250
- if (removedCount === 0) {
251
- await logOps(admin, 'booking_access_revoke_sweep_no_progress', {
252
- reason: opts.reason,
253
- grant_ids: afterRows.map((r) => r.id),
254
- batches_run: batches,
255
- }, { severity: 'error', bookingId: opts.bookingId });
256
- break;
257
- }
258
- }
259
- if (batches >= MAX_REVOKE_SWEEP_BATCHES) {
260
- const remaining = await listRevocable();
261
- if (remaining === null)
262
- return;
263
- if (remaining.length > 0) {
264
- await logOps(admin, 'booking_access_revoke_sweep_incomplete', {
265
- reason: opts.reason,
266
- remaining_count: remaining.length,
267
- batches_run: batches,
268
- }, { severity: 'error', bookingId: opts.bookingId });
269
- }
270
- }
271
- await clearAccessRevokeMarkerIfDone();
272
- }
273
- catch (e) {
274
- await logOps(admin, 'booking_access_revoke_unexpected', {
275
- reason: opts.reason,
276
- error_name: errorNameFromUnknown(e),
277
- }, { severity: 'error', bookingId: opts.bookingId });
278
- }
279
- }
@@ -1,59 +0,0 @@
1
- export interface BookingEventInput {
2
- calendarId: string;
3
- bookingId: string;
4
- startIso: string;
5
- endIso: string;
6
- summary: string;
7
- description?: string;
8
- location?: string;
9
- }
10
- export interface GcalWritebackDeps {
11
- fetch?: typeof fetch;
12
- getAccessToken?: () => Promise<string | null>;
13
- }
14
- export type WritebackResult = {
15
- ok: true;
16
- eventId: string;
17
- action: 'created' | 'updated' | 'deleted' | 'already_absent';
18
- } | {
19
- ok: false;
20
- reason: 'no_credentials' | 'no_calendar' | 'http_error' | 'exception';
21
- status?: number;
22
- detail?: string;
23
- };
24
- export declare function eventIdForBooking(bookingId: string): string;
25
- export declare function createBookingEvent(input: BookingEventInput, deps?: GcalWritebackDeps): Promise<WritebackResult>;
26
- export declare function updateBookingEvent(input: BookingEventInput, deps?: GcalWritebackDeps): Promise<WritebackResult>;
27
- export declare function deleteBookingEvent(calendarId: string | null | undefined, bookingId: string, deps?: GcalWritebackDeps): Promise<WritebackResult>;
28
- export interface WritebackOperator {
29
- googleCalendarWriteback?: boolean | null;
30
- }
31
- export declare function isGcalWritebackEnabled(operator: WritebackOperator | null | undefined): boolean;
32
- export interface WritebackBookingRow {
33
- id: string;
34
- contact_name?: string | null;
35
- contact_email?: string | null;
36
- contact_phone?: string | null;
37
- during: string;
38
- rooms?: {
39
- name?: string | null;
40
- address?: string | null;
41
- google_calendar_id?: string | null;
42
- } | null;
43
- }
44
- export declare function bookingRowToEventInput(row: WritebackBookingRow): BookingEventInput | null;
45
- type LogFn = (msg: string, detail: unknown) => void;
46
- /**
47
- * Fail-soft create for a paid booking row. Never throws; returns null when the
48
- * operator flag is off (the default), so callers can invoke it unconditionally.
49
- */
50
- export declare function writebackBookingCreated(operator: WritebackOperator | null | undefined, row: WritebackBookingRow, deps?: GcalWritebackDeps, log?: LogFn): Promise<WritebackResult | null>;
51
- export declare function writebackBookingCancelled(operator: WritebackOperator | null | undefined, calendarId: string | null | undefined, bookingId: string, deps?: GcalWritebackDeps, log?: LogFn): Promise<WritebackResult | null>;
52
- /**
53
- * Adapter matching the `createCalendarEvent` dep shape used by create-booking,
54
- * admin-create-booking, reschedule-booking and stripe-webhook. A tenant wrapper
55
- * without door hardware can pass this as that dep; it is the only way to cover
56
- * stripe-webhook's paid path without editing the webhook.
57
- */
58
- export declare function makeWritebackCreateCalendarEvent(operator: WritebackOperator, deps?: GcalWritebackDeps): (admin: unknown, row: WritebackBookingRow) => Promise<void>;
59
- export {};