@simplelayer/graniteer-core 0.2.0 → 0.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "index.js",
6
6
  "types": "index.js",
@@ -257,6 +257,31 @@ export async function handle(req: Request): Promise<Response> {
257
257
  return json(200, { ok: true, result: data ?? [] });
258
258
  }
259
259
 
260
+ case 'get_reconciling_grants': {
261
+ const { data, error } = await supabase
262
+ .from('booking_access_grants').select('*')
263
+ .eq('status', 'reconciling');
264
+ if (error) return await fail('db_error', { message: error.message });
265
+ return json(200, { ok: true, result: data ?? [] });
266
+ }
267
+
268
+ case 'try_transition_reconciling_to_active': {
269
+ const grantId = reqUuid(args, 'grant_id');
270
+ const visitorId = str(args.visitor_id);
271
+ if (!grantId) return await fail('invalid_args', {});
272
+ const r = await cas(grantId, 'reconciling', 'active', { visitor_id: visitorId });
273
+ if ('err' in r) return await fail('db_error', { message: r.err });
274
+ return json(200, { ok: true, result: r.row });
275
+ }
276
+
277
+ case 'try_transition_reconciling_to_failed': {
278
+ const grantId = reqUuid(args, 'grant_id');
279
+ if (!grantId) return await fail('invalid_args', {});
280
+ const r = await cas(grantId, 'reconciling', 'failed');
281
+ if ('err' in r) return await fail('db_error', { message: r.err });
282
+ return json(200, { ok: true, result: r.row });
283
+ }
284
+
260
285
  case 'insert_event': {
261
286
  const grantRaw = str(args.grant_id); // nullable: door-only actions have no grant
262
287
  const grantId = grantRaw === null ? null : reqUuid(args, 'grant_id');
@@ -1,16 +1,56 @@
1
1
  // Member-portal "your booking access" read.
2
2
  //
3
- // Returns, for the CALLER'S OWN upcoming/current bookings, the room and the
4
- // booking window only. This function makes NO outbound call to the door
5
- // middleware and holds no HMAC credential: booking-level access codes are not
6
- // issued yet, so every parseable booking reports status 'pending'.
3
+ // Returns, for the CALLER'S OWN upcoming/current bookings, the room, the
4
+ // booking window, and -- when the tenant's booking-bus middleware actually has
5
+ // a live door credential for that booking -- the PIN itself.
6
+ //
7
+ // B17: this makes a REAL outbound call to the door middleware
8
+ // ({busBase}/bookings/credential, the same HMAC-signed GET
9
+ // manage-booking's action==='credential' branch already uses) for each of the
10
+ // caller's own paid/upcoming bookings, in parallel. On a tenant whose
11
+ // middleware has provisioning gated off, that call comes back with no usable
12
+ // pin: the fast-path handler returns credential={type:"pin",
13
+ // status:"verified_pending_provisioning", id:null} for every booking -- no
14
+ // "pin" field at all. Every booking therefore still reports status 'pending'
15
+ // until that gate is flipped on; this wiring is inert-but-live. When the gate
16
+ // does flip, a booking with a real PIN reports status 'ready' with the pin
17
+ // attached -- no further change needed here.
7
18
  //
8
19
  // Identity model: the caller is resolved from their portal session JWT only.
9
20
  // No email and no booking id is ever read from the request body — the booking
10
21
  // set is derived server-side from bookings.contact_email = the verified email.
11
22
  import { createClient } from 'npm:@supabase/supabase-js@2';
23
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
12
24
  import { resolvePortalSessionEmail } from 'npm:@simplelayer/graniteer-core/portalSession';
13
25
  import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
26
+ import { signBus, toBusUtc } from 'npm:@simplelayer/graniteer-core/busClient';
27
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
28
+
29
+ // Loose generics, matching ops.ts/busClient.ts.
30
+ // deno-lint-ignore no-explicit-any
31
+ type SupabaseLike = SupabaseClient<any, any, any>;
32
+
33
+ /**
34
+ * The tenant's booking-bus transport identity for the credential read.
35
+ *
36
+ * Same shape and same reasoning as BusClientConfig/PortalResendInviteConfig:
37
+ * the middleware origin and the `source` identifier are deployment facts about
38
+ * one tenant, not platform constants, and a client that guessed its own origin
39
+ * or identity would be reading somebody else's doors. `env.secret` is the NAME
40
+ * of the env var holding the v2 HMAC secret (mirroring MembershipBusConfig.env),
41
+ * not its value -- which variable carries the secret is likewise a deployment
42
+ * fact.
43
+ */
44
+ export interface PortalBookingAccessConfig {
45
+ /** Origin of the tenant's middleware, e.g. https://bus.example.com. No trailing slash. */
46
+ busBase: string;
47
+ /** `source` query parameter identifying the calling tenant app. */
48
+ source: string;
49
+ env: {
50
+ /** Env var holding the booking-bus HMAC secret signBus() signs with. */
51
+ secret: string;
52
+ };
53
+ }
14
54
 
15
55
  const corsHeaders = {
16
56
  'Access-Control-Allow-Origin': '*',
@@ -19,6 +59,7 @@ const corsHeaders = {
19
59
  };
20
60
 
21
61
  const MAX_BOOKINGS = 10;
62
+ const CREDENTIAL_FETCH_TIMEOUT_MS = 8000;
22
63
 
23
64
  function json(status: number, body: unknown) {
24
65
  return new Response(JSON.stringify(body), {
@@ -39,9 +80,73 @@ function parseRange(during: string): { start: string; end: string } | null {
39
80
  return { start: s.toISOString(), end: e.toISOString() };
40
81
  }
41
82
 
42
- type Status = 'pending' | 'unavailable';
83
+ type Status = 'pending' | 'unavailable' | 'ready';
84
+
85
+ interface LiveCredential {
86
+ pin: string;
87
+ status: string | null;
88
+ valid_from_utc: string | null;
89
+ valid_to_utc: string | null;
90
+ }
91
+
92
+ /**
93
+ * Same request shape as manage-booking's action==='credential' branch
94
+ * (source=<config.source>, X-GC-Signature/X-GC-Timestamp, v2 canonical message
95
+ * via the SAME busClient signBus/toBusUtc -- sharing the crypto, not the
96
+ * request/response handling). The request-building and response-parsing logic
97
+ * here is a deliberate, separate copy rather than a shared function, so this
98
+ * read-only, best-effort fetch can never regress that already-reviewed,
99
+ * money-adjacent cancel/credential flow by editing shared code both paths
100
+ * call. Fails closed to null on ANY problem (missing config, non-200,
101
+ * malformed body, timeout) -- a credential-fetch failure must never surface as
102
+ * an error to the caller, only as "still pending".
103
+ */
104
+ async function fetchLiveCredential(
105
+ bookingId: string, slug: string, startIso: string, endIso: string, secret: string,
106
+ supabase: SupabaseLike, config: PortalBookingAccessConfig,
107
+ ): Promise<LiveCredential | null> {
108
+ try {
109
+ const startUtc = toBusUtc(startIso);
110
+ const endUtc = toBusUtc(endIso);
111
+ const ts = Math.floor(Date.now() / 1000);
112
+ const sig = await signBus('credential', bookingId, slug, startUtc, endUtc, secret, ts);
113
+ const qs = new URLSearchParams({ source: config.source, booking_id: bookingId });
114
+ const res = await fetch(`${config.busBase}/bookings/credential?${qs.toString()}`, {
115
+ method: 'GET',
116
+ headers: { 'X-GC-Signature': sig, 'X-GC-Timestamp': String(ts) },
117
+ signal: AbortSignal.timeout(CREDENTIAL_FETCH_TIMEOUT_MS),
118
+ });
119
+ if (res.status === 401) {
120
+ // Distinct from a plain gate-off/not-yet-issued response (which is a
121
+ // 200 with no pin field) -- a 401 means the signature/secret itself
122
+ // was rejected. Logged (never with the booking's PIN, since none was
123
+ // returned) so this doesn't look identical to "still pending" once
124
+ // the middleware's provisioning gate flips on. Mirrors manage-booking's
125
+ // own manage_credential_unauthorized log for the same response code.
126
+ await logOps(supabase, 'portal_credential_unauthorized', {},
127
+ { severity: 'warning', bookingId });
128
+ return null;
129
+ }
130
+ if (!res.ok) return null;
131
+ const j = await res.json().catch(() => null) as
132
+ | { cancelled?: boolean; credential?: { pin?: unknown; status?: unknown; valid_from_utc?: unknown; valid_to_utc?: unknown } }
133
+ | null;
134
+ const cred = j?.credential;
135
+ if (j?.cancelled || !cred || typeof cred.pin !== 'string' || cred.pin.length === 0) {
136
+ return null;
137
+ }
138
+ return {
139
+ pin: cred.pin,
140
+ status: typeof cred.status === 'string' ? cred.status : null,
141
+ valid_from_utc: typeof cred.valid_from_utc === 'string' ? cred.valid_from_utc : null,
142
+ valid_to_utc: typeof cred.valid_to_utc === 'string' ? cred.valid_to_utc : null,
143
+ };
144
+ } catch {
145
+ return null;
146
+ }
147
+ }
43
148
 
44
- export async function handle(req: Request): Promise<Response> {
149
+ export async function handle(req: Request, config: PortalBookingAccessConfig): Promise<Response> {
45
150
  if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
46
151
  if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
47
152
 
@@ -70,23 +175,40 @@ export async function handle(req: Request): Promise<Response> {
70
175
 
71
176
  if (error) return json(200, { bookings: [], access_check_failed: true });
72
177
 
178
+ const busSecret = Deno.env.get(config.env.secret);
73
179
  const nowMs = Date.now();
74
- const bookings = (rows ?? []).map((r) => {
180
+
181
+ const bookings = await Promise.all((rows ?? []).map(async (r) => {
75
182
  const room = (r as { rooms?: { name?: string; slug?: string } | null }).rooms ?? null;
76
183
  const range = parseRange(String((r as { during: string }).during));
77
184
  const startMs = range ? Date.parse(range.start) : null;
185
+ const bookingId = String((r as { id: string }).id);
186
+ const baseStatus: Status = range ? 'pending' : 'unavailable';
187
+
188
+ let credential: LiveCredential | null = null;
189
+ if (baseStatus === 'pending' && busSecret && room?.slug && range) {
190
+ credential = await fetchLiveCredential(
191
+ bookingId, room.slug, range.start, range.end, busSecret, admin, config);
192
+ }
193
+
78
194
  return {
79
- booking_id: String((r as { id: string }).id),
195
+ booking_id: bookingId,
80
196
  room_name: room?.name ?? 'Your room',
81
197
  start: range?.start ?? null,
82
198
  end: range?.end ?? null,
83
- status: (range ? 'pending' : 'unavailable') as Status,
199
+ status: (credential ? 'ready' : baseStatus) as Status,
84
200
  // Mirrors manage-booking/index.ts's own cancellable/within48h logic
85
201
  // exactly -- do not let these two definitions drift apart.
86
202
  cancellable: startMs !== null && startMs > nowMs,
87
203
  within48h: startMs !== null && (startMs - nowMs) < 48 * 60 * 60 * 1000,
204
+ ...(credential ? {
205
+ pin: credential.pin,
206
+ credential_status: credential.status,
207
+ valid_from_utc: credential.valid_from_utc,
208
+ valid_to_utc: credential.valid_to_utc,
209
+ } : {}),
88
210
  };
89
- });
211
+ }));
90
212
 
91
213
  return json(200, { bookings });
92
214
  } catch {