@simplelayer/graniteer-core 0.0.2 → 0.1.2
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/index.js +2 -2
- package/package.json +98 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/bookingHoldReclaim.ts +94 -0
- package/src/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/conductorAdmin.ts +141 -0
- package/src/email-templates/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/reauthentication.tsx +60 -0
- package/src/functions/admin-cancel-membership.ts +311 -0
- package/src/functions/admin-change-membership-plan.ts +308 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- package/src/functions/admin-photo-upload.ts +128 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- package/src/functions/admin-reset-mfa.ts +138 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- package/src/functions/day-pass-status.ts +89 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- package/src/functions/get-signing-link.ts +211 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- package/src/functions/print-billing-recover.ts +97 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -0
- package/src/functions/space-availability-range.ts +142 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- package/src/functions/voice-inquiry.test.ts +301 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/membership.ts +109 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +34 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/slackAlert.ts +38 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/tier1Agreement.ts +125 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Pure, DB-free day-status math for space-availability-range. Split out from
|
|
2
|
+
// index.ts so it can be exercised directly by a standalone test without
|
|
3
|
+
// pulling in Deno.serve / the npm supabase-js client.
|
|
4
|
+
|
|
5
|
+
export type DayStatus = 'open' | 'partial' | 'full';
|
|
6
|
+
|
|
7
|
+
/** Next calendar date string (UTC-arithmetic on the YYYY-MM-DD parts only — no timezone involved). */
|
|
8
|
+
export function nextDateStr(dateStr: string): string {
|
|
9
|
+
const [y, m, d] = dateStr.split('-').map(Number);
|
|
10
|
+
const dt = new Date(Date.UTC(y, m - 1, d + 1));
|
|
11
|
+
return `${dt.getUTCFullYear()}-${String(dt.getUTCMonth() + 1).padStart(2, '0')}-${String(dt.getUTCDate()).padStart(2, '0')}`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** All calendar date strings from start to end, inclusive. Caller enforces the max-range cap. */
|
|
15
|
+
export function dateRange(start: string, end: string): string[] {
|
|
16
|
+
const dates: string[] = [];
|
|
17
|
+
let cur = start;
|
|
18
|
+
while (true) {
|
|
19
|
+
dates.push(cur);
|
|
20
|
+
if (cur === end) break;
|
|
21
|
+
cur = nextDateStr(cur);
|
|
22
|
+
}
|
|
23
|
+
return dates;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Merge overlapping/adjacent [start,end) pairs, sorted ascending. */
|
|
27
|
+
export function mergeRanges(ranges: [number, number][]): [number, number][] {
|
|
28
|
+
const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
|
|
29
|
+
const out: [number, number][] = [];
|
|
30
|
+
for (const [s, e] of sorted) {
|
|
31
|
+
const last = out[out.length - 1];
|
|
32
|
+
if (last && s <= last[1]) last[1] = Math.max(last[1], e);
|
|
33
|
+
else out.push([s, e]);
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Milliseconds of `[windowStart,windowEnd)` covered by `busy`, clipped to the
|
|
40
|
+
* window. `unparsed > 0` means some row's range could not be proven free, so
|
|
41
|
+
* (matching getBusyRangesDetailed's own doc comment for read-only "what's
|
|
42
|
+
* open" surfaces) the whole window is treated as covered rather than free.
|
|
43
|
+
*/
|
|
44
|
+
export function coveredMs(
|
|
45
|
+
busy: [number, number][],
|
|
46
|
+
unparsed: number,
|
|
47
|
+
windowStart: number,
|
|
48
|
+
windowEnd: number,
|
|
49
|
+
): number {
|
|
50
|
+
if (unparsed > 0) return windowEnd - windowStart;
|
|
51
|
+
const clipped = busy
|
|
52
|
+
.map(([s, e]) => [Math.max(s, windowStart), Math.min(e, windowEnd)] as [number, number])
|
|
53
|
+
.filter(([s, e]) => e > s);
|
|
54
|
+
return mergeRanges(clipped).reduce((sum, [s, e]) => sum + (e - s), 0);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function statusForDay(
|
|
58
|
+
bookingMode: string,
|
|
59
|
+
busy: [number, number][],
|
|
60
|
+
unparsed: number,
|
|
61
|
+
windowStart: number,
|
|
62
|
+
windowEnd: number,
|
|
63
|
+
): DayStatus {
|
|
64
|
+
const covered = coveredMs(busy, unparsed, windowStart, windowEnd);
|
|
65
|
+
if (covered <= 0) return 'open';
|
|
66
|
+
if (covered >= windowEnd - windowStart) return 'full';
|
|
67
|
+
// day_block and quote have no partial state — any busy time at all reads
|
|
68
|
+
// as full (a day_block room is whole/half-day blocks, not hourly slots;
|
|
69
|
+
// a quote room has no self-serve slots at all).
|
|
70
|
+
return bookingMode === 'hourly' ? 'partial' : 'full';
|
|
71
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import webpush from "npm:web-push@3.6.7";
|
|
2
|
+
|
|
3
|
+
function errorSummary(err: unknown) {
|
|
4
|
+
const name = err instanceof Error ? err.name : undefined;
|
|
5
|
+
const message = err instanceof Error ? err.message : String(err ?? "");
|
|
6
|
+
const stack = err instanceof Error ? (err.stack ?? "").slice(0, 500) : "";
|
|
7
|
+
return { name, message, stack };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export async function handle(req: Request): Promise<Response> {
|
|
11
|
+
try {
|
|
12
|
+
const keys = webpush.generateVAPIDKeys();
|
|
13
|
+
webpush.setVapidDetails("mailto:test@example.com", keys.publicKey, keys.privateKey);
|
|
14
|
+
// Try building a real send call against a syntactically-valid but fake
|
|
15
|
+
// subscription, so we exercise the payload-encryption code path too.
|
|
16
|
+
// We EXPECT this specific send to fail (fake endpoint/keys) — we only
|
|
17
|
+
// care whether it fails with a normal push-service HTTP error (proves
|
|
18
|
+
// the crypto/encryption path ran) vs a Deno/npm compat crash (module
|
|
19
|
+
// resolution error, "createECDH is not a function", etc).
|
|
20
|
+
let sendResult;
|
|
21
|
+
try {
|
|
22
|
+
await webpush.sendNotification(
|
|
23
|
+
{
|
|
24
|
+
endpoint: "https://fcm.googleapis.com/fcm/send/fake-diagnostic-endpoint",
|
|
25
|
+
keys: {
|
|
26
|
+
p256dh: "BCvKwB2lbVjB3Ci77vzjxvzz1LvGe1I13a-b_bB2GVSlbVjB3Ci77vzjxvzz1LvGe1I13a-b_bB2GVSlbVjB3Cg",
|
|
27
|
+
auth: "8Q5g2vzz1LvGe1I13a-b",
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
JSON.stringify({ hello: "world" })
|
|
31
|
+
);
|
|
32
|
+
sendResult = "unexpected_success";
|
|
33
|
+
} catch (sendErr) {
|
|
34
|
+
sendResult = errorSummary(sendErr);
|
|
35
|
+
}
|
|
36
|
+
return new Response(JSON.stringify({ ok: true, keygen: "ok", sendResult }), {
|
|
37
|
+
headers: { "Content-Type": "application/json" },
|
|
38
|
+
});
|
|
39
|
+
} catch (e) {
|
|
40
|
+
return new Response(JSON.stringify({ ok: false, error: errorSummary(e) }), {
|
|
41
|
+
status: 500,
|
|
42
|
+
headers: { "Content-Type": "application/json" },
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// D27 stage 1 — INTERNAL store writer for booking_access_grants / booking_access_events.
|
|
2
|
+
//
|
|
3
|
+
// Called ONLY by ftw-middleware (headless Python, droplet 24.199.109.242) over HTTPS.
|
|
4
|
+
// NEVER call this from a browser: auth is a shared secret header, not a Supabase JWT.
|
|
5
|
+
// Mirrors membership-door-sync's inbound posture, inverted direction.
|
|
6
|
+
//
|
|
7
|
+
// Door path only. This function performs zero WiFi/RADIUS work.
|
|
8
|
+
|
|
9
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
10
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
11
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
12
|
+
|
|
13
|
+
function json(status: number, body: unknown) {
|
|
14
|
+
return new Response(JSON.stringify(body), {
|
|
15
|
+
status, headers: { 'Content-Type': 'application/json' },
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function safeEqual(a: string, b: string): boolean {
|
|
20
|
+
const enc = new TextEncoder();
|
|
21
|
+
const ab = enc.encode(a), bb = enc.encode(b);
|
|
22
|
+
if (ab.length !== bb.length) return false;
|
|
23
|
+
let diff = 0;
|
|
24
|
+
for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
|
|
25
|
+
return diff === 0;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
29
|
+
|
|
30
|
+
type Args = Record<string, unknown>;
|
|
31
|
+
|
|
32
|
+
function str(v: unknown): string | null {
|
|
33
|
+
if (typeof v !== 'string') return null;
|
|
34
|
+
const t = v.trim();
|
|
35
|
+
return t === '' ? null : t;
|
|
36
|
+
}
|
|
37
|
+
function reqUuid(args: Args, k: string): string | null {
|
|
38
|
+
const v = str(args[k]);
|
|
39
|
+
return v && UUID.test(v) ? v : null;
|
|
40
|
+
}
|
|
41
|
+
function reqIso(args: Args, k: string): string | null {
|
|
42
|
+
const v = str(args[k]);
|
|
43
|
+
if (!v) return null;
|
|
44
|
+
return Number.isFinite(Date.parse(v)) ? v : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function handle(req: Request): Promise<Response> {
|
|
48
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
49
|
+
|
|
50
|
+
const provided = req.headers.get('x-event-access-store-secret');
|
|
51
|
+
if (!provided) return json(401, { ok: false, error: 'unauthorized' });
|
|
52
|
+
|
|
53
|
+
const supabase = createClient(
|
|
54
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
55
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
56
|
+
{ auth: { persistSession: false, autoRefreshToken: false } },
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
const { data: gate, error: gateErr } = await supabase.rpc('get_event_access_store_secret');
|
|
60
|
+
const expected = typeof gate === 'string' ? gate : null;
|
|
61
|
+
if (gateErr || !expected || !safeEqual(provided, expected)) {
|
|
62
|
+
return json(401, { ok: false, error: 'unauthorized' });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const [ipOk, opOk] = await Promise.all([
|
|
66
|
+
checkRateLimit(supabase, 'event-access-store-ip', clientIp(req), 600, 300),
|
|
67
|
+
checkRateLimit(supabase, 'event-access-store-global', 'middleware', 1200, 300),
|
|
68
|
+
]);
|
|
69
|
+
if (!ipOk || !opOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
70
|
+
|
|
71
|
+
let body: Record<string, unknown>;
|
|
72
|
+
try { body = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
|
|
73
|
+
|
|
74
|
+
const op = String(body.op ?? '');
|
|
75
|
+
const args = (body.args ?? {}) as Args;
|
|
76
|
+
|
|
77
|
+
const fail = async (code: string, detail: Record<string, unknown>) => {
|
|
78
|
+
await logOps(supabase, 'event_access_store_error', { op, code, ...detail }, { severity: 'error' });
|
|
79
|
+
return json(code === 'db_error' ? 500 : 400, { ok: false, error: code });
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// CAS transition helper shared by every try_* op.
|
|
83
|
+
const cas = async (grantId: string, fromStatus: string, toStatus: string, extra: Record<string, unknown> = {}) => {
|
|
84
|
+
const { data, error } = await supabase
|
|
85
|
+
.from('booking_access_grants')
|
|
86
|
+
.update({ status: toStatus, updated_at: new Date().toISOString(), ...extra })
|
|
87
|
+
.eq('id', grantId).eq('status', fromStatus)
|
|
88
|
+
.select('*').maybeSingle();
|
|
89
|
+
if (error) return { err: error.message } as const;
|
|
90
|
+
return { row: data ?? null } as const;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
switch (op) {
|
|
95
|
+
case 'insert_pending_grant': {
|
|
96
|
+
const doorId = reqUuid(args, 'door_id');
|
|
97
|
+
const grantedBy = str(args.granted_by); // now text (staff email), not uuid
|
|
98
|
+
const grantedByEmail = str(args.granted_by_email);
|
|
99
|
+
const start = reqIso(args, 'access_start');
|
|
100
|
+
const end = reqIso(args, 'access_end');
|
|
101
|
+
const bookingRaw = str(args.booking_id); // empty/whitespace treated as null
|
|
102
|
+
const bookingId = bookingRaw === null ? null : reqUuid(args, 'booking_id');
|
|
103
|
+
if (!doorId || !grantedBy || !start || !end) {
|
|
104
|
+
return await fail('invalid_args', {});
|
|
105
|
+
}
|
|
106
|
+
if (bookingRaw !== null && !bookingId) return await fail('invalid_args', {});
|
|
107
|
+
const organizerEmail = str(args.organizer_email);
|
|
108
|
+
// A17: link this grant to a real member account at write time, so
|
|
109
|
+
// it's visible under "Members can view their own booking access
|
|
110
|
+
// grants" without waiting for the one-time backfill. Guest/day-pass
|
|
111
|
+
// organizers simply won't match any membership row -- auth_user_id
|
|
112
|
+
// stays null for them, same behavior as before this change.
|
|
113
|
+
//
|
|
114
|
+
// Round-2 fix (adversarial review): this used to call
|
|
115
|
+
// .ilike('email', organizerEmail) directly on caller-supplied text
|
|
116
|
+
// over a service-role (RLS-bypassing) client. %, _, and PostgREST's
|
|
117
|
+
// own '*' alias are all live wildcards in an ilike pattern, so an
|
|
118
|
+
// organizer_email containing one of those characters -- including
|
|
119
|
+
// an ordinary address with an underscore in it -- could silently
|
|
120
|
+
// match a DIFFERENT member's row and link this grant to the wrong
|
|
121
|
+
// real person, who could then read it. There's no case-insensitive
|
|
122
|
+
// exact-match filter available without a new DB function, so this
|
|
123
|
+
// does the case-fold comparison in code instead of in a LIKE/ILIKE
|
|
124
|
+
// pattern: fetch the (small, linked-members-only) candidate set
|
|
125
|
+
// server-side, then match by exact lower() equality here. Sorted by
|
|
126
|
+
// id so the pick is deterministic in the pathological case of two
|
|
127
|
+
// membership rows sharing one lowercased email.
|
|
128
|
+
let organizerAuthUserId: string | null = null;
|
|
129
|
+
if (organizerEmail) {
|
|
130
|
+
const { data: members } = await supabase
|
|
131
|
+
.from('memberships')
|
|
132
|
+
.select('id, email, auth_user_id')
|
|
133
|
+
.not('auth_user_id', 'is', null);
|
|
134
|
+
const wanted = organizerEmail.toLowerCase();
|
|
135
|
+
const match = (members ?? [])
|
|
136
|
+
.filter((m) => typeof m.email === 'string' && m.email.toLowerCase() === wanted)
|
|
137
|
+
.sort((a, b) => String(a.id).localeCompare(String(b.id)))[0];
|
|
138
|
+
organizerAuthUserId = (match?.auth_user_id as string | undefined) ?? null;
|
|
139
|
+
}
|
|
140
|
+
const row = {
|
|
141
|
+
booking_id: bookingId,
|
|
142
|
+
door_id: doorId,
|
|
143
|
+
granted_by: grantedBy,
|
|
144
|
+
granted_by_email: grantedByEmail ? grantedByEmail.toLowerCase() : null,
|
|
145
|
+
organizer_name: str(args.organizer_name),
|
|
146
|
+
organizer_email: organizerEmail,
|
|
147
|
+
organizer_phone: str(args.organizer_phone),
|
|
148
|
+
access_start: start,
|
|
149
|
+
access_end: end,
|
|
150
|
+
idempotency_key: str(args.idempotency_key),
|
|
151
|
+
status: 'pending',
|
|
152
|
+
door_state: 'policy',
|
|
153
|
+
auth_user_id: organizerAuthUserId,
|
|
154
|
+
};
|
|
155
|
+
const { data, error } = await supabase
|
|
156
|
+
.from('booking_access_grants').insert(row).select('*').single();
|
|
157
|
+
if (error) {
|
|
158
|
+
// 23505 = unique violation: the partial unique index on live grants, or the
|
|
159
|
+
// idempotency_key unique constraint. Distinguishable for the caller.
|
|
160
|
+
if (error.code === '23505') {
|
|
161
|
+
await logOps(supabase, 'event_access_store_duplicate_grant',
|
|
162
|
+
{ booking_id: bookingId, door_id: doorId, message: error.message }, { severity: 'warning' });
|
|
163
|
+
return json(409, { ok: false, error: 'duplicate_grant' });
|
|
164
|
+
}
|
|
165
|
+
return await fail('db_error', { message: error.message });
|
|
166
|
+
}
|
|
167
|
+
return json(200, { ok: true, result: data });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
case 'try_mark_grant_active': {
|
|
171
|
+
const grantId = reqUuid(args, 'grant_id');
|
|
172
|
+
const visitorId = str(args.visitor_id);
|
|
173
|
+
if (!grantId) return await fail('invalid_args', {});
|
|
174
|
+
const r = await cas(grantId, 'pending', 'active', { visitor_id: visitorId });
|
|
175
|
+
if ('err' in r) return await fail('db_error', { message: r.err });
|
|
176
|
+
return json(200, { ok: true, result: r.row });
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
case 'try_mark_grant_terminal': {
|
|
180
|
+
const grantId = reqUuid(args, 'grant_id');
|
|
181
|
+
const status = str(args.status);
|
|
182
|
+
if (!grantId || !status || !['failed', 'expired', 'revoked', 'reconciling'].includes(status)) {
|
|
183
|
+
return await fail('invalid_args', {});
|
|
184
|
+
}
|
|
185
|
+
const r = await cas(grantId, 'pending', status);
|
|
186
|
+
if ('err' in r) return await fail('db_error', { message: r.err });
|
|
187
|
+
return json(200, { ok: true, result: r.row });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
case 'try_transition_active_to_revoked':
|
|
191
|
+
case 'try_transition_pending_to_revoked':
|
|
192
|
+
case 'try_transition_revoke_failed_to_revoked':
|
|
193
|
+
case 'try_transition_active_to_expired': {
|
|
194
|
+
const grantId = reqUuid(args, 'grant_id');
|
|
195
|
+
if (!grantId) return await fail('invalid_args', {});
|
|
196
|
+
const from = op === 'try_transition_active_to_revoked' ? 'active'
|
|
197
|
+
: op === 'try_transition_pending_to_revoked' ? 'pending'
|
|
198
|
+
: op === 'try_transition_revoke_failed_to_revoked' ? 'revoke_failed'
|
|
199
|
+
: 'active'; // try_transition_active_to_expired
|
|
200
|
+
const to = op === 'try_transition_active_to_expired' ? 'expired' : 'revoked';
|
|
201
|
+
const r = await cas(grantId, from, to);
|
|
202
|
+
if ('err' in r) return await fail('db_error', { message: r.err });
|
|
203
|
+
return json(200, { ok: true, result: r.row });
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
case 'mark_revoke_failed': {
|
|
207
|
+
const grantId = reqUuid(args, 'grant_id');
|
|
208
|
+
if (!grantId) return await fail('invalid_args', {});
|
|
209
|
+
const visitorId = str(args.visitor_id);
|
|
210
|
+
const patch: Record<string, unknown> = {
|
|
211
|
+
status: 'revoke_failed', updated_at: new Date().toISOString(),
|
|
212
|
+
};
|
|
213
|
+
if (visitorId) patch.visitor_id = visitorId; // COALESCE semantics
|
|
214
|
+
const { data, error } = await supabase
|
|
215
|
+
.from('booking_access_grants').update(patch).eq('id', grantId).select('*').maybeSingle();
|
|
216
|
+
if (error) return await fail('db_error', { message: error.message });
|
|
217
|
+
return json(200, { ok: true, result: data ?? null });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
case 'get_grant': {
|
|
221
|
+
const grantId = reqUuid(args, 'grant_id');
|
|
222
|
+
if (!grantId) return await fail('invalid_args', {});
|
|
223
|
+
const { data, error } = await supabase
|
|
224
|
+
.from('booking_access_grants').select('*').eq('id', grantId).maybeSingle();
|
|
225
|
+
if (error) return await fail('db_error', { message: error.message });
|
|
226
|
+
return json(200, { ok: true, result: data ?? null });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
case 'get_grant_by_idempotency_key': {
|
|
230
|
+
const key = str(args.idempotency_key);
|
|
231
|
+
if (!key) return await fail('invalid_args', {});
|
|
232
|
+
const { data, error } = await supabase
|
|
233
|
+
.from('booking_access_grants').select('*').eq('idempotency_key', key).maybeSingle();
|
|
234
|
+
if (error) return await fail('db_error', { message: error.message });
|
|
235
|
+
return json(200, { ok: true, result: data ?? null });
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
case 'get_active_grants_for_door': {
|
|
239
|
+
const doorId = reqUuid(args, 'door_id');
|
|
240
|
+
const nowIso = reqIso(args, 'now_iso');
|
|
241
|
+
if (!doorId || !nowIso) return await fail('invalid_args', {});
|
|
242
|
+
const { data, error } = await supabase
|
|
243
|
+
.from('booking_access_grants').select('*')
|
|
244
|
+
.eq('door_id', doorId).eq('status', 'active')
|
|
245
|
+
.lte('access_start', nowIso).gte('access_end', nowIso);
|
|
246
|
+
if (error) return await fail('db_error', { message: error.message });
|
|
247
|
+
return json(200, { ok: true, result: data ?? [] });
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
case 'get_expired_active_grants': {
|
|
251
|
+
const nowIso = reqIso(args, 'now_iso');
|
|
252
|
+
if (!nowIso) return await fail('invalid_args', {});
|
|
253
|
+
const { data, error } = await supabase
|
|
254
|
+
.from('booking_access_grants').select('*')
|
|
255
|
+
.eq('status', 'active').lt('access_end', nowIso);
|
|
256
|
+
if (error) return await fail('db_error', { message: error.message });
|
|
257
|
+
return json(200, { ok: true, result: data ?? [] });
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
case 'insert_event': {
|
|
261
|
+
const grantRaw = str(args.grant_id); // nullable: door-only actions have no grant
|
|
262
|
+
const grantId = grantRaw === null ? null : reqUuid(args, 'grant_id');
|
|
263
|
+
const doorId = reqUuid(args, 'door_id');
|
|
264
|
+
const action = str(args.action);
|
|
265
|
+
if (grantRaw !== null && !grantId) return await fail('invalid_args', {});
|
|
266
|
+
if (!doorId || !action) return await fail('invalid_args', {});
|
|
267
|
+
const actor = str(args.actor_user_id); // now text (staff email), optional
|
|
268
|
+
const row: Record<string, unknown> = {
|
|
269
|
+
grant_id: grantId,
|
|
270
|
+
door_id: doorId,
|
|
271
|
+
actor_user_id: actor,
|
|
272
|
+
action,
|
|
273
|
+
requested_state: str(args.requested_state),
|
|
274
|
+
};
|
|
275
|
+
// Outcome fields are optional at insert: absent `ok` stays NULL, meaning
|
|
276
|
+
// "attempted, outcome not yet known" (update_event fills it in later).
|
|
277
|
+
if ('api_response' in args) row.api_response = args.api_response ?? null;
|
|
278
|
+
if ('observed_state_after' in args) row.observed_state_after = str(args.observed_state_after);
|
|
279
|
+
if ('ok' in args && args.ok !== null) row.ok = args.ok === true;
|
|
280
|
+
if ('error' in args) row.error = str(args.error);
|
|
281
|
+
const { data, error } = await supabase
|
|
282
|
+
.from('booking_access_events').insert(row).select('id').single();
|
|
283
|
+
if (error) return await fail('db_error', { message: error.message });
|
|
284
|
+
return json(200, { ok: true, result: { event_id: data.id } });
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
case 'update_event': {
|
|
288
|
+
const eventId = reqUuid(args, 'event_id');
|
|
289
|
+
if (!eventId) return await fail('invalid_args', {});
|
|
290
|
+
const patch: Record<string, unknown> = {
|
|
291
|
+
api_response: args.api_response ?? null,
|
|
292
|
+
observed_state_after: str(args.observed_state_after),
|
|
293
|
+
ok: args.ok === true,
|
|
294
|
+
error: str(args.error),
|
|
295
|
+
};
|
|
296
|
+
const { error } = await supabase
|
|
297
|
+
.from('booking_access_events').update(patch).eq('id', eventId);
|
|
298
|
+
if (error) return await fail('db_error', { message: error.message });
|
|
299
|
+
return json(200, { ok: true, result: { event_id: eventId } });
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
default:
|
|
303
|
+
return await fail('unknown_op', {});
|
|
304
|
+
}
|
|
305
|
+
} catch (e) {
|
|
306
|
+
await logOps(supabase, 'event_access_store_exception', { op, message: String(e) }, { severity: 'error' });
|
|
307
|
+
return json(500, { ok: false, error: 'internal_error' });
|
|
308
|
+
}
|
|
309
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
2
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Inbound ezeep print-job webhook receiver (Phase 1 ingest).
|
|
6
|
+
*
|
|
7
|
+
* Receive -> verify Basic auth -> redact -> idempotent insert into `print_jobs`.
|
|
8
|
+
* This function NEVER touches billing tables (`print_usage_periods` et al) or
|
|
9
|
+
* Stripe; the nightly rollup owns that.
|
|
10
|
+
*
|
|
11
|
+
* Auth: ezeep only supports HTTP Basic auth on outbound webhooks — no HMAC and
|
|
12
|
+
* no signature header. Known, accepted limitation; credentials live in
|
|
13
|
+
* EZEEP_WEBHOOK_USER / EZEEP_WEBHOOK_PASS.
|
|
14
|
+
*
|
|
15
|
+
* Privacy: `content.printjob.filename` is redacted to null before anything is
|
|
16
|
+
* persisted. Document names are never stored.
|
|
17
|
+
*
|
|
18
|
+
* Retry posture: ezeep retries non-2xx deliveries for ~3 days. We return 2xx
|
|
19
|
+
* for anything a retry cannot fix (unparseable payload, schema mismatch) after
|
|
20
|
+
* recording it in `ops_events`, and 5xx only for genuinely transient DB errors.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
type Json = Record<string, unknown>;
|
|
24
|
+
|
|
25
|
+
function json(status: number, body: unknown) {
|
|
26
|
+
return new Response(JSON.stringify(body), {
|
|
27
|
+
status,
|
|
28
|
+
headers: { 'Content-Type': 'application/json' },
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Constant-time string compare (Web Crypto exposes no timingSafeEqual). */
|
|
33
|
+
function timingSafeEqual(a: string, b: string): boolean {
|
|
34
|
+
if (a.length !== b.length) return false;
|
|
35
|
+
let acc = 0;
|
|
36
|
+
for (let i = 0; i < a.length; i++) acc |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
37
|
+
return acc === 0;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function checkBasicAuth(req: Request): boolean {
|
|
41
|
+
const expectedUser = Deno.env.get('EZEEP_WEBHOOK_USER');
|
|
42
|
+
const expectedPass = Deno.env.get('EZEEP_WEBHOOK_PASS');
|
|
43
|
+
if (!expectedUser || !expectedPass) {
|
|
44
|
+
console.error(JSON.stringify({ level: 'error', kind: 'ezeep_webhook_not_configured' }));
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const header = req.headers.get('Authorization') ?? '';
|
|
49
|
+
if (!header.toLowerCase().startsWith('basic ')) return false;
|
|
50
|
+
|
|
51
|
+
let decoded: string;
|
|
52
|
+
try {
|
|
53
|
+
decoded = atob(header.slice(6).trim());
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const sep = decoded.indexOf(':');
|
|
59
|
+
if (sep < 0) return false;
|
|
60
|
+
const user = decoded.slice(0, sep);
|
|
61
|
+
const pass = decoded.slice(sep + 1);
|
|
62
|
+
|
|
63
|
+
// Both compared unconditionally so a wrong username costs the same time.
|
|
64
|
+
const userOk = timingSafeEqual(user, expectedUser);
|
|
65
|
+
const passOk = timingSafeEqual(pass, expectedPass);
|
|
66
|
+
return userOk && passOk;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isObject(v: unknown): v is Json {
|
|
70
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function str(v: unknown): string | null {
|
|
74
|
+
return typeof v === 'string' && v.length > 0 ? v : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function int(v: unknown): number | null {
|
|
78
|
+
return typeof v === 'number' && Number.isFinite(v) ? Math.trunc(v) : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function bool(v: unknown): boolean | null {
|
|
82
|
+
return typeof v === 'boolean' ? v : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** ISO timestamp or null — never throws on garbage input. */
|
|
86
|
+
function ts(v: unknown): string | null {
|
|
87
|
+
const s = str(v);
|
|
88
|
+
if (!s) return null;
|
|
89
|
+
const d = new Date(s);
|
|
90
|
+
return Number.isNaN(d.getTime()) ? null : d.toISOString();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// No CORS — this is called by ezeep's servers, not a browser.
|
|
94
|
+
export async function handle(req: Request): Promise<Response> {
|
|
95
|
+
if (req.method !== 'POST') {
|
|
96
|
+
return new Response('Method not allowed', { status: 405 });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// 1. Auth first, before reading the body at all.
|
|
100
|
+
if (!checkBasicAuth(req)) {
|
|
101
|
+
return new Response('Unauthorized', {
|
|
102
|
+
status: 401,
|
|
103
|
+
headers: { 'WWW-Authenticate': 'Basic realm="ezeep-print-webhook"' },
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const supabase = createClient(
|
|
108
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
109
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
110
|
+
{ auth: { persistSession: false, autoRefreshToken: false } },
|
|
111
|
+
);
|
|
112
|
+
const opsClient = supabase as unknown as Parameters<typeof logOps>[0];
|
|
113
|
+
|
|
114
|
+
const rawBody = await req.text();
|
|
115
|
+
|
|
116
|
+
// 2. Parse + shape check. Anything we can never parse is logged and acked.
|
|
117
|
+
let payload: Json | null = null;
|
|
118
|
+
try {
|
|
119
|
+
const parsed = JSON.parse(rawBody);
|
|
120
|
+
if (isObject(parsed)) payload = parsed;
|
|
121
|
+
} catch { /* handled below */ }
|
|
122
|
+
|
|
123
|
+
const content = payload && isObject(payload.content) ? payload.content : null;
|
|
124
|
+
const printjob = content && isObject(content.printjob) ? content.printjob : null;
|
|
125
|
+
const printjobId = printjob ? str(printjob.printjob_id) : null;
|
|
126
|
+
|
|
127
|
+
if (!payload || !printjob || !printjobId) {
|
|
128
|
+
await logOps(
|
|
129
|
+
opsClient,
|
|
130
|
+
'ezeep_webhook_unparseable',
|
|
131
|
+
{
|
|
132
|
+
reason: !payload
|
|
133
|
+
? 'body_not_json_object'
|
|
134
|
+
: !printjob
|
|
135
|
+
? 'missing_content_printjob'
|
|
136
|
+
: 'missing_printjob_id',
|
|
137
|
+
topic: payload ? str(payload.topic) : null,
|
|
138
|
+
event_id: payload ? str(payload.event_id) : null,
|
|
139
|
+
raw_body: rawBody.slice(0, 8000),
|
|
140
|
+
},
|
|
141
|
+
{ severity: 'warning' },
|
|
142
|
+
);
|
|
143
|
+
// 2xx on purpose: retrying an unparseable payload for 3 days helps nobody.
|
|
144
|
+
return json(202, { received: true, stored: false, reason: 'unparseable' });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// 3. Redact the document name before anything is persisted.
|
|
148
|
+
const redactedPrintjob: Json = { ...printjob, filename: null };
|
|
149
|
+
const redactedRaw: Json = {
|
|
150
|
+
...payload,
|
|
151
|
+
content: { ...content, printjob: redactedPrintjob },
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
// 4 + 6. Field mapping (email lowercased).
|
|
155
|
+
const email = str(printjob.user_email);
|
|
156
|
+
const row = {
|
|
157
|
+
ezeep_printjob_id: printjobId,
|
|
158
|
+
ezeep_event_id: str(payload.event_id),
|
|
159
|
+
topic: str(payload.topic),
|
|
160
|
+
user_billing_code: str(printjob.user_billing_code),
|
|
161
|
+
user_email: email ? email.toLowerCase() : null,
|
|
162
|
+
ezeep_user_id: str(printjob.user_id),
|
|
163
|
+
total_printed_pages: int(printjob.total_printed_pages),
|
|
164
|
+
total_printed_sheets: int(printjob.total_printed_sheets),
|
|
165
|
+
copies: int(printjob.copies),
|
|
166
|
+
color: bool(printjob.color),
|
|
167
|
+
duplex: str(printjob.duplex),
|
|
168
|
+
paper: str(printjob.paper),
|
|
169
|
+
printer_name: str(printjob.printer_name),
|
|
170
|
+
job_created_at: ts(printjob.job_created_at) ?? ts(printjob.created) ?? ts(payload.created),
|
|
171
|
+
raw: redactedRaw,
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
// 5. Idempotent insert — a redelivery must not duplicate or error.
|
|
175
|
+
const { error } = await supabase
|
|
176
|
+
.from('print_jobs')
|
|
177
|
+
.upsert(row as never, { onConflict: 'ezeep_printjob_id', ignoreDuplicates: true });
|
|
178
|
+
|
|
179
|
+
if (error) {
|
|
180
|
+
const code = (error as { code?: string }).code ?? null;
|
|
181
|
+
// 23505 cannot normally surface with ignoreDuplicates, but if it does the
|
|
182
|
+
// row already exists — that is success from ezeep's point of view.
|
|
183
|
+
if (code === '23505') {
|
|
184
|
+
return json(200, { received: true, stored: true, duplicate: true });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Permanent-ish failures (bad column, constraint violation, malformed
|
|
188
|
+
// value) will fail identically on every retry: log and ack.
|
|
189
|
+
const permanent = typeof code === 'string' && /^(22|23|42|PGRST)/.test(code);
|
|
190
|
+
await logOps(
|
|
191
|
+
opsClient,
|
|
192
|
+
'ezeep_webhook_error',
|
|
193
|
+
{
|
|
194
|
+
printjob_id: printjobId,
|
|
195
|
+
event_id: str(payload.event_id),
|
|
196
|
+
topic: str(payload.topic),
|
|
197
|
+
code,
|
|
198
|
+
message: error.message,
|
|
199
|
+
permanent,
|
|
200
|
+
},
|
|
201
|
+
{ severity: 'error' },
|
|
202
|
+
);
|
|
203
|
+
|
|
204
|
+
if (permanent) {
|
|
205
|
+
return json(202, { received: true, stored: false, reason: 'insert_failed' });
|
|
206
|
+
}
|
|
207
|
+
// Transient (connectivity, timeout): let ezeep retry.
|
|
208
|
+
return json(500, { received: false, error: 'db_error' });
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// 7. Fast ack. No downstream calls.
|
|
212
|
+
return json(200, { received: true, stored: true });
|
|
213
|
+
}
|