@connextar/house 0.25.4 → 0.27.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.
Files changed (102) hide show
  1. package/README.md +112 -0
  2. package/dist/inbox/inbox.d.ts +104 -0
  3. package/dist/inbox/inbox.d.ts.map +1 -0
  4. package/dist/inbox/inbox.js +178 -0
  5. package/dist/inbox/inbox.js.map +1 -0
  6. package/dist/inbox/index.d.ts +11 -0
  7. package/dist/inbox/index.d.ts.map +1 -0
  8. package/dist/inbox/index.js +11 -0
  9. package/dist/inbox/index.js.map +1 -0
  10. package/dist/inbox/use-selection.d.ts +23 -0
  11. package/dist/inbox/use-selection.d.ts.map +1 -0
  12. package/dist/inbox/use-selection.js +51 -0
  13. package/dist/inbox/use-selection.js.map +1 -0
  14. package/dist/voice/handoff.d.ts +20 -0
  15. package/dist/voice/handoff.d.ts.map +1 -0
  16. package/dist/voice/handoff.js +18 -0
  17. package/dist/voice/handoff.js.map +1 -0
  18. package/dist/voice/index.d.ts +16 -0
  19. package/dist/voice/index.d.ts.map +1 -0
  20. package/dist/voice/index.js +16 -0
  21. package/dist/voice/index.js.map +1 -0
  22. package/dist/voice/opening-hours.d.ts +23 -0
  23. package/dist/voice/opening-hours.d.ts.map +1 -0
  24. package/dist/voice/opening-hours.js +117 -0
  25. package/dist/voice/opening-hours.js.map +1 -0
  26. package/dist/voice/out-of-hours.d.ts +29 -0
  27. package/dist/voice/out-of-hours.d.ts.map +1 -0
  28. package/dist/voice/out-of-hours.js +20 -0
  29. package/dist/voice/out-of-hours.js.map +1 -0
  30. package/dist/voice/phone.d.ts +33 -0
  31. package/dist/voice/phone.d.ts.map +1 -0
  32. package/dist/voice/phone.js +62 -0
  33. package/dist/voice/phone.js.map +1 -0
  34. package/dist/voice/relay/agent-client.d.ts +24 -0
  35. package/dist/voice/relay/agent-client.d.ts.map +1 -0
  36. package/dist/voice/relay/agent-client.js +45 -0
  37. package/dist/voice/relay/agent-client.js.map +1 -0
  38. package/dist/voice/relay/model.d.ts +124 -0
  39. package/dist/voice/relay/model.d.ts.map +1 -0
  40. package/dist/voice/relay/model.js +304 -0
  41. package/dist/voice/relay/model.js.map +1 -0
  42. package/dist/voice/relay/protocol.d.ts +44 -0
  43. package/dist/voice/relay/protocol.d.ts.map +1 -0
  44. package/dist/voice/relay/protocol.js +16 -0
  45. package/dist/voice/relay/protocol.js.map +1 -0
  46. package/dist/voice/relay/sentence-gate.d.ts +24 -0
  47. package/dist/voice/relay/sentence-gate.d.ts.map +1 -0
  48. package/dist/voice/relay/sentence-gate.js +65 -0
  49. package/dist/voice/relay/sentence-gate.js.map +1 -0
  50. package/dist/voice/relay/server.d.ts +71 -0
  51. package/dist/voice/relay/server.d.ts.map +1 -0
  52. package/dist/voice/relay/server.js +192 -0
  53. package/dist/voice/relay/server.js.map +1 -0
  54. package/dist/voice/relay/transfer-line.d.ts +33 -0
  55. package/dist/voice/relay/transfer-line.d.ts.map +1 -0
  56. package/dist/voice/relay/transfer-line.js +116 -0
  57. package/dist/voice/relay/transfer-line.js.map +1 -0
  58. package/dist/voice/relay-index.d.ts +13 -0
  59. package/dist/voice/relay-index.d.ts.map +1 -0
  60. package/dist/voice/relay-index.js +13 -0
  61. package/dist/voice/relay-index.js.map +1 -0
  62. package/dist/voice/session-token.d.ts +58 -0
  63. package/dist/voice/session-token.d.ts.map +1 -0
  64. package/dist/voice/session-token.js +152 -0
  65. package/dist/voice/session-token.js.map +1 -0
  66. package/dist/voice/transfer.d.ts +123 -0
  67. package/dist/voice/transfer.d.ts.map +1 -0
  68. package/dist/voice/transfer.js +95 -0
  69. package/dist/voice/transfer.js.map +1 -0
  70. package/dist/voice/twilio-request.d.ts +30 -0
  71. package/dist/voice/twilio-request.d.ts.map +1 -0
  72. package/dist/voice/twilio-request.js +46 -0
  73. package/dist/voice/twilio-request.js.map +1 -0
  74. package/dist/voice/twilio-signature.d.ts +8 -0
  75. package/dist/voice/twilio-signature.d.ts.map +1 -0
  76. package/dist/voice/twilio-signature.js +22 -0
  77. package/dist/voice/twilio-signature.js.map +1 -0
  78. package/dist/voice/twiml.d.ts +93 -0
  79. package/dist/voice/twiml.d.ts.map +1 -0
  80. package/dist/voice/twiml.js +107 -0
  81. package/dist/voice/twiml.js.map +1 -0
  82. package/package.json +19 -1
  83. package/src/inbox/inbox.ts +200 -0
  84. package/src/inbox/index.ts +33 -0
  85. package/src/inbox/use-selection.ts +60 -0
  86. package/src/voice/handoff.ts +34 -0
  87. package/src/voice/index.ts +78 -0
  88. package/src/voice/opening-hours.ts +125 -0
  89. package/src/voice/out-of-hours.ts +48 -0
  90. package/src/voice/phone.ts +68 -0
  91. package/src/voice/relay/agent-client.ts +64 -0
  92. package/src/voice/relay/model.ts +412 -0
  93. package/src/voice/relay/protocol.ts +52 -0
  94. package/src/voice/relay/sentence-gate.ts +64 -0
  95. package/src/voice/relay/server.ts +242 -0
  96. package/src/voice/relay/transfer-line.ts +114 -0
  97. package/src/voice/relay-index.ts +46 -0
  98. package/src/voice/session-token.ts +205 -0
  99. package/src/voice/transfer.ts +171 -0
  100. package/src/voice/twilio-request.ts +60 -0
  101. package/src/voice/twilio-signature.ts +27 -0
  102. package/src/voice/twiml.ts +184 -0
