@simplelayer/graniteer-core 0.3.23 → 0.3.24

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.
@@ -0,0 +1,32 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ export type SupabaseLike = SupabaseClient<any, any, any>;
3
+ export declare const ORGANIZER_GRANT_TIMEOUT_MS = 95000;
4
+ export interface RequestOrganizerGrantOptions {
5
+ bookingId: string;
6
+ /** gc-io doors.id (uuid), NOT the UniFi id; resolved from the doors table. */
7
+ doorId: string;
8
+ organizer: {
9
+ name?: string | null;
10
+ email?: string | null;
11
+ phone?: string | null;
12
+ };
13
+ startUtc: string;
14
+ endUtc: string;
15
+ /** Caller supplied, e.g. commons:<bookingId>:<doorId>. */
16
+ idempotencyKey: string;
17
+ actingUserId: string;
18
+ busBase?: string;
19
+ fetchImpl?: typeof fetch;
20
+ timeoutMs?: number;
21
+ }
22
+ export type RequestOrganizerGrantError = 'invalid_input' | 'door_lookup_failed' | 'door_not_found' | 'door_not_provisioned' | 'door_not_live' | 'lockdown_not_verified' | 'secret_missing' | 'middleware_unreachable' | 'middleware_rejected' | 'middleware_error' | 'bad_response' | 'unexpected';
23
+ export type RequestOrganizerGrantResult = {
24
+ ok: true;
25
+ grant_id: string;
26
+ idempotent: boolean;
27
+ } | {
28
+ ok: false;
29
+ error: RequestOrganizerGrantError;
30
+ status?: number;
31
+ };
32
+ export declare function requestOrganizerGrant(admin: SupabaseLike, opts: RequestOrganizerGrantOptions): Promise<RequestOrganizerGrantResult>;
@@ -0,0 +1,195 @@
1
+ // Request an organizer door-access grant for a booking via the tenant
2
+ // middleware's signed /admin/event-access/grant path (same e1 HMAC contract and
3
+ // outbound body as the staff "grant" branch in event-access-admin.ts).
4
+ //
5
+ // Unattended path that can open physical doors: every step fails closed, the
6
+ // function never throws, and nothing sensitive (PINs, organizer PII, secret,
7
+ // signature, raw response) is returned or logged.
8
+ import { logOps } from '../ops.js';
9
+ import { sha256Hex, signBusMessage } from '../busSignature.js';
10
+ import { getEventAccessBusBase } from '../tenant-config.js';
11
+ // Grant-only headroom, same as event-access-admin's GRANT_TIMEOUT_MS: the
12
+ // middleware mints PINs with a retry loop (worst case ~85s) and the Cloudflare
13
+ // Tunnel edge cuts proxied HTTP at ~100s, so 95s clears the former and there
14
+ // is no point going higher.
15
+ export const ORGANIZER_GRANT_TIMEOUT_MS = 95_000;
16
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
+ const SAFE_ERROR_CODE = /^[a-z_]{1,64}$/;
18
+ // Explicit zone required: a zone-less string would be parsed as server-local time.
19
+ const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/i;
20
+ const MAX_IDEMPOTENCY_KEY_LENGTH = 200;
21
+ function errorName(e) {
22
+ if (e instanceof Error && e.name)
23
+ return e.name;
24
+ return 'Error';
25
+ }
26
+ async function safeLog(admin, kind, detail, bookingId) {
27
+ try {
28
+ await logOps(admin, kind, detail, { severity: 'error', ...(bookingId ? { bookingId } : {}) });
29
+ }
30
+ catch { /* logging must never throw or change the result */ }
31
+ }
32
+ function optionalText(v) {
33
+ if (v === undefined || v === null)
34
+ return null;
35
+ if (typeof v !== 'string')
36
+ return undefined;
37
+ const t = v.trim();
38
+ return t === '' ? null : t;
39
+ }
40
+ function requiredText(v) {
41
+ if (typeof v !== 'string')
42
+ return null;
43
+ const t = v.trim();
44
+ return t === '' ? null : t;
45
+ }
46
+ function instant(v) {
47
+ if (typeof v !== 'string')
48
+ return null;
49
+ const t = v.trim();
50
+ if (!ISO_INSTANT.test(t))
51
+ return null;
52
+ const ms = Date.parse(t);
53
+ if (!Number.isFinite(ms))
54
+ return null;
55
+ return new Date(ms).toISOString();
56
+ }
57
+ function validate(opts) {
58
+ if (!opts || typeof opts !== 'object')
59
+ return null;
60
+ const bookingId = requiredText(opts.bookingId);
61
+ const doorId = requiredText(opts.doorId);
62
+ if (!bookingId || !UUID.test(bookingId) || !doorId || !UUID.test(doorId))
63
+ return null;
64
+ const start = instant(opts.startUtc);
65
+ const end = instant(opts.endUtc);
66
+ if (!start || !end)
67
+ return null;
68
+ if (!(Date.parse(end) > Date.parse(start)))
69
+ return null;
70
+ const idempotencyKey = requiredText(opts.idempotencyKey);
71
+ const actingUserId = requiredText(opts.actingUserId);
72
+ if (!idempotencyKey || idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH || !actingUserId)
73
+ return null;
74
+ const org = opts.organizer;
75
+ if (!org || typeof org !== 'object')
76
+ return null;
77
+ const name = optionalText(org.name);
78
+ const email = optionalText(org.email);
79
+ const phone = optionalText(org.phone);
80
+ if (name === undefined || email === undefined || phone === undefined)
81
+ return null;
82
+ return { bookingId, doorId, person: { name, email, phone }, start, end, idempotencyKey, actingUserId };
83
+ }
84
+ export async function requestOrganizerGrant(admin, opts) {
85
+ let logBookingId;
86
+ try {
87
+ const input = validate(opts);
88
+ if (!input)
89
+ return { ok: false, error: 'invalid_input' };
90
+ logBookingId = input.bookingId;
91
+ // Door resolution: doors.id -> UniFi door id. Stricter than the staff path
92
+ // (this is the unattended path): must be live and lockdown-verified.
93
+ const { data: doorData, error: doorErr } = await admin
94
+ .from('doors').select('id,unifi_door_id,status,lockdown_verified').eq('id', input.doorId).maybeSingle();
95
+ if (doorErr) {
96
+ await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_lookup_failed' }, logBookingId);
97
+ return { ok: false, error: 'door_lookup_failed' };
98
+ }
99
+ if (!doorData) {
100
+ await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_not_found' }, logBookingId);
101
+ return { ok: false, error: 'door_not_found' };
102
+ }
103
+ const door = doorData;
104
+ const unifi = typeof door.unifi_door_id === 'string' ? door.unifi_door_id.trim() : '';
105
+ if (!unifi || unifi === 'PENDING') {
106
+ await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_not_provisioned' }, logBookingId);
107
+ return { ok: false, error: 'door_not_provisioned' };
108
+ }
109
+ if (door.status !== 'live') {
110
+ await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_not_live' }, logBookingId);
111
+ return { ok: false, error: 'door_not_live' };
112
+ }
113
+ if (door.lockdown_verified !== true) {
114
+ await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'lockdown_not_verified' }, logBookingId);
115
+ return { ok: false, error: 'lockdown_not_verified' };
116
+ }
117
+ const { data: secretRaw, error: secretErr } = await admin.rpc('get_event_access_hmac_secret');
118
+ const secret = typeof secretRaw === 'string' ? secretRaw : null;
119
+ if (secretErr || !secret) {
120
+ await safeLog(admin, 'commons_organizer_grant_secret_missing', {}, logBookingId);
121
+ return { ok: false, error: 'secret_missing' };
122
+ }
123
+ // Mirrors event-access-admin.ts's grant branch (key order is part of the signed bytes).
124
+ const outbound = {
125
+ acting_user_id: input.actingUserId,
126
+ person: {
127
+ name: input.person.name,
128
+ email: input.person.email,
129
+ phone: input.person.phone,
130
+ },
131
+ room: { booking_id: input.bookingId },
132
+ door_id: unifi,
133
+ start: input.start,
134
+ end: input.end,
135
+ idempotency_key: input.idempotencyKey,
136
+ };
137
+ const rawBody = JSON.stringify(outbound);
138
+ const bodyHash = await sha256Hex(rawBody);
139
+ const ts = String(Math.floor(Date.now() / 1000));
140
+ const signature = await signBusMessage(['e1', 'grant', ts, bodyHash].join('\n'), secret);
141
+ const busBase = opts.busBase ?? getEventAccessBusBase();
142
+ const doFetch = opts.fetchImpl ?? fetch;
143
+ const timeoutMs = typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
144
+ ? opts.timeoutMs
145
+ : ORGANIZER_GRANT_TIMEOUT_MS;
146
+ let res;
147
+ try {
148
+ res = await doFetch(`${busBase}/admin/event-access/grant`, {
149
+ method: 'POST',
150
+ headers: {
151
+ 'Content-Type': 'application/json',
152
+ 'X-Event-Access-Signature': signature,
153
+ 'X-Event-Access-Timestamp': ts,
154
+ },
155
+ body: rawBody,
156
+ signal: AbortSignal.timeout(timeoutMs),
157
+ });
158
+ }
159
+ catch (e) {
160
+ await safeLog(admin, 'commons_organizer_grant_call_error', { error_name: errorName(e) }, logBookingId);
161
+ return { ok: false, error: 'middleware_unreachable' };
162
+ }
163
+ let parsed = null;
164
+ try {
165
+ const text = await res.text();
166
+ parsed = text ? JSON.parse(text) : null;
167
+ }
168
+ catch {
169
+ parsed = null;
170
+ }
171
+ const parsedObj = parsed && typeof parsed === 'object' ? parsed : null;
172
+ if (!res.ok) {
173
+ const detail = { status: res.status };
174
+ const code = parsedObj?.error;
175
+ if (typeof code === 'string' && SAFE_ERROR_CODE.test(code))
176
+ detail.error_code = code;
177
+ await safeLog(admin, 'commons_organizer_grant_call_failed', detail, logBookingId);
178
+ return {
179
+ ok: false,
180
+ error: res.status === 401 || res.status === 403 ? 'middleware_rejected' : 'middleware_error',
181
+ status: res.status,
182
+ };
183
+ }
184
+ const grantId = parsedObj?.grant_id;
185
+ if (!parsedObj || parsedObj.ok !== true || typeof grantId !== 'string' || grantId.trim() === '') {
186
+ await safeLog(admin, 'commons_organizer_grant_bad_response', { status: res.status }, logBookingId);
187
+ return { ok: false, error: 'bad_response', status: res.status };
188
+ }
189
+ return { ok: true, grant_id: grantId, idempotent: parsedObj.idempotent === true };
190
+ }
191
+ catch (e) {
192
+ await safeLog(admin, 'commons_organizer_grant_call_error', { error_name: errorName(e) }, logBookingId);
193
+ return { ok: false, error: 'unexpected' };
194
+ }
195
+ }
@@ -9,3 +9,10 @@ export declare function bookingRowRequiresBackstopRevoke(booking: {
9
9
  access_revoke_required_at?: string | null;
10
10
  }): boolean;
