@simplelayer/graniteer-core 0.0.1 → 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,113 @@
|
|
|
1
|
+
// Pure payload parsing/decision logic for the `call_analyzed` Retell event,
|
|
2
|
+
// split out of retell-call-webhook/index.ts so it's importable and testable
|
|
3
|
+
// without booting the HTTP handler (which calls Deno.serve at module load).
|
|
4
|
+
import { z } from 'npm:zod@3.23.8';
|
|
5
|
+
|
|
6
|
+
// Outcomes the Retell agent's post-call analysis is configured to emit.
|
|
7
|
+
export const CallOutcome = z.enum([
|
|
8
|
+
'booking_completed',
|
|
9
|
+
'transferred_to_staff',
|
|
10
|
+
'transferred_to_event_day',
|
|
11
|
+
'transfer_failed_no_answer',
|
|
12
|
+
'tool_error_occurred',
|
|
13
|
+
'inquiry_only_no_action',
|
|
14
|
+
'abandoned_unclear',
|
|
15
|
+
// Added 2026-08-25: the Retell agent's post_call_analysis_data gained these
|
|
16
|
+
// two outcome values on 2026-08-24 (round 2, day pass + membership signup
|
|
17
|
+
// tools) but this enum was never updated to match. Because call_outcome is
|
|
18
|
+
// strictly typed here (not passthrough), any call_analyzed payload with one
|
|
19
|
+
// of the two missing values failed the whole zod parse, and the webhook
|
|
20
|
+
// handler silently no-opped (zero ops_events logging, zero alerting, zero
|
|
21
|
+
// fallback GHL sync) for every such call since 2026-08-24. See the
|
|
22
|
+
// gc-voice-ai-agent skill's 2026-08-25 dated log for the full incident —
|
|
23
|
+
// keep this enum in sync with the agent's real post_call_analysis_data
|
|
24
|
+
// call_outcome enum going forward; check both any time either changes.
|
|
25
|
+
'day_pass_purchased',
|
|
26
|
+
'membership_signup_completed',
|
|
27
|
+
// Added 2026-09-04, restored 2026-09-10 after an accidental removal: the
|
|
28
|
+
// agent emits this when a caller reaches us outside business hours and
|
|
29
|
+
// leaves a callback request. Missing from this enum, the whole
|
|
30
|
+
// call_analyzed payload fails to parse and the call is silently dropped
|
|
31
|
+
// (no ops_events row, no alert, no GHL fallback sync) -- see the
|
|
32
|
+
// 2026-08-25 incident note above.
|
|
33
|
+
'callback_logged_after_hours',
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
// Every field here is optional/may be absent — the agent's analysis prompt
|
|
37
|
+
// can fail to extract a field, or simply have nothing to say for it.
|
|
38
|
+
const CustomAnalysisData = z.object({
|
|
39
|
+
call_outcome: CallOutcome.optional(),
|
|
40
|
+
caller_name: z.string().max(200).optional(),
|
|
41
|
+
callback_number: z.string().max(40).optional(),
|
|
42
|
+
inquiry_reason: z.string().max(2000).optional(),
|
|
43
|
+
had_tool_error: z.boolean().optional(),
|
|
44
|
+
callback_promised: z.boolean().optional(),
|
|
45
|
+
}).partial().passthrough();
|
|
46
|
+
|
|
47
|
+
const CallAnalyzedBody = z.object({
|
|
48
|
+
event: z.literal('call_analyzed'),
|
|
49
|
+
call: z.object({
|
|
50
|
+
call_id: z.string().max(200).optional(),
|
|
51
|
+
duration_ms: z.number().optional(),
|
|
52
|
+
start_timestamp: z.number().optional(),
|
|
53
|
+
end_timestamp: z.number().optional(),
|
|
54
|
+
from_number: z.string().max(40).optional(),
|
|
55
|
+
call_analysis: z.object({
|
|
56
|
+
custom_analysis_data: CustomAnalysisData.optional(),
|
|
57
|
+
}).partial().passthrough().optional(),
|
|
58
|
+
}).partial().passthrough().optional(),
|
|
59
|
+
}).passthrough();
|
|
60
|
+
|
|
61
|
+
// Any other Retell event (call_started, call_ended, ...) — just the event
|
|
62
|
+
// name matters here; the payload otherwise passes through unread.
|
|
63
|
+
const OtherEventBody = z.object({ event: z.string() }).passthrough();
|
|
64
|
+
|
|
65
|
+
const OUTCOMES_REQUIRING_ALERT = new Set(['transfer_failed_no_answer', 'tool_error_occurred']);
|
|
66
|
+
|
|
67
|
+
export interface ParsedCallAnalyzed {
|
|
68
|
+
callId: string | null;
|
|
69
|
+
callOutcome: z.infer<typeof CallOutcome> | null;
|
|
70
|
+
callerName: string | null;
|
|
71
|
+
callbackNumber: string | null;
|
|
72
|
+
inquiryReason: string | null;
|
|
73
|
+
hadToolError: boolean | null;
|
|
74
|
+
durationMs: number | null;
|
|
75
|
+
needsAlert: boolean;
|
|
76
|
+
fromNumber: string | null;
|
|
77
|
+
callbackPromised: boolean | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** True for the "act on this" event; false for any other Retell event type. */
|
|
81
|
+
export function isCallAnalyzedEvent(raw: unknown): boolean {
|
|
82
|
+
const parsed = OtherEventBody.safeParse(raw);
|
|
83
|
+
return parsed.success && parsed.data.event === 'call_analyzed';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Returns null if `raw` isn't a well-formed call_analyzed payload. */
|
|
87
|
+
export function parseCallAnalyzed(raw: unknown): ParsedCallAnalyzed | null {
|
|
88
|
+
const parsed = CallAnalyzedBody.safeParse(raw);
|
|
89
|
+
if (!parsed.success) return null;
|
|
90
|
+
|
|
91
|
+
const call = parsed.data.call ?? {};
|
|
92
|
+
const data = call.call_analysis?.custom_analysis_data ?? {};
|
|
93
|
+
const durationMs = call.duration_ms
|
|
94
|
+
?? (typeof call.start_timestamp === 'number' && typeof call.end_timestamp === 'number'
|
|
95
|
+
? call.end_timestamp - call.start_timestamp
|
|
96
|
+
: null);
|
|
97
|
+
|
|
98
|
+
const badOutcome = data.call_outcome !== undefined && OUTCOMES_REQUIRING_ALERT.has(data.call_outcome);
|
|
99
|
+
const needsAlert = badOutcome || data.had_tool_error === true;
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
callId: call.call_id ?? null,
|
|
103
|
+
callOutcome: data.call_outcome ?? null,
|
|
104
|
+
callerName: data.caller_name ?? null,
|
|
105
|
+
callbackNumber: data.callback_number ?? null,
|
|
106
|
+
inquiryReason: data.inquiry_reason ?? null,
|
|
107
|
+
hadToolError: data.had_tool_error ?? null,
|
|
108
|
+
durationMs,
|
|
109
|
+
needsAlert,
|
|
110
|
+
fromNumber: call.from_number ?? null,
|
|
111
|
+
callbackPromised: data.callback_promised ?? null,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { assert, assertEquals, assertFalse } from 'https://deno.land/std@0.224.0/assert/mod.ts';
|
|
2
|
+
import {
|
|
3
|
+
computeRetellSignature,
|
|
4
|
+
timingSafeEqualHex,
|
|
5
|
+
verifyRetellSignature,
|
|
6
|
+
RETELL_SIGNATURE_HEADER,
|
|
7
|
+
RETELL_MAX_SKEW_MS,
|
|
8
|
+
} from './retellSignature.ts';
|
|
9
|
+
|
|
10
|
+
const SECRET = 'test-signing-secret';
|
|
11
|
+
const BODY = JSON.stringify({ event: 'call_analyzed', call: { call_id: 'call_123' } });
|
|
12
|
+
|
|
13
|
+
function withEnv(key: string, value: string | undefined, fn: () => Promise<void> | void) {
|
|
14
|
+
const prev = Deno.env.get(key);
|
|
15
|
+
if (value === undefined) Deno.env.delete(key);
|
|
16
|
+
else Deno.env.set(key, value);
|
|
17
|
+
return (async () => {
|
|
18
|
+
try {
|
|
19
|
+
await fn();
|
|
20
|
+
} finally {
|
|
21
|
+
if (prev === undefined) Deno.env.delete(key);
|
|
22
|
+
else Deno.env.set(key, prev);
|
|
23
|
+
}
|
|
24
|
+
})();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function signedRequest(secret: string, body: string, tsMs: number): Promise<Request> {
|
|
28
|
+
const ts = String(tsMs);
|
|
29
|
+
const digest = await computeRetellSignature(secret, body, ts);
|
|
30
|
+
return new Request('https://example.com/retell-call-webhook', {
|
|
31
|
+
method: 'POST',
|
|
32
|
+
headers: { [RETELL_SIGNATURE_HEADER]: `v=${ts},d=${digest}` },
|
|
33
|
+
body,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
Deno.test('timingSafeEqualHex: equal strings match', () => {
|
|
38
|
+
assert(timingSafeEqualHex('abc123', 'abc123'));
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
Deno.test('timingSafeEqualHex: differing strings do not match', () => {
|
|
42
|
+
assertFalse(timingSafeEqualHex('abc123', 'abc124'));
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
Deno.test('timingSafeEqualHex: differing lengths do not match', () => {
|
|
46
|
+
assertFalse(timingSafeEqualHex('abc123', 'abc12'));
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
Deno.test('verifyRetellSignature: no-op (returns true) when secret unset', async () => {
|
|
50
|
+
await withEnv('RETELL_SIGNING_SECRET', undefined, async () => {
|
|
51
|
+
const req = new Request('https://example.com/x', { method: 'POST', body: BODY });
|
|
52
|
+
assert(await verifyRetellSignature(req, BODY, 'test-caller'));
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
Deno.test('verifyRetellSignature: accepts a correctly signed request', async () => {
|
|
57
|
+
await withEnv('RETELL_SIGNING_SECRET', SECRET, async () => {
|
|
58
|
+
const req = await signedRequest(SECRET, BODY, Date.now());
|
|
59
|
+
assert(await verifyRetellSignature(req, BODY, 'test-caller'));
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
Deno.test('verifyRetellSignature: rejects a missing signature header once secret is set', async () => {
|
|
64
|
+
await withEnv('RETELL_SIGNING_SECRET', SECRET, async () => {
|
|
65
|
+
const req = new Request('https://example.com/x', { method: 'POST', body: BODY });
|
|
66
|
+
assertFalse(await verifyRetellSignature(req, BODY, 'test-caller'));
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
Deno.test('verifyRetellSignature: rejects a tampered digest', async () => {
|
|
71
|
+
await withEnv('RETELL_SIGNING_SECRET', SECRET, async () => {
|
|
72
|
+
const ts = String(Date.now());
|
|
73
|
+
const digest = await computeRetellSignature(SECRET, BODY, ts);
|
|
74
|
+
const tampered = digest.slice(0, -1) + (digest.at(-1) === '0' ? '1' : '0');
|
|
75
|
+
const req = new Request('https://example.com/x', {
|
|
76
|
+
method: 'POST',
|
|
77
|
+
headers: { [RETELL_SIGNATURE_HEADER]: `v=${ts},d=${tampered}` },
|
|
78
|
+
body: BODY,
|
|
79
|
+
});
|
|
80
|
+
assertFalse(await verifyRetellSignature(req, BODY, 'test-caller'));
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
Deno.test('verifyRetellSignature: rejects a digest computed with the wrong secret', async () => {
|
|
85
|
+
await withEnv('RETELL_SIGNING_SECRET', SECRET, async () => {
|
|
86
|
+
const req = await signedRequest('some-other-secret', BODY, Date.now());
|
|
87
|
+
assertFalse(await verifyRetellSignature(req, BODY, 'test-caller'));
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
Deno.test('verifyRetellSignature: rejects a signature older than the replay window', async () => {
|
|
92
|
+
await withEnv('RETELL_SIGNING_SECRET', SECRET, async () => {
|
|
93
|
+
const staleTs = Date.now() - (RETELL_MAX_SKEW_MS + 60_000);
|
|
94
|
+
const req = await signedRequest(SECRET, BODY, staleTs);
|
|
95
|
+
assertFalse(await verifyRetellSignature(req, BODY, 'test-caller'));
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
Deno.test('verifyRetellSignature: rejects a malformed header', async () => {
|
|
100
|
+
await withEnv('RETELL_SIGNING_SECRET', SECRET, async () => {
|
|
101
|
+
const req = new Request('https://example.com/x', {
|
|
102
|
+
method: 'POST',
|
|
103
|
+
headers: { [RETELL_SIGNATURE_HEADER]: 'not-the-right-shape' },
|
|
104
|
+
body: BODY,
|
|
105
|
+
});
|
|
106
|
+
assertFalse(await verifyRetellSignature(req, BODY, 'test-caller'));
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
Deno.test('verifyRetellSignature: same digest is rejected if the raw body differs', async () => {
|
|
111
|
+
await withEnv('RETELL_SIGNING_SECRET', SECRET, async () => {
|
|
112
|
+
const ts = String(Date.now());
|
|
113
|
+
const digest = await computeRetellSignature(SECRET, BODY, ts);
|
|
114
|
+
const req = new Request('https://example.com/x', {
|
|
115
|
+
method: 'POST',
|
|
116
|
+
headers: { [RETELL_SIGNATURE_HEADER]: `v=${ts},d=${digest}` },
|
|
117
|
+
body: BODY + 'tampered-suffix',
|
|
118
|
+
});
|
|
119
|
+
// Pass the tampered body as the "rawBody" the caller actually read.
|
|
120
|
+
assertFalse(await verifyRetellSignature(req, BODY + 'tampered-suffix', 'test-caller'));
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
Deno.test('computeRetellSignature: matches Retell.verify\'s HMAC-SHA256(body+timestamp) construction', async () => {
|
|
125
|
+
const ts = '1700000000000';
|
|
126
|
+
const digest = await computeRetellSignature('k', 'payload', ts);
|
|
127
|
+
const key = await crypto.subtle.importKey(
|
|
128
|
+
'raw',
|
|
129
|
+
new TextEncoder().encode('k'),
|
|
130
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
131
|
+
false,
|
|
132
|
+
['sign'],
|
|
133
|
+
);
|
|
134
|
+
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode('payload' + ts));
|
|
135
|
+
const expected = Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
136
|
+
assertEquals(digest, expected);
|
|
137
|
+
});
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Shared Retell webhook signature verification, used by both `voice-booking`
|
|
2
|
+
// and `retell-call-webhook` — do not reimplement this per function.
|
|
3
|
+
//
|
|
4
|
+
// Header `X-Retell-Signature: v={unix_ms},d={hex}`; digest is
|
|
5
|
+
// HMAC-SHA256(raw_body + timestamp_string) keyed with RETELL_SIGNING_SECRET,
|
|
6
|
+
// with the timestamp used verbatim as it appears in the header. Matches
|
|
7
|
+
// Retell's `Retell.verify(body, apiKey, signature)` helper.
|
|
8
|
+
// While RETELL_SIGNING_SECRET is unset this is a no-op: one console.warn plus
|
|
9
|
+
// a best-effort Slack alert (so the gap doesn't fire silently in production
|
|
10
|
+
// with nobody noticing), and the request proceeds. Enforcement turns on by
|
|
11
|
+
// itself the moment the secret exists.
|
|
12
|
+
import { sendSlackAlert, OPS_ALERTS_CHANNEL_ID } from './slackAlert.ts';
|
|
13
|
+
|
|
14
|
+
export const RETELL_SIGNATURE_HEADER = 'X-Retell-Signature';
|
|
15
|
+
export const RETELL_MAX_SKEW_MS = 5 * 60 * 1000;
|
|
16
|
+
|
|
17
|
+
export function timingSafeEqualHex(a: string, b: string): boolean {
|
|
18
|
+
// Fixed-length walk: a length mismatch still consumes the whole loop.
|
|
19
|
+
const len = Math.max(a.length, b.length);
|
|
20
|
+
let diff = a.length ^ b.length;
|
|
21
|
+
for (let i = 0; i < len; i++) {
|
|
22
|
+
diff |= (a.charCodeAt(i) | 0) ^ (b.charCodeAt(i) | 0);
|
|
23
|
+
}
|
|
24
|
+
return diff === 0;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Computes the expected hex digest for a given raw body + header timestamp.
|
|
29
|
+
* Split out from `verifyRetellSignature` so tests can exercise the HMAC
|
|
30
|
+
* computation directly without constructing a `Request`.
|
|
31
|
+
*/
|
|
32
|
+
export async function computeRetellSignature(
|
|
33
|
+
secret: string,
|
|
34
|
+
rawBody: string,
|
|
35
|
+
timestampRaw: string,
|
|
36
|
+
): Promise<string> {
|
|
37
|
+
const key = await crypto.subtle.importKey(
|
|
38
|
+
'raw',
|
|
39
|
+
new TextEncoder().encode(secret),
|
|
40
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
41
|
+
false,
|
|
42
|
+
['sign'],
|
|
43
|
+
);
|
|
44
|
+
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(rawBody + timestampRaw));
|
|
45
|
+
return Array.from(new Uint8Array(sig))
|
|
46
|
+
.map((b) => b.toString(16).padStart(2, '0'))
|
|
47
|
+
.join('');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* `callerLabel` (e.g. 'voice-booking', 'retell-call-webhook') is only used to
|
|
52
|
+
* namespace the console.warn / Slack alert when the secret is unset.
|
|
53
|
+
*/
|
|
54
|
+
export async function verifyRetellSignature(
|
|
55
|
+
req: Request,
|
|
56
|
+
rawBody: string,
|
|
57
|
+
callerLabel: string,
|
|
58
|
+
): Promise<boolean> {
|
|
59
|
+
const secret = Deno.env.get('RETELL_SIGNING_SECRET');
|
|
60
|
+
if (!secret) {
|
|
61
|
+
console.warn(`[${callerLabel}] RETELL_SIGNING_SECRET not set — signature verification disabled`);
|
|
62
|
+
// Best-effort — must never block or throw over a missing/unreachable Slack.
|
|
63
|
+
void sendSlackAlert(
|
|
64
|
+
OPS_ALERTS_CHANNEL_ID,
|
|
65
|
+
`:warning: GC Connect *${callerLabel}* received a Retell webhook with RETELL_SIGNING_SECRET unset — signature verification is disabled.`,
|
|
66
|
+
);
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const header = req.headers.get(RETELL_SIGNATURE_HEADER);
|
|
71
|
+
if (!header) return false;
|
|
72
|
+
|
|
73
|
+
const m = /^v=(\d+),d=([0-9a-fA-F]+)$/.exec(header.trim());
|
|
74
|
+
if (!m) return false;
|
|
75
|
+
const [, tsRaw, provided] = m;
|
|
76
|
+
|
|
77
|
+
const ts = Number(tsRaw);
|
|
78
|
+
if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > RETELL_MAX_SKEW_MS) return false;
|
|
79
|
+
|
|
80
|
+
const expected = await computeRetellSignature(secret, rawBody, tsRaw);
|
|
81
|
+
return timingSafeEqualHex(expected, provided.toLowerCase());
|
|
82
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small reusable Slack alert helper. Posts via chat.postMessage using the
|
|
3
|
+
* SLACK_BOT_TOKEN secret. Never throws and never blocks its caller on a
|
|
4
|
+
* Slack outage — a missed alert must never turn into a 500 for whatever
|
|
5
|
+
* triggered it.
|
|
6
|
+
*
|
|
7
|
+
* Distinct from `_shared/ops.ts`'s own built-in Slack fallback (which reads
|
|
8
|
+
* OPS_ALERT_SLACK_CHANNEL_ID and only fires for severity:'error' rows): this
|
|
9
|
+
* helper always posts to an explicit channel id, for call sites that need a
|
|
10
|
+
* guaranteed destination regardless of whether that env var is configured.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
// #ops-alerts
|
|
14
|
+
export const OPS_ALERTS_CHANNEL_ID = 'C0BQDT4L197';
|
|
15
|
+
|
|
16
|
+
export async function sendSlackAlert(channelId: string, text: string): Promise<void> {
|
|
17
|
+
const token = Deno.env.get('SLACK_BOT_TOKEN');
|
|
18
|
+
if (!token) {
|
|
19
|
+
console.warn('[slackAlert] SLACK_BOT_TOKEN not set — skipping alert:', text);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
const res = await fetch('https://slack.com/api/chat.postMessage', {
|
|
24
|
+
method: 'POST',
|
|
25
|
+
headers: {
|
|
26
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
27
|
+
Authorization: `Bearer ${token}`,
|
|
28
|
+
},
|
|
29
|
+
body: JSON.stringify({ channel: channelId, text }),
|
|
30
|
+
});
|
|
31
|
+
const body = await res.json().catch(() => null) as { ok?: boolean; error?: string } | null;
|
|
32
|
+
if (!body?.ok) {
|
|
33
|
+
console.warn('[slackAlert] chat.postMessage failed:', body?.error ?? `http_${res.status}`);
|
|
34
|
+
}
|
|
35
|
+
} catch (e) {
|
|
36
|
+
console.warn('[slackAlert] chat.postMessage error:', e);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// TEST-ONLY recording fake for a Supabase/PostgREST client.
|
|
2
|
+
//
|
|
3
|
+
// Generic — no tenant or feature-specific knowledge. Implements no transport
|
|
4
|
+
// of any kind: no fetch, no sockets. Extracted 2026-09-15 from what was
|
|
5
|
+
// migrationCheckoutFakes.ts, which bundled this generic Supabase double with
|
|
6
|
+
// migration-checkout-specific Stripe fakes; the Stripe half (and the whole
|
|
7
|
+
// migration-checkout feature) was dropped from this package per a Kyle
|
|
8
|
+
// decision (migrationCheckout* stays GC-only, not ported to core) — this
|
|
9
|
+
// file is the reusable part that survived the split.
|
|
10
|
+
|
|
11
|
+
export interface RecordedDbCall {
|
|
12
|
+
table: string;
|
|
13
|
+
op: 'select' | 'insert' | 'update' | 'delete' | 'none';
|
|
14
|
+
columns?: string;
|
|
15
|
+
payload?: unknown;
|
|
16
|
+
filters: Array<{ kind: string; args: unknown[] }>;
|
|
17
|
+
terminal: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface RecordedRpcCall {
|
|
21
|
+
fn: string;
|
|
22
|
+
args: unknown;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface DbResult {
|
|
26
|
+
data: unknown;
|
|
27
|
+
error: { message: string; code?: string } | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type DbResponder = (call: RecordedDbCall) => DbResult;
|
|
31
|
+
export type RpcResponder = (call: RecordedRpcCall) => DbResult;
|
|
32
|
+
|
|
33
|
+
const OK: DbResult = { data: null, error: null };
|
|
34
|
+
|
|
35
|
+
class FakeQuery implements PromiseLike<DbResult> {
|
|
36
|
+
private settled: Promise<DbResult> | null = null;
|
|
37
|
+
|
|
38
|
+
constructor(
|
|
39
|
+
private rec: RecordedDbCall,
|
|
40
|
+
private responder: DbResponder,
|
|
41
|
+
private log: RecordedDbCall[],
|
|
42
|
+
) {}
|
|
43
|
+
|
|
44
|
+
select(columns?: string): this { this.rec.op = 'select'; this.rec.columns = columns; return this; }
|
|
45
|
+
insert(payload: unknown): this { this.rec.op = 'insert'; this.rec.payload = payload; return this; }
|
|
46
|
+
update(payload: unknown): this { this.rec.op = 'update'; this.rec.payload = payload; return this; }
|
|
47
|
+
delete(): this { this.rec.op = 'delete'; return this; }
|
|
48
|
+
|
|
49
|
+
eq(...args: unknown[]): this { this.rec.filters.push({ kind: 'eq', args }); return this; }
|
|
50
|
+
neq(...args: unknown[]): this { this.rec.filters.push({ kind: 'neq', args }); return this; }
|
|
51
|
+
not(...args: unknown[]): this { this.rec.filters.push({ kind: 'not', args }); return this; }
|
|
52
|
+
in(...args: unknown[]): this { this.rec.filters.push({ kind: 'in', args }); return this; }
|
|
53
|
+
gt(...args: unknown[]): this { this.rec.filters.push({ kind: 'gt', args }); return this; }
|
|
54
|
+
gte(...args: unknown[]): this { this.rec.filters.push({ kind: 'gte', args }); return this; }
|
|
55
|
+
lt(...args: unknown[]): this { this.rec.filters.push({ kind: 'lt', args }); return this; }
|
|
56
|
+
order(...args: unknown[]): this { this.rec.filters.push({ kind: 'order', args }); return this; }
|
|
57
|
+
limit(...args: unknown[]): this { this.rec.filters.push({ kind: 'limit', args }); return this; }
|
|
58
|
+
|
|
59
|
+
maybeSingle(): Promise<DbResult> { this.rec.terminal = 'maybeSingle'; return this.resolve(); }
|
|
60
|
+
single(): Promise<DbResult> { this.rec.terminal = 'single'; return this.resolve(); }
|
|
61
|
+
|
|
62
|
+
then<R1 = DbResult, R2 = never>(
|
|
63
|
+
onOk?: ((v: DbResult) => R1 | PromiseLike<R1>) | null,
|
|
64
|
+
onErr?: ((e: unknown) => R2 | PromiseLike<R2>) | null,
|
|
65
|
+
): PromiseLike<R1 | R2> {
|
|
66
|
+
return this.resolve().then(onOk, onErr);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private resolve(): Promise<DbResult> {
|
|
70
|
+
if (!this.settled) {
|
|
71
|
+
this.log.push(this.rec);
|
|
72
|
+
let out: DbResult;
|
|
73
|
+
try {
|
|
74
|
+
out = this.responder(this.rec) ?? OK;
|
|
75
|
+
} catch (e) {
|
|
76
|
+
return Promise.reject(e);
|
|
77
|
+
}
|
|
78
|
+
this.settled = Promise.resolve(out);
|
|
79
|
+
}
|
|
80
|
+
return this.settled;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface FakeSupabase {
|
|
85
|
+
from(table: string): FakeQuery;
|
|
86
|
+
rpc(fn: string, args?: unknown): Promise<DbResult>;
|
|
87
|
+
/** Every PostgREST call made, in order. */
|
|
88
|
+
readonly dbCalls: RecordedDbCall[];
|
|
89
|
+
/** Every .rpc() call made, in order. */
|
|
90
|
+
readonly rpcCalls: RecordedRpcCall[];
|
|
91
|
+
/** Convenience: db calls against one table. */
|
|
92
|
+
callsTo(table: string): RecordedDbCall[];
|
|
93
|
+
/** Convenience: writes (insert/update/delete) against one table. */
|
|
94
|
+
writesTo(table: string): RecordedDbCall[];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function makeFakeSupabase(opts: {
|
|
98
|
+
db?: DbResponder;
|
|
99
|
+
rpc?: RpcResponder;
|
|
100
|
+
} = {}): FakeSupabase {
|
|
101
|
+
const dbCalls: RecordedDbCall[] = [];
|
|
102
|
+
const rpcCalls: RecordedRpcCall[] = [];
|
|
103
|
+
const db = opts.db ?? (() => OK);
|
|
104
|
+
const rpc = opts.rpc ?? (() => OK);
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
dbCalls,
|
|
108
|
+
rpcCalls,
|
|
109
|
+
from(table: string) {
|
|
110
|
+
return new FakeQuery(
|
|
111
|
+
{ table, op: 'none', filters: [], terminal: 'await' },
|
|
112
|
+
db,
|
|
113
|
+
dbCalls,
|
|
114
|
+
);
|
|
115
|
+
},
|
|
116
|
+
rpc(fn: string, args?: unknown) {
|
|
117
|
+
const call: RecordedRpcCall = { fn, args };
|
|
118
|
+
rpcCalls.push(call);
|
|
119
|
+
return Promise.resolve(rpc(call) ?? OK);
|
|
120
|
+
},
|
|
121
|
+
callsTo(table: string) { return dbCalls.filter((c) => c.table === table); },
|
|
122
|
+
writesTo(table: string) {
|
|
123
|
+
return dbCalls.filter((c) => c.table === table && c.op !== 'select' && c.op !== 'none');
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Reads the value an `update` payload set for one column, or `undefined`. */
|
|
129
|
+
export function updatedValue(call: RecordedDbCall, column: string): unknown {
|
|
130
|
+
return (call.payload as Record<string, unknown> | undefined)?.[column];
|
|
131
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
2
|
+
|
|
3
|
+
type SupabaseLike = SupabaseClient<any, 'public', any>;
|
|
4
|
+
|
|
5
|
+
export const TERMS_BUCKET = 'contract-templates';
|
|
6
|
+
export const TIER1_TERMS_DIR = 'booking-terms/tier1';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Authoritative contract tier for a room, resolved in the DATABASE via
|
|
10
|
+
* public.resolve_room_contract_tier() -> private.room_contract_tier().
|
|
11
|
+
* Never derive tier from client input or from rooms.booking_mode.
|
|
12
|
+
* Returns null when the room is not contract-mapped.
|
|
13
|
+
*/
|
|
14
|
+
export async function resolveContractTier(
|
|
15
|
+
supabase: SupabaseLike,
|
|
16
|
+
roomId: string,
|
|
17
|
+
): Promise<number | null> {
|
|
18
|
+
const { data, error } = await supabase.rpc('resolve_room_contract_tier', { p_room_id: roomId });
|
|
19
|
+
if (error) throw error;
|
|
20
|
+
return data === null || data === undefined ? null : Number(data);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function sha256Hex(bytes: Uint8Array): Promise<string> {
|
|
24
|
+
const digest = await crypto.subtle.digest('SHA-256', bytes as unknown as BufferSource);
|
|
25
|
+
return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface Tier1Terms {
|
|
29
|
+
version: string;
|
|
30
|
+
path: string;
|
|
31
|
+
content_sha256: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Loads the current Tier 1 terms artifact and hashes the EXACT bytes we served.
|
|
36
|
+
* The hash is always computed here — a client-supplied hash is never accepted.
|
|
37
|
+
* `declaredVersion` (what the browser rendered) must equal the manifest's
|
|
38
|
+
* current_version, otherwise the caller must reject with `terms_version_stale`.
|
|
39
|
+
*/
|
|
40
|
+
export async function loadTier1Terms(
|
|
41
|
+
supabase: SupabaseLike,
|
|
42
|
+
declaredVersion: string | null,
|
|
43
|
+
): Promise<
|
|
44
|
+
| { ok: true; terms: Tier1Terms }
|
|
45
|
+
| { ok: false; error: 'terms_unavailable' | 'terms_version_stale'; current_version?: string }
|
|
46
|
+
> {
|
|
47
|
+
const manifestRes = await supabase.storage.from(TERMS_BUCKET).download(`${TIER1_TERMS_DIR}/manifest.json`);
|
|
48
|
+
if (manifestRes.error || !manifestRes.data) return { ok: false, error: 'terms_unavailable' };
|
|
49
|
+
let current: string;
|
|
50
|
+
try {
|
|
51
|
+
const parsed = JSON.parse(await manifestRes.data.text()) as { current_version?: string };
|
|
52
|
+
if (!parsed.current_version) return { ok: false, error: 'terms_unavailable' };
|
|
53
|
+
current = parsed.current_version;
|
|
54
|
+
} catch {
|
|
55
|
+
return { ok: false, error: 'terms_unavailable' };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (declaredVersion !== null && declaredVersion !== current) {
|
|
59
|
+
return { ok: false, error: 'terms_version_stale', current_version: current };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const path = `${TIER1_TERMS_DIR}/${current}.md`;
|
|
63
|
+
const docRes = await supabase.storage.from(TERMS_BUCKET).download(path);
|
|
64
|
+
if (docRes.error || !docRes.data) return { ok: false, error: 'terms_unavailable' };
|
|
65
|
+
const bytes = new Uint8Array(await docRes.data.arrayBuffer());
|
|
66
|
+
|
|
67
|
+
return { ok: true, terms: { version: current, path, content_sha256: await sha256Hex(bytes) } };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface Tier1AgreementInput {
|
|
71
|
+
bookingId: string;
|
|
72
|
+
roomSlug: string | null;
|
|
73
|
+
terms: Tier1Terms;
|
|
74
|
+
// How the acceptance was captured. Omitted (every existing web-checkout
|
|
75
|
+
// caller) defaults to 'click_through' — that default must never change
|
|
76
|
+
// for a caller that doesn't pass this.
|
|
77
|
+
method?: 'click_through' | 'phone_verbal';
|
|
78
|
+
signerName: string | null;
|
|
79
|
+
signerEmail: string | null;
|
|
80
|
+
signerIp: string | null;
|
|
81
|
+
signerUserAgent: string | null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Records the Tier 1 acceptance. `booking_agreements.booking_id` is
|
|
86
|
+
* UNIQUE, so a duplicate insert (retry / reschedule re-entry) is a no-op.
|
|
87
|
+
*/
|
|
88
|
+
export async function insertTier1Agreement(
|
|
89
|
+
supabase: SupabaseLike,
|
|
90
|
+
input: Tier1AgreementInput,
|
|
91
|
+
): Promise<{ error: string | null }> {
|
|
92
|
+
const nowIso = new Date().toISOString();
|
|
93
|
+
const { error } = await supabase.from('booking_agreements').insert({
|
|
94
|
+
booking_id: input.bookingId,
|
|
95
|
+
tier: 1,
|
|
96
|
+
tier_source: 'mapped',
|
|
97
|
+
room_slug_at_capture: input.roomSlug,
|
|
98
|
+
capture_method: input.method ?? 'click_through',
|
|
99
|
+
status: 'completed',
|
|
100
|
+
completed_at: nowIso,
|
|
101
|
+
document_version: input.terms.version,
|
|
102
|
+
content_sha256: input.terms.content_sha256,
|
|
103
|
+
content_url: `${TERMS_BUCKET}/${input.terms.path}`,
|
|
104
|
+
signer_name: input.signerName,
|
|
105
|
+
signer_email: input.signerEmail,
|
|
106
|
+
signer_ip: input.signerIp,
|
|
107
|
+
signer_user_agent: input.signerUserAgent,
|
|
108
|
+
} as never);
|
|
109
|
+
// 23505 = booking already has an agreement row; treat as success.
|
|
110
|
+
const code = (error as { code?: string } | null)?.code;
|
|
111
|
+
if (error && code !== '23505') return { error: error.message };
|
|
112
|
+
return { error: null };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** First hop of x-forwarded-for, matching _shared/rateLimit.ts's clientIp(). */
|
|
116
|
+
export function signerIpFrom(req: Request): string | null {
|
|
117
|
+
const xff = req.headers.get('x-forwarded-for');
|
|
118
|
+
const first = xff?.split(',')[0]?.trim();
|
|
119
|
+
return first && first.length > 0 ? first : null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function signerUserAgentFrom(req: Request): string | null {
|
|
123
|
+
const ua = req.headers.get('user-agent');
|
|
124
|
+
return ua ? ua.slice(0, 500) : null;
|
|
125
|
+
}
|