@@ -0,0 +1,242 @@
1
+ import { createServer, type IncomingMessage, type Server } from "node:http";
2
+
3
+ import { WebSocketServer } from "ws";
4
+
5
+ import { healthText, type BuildInfo } from "../../health/health.js";
6
+ import { verifyVoiceSession, type VoiceSession, type VoiceVerifier } from "../session-token.js";
7
+ import { isValidTwilioSignature } from "../twilio-signature.js";
8
+ import { parseInbound, type OutboundMessage, type SetupMessage } from "./protocol.js";
9
+
10
+ /**
11
+ * How the relay checks Twilio's signature on the WebSocket upgrade: refuse a bad
12
+ * one (`enforce`), only log it (`log`, for the first calls after the deploy that
13
+ * turns this on), or not at all (`off`, for tests and local smoke runs).
14
+ */
15
+ export type TwilioUpgradeCheck =
16
+ | { mode: "enforce" | "log"; authToken: string; /** The wss:// URL Twilio is given. */ publicUrl?: string }
17
+ | { mode: "off" };
18
+
19
+ export interface RelayLimits {
20
+ /** Calls one tenant can have open at once. More are refused, and Twilio's handoff puts them through. */
21
+ callsPerTenant: number;
22
+ /** Sockets connected but not yet set up, across the relay. */
23
+ pendingSockets: number;
24
+ }
25
+
26
+ export const DEFAULT_RELAY_LIMITS: RelayLimits = { callsPerTenant: 20, pendingSockets: 50 };
27
+
28
+ /** One call's conversation, as the app builds it. */
29
+ export interface RelaySession {
30
+ onPrompt(text: string): void | Promise<void>;
31
+ onInterrupt(): void;
32
+ onDtmf?(digit: string): void;
33
+ /** The socket closed: post the call log. */
34
+ close(): void | Promise<void>;
35
+ }
36
+
37
+ export interface RelaySessionContext {
38
+ /** The verified token: tenant, call, caller number. */
39
+ session: VoiceSession;
40
+ /** The raw token, for the app's agent API (Bearer). */
41
+ token: string;
42
+ setup: SetupMessage;
43
+ /** `customParameters` from `setup`, with anything that isn't a string dropped. */
44
+ parameters: Record<string, string>;
45
+ send: (message: OutboundMessage) => void;
46
+ log: (event: string, detail?: Record<string, unknown>) => void;
47
+ }
48
+
49
+ export interface RelayOptions {
50
+ port: number;
51
+ /** Verifies session tokens: the app's Ed25519 public key (and an old secret during a move). */
52
+ verifier: VoiceVerifier;
53
+ createSession: (context: RelaySessionContext) => RelaySession;
54
+ /** Twilio's signature on the upgrade. Default: off. */
55
+ twilio?: TwilioUpgradeCheck;
56
+ limits?: Partial<RelayLimits>;
57
+ log?: (event: string, detail?: Record<string, unknown>) => void;
58
+ /** Which build this is, said by `GET /healthz` (`buildInfo` from `@connextar/house/health`). */
59
+ build?: BuildInfo;
60
+ }
61
+
62
+ const text = (value: unknown): string => (typeof value === "string" ? value : "");
63
+
64
+ /**
65
+ * The URL Twilio signed. With a public URL configured, that one only: the
66
+ * request's own host headers are the caller's to choose.
67
+ */
68
+ function upgradeUrls(req: IncomingMessage, publicUrl: string | undefined): string[] {
69
+ if (publicUrl) return [publicUrl];
70
+ const host = text(req.headers["x-forwarded-host"]) || text(req.headers.host);
71
+ return host ? [`wss://${host}${req.url ?? ""}`] : [];
72
+ }
73
+
74
+ /**
75
+ * The voice relay: Twilio ConversationRelay connects here over WebSocket for
76
+ * each AI call. Lifted from PharmaLineAI (0.27.7); the call session is the app's,
77
+ * passed in as `createSession`.
78
+ *
79
+ * `GET /healthz` answers `ok` and the build for the host's health check;
80
+ * WebSocket upgrades are on `/relay`. Who gets in, checked in this order:
81
+ * 1. **Twilio's signature on the upgrade**, so the socket comes from Twilio.
82
+ * 2. **A session token in the `setup` message**, for the same call, minted by the
83
+ * app's webhook with a key the relay can check but never use to mint.
84
+ * 3. **Once per token**: a token that has opened a socket can't open another.
85
+ * 4. **Room**: a tenant has a ceiling on calls open at once, and the relay on
86
+ * sockets still waiting to set up. A refused socket is a failed session to
87
+ * Twilio, which the app's handoff webhook treats as "put them through".
88
+ */
89
+ export function startRelay(o: RelayOptions): Promise<Server> {
90
+ const log = o.log ?? ((event, detail) => console.log(`[voice-relay] ${event}`, detail ?? ""));
91
+ const limits = { ...DEFAULT_RELAY_LIMITS, ...o.limits };
92
+ const twilio = o.twilio ?? { mode: "off" as const };
93
+
94
+ /** Token ids that have opened a socket, until the token expires (ms). */
95
+ const usedTokens = new Map<string, number>();
96
+ const callsByTenant = new Map<string, number>();
97
+ let pending = 0;
98
+
99
+ const forgetExpired = () => {
100
+ const now = Date.now();
101
+ for (const [id, expiresAt] of usedTokens) if (expiresAt < now) usedTokens.delete(id);
102
+ };
103
+
104
+ const server = createServer((req, res) => {
105
+ if (req.url === "/healthz") {
106
+ res
107
+ .writeHead(200, {
108
+ "content-type": "text/plain; charset=utf-8",
109
+ "cache-control": "no-store",
110
+ "x-content-type-options": "nosniff",
111
+ })
112
+ .end(healthText(o.build));
113
+ return;
114
+ }
115
+ res.writeHead(404).end();
116
+ });
117
+
118
+ // ConversationRelay messages are a sentence or two of JSON; nothing legitimate comes near this.
119
+ const wss = new WebSocketServer({
120
+ server,
121
+ path: "/relay",
122
+ maxPayload: 64 * 1024,
123
+ verifyClient: ({ req }, done) => {
124
+ if (twilio.mode === "off") return done(true);
125
+ const signature = text(req.headers["x-twilio-signature"]) || null;
126
+ if (isValidTwilioSignature(twilio.authToken, signature, upgradeUrls(req, twilio.publicUrl), {})) {
127
+ return done(true);
128
+ }
129
+ log("upgrade_signature_invalid", { mode: twilio.mode, presented: Boolean(signature) });
130
+ if (twilio.mode === "log") return done(true);
131
+ return done(false, 403, "Forbidden");
132
+ },
133
+ });
134
+
135
+ wss.on("connection", (ws) => {
136
+ let session: RelaySession | null = null;
137
+ let tenant: string | null = null;
138
+ let waiting = true;
139
+ const stopWaiting = () => {
140
+ if (waiting) {
141
+ waiting = false;
142
+ pending -= 1;
143
+ }
144
+ };
145
+
146
+ if (pending >= limits.pendingSockets) {
147
+ log("refused_busy", { pending });
148
+ ws.close(1013, "busy");
149
+ return;
150
+ }
151
+ pending += 1;
152
+
153
+ const send = (message: OutboundMessage) => {
154
+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message));
155
+ };
156
+ const setupTimer = setTimeout(() => {
157
+ if (!session) ws.close(1008, "setup required");
158
+ }, 10_000);
159
+
160
+ // A bad frame must cost this socket, never the process: an exception escaping a listener,
161
+ // or an 'error' with nobody listening, would take the relay down for every call.
162
+ ws.on("error", (error) => {
163
+ log("socket_error", { message: error.message });
164
+ ws.terminate();
165
+ });
166
+
167
+ ws.on("message", (raw) => {
168
+ try {
169
+ const message = parseInbound(raw.toString());
170
+ if (!message) return;
171
+
172
+ if (message.type === "setup") {
173
+ if (session) return;
174
+ // Messages are cast, not validated: anything that isn't a string is treated as absent.
175
+ const token = text(message.customParameters?.sessionToken);
176
+ const callSid = text(message.callSid);
177
+ const verified = verifyVoiceSession(o.verifier, token);
178
+ if (!verified || verified.callSid !== callSid) {
179
+ log("rejected", { callSid });
180
+ ws.close(1008, "invalid session");
181
+ return;
182
+ }
183
+ forgetExpired();
184
+ if (usedTokens.has(verified.tokenId)) {
185
+ log("rejected_reused", { callSid });
186
+ ws.close(1008, "session already used");
187
+ return;
188
+ }
189
+ const open = callsByTenant.get(verified.tenantId) ?? 0;
190
+ if (open >= limits.callsPerTenant) {
191
+ log("refused_tenant_busy", { callSid, open });
192
+ ws.close(1013, "busy");
193
+ return;
194
+ }
195
+ usedTokens.set(verified.tokenId, verified.expiresAt * 1000);
196
+ tenant = verified.tenantId;
197
+ callsByTenant.set(tenant, open + 1);
198
+ stopWaiting();
199
+ clearTimeout(setupTimer);
200
+
201
+ const parameters: Record<string, string> = {};
202
+ for (const [k, v] of Object.entries(message.customParameters ?? {})) {
203
+ if (typeof v === "string") parameters[k] = v;
204
+ }
205
+ session = o.createSession({
206
+ session: verified,
207
+ token,
208
+ setup: message,
209
+ parameters,
210
+ send,
211
+ log: (event, detail) => log(event, { callSid, ...detail }),
212
+ });
213
+ log("call_started", { callSid });
214
+ return;
215
+ }
216
+
217
+ if (!session) return;
218
+ if (message.type === "prompt" && message.last !== false) void session.onPrompt(text(message.voicePrompt));
219
+ else if (message.type === "interrupt") session.onInterrupt();
220
+ else if (message.type === "dtmf") session.onDtmf?.(text(message.digit));
221
+ else if (message.type === "error") log("twilio_error", { description: text(message.description) });
222
+ } catch (error) {
223
+ log("bad_message", { message: error instanceof Error ? error.message : "unknown" });
224
+ if (!session) ws.close(1008, "bad message");
225
+ }
226
+ });
227
+
228
+ ws.on("close", () => {
229
+ clearTimeout(setupTimer);
230
+ stopWaiting();
231
+ if (tenant) {
232
+ const open = (callsByTenant.get(tenant) ?? 1) - 1;
233
+ if (open > 0) callsByTenant.set(tenant, open);
234
+ else callsByTenant.delete(tenant);
235
+ tenant = null;
236
+ }
237
+ void session?.close();
238
+ });
239
+ });
240
+
241
+ return new Promise((resolve) => server.listen(o.port, () => resolve(server)));
242
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Speaks the `say` of a transfer tool call while its arguments are still being written.
3
+ *
4
+ * The line a caller hears before a transfer is an argument of the tool call, and a tool call only
5
+ * arrives whole — measured, transfers reached their first word half a second after answers did.
6
+ * Both providers stream the arguments as JSON text; this reads the `say` string out of that text
7
+ * as it grows and hands each new piece on to be spoken.
8
+ *
9
+ * If the call has already set one of the `silentKeys` to `true` before `say` begins, nothing is
10
+ * spoken: the app's session says a fixed line instead. PharmaLine passes `emergency` (its 999
11
+ * line) and `pharmacy_first` (the transfer may be held while questions are asked). A flag that
12
+ * arrives after the line has started is still honoured by the session's fixed line.
13
+ */
14
+ export class TransferLineStream {
15
+ private json = "";
16
+ private spoken = 0;
17
+ private silenced = false;
18
+ private readonly said: string;
19
+ private readonly silentFlag: RegExp | null;
20
+
21
+ /**
22
+ * `alreadySaid`: what the model said out loud in the same reply before the call began. Models
23
+ * were found writing "I will put you through to the pharmacist now." as words and then again as
24
+ * the line (D5, 2026-10-18): the caller heard it twice. With words already said, the line is
25
+ * held a sentence at a time and any sentence that repeats them is dropped.
26
+ */
27
+ constructor(
28
+ private readonly speak: (piece: string) => void,
29
+ alreadySaid = "",
30
+ silentKeys: readonly string[] = [],
31
+ ) {
32
+ this.said = comparable(alreadySaid);
33
+ const keys = silentKeys.map((k) => k.replace(/[^A-Za-z0-9_]/g, "")).filter(Boolean);
34
+ this.silentFlag = keys.length ? new RegExp(`"(?:${keys.join("|")})"\\s*:\\s*true`) : null;
35
+ }
36
+
37
+ /** More of the arguments' JSON text. */
38
+ push(delta: string): void {
39
+ this.json += delta;
40
+ const start = /"say"\s*:\s*"/.exec(this.json);
41
+ if (!start) {
42
+ // A flagged call gets the session's fixed line instead.
43
+ if (this.silentFlag?.test(this.json)) this.silenced = true;
44
+ return;
45
+ }
46
+ if (this.silenced) return;
47
+ const { text, closed } = readString(this.json, start.index + start[0].length);
48
+ const line = text.replace(/\s+/g, " ");
49
+ if (!this.said) {
50
+ const fresh = line.slice(this.spoken);
51
+ if (fresh) {
52
+ this.spoken = line.length;
53
+ this.speak(fresh);
54
+ }
55
+ return;
56
+ }
57
+ // Only whole sentences — the last one once the string has closed — so a repeat can be dropped.
58
+ const rest = line.slice(this.spoken);
59
+ let upTo = closed ? rest.length : 0;
60
+ if (!closed) for (const m of rest.matchAll(/[.!?]+\s+/g)) upTo = m.index + m[0].length;
61
+ if (!upTo) return;
62
+ for (const sentence of rest.slice(0, upTo).match(/[^.!?]+(?:[.!?]+\s*|$)/g) ?? []) {
63
+ const key = comparable(sentence);
64
+ if (key && !this.said.includes(key)) this.speak(sentence);
65
+ }
66
+ this.spoken += upTo;
67
+ }
68
+
69
+ /** Whether any of the line has been spoken. */
70
+ get started(): boolean {
71
+ return this.spoken > 0;
72
+ }
73
+ }
74
+
75
+ /** Words only, lower case — so "Now." and "now" compare the same. */
76
+ function comparable(text: string): string {
77
+ return text
78
+ .toLowerCase()
79
+ .replace(/[’‘]/g, "'")
80
+ .replace(/[^a-z0-9']+/g, " ")
81
+ .trim();
82
+ }
83
+
84
+ const ESCAPES: Record<string, string> = { n: " ", t: " ", r: "", b: "", f: "", '"': '"', "\\": "\\", "/": "/" };
85
+
86
+ /**
87
+ * A JSON string's contents from `from`, as far as it has been written: stops at the closing quote
88
+ * (`closed`), or before a half-written escape.
89
+ */
90
+ function readString(json: string, from: number): { text: string; closed: boolean } {
91
+ let out = "";
92
+ let i = from;
93
+ while (i < json.length) {
94
+ const c = json[i]!;
95
+ if (c === '"') return { text: out, closed: true };
96
+ if (c !== "\\") {
97
+ out += c;
98
+ i += 1;
99
+ continue;
100
+ }
101
+ const next = json[i + 1];
102
+ if (next === undefined) break;
103
+ if (next === "u") {
104
+ const hex = json.slice(i + 2, i + 6);
105
+ if (hex.length < 4) break;
106
+ out += String.fromCharCode(parseInt(hex, 16));
107
+ i += 6;
108
+ continue;
109
+ }
110
+ out += ESCAPES[next] ?? next;
111
+ i += 2;
112
+ }
113
+ return { text: out, closed: false };
114
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * `@connextar/house/voice/relay`: the long-running half of a voice line, the
3
+ * WebSocket server Twilio ConversationRelay connects to, and the streaming dialog
4
+ * model it talks through. Node only; needs `ws`, and the SDK of whichever
5
+ * provider is configured (`@anthropic-ai/sdk`, `openai`).
6
+ */
7
+ export {
8
+ parseInbound,
9
+ type DtmfMessage,
10
+ type ErrorMessage,
11
+ type InboundMessage,
12
+ type InterruptMessage,
13
+ type OutboundMessage,
14
+ type PromptMessage,
15
+ type SetupMessage,
16
+ } from "./relay/protocol.js";
17
+ export { keepSentences, SentenceGate } from "./relay/sentence-gate.js";
18
+ export { TransferLineStream } from "./relay/transfer-line.js";
19
+ export {
20
+ DEFAULT_RELAY_LIMITS,
21
+ startRelay,
22
+ type RelayLimits,
23
+ type RelayOptions,
24
+ type RelaySession,
25
+ type RelaySessionContext,
26
+ type TwilioUpgradeCheck,
27
+ } from "./relay/server.js";
28
+ export {
29
+ anthropicTools,
30
+ anthropicUsage,
31
+ cacheKey,
32
+ createDialogModel,
33
+ openAiTools,
34
+ openAiUsage,
35
+ toResponsesInput,
36
+ withConversationCached,
37
+ type ContentBlock,
38
+ type DialogMessage,
39
+ type DialogModel,
40
+ type DialogModelOptions,
41
+ type DialogTool,
42
+ type ModelTurn,
43
+ type ToolResultBlock,
44
+ type TurnUsage,
45
+ } from "./relay/model.js";
46
+ export { AgentApiError, createAgentFetch, type AgentFetch, type AgentFetchOptions } from "./relay/agent-client.js";
@@ -0,0 +1,205 @@
1
+ import {
2
+ createHmac,
3
+ createPrivateKey,
4
+ createPublicKey,
5
+ generateKeyPairSync,
6
+ randomBytes,
7
+ sign,
8
+ timingSafeEqual,
9
+ verify,
10
+ type KeyObject,
11
+ } from "node:crypto";
12
+
13
+ /**
14
+ * Voice session tokens — short-lived, per-call credentials the voice relay uses to reach the agent
15
+ * API on behalf of one tenant (a pharmacy, a business), instead of holding API keys.
16
+ *
17
+ * **`vs2.` — signed with Ed25519 (0.18.0).** `vs2.<base64url payload>.<base64url signature>`. The app
18
+ * holds the private key and is the only thing that can mint a token; the relay holds the public key
19
+ * and can only check one. Before this, both held one HMAC secret, so whoever could read the relay's
20
+ * environment could mint a token for any tenant (security round 2, #5).
21
+ *
22
+ * **`vst.` — HMAC-SHA256, the old format.** Still verified wherever `VOICE_SESSION_SECRET` is set, so
23
+ * calls in progress at the deploy survive; the secret is removed one release later, and then a `vst.`
24
+ * token verifies nowhere.
25
+ *
26
+ * Payload `{ o: tenantId, c: callSid, e: expiry (unix s), n?: caller number, j?: token id }`. `n` is the
27
+ * number from Twilio's signed webhook (the identity gate counts a caller's failures across calls by
28
+ * it); `j` is random, so the relay can let each token open one socket only.
29
+ */
30
+
31
+ export const VOICE_SESSION_TTL_SECONDS = 2 * 60 * 60;
32
+
33
+ const HMAC = "vst";
34
+ const ED25519 = "vs2";
35
+
36
+ export interface VoiceSession {
37
+ tenantId: string;
38
+ callSid: string;
39
+ expiresAt: number;
40
+ /** The caller's number as Twilio presented it, when there was one. */
41
+ callerNumber: string | null;
42
+ /** Unique to this token — what the relay remembers to refuse a second socket. */
43
+ tokenId: string;
44
+ }
45
+
46
+ /** What mints tokens: the Ed25519 private key, or — until it is set — the old shared secret. */
47
+ export interface VoiceSigner {
48
+ privateKey?: string;
49
+ secret?: string;
50
+ }
51
+
52
+ /**
53
+ * What checks them: the Ed25519 public key — or two, comma-separated, while a key is rotated — and
54
+ * the old secret for the release in between.
55
+ */
56
+ export interface VoiceVerifier {
57
+ publicKey?: string;
58
+ secret?: string;
59
+ }
60
+
61
+ const asSigner = (s: string | VoiceSigner): VoiceSigner => (typeof s === "string" ? { secret: s } : s);
62
+ const asVerifier = (v: string | VoiceVerifier): VoiceVerifier => (typeof v === "string" ? { secret: v } : v);
63
+
64
+ /* ── keys ─────────────────────────────────────────────────────────────────── */
65
+
66
+ const keyCache = new Map<string, KeyObject>();
67
+
68
+ /** A private key as stored in the environment: base64url PKCS#8 DER, one line. */
69
+ function privateKeyFrom(encoded: string): KeyObject {
70
+ const cacheKey = `private:${encoded}`;
71
+ let key = keyCache.get(cacheKey);
72
+ if (!key) {
73
+ key = createPrivateKey({ key: Buffer.from(encoded.trim(), "base64url"), format: "der", type: "pkcs8" });
74
+ if (key.asymmetricKeyType !== "ed25519") throw new Error("VOICE_SESSION_PRIVATE_KEY is not an Ed25519 key");
75
+ keyCache.set(cacheKey, key);
76
+ }
77
+ return key;
78
+ }
79
+
80
+ /** A public key as stored in the environment: base64url SPKI DER, one line. */
81
+ function publicKeyFrom(encoded: string): KeyObject {
82
+ const cacheKey = `public:${encoded}`;
83
+ let key = keyCache.get(cacheKey);
84
+ if (!key) {
85
+ key = createPublicKey({ key: Buffer.from(encoded.trim(), "base64url"), format: "der", type: "spki" });
86
+ if (key.asymmetricKeyType !== "ed25519") throw new Error("VOICE_SESSION_PUBLIC_KEY is not an Ed25519 key");
87
+ keyCache.set(cacheKey, key);
88
+ }
89
+ return key;
90
+ }
91
+
92
+ /** The public key that goes with a private one — the app checks its own tokens with it. */
93
+ export function publicKeyFor(privateKey: string): string {
94
+ return createPublicKey(privateKeyFrom(privateKey)).export({ format: "der", type: "spki" }).toString("base64url");
95
+ }
96
+
97
+ /** A new key pair, as `npm run voice:keys` prints it. */
98
+ export function generateVoiceSessionKeys(): { privateKey: string; publicKey: string } {
99
+ const pair = generateKeyPairSync("ed25519");
100
+ return {
101
+ privateKey: pair.privateKey.export({ format: "der", type: "pkcs8" }).toString("base64url"),
102
+ publicKey: pair.publicKey.export({ format: "der", type: "spki" }).toString("base64url"),
103
+ };
104
+ }
105
+
106
+ /** Whether a public key setting (one key, or two comma-separated) can be read — for a startup check. */
107
+ export function isUsablePublicKey(encoded: string): boolean {
108
+ const keys = encoded.split(",").map((k) => k.trim());
109
+ if (!keys.length || keys.some((k) => !k)) return false;
110
+ try {
111
+ keys.forEach(publicKeyFrom);
112
+ return true;
113
+ } catch {
114
+ return false;
115
+ }
116
+ }
117
+
118
+ /* ── tokens ───────────────────────────────────────────────────────────────── */
119
+
120
+ export function isVoiceSessionToken(token: string): boolean {
121
+ return token.startsWith(`${HMAC}.`) || token.startsWith(`${ED25519}.`);
122
+ }
123
+
124
+ function hmac(secret: string, payload: string): string {
125
+ return createHmac("sha256", secret).update(`${HMAC}.${payload}`).digest("base64url");
126
+ }
127
+
128
+ export function signVoiceSession(
129
+ signer: string | VoiceSigner,
130
+ session: { tenantId: string; callSid: string; callerNumber?: string | null },
131
+ now = Date.now(),
132
+ ttlSeconds = VOICE_SESSION_TTL_SECONDS,
133
+ ): string {
134
+ const { privateKey, secret } = asSigner(signer);
135
+ const body = {
136
+ o: session.tenantId,
137
+ c: session.callSid,
138
+ e: Math.floor(now / 1000) + ttlSeconds,
139
+ ...(session.callerNumber ? { n: session.callerNumber } : {}),
140
+ };
141
+ if (privateKey) {
142
+ const payload = Buffer.from(JSON.stringify({ ...body, j: randomBytes(12).toString("base64url") })).toString(
143
+ "base64url",
144
+ );
145
+ const signature = sign(null, Buffer.from(`${ED25519}.${payload}`), privateKeyFrom(privateKey));
146
+ return `${ED25519}.${payload}.${signature.toString("base64url")}`;
147
+ }
148
+ if (!secret) throw new Error("Neither VOICE_SESSION_PRIVATE_KEY nor VOICE_SESSION_SECRET is set");
149
+ const payload = Buffer.from(JSON.stringify(body)).toString("base64url");
150
+ return `${HMAC}.${payload}.${hmac(secret, payload)}`;
151
+ }
152
+
153
+ /** The session a token was minted for, or null if it's malformed, forged, expired or unverifiable here. */
154
+ export function verifyVoiceSession(
155
+ verifier: string | VoiceVerifier,
156
+ token: string,
157
+ now = Date.now(),
158
+ ): VoiceSession | null {
159
+ const { publicKey, secret } = asVerifier(verifier);
160
+ const [prefix, payload, signature, extra] = token.split(".");
161
+ if (!payload || !signature || extra !== undefined) return null;
162
+
163
+ if (prefix === ED25519) {
164
+ if (!publicKey) return null;
165
+ const signed = Buffer.from(`${ED25519}.${payload}`);
166
+ const presented = Buffer.from(signature, "base64url");
167
+ const ok = publicKey.split(",").some((key) => {
168
+ try {
169
+ return verify(null, signed, publicKeyFrom(key), presented);
170
+ } catch {
171
+ return false;
172
+ }
173
+ });
174
+ if (!ok) return null;
175
+ } else if (prefix === HMAC) {
176
+ if (!secret) return null;
177
+ const expected = Buffer.from(hmac(secret, payload));
178
+ const presented = Buffer.from(signature);
179
+ if (expected.length !== presented.length || !timingSafeEqual(expected, presented)) return null;
180
+ } else {
181
+ return null;
182
+ }
183
+
184
+ try {
185
+ const data = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
186
+ o?: unknown;
187
+ c?: unknown;
188
+ e?: unknown;
189
+ n?: unknown;
190
+ j?: unknown;
191
+ };
192
+ if (typeof data.o !== "string" || typeof data.c !== "string" || typeof data.e !== "number") return null;
193
+ if (data.e * 1000 < now) return null;
194
+ return {
195
+ tenantId: data.o,
196
+ callSid: data.c,
197
+ expiresAt: data.e,
198
+ callerNumber: typeof data.n === "string" ? data.n : null,
199
+ // An old token has no id of its own; its call is one socket's worth.
200
+ tokenId: typeof data.j === "string" ? data.j : `call:${data.c}`,
201
+ };
202
+ } catch {
203
+ return null;
204
+ }
205
+ }