@simplelayer/graniteer-core 0.3.10 → 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
|
+
}
|
|
@@ -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.
|
|
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"
|