@simplelayer/graniteer-core 0.0.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +169 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/agreementCheckout.ts +250 -0
- package/src/agreementPortalEmail.ts +128 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/billingPortalLinkEmail.ts +117 -0
- package/src/bookingAgreementEmail.ts +149 -0
- package/src/bookingEffects.ts +388 -0
- package/src/bookingHoldReclaim.ts +94 -0
- package/src/busClient.ts +268 -0
- package/src/busSignature.ts +71 -0
- package/src/checkoutCoupon.test.ts +675 -0
- package/src/checkoutCoupon.ts +455 -0
- package/src/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/commonsDeposit.ts +298 -0
- package/src/commonsDepositWebhook.ts +237 -0
- package/src/conductorAdmin.ts +141 -0
- package/src/dayPassConfirmation.ts +230 -0
- package/src/dunningEmails.test.ts +263 -0
- package/src/dunningEmails.ts +203 -0
- package/src/email-templates/brand.ts +93 -0
- package/src/email-templates/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/magic-link.tsx +59 -0
- package/src/email-templates/reauthentication.tsx +60 -0
- package/src/email-templates/recovery.tsx +59 -0
- package/src/email-templates/signup.tsx +67 -0
- package/src/functions/admin-cancel-membership.ts +311 -0
- package/src/functions/admin-change-membership-plan.ts +312 -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-booking.ts +460 -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-issue-day-pass.ts +231 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- package/src/functions/admin-mint-billing-portal-link.ts +168 -0
- package/src/functions/admin-mint-portal-link.ts +62 -0
- package/src/functions/admin-photo-upload.ts +128 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- package/src/functions/admin-request-trial.ts +366 -0
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
- package/src/functions/admin-reset-mfa.ts +138 -0
- package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
- package/src/functions/admin-retry-invoice-payment.ts +333 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
- package/src/functions/admin-revoke-agreement.ts +467 -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/auth-email-hook.ts +259 -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/booking-status.ts +149 -0
- package/src/functions/conductor.ts +505 -0
- package/src/functions/create-agreement.ts +537 -0
- package/src/functions/create-booking.ts +648 -0
- package/src/functions/create-day-pass-checkout.ts +218 -0
- package/src/functions/create-portal-session.ts +142 -0
- package/src/functions/create-subscription-checkout.test.ts +222 -0
- package/src/functions/create-subscription-checkout.ts +440 -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-admin.ts +277 -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/fetch-avatar-original.ts +457 -0
- package/src/functions/get-provider-sign-link.ts +155 -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/manage-booking.ts +472 -0
- package/src/functions/mcp.ts +67 -0
- package/src/functions/member-door-action.test.ts +1248 -0
- package/src/functions/member-door-action.ts +863 -0
- package/src/functions/member-unifi-mapping.test.ts +516 -0
- package/src/functions/member-unifi-mapping.ts +206 -0
- package/src/functions/membership-door-sync.ts +956 -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/portal-request-login.ts +192 -0
- package/src/functions/portal-resend-invite.ts +248 -0
- package/src/functions/portal-submit-event.ts +168 -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/push-send.ts +348 -0
- package/src/functions/push-test.ts +234 -0
- package/src/functions/request-portal-link.ts +211 -0
- package/src/functions/reschedule-booking.ts +649 -0
- package/src/functions/review-ratings.ts +113 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -0
- package/src/functions/space-availability-range.ts +142 -0
- package/src/functions/stripe-db-reconcile.ts +319 -0
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
- package/src/functions/stripe-webhook.ts +2595 -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/touch-pass-signup.ts +478 -0
- package/src/functions/upload-booking-display-image.ts +179 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- package/src/functions/voice-booking.ts +453 -0
- package/src/functions/voice-day-pass.ts +346 -0
- package/src/functions/voice-inquiry.test.ts +301 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-membership-signup.ts +355 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/functions/voice-tour-booking.ts +429 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlEventInquiry.ts +143 -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/mailArrivalEmail.ts +121 -0
- package/src/manageToken.ts +363 -0
- package/src/membership.ts +109 -0
- package/src/membershipBusClient.ts +537 -0
- package/src/membershipWelcome.ts +683 -0
- package/src/migrationCheckout.ts +366 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +88 -0
- package/src/paymentLinkEmail.ts +123 -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/signedUnpaidReminderEmail.test.ts +246 -0
- package/src/signedUnpaidReminderEmail.ts +132 -0
- package/src/slackAlert.ts +38 -0
- package/src/stripeCoworkingPortal.ts +91 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/supportTicketEmail.ts +119 -0
- package/src/tier1Agreement.ts +125 -0
- package/src/unifiAccessPolicies.ts +228 -0
- package/src/unifiGroups.ts +129 -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,246 @@
|
|
|
1
|
+
// Unit tests for signedUnpaidReminderEmail.ts: sendSignedUnpaidReminderEmail's
|
|
2
|
+
// GHL upsert+send outcomes, escaping, and content shape.
|
|
3
|
+
//
|
|
4
|
+
// Run with:
|
|
5
|
+
// deno test --node-modules-dir=auto --allow-env --allow-net --allow-read \
|
|
6
|
+
// src/signedUnpaidReminderEmail.test.ts
|
|
7
|
+
//
|
|
8
|
+
// NO REAL NETWORK, NO REAL DB: fetch is a global stub (same style as
|
|
9
|
+
// dunningEmails.test.ts) and the Supabase client is a minimal in-memory stub
|
|
10
|
+
// that only supports what sendSignedUnpaidReminderEmail actually calls
|
|
11
|
+
// (ops_events inserts via logOps).
|
|
12
|
+
import { assert, assertEquals } from 'https://deno.land/std@0.224.0/assert/mod.ts';
|
|
13
|
+
import { sendSignedUnpaidReminderEmail } from './signedUnpaidReminderEmail.ts';
|
|
14
|
+
|
|
15
|
+
const EMAIL = 'tenant@example.com';
|
|
16
|
+
const PORTAL_URL = 'https://granitecity.io/agreement-portal?token=abc.def';
|
|
17
|
+
const OPERATOR = { name: 'Granite City Workspaces', shortName: 'Granite City', domain: 'granitecity.io', supportEmail: 'info@granitecity.io' };
|
|
18
|
+
|
|
19
|
+
function withEnv(overrides: Record<string, string | undefined>, fn: () => Promise<void>): Promise<void> {
|
|
20
|
+
const prior: Record<string, string | undefined> = {};
|
|
21
|
+
for (const k of Object.keys(overrides)) prior[k] = Deno.env.get(k);
|
|
22
|
+
for (const [k, v] of Object.entries(overrides)) {
|
|
23
|
+
if (v === undefined) Deno.env.delete(k); else Deno.env.set(k, v);
|
|
24
|
+
}
|
|
25
|
+
return fn().finally(() => {
|
|
26
|
+
for (const [k, v] of Object.entries(prior)) {
|
|
27
|
+
if (v === undefined) Deno.env.delete(k); else Deno.env.set(k, v);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// deno-lint-ignore no-explicit-any
|
|
33
|
+
function stubClient(): { client: any; opsEvents: Array<Record<string, unknown>> } {
|
|
34
|
+
const opsEvents: Array<Record<string, unknown>> = [];
|
|
35
|
+
const builder = (table: string) => ({
|
|
36
|
+
insert: (p: Record<string, unknown>) => {
|
|
37
|
+
if (table === 'ops_events') opsEvents.push(p);
|
|
38
|
+
return Promise.resolve({ data: null, error: null });
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
return { client: { from: (table: string) => builder(table) }, opsEvents };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
Deno.test('sendSignedUnpaidReminderEmail: GHL not configured -> skipped, no network call', async () => {
|
|
45
|
+
await withEnv({ GHL_API_KEY: undefined, GHL_LOCATION_ID: undefined }, async () => {
|
|
46
|
+
const stub = stubClient();
|
|
47
|
+
let fetchCalled = false;
|
|
48
|
+
const original = globalThis.fetch;
|
|
49
|
+
// deno-lint-ignore no-explicit-any
|
|
50
|
+
(globalThis as any).fetch = async () => { fetchCalled = true; return new Response('{}', { status: 200 }); };
|
|
51
|
+
let result: string;
|
|
52
|
+
try {
|
|
53
|
+
result = await sendSignedUnpaidReminderEmail(stub.client, { email: EMAIL, portalUrl: PORTAL_URL }, OPERATOR);
|
|
54
|
+
} finally {
|
|
55
|
+
globalThis.fetch = original;
|
|
56
|
+
}
|
|
57
|
+
assertEquals(result, 'skipped');
|
|
58
|
+
assert(!fetchCalled, 'must not call GHL when unconfigured');
|
|
59
|
+
assertEquals(stub.opsEvents.length, 1);
|
|
60
|
+
assertEquals(stub.opsEvents[0].kind, 'agreement_signed_unpaid_reminder_skipped');
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
Deno.test('sendSignedUnpaidReminderEmail: happy path -> sent, correct tags/contactId/portal link', async () => {
|
|
65
|
+
await withEnv({ GHL_API_KEY: 'key123', GHL_LOCATION_ID: 'loc123' }, async () => {
|
|
66
|
+
const stub = stubClient();
|
|
67
|
+
const calls: Array<{ url: string; body: Record<string, unknown> }> = [];
|
|
68
|
+
const original = globalThis.fetch;
|
|
69
|
+
// deno-lint-ignore no-explicit-any
|
|
70
|
+
(globalThis as any).fetch = async (input: string | URL | Request, init?: RequestInit) => {
|
|
71
|
+
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
|
72
|
+
const body = init?.body ? JSON.parse(init.body as string) : {};
|
|
73
|
+
calls.push({ url, body });
|
|
74
|
+
if (url.endsWith('/contacts/upsert')) {
|
|
75
|
+
return new Response(JSON.stringify({ contact: { id: 'contact-1' } }), { status: 200 });
|
|
76
|
+
}
|
|
77
|
+
return new Response(JSON.stringify({ ok: true }), { status: 200 });
|
|
78
|
+
};
|
|
79
|
+
let result: string;
|
|
80
|
+
try {
|
|
81
|
+
result = await sendSignedUnpaidReminderEmail(stub.client, {
|
|
82
|
+
email: EMAIL, name: 'Jamie Rivera', portalUrl: PORTAL_URL, officeNumber: '204',
|
|
83
|
+
}, OPERATOR);
|
|
84
|
+
} finally {
|
|
85
|
+
globalThis.fetch = original;
|
|
86
|
+
}
|
|
87
|
+
assertEquals(result, 'sent');
|
|
88
|
+
assertEquals(calls.length, 2);
|
|
89
|
+
assertEquals(calls[0].url, 'https://services.leadconnectorhq.com/contacts/upsert');
|
|
90
|
+
assertEquals(calls[0].body.firstName, 'Jamie');
|
|
91
|
+
assertEquals(calls[0].body.lastName, 'Rivera');
|
|
92
|
+
assert((calls[0].body.tags as string[]).includes('Signed Unpaid Reminder'));
|
|
93
|
+
assertEquals(calls[1].url, 'https://services.leadconnectorhq.com/conversations/messages');
|
|
94
|
+
assertEquals(calls[1].body.contactId, 'contact-1');
|
|
95
|
+
assert((calls[1].body.html as string).includes(PORTAL_URL));
|
|
96
|
+
assert((calls[1].body.html as string).includes('office 204'));
|
|
97
|
+
assert(!(calls[1].body.html as string).includes('${'), 'no unresolved template literal should reach the sent HTML');
|
|
98
|
+
assertEquals(stub.opsEvents.length, 1);
|
|
99
|
+
assertEquals(stub.opsEvents[0].kind, 'agreement_signed_unpaid_reminder_sent');
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
Deno.test('sendSignedUnpaidReminderEmail: no name -> greets "there", CRM name omitted (never overwritten with a placeholder)', async () => {
|
|
104
|
+
await withEnv({ GHL_API_KEY: 'key123', GHL_LOCATION_ID: 'loc123' }, async () => {
|
|
105
|
+
const stub = stubClient();
|
|
106
|
+
const calls: Array<{ url: string; body: Record<string, unknown> }> = [];
|
|
107
|
+
const original = globalThis.fetch;
|
|
108
|
+
// deno-lint-ignore no-explicit-any
|
|
109
|
+
(globalThis as any).fetch = async (input: string | URL | Request, init?: RequestInit) => {
|
|
110
|
+
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
|
111
|
+
const body = init?.body ? JSON.parse(init.body as string) : {};
|
|
112
|
+
calls.push({ url, body });
|
|
113
|
+
if (url.endsWith('/contacts/upsert')) {
|
|
114
|
+
return new Response(JSON.stringify({ contact: { id: 'contact-1' } }), { status: 200 });
|
|
115
|
+
}
|
|
116
|
+
return new Response(JSON.stringify({ ok: true }), { status: 200 });
|
|
117
|
+
};
|
|
118
|
+
try {
|
|
119
|
+
await sendSignedUnpaidReminderEmail(stub.client, { email: EMAIL, name: null, portalUrl: PORTAL_URL }, OPERATOR);
|
|
120
|
+
} finally {
|
|
121
|
+
globalThis.fetch = original;
|
|
122
|
+
}
|
|
123
|
+
assertEquals(calls[0].body.firstName, undefined);
|
|
124
|
+
assertEquals(calls[0].body.lastName, undefined);
|
|
125
|
+
assert((calls[1].body.html as string).includes('Hi there,'));
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
Deno.test('sendSignedUnpaidReminderEmail: name containing HTML is escaped in the sent body', async () => {
|
|
130
|
+
await withEnv({ GHL_API_KEY: 'key123', GHL_LOCATION_ID: 'loc123' }, async () => {
|
|
131
|
+
const stub = stubClient();
|
|
132
|
+
const calls: Array<{ url: string; body: Record<string, unknown> }> = [];
|
|
133
|
+
const original = globalThis.fetch;
|
|
134
|
+
// deno-lint-ignore no-explicit-any
|
|
135
|
+
(globalThis as any).fetch = async (input: string | URL | Request, init?: RequestInit) => {
|
|
136
|
+
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
|
137
|
+
const body = init?.body ? JSON.parse(init.body as string) : {};
|
|
138
|
+
calls.push({ url, body });
|
|
139
|
+
if (url.endsWith('/contacts/upsert')) {
|
|
140
|
+
return new Response(JSON.stringify({ contact: { id: 'contact-1' } }), { status: 200 });
|
|
141
|
+
}
|
|
142
|
+
return new Response(JSON.stringify({ ok: true }), { status: 200 });
|
|
143
|
+
};
|
|
144
|
+
try {
|
|
145
|
+
await sendSignedUnpaidReminderEmail(stub.client, {
|
|
146
|
+
email: EMAIL, name: '<script>alert(1)</script>', portalUrl: PORTAL_URL,
|
|
147
|
+
}, OPERATOR);
|
|
148
|
+
} finally {
|
|
149
|
+
globalThis.fetch = original;
|
|
150
|
+
}
|
|
151
|
+
assert(!(calls[1].body.html as string).includes('<script>alert(1)</script>'));
|
|
152
|
+
assert((calls[1].body.html as string).includes('<script>'));
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
Deno.test('sendSignedUnpaidReminderEmail: GHL upsert 500 -> failed_retryable', async () => {
|
|
157
|
+
await withEnv({ GHL_API_KEY: 'key123', GHL_LOCATION_ID: 'loc123' }, async () => {
|
|
158
|
+
const stub = stubClient();
|
|
159
|
+
const original = globalThis.fetch;
|
|
160
|
+
// deno-lint-ignore no-explicit-any
|
|
161
|
+
(globalThis as any).fetch = async () => new Response('server error', { status: 500 });
|
|
162
|
+
let result: string;
|
|
163
|
+
try {
|
|
164
|
+
result = await sendSignedUnpaidReminderEmail(stub.client, { email: EMAIL, portalUrl: PORTAL_URL }, OPERATOR);
|
|
165
|
+
} finally {
|
|
166
|
+
globalThis.fetch = original;
|
|
167
|
+
}
|
|
168
|
+
assertEquals(result, 'failed_retryable');
|
|
169
|
+
assertEquals(stub.opsEvents[0].kind, 'agreement_signed_unpaid_reminder_failed');
|
|
170
|
+
assertEquals(stub.opsEvents[0].severity, 'warning');
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
Deno.test('sendSignedUnpaidReminderEmail: GHL upsert 400 -> failed_permanent', async () => {
|
|
175
|
+
await withEnv({ GHL_API_KEY: 'key123', GHL_LOCATION_ID: 'loc123' }, async () => {
|
|
176
|
+
const stub = stubClient();
|
|
177
|
+
const original = globalThis.fetch;
|
|
178
|
+
// deno-lint-ignore no-explicit-any
|
|
179
|
+
(globalThis as any).fetch = async () => new Response('bad request', { status: 400 });
|
|
180
|
+
let result: string;
|
|
181
|
+
try {
|
|
182
|
+
result = await sendSignedUnpaidReminderEmail(stub.client, { email: EMAIL, portalUrl: PORTAL_URL }, OPERATOR);
|
|
183
|
+
} finally {
|
|
184
|
+
globalThis.fetch = original;
|
|
185
|
+
}
|
|
186
|
+
assertEquals(result, 'failed_permanent');
|
|
187
|
+
assertEquals(stub.opsEvents[0].kind, 'agreement_signed_unpaid_reminder_failed');
|
|
188
|
+
assertEquals(stub.opsEvents[0].severity, 'error');
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
Deno.test('sendSignedUnpaidReminderEmail: upsert ok but conversations/messages send 429 -> failed_retryable', async () => {
|
|
193
|
+
await withEnv({ GHL_API_KEY: 'key123', GHL_LOCATION_ID: 'loc123' }, async () => {
|
|
194
|
+
const stub = stubClient();
|
|
195
|
+
const original = globalThis.fetch;
|
|
196
|
+
// deno-lint-ignore no-explicit-any
|
|
197
|
+
(globalThis as any).fetch = async (input: string | URL | Request) => {
|
|
198
|
+
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
|
199
|
+
if (url.endsWith('/contacts/upsert')) {
|
|
200
|
+
return new Response(JSON.stringify({ contact: { id: 'contact-1' } }), { status: 200 });
|
|
201
|
+
}
|
|
202
|
+
return new Response('rate limited', { status: 429 });
|
|
203
|
+
};
|
|
204
|
+
let result: string;
|
|
205
|
+
try {
|
|
206
|
+
result = await sendSignedUnpaidReminderEmail(stub.client, { email: EMAIL, portalUrl: PORTAL_URL }, OPERATOR);
|
|
207
|
+
} finally {
|
|
208
|
+
globalThis.fetch = original;
|
|
209
|
+
}
|
|
210
|
+
assertEquals(result, 'failed_retryable');
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
Deno.test('sendSignedUnpaidReminderEmail: upsert response with no contact id -> failed_permanent', async () => {
|
|
215
|
+
await withEnv({ GHL_API_KEY: 'key123', GHL_LOCATION_ID: 'loc123' }, async () => {
|
|
216
|
+
const stub = stubClient();
|
|
217
|
+
const original = globalThis.fetch;
|
|
218
|
+
// deno-lint-ignore no-explicit-any
|
|
219
|
+
(globalThis as any).fetch = async () => new Response(JSON.stringify({}), { status: 200 });
|
|
220
|
+
let result: string;
|
|
221
|
+
try {
|
|
222
|
+
result = await sendSignedUnpaidReminderEmail(stub.client, { email: EMAIL, portalUrl: PORTAL_URL }, OPERATOR);
|
|
223
|
+
} finally {
|
|
224
|
+
globalThis.fetch = original;
|
|
225
|
+
}
|
|
226
|
+
assertEquals(result, 'failed_permanent');
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
Deno.test('sendSignedUnpaidReminderEmail: AbortError (timeout) -> failed_retryable', async () => {
|
|
231
|
+
await withEnv({ GHL_API_KEY: 'key123', GHL_LOCATION_ID: 'loc123' }, async () => {
|
|
232
|
+
const stub = stubClient();
|
|
233
|
+
const original = globalThis.fetch;
|
|
234
|
+
// deno-lint-ignore no-explicit-any
|
|
235
|
+
(globalThis as any).fetch = async () => {
|
|
236
|
+
const e = new Error('aborted'); e.name = 'AbortError'; throw e;
|
|
237
|
+
};
|
|
238
|
+
let result: string;
|
|
239
|
+
try {
|
|
240
|
+
result = await sendSignedUnpaidReminderEmail(stub.client, { email: EMAIL, portalUrl: PORTAL_URL }, OPERATOR);
|
|
241
|
+
} finally {
|
|
242
|
+
globalThis.fetch = original;
|
|
243
|
+
}
|
|
244
|
+
assertEquals(result, 'failed_retryable');
|
|
245
|
+
});
|
|
246
|
+
});
|