11
11
  export declare function handle(req: Request): Promise<Response>;
12
+ export interface BookingAccessRevokeBackstopConfig {
13
+ /** Hand-maintained deploy-verification marker returned by the GET branch. */
14
+ buildMarker: string;
15
+ }
16
+ /** Wraps `handle` with an unauthenticated deploy-verification GET (no DB, no secrets);
17
+ * every other method is delegated to `handle` unchanged. */
18
+ export declare function createBookingAccessRevokeBackstopHandler(config: BookingAccessRevokeBackstopConfig): (req: Request) => Promise<Response>;
@@ -119,3 +119,14 @@ export async function handle(req) {
119
119
  headers: { 'Content-Type': 'application/json' },
120
120
  });
121
121
  }
122
+ /** Wraps `handle` with an unauthenticated deploy-verification GET (no DB, no secrets);
123
+ * every other method is delegated to `handle` unchanged. */
124
+ export function createBookingAccessRevokeBackstopHandler(config) {
125
+ const buildMarker = config.buildMarker;
126
+ return (req) => {
127
+ if (req.method === 'GET') {
128
+ return Promise.resolve(new Response(JSON.stringify({ ok: true, function: 'booking-access-revoke-backstop', build: buildMarker }), { status: 200, headers: { 'Content-Type': 'application/json' } }));
129
+ }
130
+ return handle(req);
131
+ };
132
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.23",
3
+ "version": "0.3.24",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -417,6 +417,14 @@
417
417
  "types": "./dist/functions/boldsign-sender-identity.d.ts",
418
418
  "default": "./dist/functions/boldsign-sender-identity.js"
419
419
  },
420
+ "./functions/booking-access-grant": {
421
+ "types": "./dist/functions/booking-access-grant.d.ts",
422
+ "default": "./dist/functions/booking-access-grant.js"
423
+ },
424
+ "./functions/booking-access-revoke": {
425
+ "types": "./dist/functions/booking-access-revoke.d.ts",
426
+ "default": "./dist/functions/booking-access-revoke.js"
427
+ },
420
428
  "./functions/booking-access-revoke-backstop": {
421
429
  "types": "./dist/functions/booking-access-revoke-backstop.d.ts",
422
430
  "default": "./dist/functions/booking-access-revoke-backstop.js"