@simplelayer/graniteer-core 0.3.9 → 0.3.12

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 @@
1
+ export declare function handle(req: Request): Promise<Response>;
@@ -0,0 +1,120 @@
1
+ // supabase/functions/admin-acknowledge-contract-violation/index.ts
2
+ //
3
+ // Simple acknowledge workflow for booking_contract_violations rows (see
4
+ // claude/booking-contract-violations-ack-scope.md in the FTW Access Platform
5
+ // project). on_booking_paid_transition() inserts a row here whenever a paid
6
+ // booking settles with no proper agreement -- staff-offline bookings via
7
+ // admin-create-booking are the recurring source (see
8
+ // admin-create-booking-agreement-gap-scope.md). This does not change or gate
9
+ // anything about the booking itself; it just lets a verified admin record
10
+ // that they reviewed a violation row, mirroring the acknowledged_at /
11
+ // acknowledged_by_email columns that already exist on the table.
12
+ import { createClient } from '@supabase/supabase-js';
13
+ import { z } from 'zod';
14
+ import { jwtVerify, createRemoteJWKSet } from 'jose';
15
+ import { clientIp, checkRateLimit } from '../rateLimit.js';
16
+ import { logOps } from '../ops.js';
17
+ const corsHeaders = {
18
+ 'Access-Control-Allow-Origin': '*',
19
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
20
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
21
+ };
22
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
23
+ let jwksCache = null;
24
+ function getJwks(supabaseUrl) {
25
+ if (!jwksCache)
26
+ jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
27
+ return jwksCache;
28
+ }
29
+ async function verifyCaller(authHeader, supabaseUrl) {
30
+ if (!authHeader?.toLowerCase().startsWith('bearer '))
31
+ return null;
32
+ const token = authHeader.slice(7).trim();
33
+ try {
34
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
35
+ const claims = payload;
36
+ if (!claims.sub)
37
+ return null;
38
+ return claims;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ function json(status, body) {
45
+ return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
46
+ }
47
+ function fail(status, code, error, extra) {
48
+ return json(status, { ok: false, status, code, error, ...(extra ?? {}) });
49
+ }
50
+ const Body = z.object({
51
+ violation_id: z.string().uuid(),
52
+ });
53
+ export async function handle(req) {
54
+ if (req.method === 'OPTIONS')
55
+ return new Response('ok', { headers: corsHeaders });
56
+ if (req.method !== 'POST')
57
+ return fail(405, 'method_not_allowed', 'Method not allowed.');
58
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
59
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
60
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
61
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
62
+ if (!caller)
63
+ return fail(401, 'unauthenticated', 'Not signed in.');
64
+ if (caller.aal !== 'aal2')
65
+ return fail(403, 'mfa_required', 'Two-factor authentication is required.');
66
+ const callerEmail = (caller.email ?? '').toLowerCase();
67
+ if (!callerEmail)
68
+ return fail(403, 'no_email', 'Caller has no email claim.');
69
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
70
+ const [ipOk, emailOk] = await Promise.all([
71
+ checkRateLimit(admin, 'admin-acknowledge-contract-violation-ip', clientIp(req), 30, 300),
72
+ checkRateLimit(admin, 'admin-acknowledge-contract-violation-email', callerEmail, 30, 300),
73
+ ]);
74
+ if (!ipOk || !emailOk)
75
+ return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
76
+ const { data: allow, error: allowErr } = await admin.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
77
+ if (allowErr)
78
+ return fail(500, 'allowlist_lookup_failed', allowErr.message);
79
+ if (!allow)
80
+ return fail(403, 'not_authorized', 'Not authorized.');
81
+ let raw;
82
+ try {
83
+ raw = await req.json();
84
+ }
85
+ catch {
86
+ return fail(400, 'invalid_json', 'Body was not valid JSON.');
87
+ }
88
+ const parsed = Body.safeParse(raw);
89
+ if (!parsed.success)
90
+ return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
91
+ const { violation_id } = parsed.data;
92
+ const { data: violation, error: vErr } = await admin
93
+ .from('booking_contract_violations')
94
+ .select('id,booking_id,acknowledged_at')
95
+ .eq('id', violation_id)
96
+ .maybeSingle();
97
+ if (vErr)
98
+ return fail(500, 'violation_lookup_failed', vErr.message);
99
+ if (!violation)
100
+ return fail(404, 'violation_not_found', 'Violation row not found.');
101
+ const ackAt = new Date().toISOString();
102
+ // CAS on acknowledged_at IS NULL -- two admins acknowledging the same row
103
+ // at once is harmless (first write wins, second gets a clean 409 instead
104
+ // of silently overwriting who actually reviewed it).
105
+ const { data: updated, error: updErr } = await admin
106
+ .from('booking_contract_violations')
107
+ .update({ acknowledged_at: ackAt, acknowledged_by_email: callerEmail })
108
+ .eq('id', violation_id)
109
+ .is('acknowledged_at', null)
110
+ .select('id')
111
+ .maybeSingle();
112
+ if (updErr)
113
+ return fail(500, 'update_failed', updErr.message);
114
+ if (!updated)
115
+ return fail(409, 'already_acknowledged', 'This violation was already acknowledged — reload and try again.');
116
+ await logOps(admin, 'contract_violation_acknowledged', {
117
+ violation_id, booking_id: violation.booking_id, actor: callerEmail, actor_user_id: caller.sub,
118
+ }, { severity: 'info', bookingId: violation.booking_id }).catch(() => { });
119
+ return json(200, { ok: true, violation_id, acknowledged_at: ackAt });
120
+ }
@@ -28,9 +28,8 @@ import { checkConductorRateLimit, fetchConductorKey, insertConductorEvent, } fro
28
28
  const MODEL = 'claude-haiku-4-5-20251001';
29
29
  /** Short Q&A answer, not a report — deliberately not ls-quarterly-brief's 8000. */
30
30
  const MAX_TOKENS = 1024;
31
- const KB_LIMIT = 30;
32
- /** Per-article body cap, so one long runbook can't crowd out the other 29. */
33
- const KB_BODY_CHARS = 2500;
31
+ /** Per-article body cap. At most eight ranked articles are loaded, so each can keep more of its text. */
32
+ const KB_BODY_CHARS = 6000;
34
33
  const QUESTION_MAX_CHARS = 2000;
35
34
  /**
36
35
  * Bound on what gets stored in the audit row. MAX_TOKENS = 1024 caps a real
@@ -271,19 +270,43 @@ export async function handle(req, operator) {
271
270
  // future third audience value cannot silently start appearing in members'
272
271
  // prompts before anyone revisits this line.
273
272
  //
274
- // KNOWN v1 LIMITATION, not an oversight: "the 30 most recently updated
275
- // articles" is the whole of the relevance ranking. There is no search index or
276
- // embedding store in this repo to rank against, so an article that would have
277
- // answered the question can fall outside the window. Out of scope for v1.
273
+ // Ranking is public.search_kb_articles(), called on this same caller-JWT
274
+ // client. The function is SECURITY INVOKER, so RLS stays the authorization
275
+ // boundary; `audiences` is the same narrowing filter as the old select
276
+ // (member: ['member'], staff: ['admin','member']) and is applied again inside
277
+ // the function. A full-text miss falls back to newest-first there — still
278
+ // inside that audience list, still capped. This package does not apply that
279
+ // SQL. PGRST202 (function not in the PostgREST schema cache) means the
280
+ // operator has not applied the migration yet: fall back in-process to the
281
+ // previous newest-30 table select on the same caller-JWT client, so an
282
+ // upgrade without the RPC does not silently wipe the knowledge base. Any
283
+ // other RPC error, or a payload that is not an article array, still takes
284
+ // the fail-soft path below rather than telling the model the library is empty.
278
285
  const kbAudiences = actorType === 'staff' ? ['admin', 'member'] : ['member'];
279
- const { data: kbRows, error: kbErr } = await reader
280
- .from('kb_articles')
281
- .select('slug,title,audience,tool,tags,body_markdown')
282
- .in('audience', kbAudiences)
283
- .order('updated_at', { ascending: false })
284
- .limit(KB_LIMIT);
286
+ let { data: kbRows, error: kbErr } = await reader.rpc('search_kb_articles', {
287
+ q: question,
288
+ audiences: kbAudiences,
289
+ max_rows: 8,
290
+ });
291
+ if (kbErr?.code === 'PGRST202') {
292
+ console.warn('[conductor] search_kb_articles missing (PGRST202); falling back to newest-30 table select');
293
+ const fallback = await reader
294
+ .from('kb_articles')
295
+ .select('slug,title,audience,tool,tags,body_markdown')
296
+ .in('audience', kbAudiences)
297
+ .order('updated_at', { ascending: false })
298
+ .limit(30);
299
+ kbRows = fallback.data;
300
+ kbErr = fallback.error;
301
+ }
302
+ // null / non-array is "returned nothing", distinct from a real empty list
303
+ // (no articles in this audience). Only the former is a failed load.
304
+ const kbList = Array.isArray(kbRows) ? kbRows : null;
285
305
  if (kbErr)
286
306
  console.warn('[conductor] kb_articles read failed', kbErr.message);
307
+ else if (kbList === null)
308
+ console.warn('[conductor] kb_articles read failed', 'search_kb_articles returned nothing');
309
+ const kbUnavailable = Boolean(kbErr) || kbList === null;
287
310
  // Own-record context is member-only in v1. Staff Conductor answers
288
311
  // wayfinding from kb_articles only — there is no "which member" input, and
289
312
  // building a staff member-lookup is explicitly out of scope.
@@ -337,10 +360,10 @@ export async function handle(req, operator) {
337
360
  const open = `<<<${fence}>>>`;
338
361
  const close = `<<<END ${fence}>>>`;
339
362
  const fenced = (label, body) => [`## ${label}`, open, body, close].join('\n');
340
- const kbBlock = kbErr
363
+ const kbBlock = kbUnavailable
341
364
  ? '(Help articles could NOT be loaded for this request. This is not a statement that none exist.)'
342
- : (kbRows ?? []).length
343
- ? (kbRows ?? [])
365
+ : kbList.length
366
+ ? kbList
344
367
  .map((a) => {
345
368
  const tags = Array.isArray(a.tags) ? a.tags.join(', ') : '';
346
369
  return [
@@ -6,6 +6,7 @@ import { resolvePortalSessionEmail } from '../portalSession.js';
6
6
  import { logOps } from '../ops.js';
7
7
  import { deriveReservationWifiCode, isReservationWifiRoom } from '../reservationWifiCode.js';
8
8
  import { buildCancellationCreditGrants } from '../rescheduleCredit.js';
9
+ import { sha256Hex, signBusMessage } from '../busSignature.js';
9
10
  const corsHeaders = {
10
11
  'Access-Control-Allow-Origin': '*',
11
12
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -19,6 +20,68 @@ function json(status, body) {
19
20
  headers: { ...corsHeaders, 'Content-Type': 'application/json' },
20
21
  });
21
22
  }
23
+ // Same "e1" HMAC scheme as event-access-admin.ts's signE1 (identical secret,
24
+ // signing helper, and msg shape) — see that file's own PINNED CROSS-REPO
25
+ // CONTRACT note. Duplicated rather than imported: event-access-admin.ts's
26
+ // version is a module-private function, not exported.
27
+ async function signOrganizerLinkE1(secret, verb, ts, bodyHashHex) {
28
+ const msg = ['e1', verb, ts, bodyHashHex].join('\n');
29
+ return signBusMessage(msg, secret);
30
+ }
31
+ const ORGANIZER_LINK_EXPECTED_ORIGIN = 'https://ftw.granitecity.io';
32
+ async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId) {
33
+ // Every failure path logs a breadcrumb (severity 'warning', same as the
34
+ // sibling credential branch's manage_credential_unauthorized) so a broken
35
+ // contract is visible in ops_events/Slack, even though the customer-facing
36
+ // response never surfaces it -- it just gets a null url.
37
+ const fail = async (reason, detail = {}) => {
38
+ await logOps(admin, 'manage_organizer_link_mint_failed', { reason, grant_id: grantId, ...detail }, { severity: 'warning', bookingId });
39
+ return null;
40
+ };
41
+ try {
42
+ const { data: secretRaw, error: secretErr } = await admin.rpc('get_event_access_hmac_secret');
43
+ const secret = typeof secretRaw === 'string' ? secretRaw : null;
44
+ if (secretErr || !secret)
45
+ return await fail('missing_secret');
46
+ const outbound = { acting_user_id: actingUserId, grant_id: grantId };
47
+ const rawBody = JSON.stringify(outbound);
48
+ const bodyHash = await sha256Hex(rawBody);
49
+ const ts = String(Math.floor(Date.now() / 1000));
50
+ const signature = await signOrganizerLinkE1(secret, 'organizer_link', ts, bodyHash);
51
+ const res = await fetch('https://ftw.granitecity.io/admin/event-access/organizer-link', {
52
+ method: 'POST',
53
+ headers: {
54
+ 'Content-Type': 'application/json',
55
+ 'X-Event-Access-Signature': signature,
56
+ 'X-Event-Access-Timestamp': ts,
57
+ },
58
+ body: rawBody,
59
+ signal: AbortSignal.timeout(10000),
60
+ });
61
+ if (!res.ok)
62
+ return await fail('http_error', { status: res.status });
63
+ const j = await res.json().catch(() => null);
64
+ if (!j?.ok || typeof j.url !== 'string' || j.url.length === 0)
65
+ return await fail('invalid_response');
66
+ // The response isn't otherwise authenticated (no signature on the reply),
67
+ // so a compromised/misconfigured middleware could hand back an
68
+ // attacker-controlled URL. Reject anything not on the expected origin
69
+ // rather than trusting it blindly.
70
+ let origin;
71
+ try {
72
+ origin = new URL(j.url).origin;
73
+ }
74
+ catch {
75
+ origin = null;
76
+ }
77
+ if (origin !== ORGANIZER_LINK_EXPECTED_ORIGIN)
78
+ return await fail('origin_mismatch', { origin });
79
+ return j.url;
80
+ }
81
+ catch (e) {
82
+ return await fail('exception', { message: String(e) });
83
+ }
84
+ }
22
85
  function parseTstzRange(range) {
23
86
  const m = range.match(/[[(]"?([^",)]+)"?,"?([^",)]+)"?[\])]/);
24
87
  if (!m)
@@ -277,7 +340,7 @@ export async function handle(req, operator, deps) {
277
340
  try {
278
341
  const { data, error } = await admin
279
342
  .from('booking_access_grants')
280
- .select('unlock_pin,relock_pin,access_start,access_end,status')
343
+ .select('id,unlock_pin,relock_pin,access_start,access_end,status')
281
344
  .eq('booking_id', b.id).eq('status', 'active')
282
345
  .order('created_at', { ascending: false }).limit(1).maybeSingle();
283
346
  if (error || !data)
@@ -285,11 +348,22 @@ export async function handle(req, operator, deps) {
285
348
  const grant = data;
286
349
  if (!grant.unlock_pin && !grant.relock_pin)
287
350
  return json(404, { error: 'no_credential' });
351
+ // Organizer early-manual-lock/unlock link (D35 follow-up): only attempt
352
+ // the mint while the grant itself is still within its active window —
353
+ // no point minting a link for a grant that's already over. Never blocks
354
+ // or alters the PIN response: a failed/skipped mint is just a null url.
355
+ let organizerLinkUrl = null;
356
+ const grantEndMs = grant.access_end ? new Date(grant.access_end).getTime() : NaN;
357
+ const grantWithinWindow = !Number.isFinite(grantEndMs) || grantEndMs > Date.now();
358
+ if (grant.id && grantWithinWindow) {
359
+ organizerLinkUrl = await mintOrganizerLinkUrl(admin, `customer:${authedEmail}`, grant.id, b.id);
360
+ }
288
361
  return json(200, {
289
362
  unlock_pin: grant.unlock_pin ?? null,
290
363
  relock_pin: grant.relock_pin ?? null,
291
364
  valid_from_utc: grant.access_start ?? null,
292
365
  valid_to_utc: grant.access_end ?? null,
366
+ organizer_link_url: organizerLinkUrl,
293
367
  });
294
368
  }
295
369
  catch {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.9",
3
+ "version": "0.3.12",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -273,6 +273,10 @@
273
273
  "types": "./dist/tier1Agreement.d.ts",
274
274
  "default": "./dist/tier1Agreement.js"
275
275
  },
276
+ "./functions/admin-acknowledge-contract-violation": {
277
+ "types": "./dist/functions/admin-acknowledge-contract-violation.d.ts",
278
+ "default": "./dist/functions/admin-acknowledge-contract-violation.js"
279
+ },
276
280
  "./functions/admin-cancel-membership": {
277
281
  "types": "./dist/functions/admin-cancel-membership.d.ts",
278
282
  "default": "./dist/functions/admin-cancel-membership.js"