Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

refactor(twilio): use chat sdk twilio primitives (#422)

josh74ce1644e53e
diff --git a/.changeset/fresh-zebras-win.md b/.changeset/fresh-zebras-win.md
new file mode 100644
index 000000000..687a7f4a8
--- /dev/null
+++ b/.changeset/fresh-zebras-win.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+reuse chat sdk twilio primitives for webhook, api, and voice helpers
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 4f0d6dd56..1fc410667 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -296,6 +296,7 @@
"@ai-sdk/provider-utils": "catalog:",
"@chat-adapter/slack": "4.31.0",
"@chat-adapter/state-memory": "4.31.0",
+ "@chat-adapter/twilio": "4.31.0",
"@clack/core": "1.3.1",
"@nuxt/kit": "^4.0.0",
"@standard-schema/spec": "1.1.0",
diff --git a/packages/eve/scripts/vendor-compiled/@chat-adapter/twilio.mjs b/packages/eve/scripts/vendor-compiled/@chat-adapter/twilio.mjs
new file mode 100644
index 000000000..39b2fd957
--- /dev/null
+++ b/packages/eve/scripts/vendor-compiled/@chat-adapter/twilio.mjs
@@ -0,0 +1,39 @@
+import { createDeclarationCopier } from "../_shared.mjs";
+
+export default {
+ packageName: "@chat-adapter/twilio",
+ compiledPath: "@chat-adapter/twilio",
+ entries: [
+ {
+ outputPath: "index",
+ },
+ {
+ input: "@chat-adapter/twilio/api",
+ outputPath: "api",
+ },
+ {
+ input: "@chat-adapter/twilio/webhook",
+ outputPath: "webhook",
+ },
+ {
+ input: "@chat-adapter/twilio/voice",
+ outputPath: "voice",
+ },
+ {
+ input: "@chat-adapter/twilio/format",
+ outputPath: "format",
+ },
+ ],
+ copyDeclarations: createDeclarationCopier({
+ files: [
+ { source: "index.d.ts", output: "index.d.ts" },
+ { source: "api.d.ts", output: "api.d.ts" },
+ { source: "webhook.d.ts", output: "webhook.d.ts" },
+ { source: "voice.d.ts", output: "voice.d.ts" },
+ { source: "format.d.ts", output: "format.d.ts" },
+ ],
+ rewrites: {
+ chat: { kind: "vendored", compiledPath: "chat" },
+ },
+ }),
+};
diff --git a/packages/eve/scripts/vendor-compiled/index.mjs b/packages/eve/scripts/vendor-compiled/index.mjs
index 90db9a6d9..92e662cf2 100644
--- a/packages/eve/scripts/vendor-compiled/index.mjs
+++ b/packages/eve/scripts/vendor-compiled/index.mjs
@@ -13,6 +13,7 @@ import providerUtils from "./@ai-sdk/provider-utils.mjs";
import chatAdapterSlack from "./@chat-adapter/slack.mjs";
import chatAdapterStateMemory from "./@chat-adapter/state-memory.mjs";
+import chatAdapterTwilio from "./@chat-adapter/twilio.mjs";
import opentelemetryApi from "./@opentelemetry/api.mjs";
import standardSchemaSpec from "./@standard-schema/spec.mjs";
@@ -44,6 +45,7 @@ export const MODULES = [
chat,
chatAdapterSlack,
chatAdapterStateMemory,
+ chatAdapterTwilio,
chokidar,
commander,
experimentalAiSdkCodeMode,
diff --git a/packages/eve/src/public/channels/twilio/api.test.ts b/packages/eve/src/public/channels/twilio/api.test.ts
index 030a36538..d78539db8 100644
--- a/packages/eve/src/public/channels/twilio/api.test.ts
+++ b/packages/eve/src/public/channels/twilio/api.test.ts
@@ -68,6 +68,23 @@ describe("Twilio REST API wrapper", () => {
});
});
+ it("returns non-ok responses instead of throwing on Twilio HTTP errors", async () => {
+ const mockFetch: typeof fetch = async () =>
+ new Response(JSON.stringify({ code: 20_001, message: "bad request" }), { status: 400 });
+
+ const result = await callTwilioApi({
+ body: { Body: "hello" },
+ fetch: mockFetch,
+ path: "/2010-04-01/Accounts/AC123/Messages.json",
+ });
+
+ expect(result).toEqual({
+ body: { code: 20_001, message: "bad request" },
+ ok: false,
+ status: 400,
+ });
+ });
+
it("sendTwilioMessage posts to the Messages resource with normal defaults", async () => {
const mock = buildFetchMock();
diff --git a/packages/eve/src/public/channels/twilio/api.ts b/packages/eve/src/public/channels/twilio/api.ts
index 1a8b48198..e96aebdce 100644
--- a/packages/eve/src/public/channels/twilio/api.ts
+++ b/packages/eve/src/public/channels/twilio/api.ts
@@ -1,32 +1,29 @@
-/**
- * Minimal Twilio REST API wrapper used by the Twilio channel.
- *
- * Requests use Twilio's normal `application/x-www-form-urlencoded`
- * body encoding and HTTP Basic auth. No Twilio SDK dependency is
- * required or exposed through eve public APIs.
- */
+import {
+ callTwilioApi as callPrimitive,
+ encodeTwilioForm,
+ resolveTwilioCredential,
+ TwilioApiError,
+ type TwilioApiResponse,
+ type TwilioCredential,
+ type TwilioFetch,
+} from "#compiled/@chat-adapter/twilio/api.js";
import { resolveTwilioAuthToken, type TwilioAuthToken } from "#public/channels/twilio/verify.js";
/**
- * Builds the Twilio channel-local continuation token
- * (`<from>:<to>`). Route `send()` namespaces this with the channel
- * name before passing it to the runtime (`twilio:<from>:<to>`), so
- * Twilio routes should pass the raw channel-local form returned
- * here. `to` may be empty for proactive sessions that don't yet know
- * the Twilio sender number.
+ * Builds the Twilio channel-local continuation token (`<from>:<to>`).
+ * Eve namespaces this with the channel name before handing it to the runtime.
*/
export function twilioContinuationToken(from: string, to: string | undefined): string {
return `${from}:${to ?? ""}`;
}
/** Twilio Account SID, materialized directly or from an async secret provider. */
-export type TwilioAccountSid = string | (() => string | Promise<string>);
+export type TwilioAccountSid = TwilioCredential;
-/** Fetch implementation override matching the global `fetch` signature. Defaults to the runtime global; supply a custom one for tests or non-standard runtimes. */
-export type TwilioFetch = typeof fetch;
+export type { TwilioApiResponse, TwilioFetch };
-/** Credentials required for Twilio REST API calls and webhook verification. */
+/** Credentials used for Twilio REST API calls and webhook verification. */
export interface TwilioCredentials {
readonly accountSid?: TwilioAccountSid;
readonly authToken?: TwilioAuthToken;
@@ -39,17 +36,6 @@ export interface TwilioApiOptions {
readonly fetch?: TwilioFetch;
}
-/**
- * Result of a Twilio REST call: HTTP `status`, an `ok` flag, and `body`.
- * `body` holds parsed JSON for a JSON response, the raw text string
- * otherwise, or `null` when empty.
- */
-export interface TwilioApiResponse {
- readonly status: number;
- readonly ok: boolean;
- readonly body: unknown;
-}
-
/** Parameters for creating an outbound Twilio message. */
export interface TwilioSendMessageInput extends TwilioApiOptions {
readonly to: string;
@@ -67,16 +53,21 @@ export interface TwilioUpdateCallInput extends TwilioApiOptions {
/** Resolves a Twilio Account SID, falling back to `TWILIO_ACCOUNT_SID`. */
export async function resolveTwilioAccountSid(accountSid?: TwilioAccountSid): Promise<string> {
- const source = accountSid ?? process.env.TWILIO_ACCOUNT_SID;
- if (!source) throw new Error("TWILIO_ACCOUNT_SID is required.");
- return typeof source === "function" ? await source() : source;
+ try {
+ return await resolveTwilioCredential(accountSid, "TWILIO_ACCOUNT_SID");
+ } catch (error) {
+ if (error instanceof TwilioApiError && error.status === 0) {
+ throw new Error("TWILIO_ACCOUNT_SID is required.");
+ }
+ throw error;
+ }
}
/**
* Calls Twilio's REST API with Basic auth and form-encoded body fields.
*
- * `path` is relative to `https://api.twilio.com` by default and may be
- * pointed elsewhere through `apiBaseUrl` for tests or proxies.
+ * The return shape intentionally preserves Eve's previous non-throwing HTTP
+ * behavior: non-2xx Twilio responses become `{ ok: false, status, body }`.
*/
export async function callTwilioApi(input: {
readonly credentials?: TwilioCredentials;
@@ -85,24 +76,16 @@ export async function callTwilioApi(input: {
readonly path: string;
readonly body: Readonly<Record<string, string | number | boolean | undefined | null>>;
}): Promise<TwilioApiResponse> {
- const accountSid = await resolveTwilioAccountSid(input.credentials?.accountSid);
- const authToken = await resolveTwilioAuthToken(input.credentials?.authToken);
- const apiFetch = input.fetch ?? fetch;
- const url = `${input.apiBaseUrl ?? "https://api.twilio.com"}${input.path}`;
- const body = encodeForm(input.body);
- const response = await apiFetch(url, {
- method: "POST",
- headers: {
- authorization: `Basic ${Buffer.from(`${accountSid}:${authToken}`).toString("base64")}`,
- "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
- },
- body,
- });
- return {
- status: response.status,
- ok: response.ok,
- body: await parseResponseBody(response),
- };
+ const credentials = await resolveCredentials(input.credentials);
+ return preserveTwilioApiResponse(
+ callPrimitive({
+ apiBaseUrl: input.apiBaseUrl,
+ body: encodeTwilioForm(input.body),
+ credentials,
+ fetch: input.fetch,
+ path: input.path,
+ }),
+ );
}
/** Sends an outbound SMS/MMS-style message via Twilio's Messages resource. */
@@ -111,52 +94,63 @@ export async function sendTwilioMessage(input: TwilioSendMessageInput): Promise<
throw new Error("twilioChannel: sending a message requires from or messagingServiceSid.");
}
const accountSid = await resolveTwilioAccountSid(input.credentials?.accountSid);
- return callTwilioApi({
- apiBaseUrl: input.apiBaseUrl,
- credentials: input.credentials,
- fetch: input.fetch,
- path: `/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`,
- body: {
- Body: input.body,
- From: input.from,
- MessagingServiceSid: input.messagingServiceSid,
- StatusCallback: input.statusCallbackUrl,
- To: input.to,
- },
- });
+ const credentials = await resolveCredentials(input.credentials);
+ return preserveTwilioApiResponse(
+ callPrimitive({
+ apiBaseUrl: input.apiBaseUrl,
+ body: encodeTwilioForm({
+ Body: input.body,
+ From: input.from,
+ MessagingServiceSid: input.messagingServiceSid,
+ StatusCallback: input.statusCallbackUrl,
+ To: input.to,
+ }),
+ credentials,
+ fetch: input.fetch,
+ path: `/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`,
+ }),
+ );
}
/** Updates a live Twilio call by posting replacement TwiML to the Calls resource. */
export async function updateTwilioCall(input: TwilioUpdateCallInput): Promise<TwilioApiResponse> {
const accountSid = await resolveTwilioAccountSid(input.credentials?.accountSid);
- return callTwilioApi({
- apiBaseUrl: input.apiBaseUrl,
- credentials: input.credentials,
- fetch: input.fetch,
- path: `/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Calls/${encodeURIComponent(
- input.callSid,
- )}.json`,
- body: { Twiml: input.twiml },
- });
+ const credentials = await resolveCredentials(input.credentials);
+ return preserveTwilioApiResponse(
+ callPrimitive({
+ apiBaseUrl: input.apiBaseUrl,
+ body: encodeTwilioForm({ Twiml: input.twiml }),
+ credentials,
+ fetch: input.fetch,
+ path: `/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Calls/${encodeURIComponent(
+ input.callSid,
+ )}.json`,
+ }),
+ );
}
-function encodeForm(
- body: Readonly<Record<string, string | number | boolean | undefined | null>>,
-): URLSearchParams {
- const params = new URLSearchParams();
- for (const [key, value] of Object.entries(body)) {
- if (value === undefined || value === null) continue;
- params.set(key, String(value));
- }
- return params;
+async function resolveCredentials(
+ credentials: TwilioCredentials | undefined,
+): Promise<{ accountSid: string; authToken: string }> {
+ return {
+ accountSid: await resolveTwilioAccountSid(credentials?.accountSid),
+ authToken: await resolveTwilioAuthToken(credentials?.authToken),
+ };
}
-async function parseResponseBody(response: Response): Promise<unknown> {
- const text = await response.text();
- if (!text) return null;
+async function preserveTwilioApiResponse(
+ response: Promise<TwilioApiResponse>,
+): Promise<TwilioApiResponse> {
try {
- return JSON.parse(text);
- } catch {
- return text;
+ return await response;
+ } catch (error) {
+ if (error instanceof TwilioApiError && error.status !== 0) {
+ return {
+ body: error.body,
+ ok: false,
+ status: error.status,
+ };
+ }
+ throw error;
}
}
diff --git a/packages/eve/src/public/channels/twilio/inbound.ts b/packages/eve/src/public/channels/twilio/inbound.ts
index ea54a18b1..19c5aee8b 100644
--- a/packages/eve/src/public/channels/twilio/inbound.ts
+++ b/packages/eve/src/public/channels/twilio/inbound.ts
@@ -1,17 +1,21 @@
-/**
- * Twilio inbound webhook parsing and prompt shaping.
- *
- * The channel owns these small data shapes instead of exposing raw
- * Twilio webhook payloads as the public API surface.
- */
-
-/** Channel-owned representation of one inbound Twilio text message. */
+import {
+ parseTwilioWebhookBody,
+ type TwilioMediaPayload,
+} from "#compiled/@chat-adapter/twilio/webhook.js";
+import {
+ parseTwilioVoiceCall as parsePrimitiveVoiceCall,
+ parseTwilioVoiceTranscription as parsePrimitiveVoiceTranscription,
+} from "#compiled/@chat-adapter/twilio/voice.js";
+
+/** Channel-owned representation of one inbound Twilio text or media message. */
export interface TwilioTextMessage {
readonly from: string;
readonly to: string | undefined;
readonly body: string;
readonly messageSid: string | undefined;
readonly accountSid: string | undefined;
+ /** MMS media metadata parsed from Twilio's `MediaUrl*` webhook fields. */
+ readonly media?: readonly TwilioMediaPayload[];
readonly raw: URLSearchParams;
}
@@ -40,11 +44,7 @@ const TWILIO_SMS_RESPONSE_INSTRUCTIONS =
"tables, headings, code fences, and long lists. Ask at most one short follow-up question " +
"when more information is needed.";
-/**
- * Inbound identity fields for the model-visible `<twilio_context>` block.
- * Stores the caller and receiver numbers, the originating SID, and the turn
- * medium (text or voice).
- */
+/** Inbound identity fields for the model-visible `<twilio_context>` block. */
export interface TwilioInboundContext {
readonly from: string;
readonly to?: string;
@@ -53,69 +53,62 @@ export interface TwilioInboundContext {
readonly channel: "text" | "voice";
}
-/** Parses Twilio's incoming-message webhook fields. */
+/** Parses Twilio's incoming-message webhook fields into Eve's text payload. */
export function parseTwilioTextMessage(params: URLSearchParams): TwilioTextMessage | null {
- const from = requiredParam(params, "From");
- const body = requiredParam(params, "Body");
- if (!from || !body) return null;
+ const payload = parseTwilioWebhookBody(params);
+ if (payload.kind !== "text") {
+ return null;
+ }
return {
- accountSid: optionalParam(params, "AccountSid"),
- body,
- from,
- messageSid: optionalParam(params, "MessageSid") ?? optionalParam(params, "SmsMessageSid"),
- raw: params,
- to: optionalParam(params, "To"),
+ accountSid: payload.accountSid,
+ body: payload.body,
+ from: payload.from,
+ media: payload.media,
+ messageSid: payload.messageSid,
+ raw: payload.raw,
+ to: payload.to,
};
}
-/** Parses Twilio's incoming-call webhook fields. */
+/** Parses Twilio's incoming-call webhook fields into Eve's voice payload. */
export function parseTwilioVoiceCall(params: URLSearchParams): TwilioVoiceCall | null {
- const from = requiredParam(params, "From") ?? requiredParam(params, "Caller");
- if (!from) return null;
+ const call = parsePrimitiveVoiceCall(params);
+ if (!call) {
+ return null;
+ }
return {
- accountSid: optionalParam(params, "AccountSid"),
- callSid: optionalParam(params, "CallSid"),
- from,
- raw: params,
- to: optionalParam(params, "To") ?? optionalParam(params, "Called"),
+ accountSid: call.accountSid,
+ callSid: call.callSid,
+ from: call.from,
+ raw: call.raw,
+ to: call.to,
};
}
/**
- * Parses Twilio voice transcription fields.
+ * Parses Twilio speech callbacks.
*
- * Supports `<Gather input="speech">` (`SpeechResult`), recording
- * transcription callbacks (`TranscriptionText`), and real-time
- * transcription callbacks (`TranscriptionData` JSON). Real-time partial
- * results are ignored until Twilio marks them final.
+ * Supports `<Gather input="speech">`, recording transcription callbacks, and
+ * real-time transcription callbacks. Real-time partial results are ignored.
*/
export function parseTwilioVoiceTranscription(
params: URLSearchParams,
): TwilioVoiceTranscription | null {
- const from = requiredParam(params, "From") ?? requiredParam(params, "Caller");
- if (!from) return null;
-
- const parsedData = parseTranscriptionData(optionalParam(params, "TranscriptionData"));
- const final = optionalParam(params, "Final");
- if (final === "false") return null;
-
- const text =
- optionalParam(params, "SpeechResult") ??
- optionalParam(params, "TranscriptionText") ??
- parsedData?.transcript ??
- "";
- if (!text.trim()) return null;
+ const transcription = parsePrimitiveVoiceTranscription(params);
+ if (!transcription?.from) {
+ return null;
+ }
return {
- callSid: optionalParam(params, "CallSid"),
- confidence: parseConfidence(optionalParam(params, "Confidence") ?? parsedData?.confidence),
- from,
- raw: params,
- text,
- to: optionalParam(params, "To") ?? optionalParam(params, "Called"),
- transcriptionSid: optionalParam(params, "TranscriptionSid"),
+ callSid: transcription.callSid,
+ confidence: transcription.confidence,
+ from: transcription.from,
+ raw: transcription.raw,
+ text: transcription.text,
+ to: transcription.to,
+ transcriptionSid: transcription.transcriptionSid,
};
}
@@ -134,37 +127,3 @@ export function formatTwilioContextBlock(context: TwilioInboundContext): string
];
return lines.join("\n");
}
-
-function requiredParam(params: URLSearchParams, name: string): string | null {
- const value = params.get(name);
- return value && value.trim().length > 0 ? value : null;
-}
-
-function optionalParam(params: URLSearchParams, name: string): string | undefined {
- const value = params.get(name);
- return value === null || value.length === 0 ? undefined : value;
-}
-
-function parseTranscriptionData(
- value: string | undefined,
-): { transcript?: string; confidence?: string } | null {
- if (!value) return null;
- try {
- const parsed = JSON.parse(value) as { transcript?: unknown; confidence?: unknown };
- return {
- confidence:
- typeof parsed.confidence === "number" || typeof parsed.confidence === "string"
- ? String(parsed.confidence)
- : undefined,
- transcript: typeof parsed.transcript === "string" ? parsed.transcript : undefined,
- };
- } catch {
- return null;
- }
-}
-
-function parseConfidence(value: string | undefined): number | undefined {
- if (value === undefined) return undefined;
- const parsed = Number(value);
- return Number.isFinite(parsed) ? parsed : undefined;
-}
diff --git a/packages/eve/src/public/channels/twilio/routing.ts b/packages/eve/src/public/channels/twilio/routing.ts
new file mode 100644
index 000000000..1fc5183c6
--- /dev/null
+++ b/packages/eve/src/public/channels/twilio/routing.ts
@@ -0,0 +1,61 @@
+import { createLogger } from "#internal/logging.js";
+import type { TwilioChannelConfig } from "#public/channels/twilio/twilioChannel.js";
+import { verifyTwilioRequest } from "#public/channels/twilio/verify.js";
+
+const log = createLogger("twilio.channel");
+
+export interface TwilioRoutes {
+ readonly messages: string;
+ readonly transcription: string;
+ readonly voice: string;
+}
+
+export type TwilioVerifyResult = {
+ readonly body: string;
+ readonly params: URLSearchParams;
+} | null;
+
+export function buildTwilioRoutes(baseRoute: string): TwilioRoutes {
+ const base = baseRoute.endsWith("/") ? baseRoute.slice(0, -1) : baseRoute;
+ return {
+ messages: `${base}/messages`,
+ transcription: `${base}/voice/transcription`,
+ voice: `${base}/voice`,
+ };
+}
+
+export async function verifyTwilioInbound(
+ req: Request,
+ config: TwilioChannelConfig,
+): Promise<TwilioVerifyResult> {
+ try {
+ return await verifyTwilioRequest(req, {
+ authToken: config.credentials?.authToken,
+ webhookUrl: config.webhookUrl,
+ });
+ } catch (error) {
+ log.warn("twilio inbound verification failed", { error });
+ return null;
+ }
+}
+
+export async function buildTwilioActionUrl(
+ request: Request,
+ config: TwilioChannelConfig,
+ route: string,
+): Promise<string> {
+ const base =
+ typeof config.publicBaseUrl === "function"
+ ? await config.publicBaseUrl(request)
+ : config.publicBaseUrl;
+ if (base) return new URL(route, ensureTrailingSlash(base)).toString();
+
+ const url = new URL(request.url);
+ url.pathname = route;
+ url.search = "";
+ return url.toString();
+}
+
+function ensureTrailingSlash(value: string): string {
+ return value.endsWith("/") ? value : `${value}/`;
+}
diff --git a/packages/eve/src/public/channels/twilio/twilioChannel.test.ts b/packages/eve/src/public/channels/twilio/twilioChannel.test.ts
index c25c7e12d..c771cdd68 100644
--- a/packages/eve/src/public/channels/twilio/twilioChannel.test.ts
+++ b/packages/eve/src/public/channels/twilio/twilioChannel.test.ts
@@ -7,7 +7,8 @@ import { isHttpRouteDefinition } from "#channel/routes.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import { SessionKey } from "#context/keys.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
-import { twilioChannel } from "#public/channels/twilio/twilioChannel.js";
+import type { TwilioTextMessage } from "#public/channels/twilio/inbound.js";
+import { twilioChannel, type TwilioContext } from "#public/channels/twilio/twilioChannel.js";
import { signTwilioRequest } from "#public/channels/twilio/verify.js";
const AUTH_TOKEN = "test-auth-token";
@@ -72,6 +73,24 @@ function signedFormRequest(path: string, params: URLSearchParams): Request {
});
}
+function signedGetRequest(path: string, params: URLSearchParams): Request {
+ const url = new URL(`https://example.com${path}`);
+ for (const [key, value] of params) {
+ url.searchParams.append(key, value);
+ }
+ const signature = signTwilioRequest({
+ authToken: AUTH_TOKEN,
+ params: new URLSearchParams(),
+ url: url.toString(),
+ });
+ return new Request(url, {
+ headers: {
+ "x-twilio-signature": signature,
+ },
+ method: "GET",
+ });
+}
+
async function firePost(
channel: unknown,
path: string,
@@ -107,6 +126,41 @@ async function firePost(
return { response, send, waitUntil };
}
+async function fireGet(
+ channel: unknown,
+ path: string,
+ params: URLSearchParams,
+): Promise<{
+ response: Response;
+ send: ReturnType<typeof vi.fn>;
+ waitUntil: ReturnType<typeof vi.fn>;
+}> {
+ const compiled = asCompiled(channel);
+ const get = compiled.routes.find((r) => r.method === "GET" && r.path === path);
+ if (!get || !isHttpRouteDefinition(get)) {
+ throw new Error(`Expected Twilio channel to define GET ${path}.`);
+ }
+ const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });
+ const waitUntil = vi.fn();
+
+ const response = await get.handler(signedGetRequest(path, params), {
+ getSession: vi.fn() as any,
+ params: {},
+ requestIp: null,
+ send,
+ waitUntil,
+ } as any);
+
+ let drained = 0;
+ while (drained < waitUntil.mock.calls.length) {
+ const pending = waitUntil.mock.calls.slice(drained).map(([task]) => task as Promise<unknown>);
+ drained = waitUntil.mock.calls.length;
+ await Promise.allSettled(pending);
+ }
+
+ return { response, send, waitUntil };
+}
+
describe("twilioChannel() inbound text pipeline", () => {
const ORIGINAL_AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN;
@@ -125,8 +179,11 @@ describe("twilioChannel() inbound text pipeline", () => {
it("mounts message, voice, and transcription routes below the base route", () => {
const channel = twilioChannel({ allowFrom: "*", route: "/twilio" });
expect(channel.routes.map((route) => ({ method: route.method, path: route.path }))).toEqual([
+ { method: "GET", path: "/twilio/messages" },
{ method: "POST", path: "/twilio/messages" },
+ { method: "GET", path: "/twilio/voice" },
{ method: "POST", path: "/twilio/voice" },
+ { method: "GET", path: "/twilio/voice/transcription" },
{ method: "POST", path: "/twilio/voice/transcription" },
]);
});
@@ -174,6 +231,57 @@ describe("twilioChannel() inbound text pipeline", () => {
});
});
+ it("dispatches verified GET inbound text webhooks", async () => {
+ const channel = twilioChannel({ allowFrom: "*" });
+ const params = new URLSearchParams({
+ Body: "hello from get",
+ From: "+15551234567",
+ MessageSid: "SM123",
+ To: "+15557654321",
+ });
+
+ const { response, send } = await fireGet(channel, "/eve/v1/twilio/messages", params);
+
+ expect(response.status).toBe(200);
+ expect(send).toHaveBeenCalledTimes(1);
+ const [payload, options] = send.mock.calls[0]!;
+ expect(payload).toMatchObject({ message: "hello from get" });
+ expect(options).toMatchObject({
+ continuationToken: "+15551234567:+15557654321",
+ state: {
+ from: "+15551234567",
+ lastMessageSid: "SM123",
+ to: "+15557654321",
+ },
+ });
+ });
+
+ it("passes inbound media metadata from Twilio message webhooks", async () => {
+ const onText = vi.fn((_ctx: TwilioContext, _message: TwilioTextMessage) => ({ auth: null }));
+ const channel = twilioChannel({ allowFrom: "*", onText });
+ const params = new URLSearchParams({
+ Body: "see attached",
+ From: "+15551234567",
+ MediaContentType0: "image/png",
+ MediaUrl0: "https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123/Media/ME123",
+ NumMedia: "1",
+ To: "+15557654321",
+ });
+
+ await firePost(channel, "/eve/v1/twilio/messages", params);
+
+ expect(onText).toHaveBeenCalledTimes(1);
+ expect(onText.mock.calls[0]![1]).toMatchObject({
+ body: "see attached",
+ media: [
+ {
+ contentType: "image/png",
+ url: "https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123/Media/ME123",
+ },
+ ],
+ });
+ });
+
it("drops inbound text when the sender is not in allowFrom", async () => {
const channel = twilioChannel({ allowFrom: ["+15550000000"] });
const params = new URLSearchParams({
diff --git a/packages/eve/src/public/channels/twilio/twilioChannel.ts b/packages/eve/src/public/channels/twilio/twilioChannel.ts
index 999940a67..ff9ae8644 100644
--- a/packages/eve/src/public/channels/twilio/twilioChannel.ts
+++ b/packages/eve/src/public/channels/twilio/twilioChannel.ts
@@ -1,5 +1,6 @@
import type { SessionHandle } from "#channel/session.js";
import type { SessionAuthContext } from "#channel/types.js";
+import type { RouteHandler } from "#channel/routes.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
import type { ChannelSessionOps } from "#public/definitions/defineChannel.js";
@@ -35,12 +36,15 @@ import {
sayTwilioResponse,
} from "#public/channels/twilio/twiml.js";
import {
- verifyTwilioRequest,
- type TwilioAuthToken,
- type TwilioWebhookUrl,
-} from "#public/channels/twilio/verify.js";
+ buildTwilioActionUrl,
+ buildTwilioRoutes,
+ verifyTwilioInbound,
+ type TwilioRoutes,
+} from "#public/channels/twilio/routing.js";
+import { type TwilioAuthToken, type TwilioWebhookUrl } from "#public/channels/twilio/verify.js";
import {
defineChannel,
+ GET,
POST,
type Channel,
type SendFn,
@@ -278,11 +282,14 @@ export interface TwilioChannel extends Channel<
/** Twilio channel factory for SMS and speech-transcribed inbound calls. */
export function twilioChannel(config: TwilioChannelConfig): TwilioChannel {
assertAllowFromConfigured(config);
- const routes = buildRoutes(config.route ?? "/eve/v1/twilio");
+ const routes = buildTwilioRoutes(config.route ?? "/eve/v1/twilio");
const onText = config.onText ?? defaultOnText;
const onVoice = config.onVoice ?? defaultOnVoice;
const onVoiceTranscription = config.onVoiceTranscription ?? defaultOnVoiceTranscription;
const mergedEvents: TwilioChannelEvents = { ...defaultEvents, ...config.events };
+ const messages = handleTwilioMessages({ config, onText });
+ const voice = handleTwilioVoice({ config, onVoice, routes });
+ const transcription = handleTwilioTranscription({ config, onVoiceTranscription, routes });
return defineChannel<
TwilioChannelState,
@@ -311,77 +318,12 @@ export function twilioChannel(config: TwilioChannelConfig): TwilioChannel {
},
routes: [
- POST<TwilioChannelState>(routes.messages, async (req, { send, waitUntil }) => {
- const verified = await verifyInbound(req, config);
- if (verified === null) return new Response("unauthorized", { status: 401 });
-
- const message = parseTwilioTextMessage(verified.params);
- if (!message) return emptyTwilioResponse();
- if (!(await isAllowed(message.from, config.allowFrom)))
- return new Response("forbidden", { status: 403 });
-
- waitUntil(dispatchText({ config, message, onText, send }));
- return emptyTwilioResponse();
- }),
-
- POST<TwilioChannelState>(routes.voice, async (req) => {
- const verified = await verifyInbound(req, config);
- if (verified === null) return new Response("unauthorized", { status: 401 });
-
- const call = parseTwilioVoiceCall(verified.params);
- if (!call) return sayTwilioResponse("Missing caller information.");
- if (!(await isAllowed(call.from, config.allowFrom)))
- return new Response("forbidden", { status: 403 });
-
- const voiceResult = await acceptVoiceCall({
- call,
- config,
- onVoice,
- });
- if (voiceResult === null) return new Response("forbidden", { status: 403 });
- const voiceOptions = voiceResult ?? {};
-
- return gatherSpeechTwilioResponse({
- actionUrl: await buildActionUrl(req, config, routes.transcription),
- hints: voiceOptions.hints ?? config.voice?.hints,
- language: voiceOptions.language ?? config.voice?.language,
- profanityFilter: voiceOptions.profanityFilter ?? config.voice?.profanityFilter,
- prompt:
- voiceOptions.prompt ??
- config.voice?.prompt ??
- "Please say your message after the tone.",
- speechModel: voiceOptions.speechModel ?? config.voice?.speechModel,
- speechTimeout: voiceOptions.speechTimeout ?? config.voice?.speechTimeout ?? "auto",
- timeoutSeconds: voiceOptions.timeoutSeconds ?? config.voice?.timeoutSeconds,
- voice: voiceOptions.voice ?? config.voice?.voice,
- });
- }),
-
- POST<TwilioChannelState>(routes.transcription, async (req, { send, waitUntil }) => {
- const verified = await verifyInbound(req, config);
- if (verified === null) return new Response("unauthorized", { status: 401 });
-
- const transcription = parseTwilioVoiceTranscription(verified.params);
- if (!transcription) {
- return gatherSpeechTwilioResponse({
- actionUrl: await buildActionUrl(req, config, routes.transcription),
- language: config.voice?.language,
- prompt: config.voice?.prompt ?? "Please say your message after the tone.",
- speechTimeout: config.voice?.speechTimeout ?? "auto",
- timeoutSeconds: config.voice?.timeoutSeconds,
- });
- }
- if (!(await isAllowed(transcription.from, config.allowFrom))) {
- return new Response("forbidden", { status: 403 });
- }
-
- waitUntil(
- dispatchVoiceTranscription({ config, onVoiceTranscription, send, transcription }),
- );
- return sayTwilioResponse(
- config.voice?.acknowledgement ?? "Thanks. I'll follow up by text.",
- );
- }),
+ GET<TwilioChannelState>(routes.messages, messages),
+ POST<TwilioChannelState>(routes.messages, messages),
+ GET<TwilioChannelState>(routes.voice, voice),
+ POST<TwilioChannelState>(routes.voice, voice),
+ GET<TwilioChannelState>(routes.transcription, transcription),
+ POST<TwilioChannelState>(routes.transcription, transcription),
],
async receive(input, { send }) {
@@ -406,6 +348,109 @@ export function twilioChannel(config: TwilioChannelConfig): TwilioChannel {
});
}
+function handleTwilioMessages(input: {
+ readonly config: TwilioChannelConfig;
+ readonly onText: NonNullable<TwilioChannelConfig["onText"]>;
+}): RouteHandler<TwilioChannelState> {
+ return async (req, { send, waitUntil }) => {
+ const verified = await verifyTwilioInbound(req, input.config);
+ if (verified === null) return new Response("unauthorized", { status: 401 });
+
+ const message = parseTwilioTextMessage(verified.params);
+ if (!message) return emptyTwilioResponse();
+ if (!(await isAllowed(message.from, input.config.allowFrom))) {
+ return new Response("forbidden", { status: 403 });
+ }
+
+ waitUntil(
+ dispatchText({
+ config: input.config,
+ message,
+ onText: input.onText,
+ send,
+ }),
+ );
+ return emptyTwilioResponse();
+ };
+}
+
+function handleTwilioVoice(input: {
+ readonly config: TwilioChannelConfig;
+ readonly onVoice: NonNullable<TwilioChannelConfig["onVoice"]>;
+ readonly routes: TwilioRoutes;
+}): RouteHandler<TwilioChannelState> {
+ return async (req) => {
+ const verified = await verifyTwilioInbound(req, input.config);
+ if (verified === null) return new Response("unauthorized", { status: 401 });
+
+ const call = parseTwilioVoiceCall(verified.params);
+ if (!call) return sayTwilioResponse("Missing caller information.");
+ if (!(await isAllowed(call.from, input.config.allowFrom))) {
+ return new Response("forbidden", { status: 403 });
+ }
+
+ const voiceResult = await acceptVoiceCall({
+ call,
+ config: input.config,
+ onVoice: input.onVoice,
+ });
+ if (voiceResult === null) return new Response("forbidden", { status: 403 });
+ const voiceOptions = voiceResult ?? {};
+
+ return gatherSpeechTwilioResponse({
+ actionUrl: await buildTwilioActionUrl(req, input.config, input.routes.transcription),
+ hints: voiceOptions.hints ?? input.config.voice?.hints,
+ language: voiceOptions.language ?? input.config.voice?.language,
+ profanityFilter: voiceOptions.profanityFilter ?? input.config.voice?.profanityFilter,
+ prompt:
+ voiceOptions.prompt ??
+ input.config.voice?.prompt ??
+ "Please say your message after the tone.",
+ speechModel: voiceOptions.speechModel ?? input.config.voice?.speechModel,
+ speechTimeout: voiceOptions.speechTimeout ?? input.config.voice?.speechTimeout ?? "auto",
+ timeoutSeconds: voiceOptions.timeoutSeconds ?? input.config.voice?.timeoutSeconds,
+ voice: voiceOptions.voice ?? input.config.voice?.voice,
+ });
+ };
+}
+
+function handleTwilioTranscription(input: {
+ readonly config: TwilioChannelConfig;
+ readonly onVoiceTranscription: NonNullable<TwilioChannelConfig["onVoiceTranscription"]>;
+ readonly routes: TwilioRoutes;
+}): RouteHandler<TwilioChannelState> {
+ return async (req, { send, waitUntil }) => {
+ const verified = await verifyTwilioInbound(req, input.config);
+ if (verified === null) return new Response("unauthorized", { status: 401 });
+
+ const transcription = parseTwilioVoiceTranscription(verified.params);
+ if (!transcription) {
+ return gatherSpeechTwilioResponse({
+ actionUrl: await buildTwilioActionUrl(req, input.config, input.routes.transcription),
+ language: input.config.voice?.language,
+ prompt: input.config.voice?.prompt ?? "Please say your message after the tone.",
+ speechTimeout: input.config.voice?.speechTimeout ?? "auto",
+ timeoutSeconds: input.config.voice?.timeoutSeconds,
+ });
+ }
+ if (!(await isAllowed(transcription.from, input.config.allowFrom))) {
+ return new Response("forbidden", { status: 403 });
+ }
+
+ waitUntil(
+ dispatchVoiceTranscription({
+ config: input.config,
+ onVoiceTranscription: input.onVoiceTranscription,
+ send,
+ transcription,
+ }),
+ );
+ return sayTwilioResponse(
+ input.config.voice?.acknowledgement ?? "Thanks. I'll follow up by text.",
+ );
+ };
+}
+
function rebuildTwilioContext(
state: TwilioChannelState,
_session: SessionHandle,
@@ -471,19 +516,6 @@ function buildTwilioHandle(input: {
};
}
-function buildRoutes(baseRoute: string): {
- messages: string;
- voice: string;
- transcription: string;
-} {
- const base = baseRoute.endsWith("/") ? baseRoute.slice(0, -1) : baseRoute;
- return {
- messages: `${base}/messages`,
- transcription: `${base}/voice/transcription`,
- voice: `${base}/voice`,
- };
-}
-
function assertAllowFromConfigured(
config: TwilioChannelConfig | undefined,
): asserts config is TwilioChannelConfig {
@@ -492,21 +524,6 @@ function assertAllowFromConfigured(
}
}
-async function verifyInbound(
- req: Request,
- config: TwilioChannelConfig,
-): Promise<{ body: string; params: URLSearchParams } | null> {
- try {
- return await verifyTwilioRequest(req, {
- authToken: config.credentials?.authToken,
- webhookUrl: config.webhookUrl,
- });
- } catch (error) {
- log.warn("twilio inbound verification failed", { error });
- return null;
- }
-}
-
async function dispatchText(input: {
readonly config: TwilioChannelConfig;
readonly message: TwilioTextMessage;
@@ -644,27 +661,6 @@ async function isAllowed(from: string, allowFrom: TwilioAllowFrom): Promise<bool
return typeof resolved === "string" ? resolved === from : resolved.includes(from);
}
-async function buildActionUrl(
- request: Request,
- config: TwilioChannelConfig,
- route: string,
-): Promise<string> {
- const base =
- typeof config.publicBaseUrl === "function"
- ? await config.publicBaseUrl(request)
- : config.publicBaseUrl;
- if (base) return new URL(route, ensureTrailingSlash(base)).toString();
-
- const url = new URL(request.url);
- url.pathname = route;
- url.search = "";
- return url.toString();
-}
-
-function ensureTrailingSlash(value: string): string {
- return value.endsWith("/") ? value : `${value}/`;
-}
-
function readString(value: unknown): string | undefined {
return typeof value === "string" && value.length > 0 ? value : undefined;
}
diff --git a/packages/eve/src/public/channels/twilio/twiml.ts b/packages/eve/src/public/channels/twilio/twiml.ts
index 029ab52cc..8aa602774 100644
--- a/packages/eve/src/public/channels/twilio/twiml.ts
+++ b/packages/eve/src/public/channels/twilio/twiml.ts
@@ -1,89 +1,18 @@
-/**
- * Tiny TwiML builders for Twilio webhook responses.
- *
- * The channel keeps TwiML generation local so callers do not need the
- * Twilio SDK just to acknowledge a webhook or gather speech.
- */
+import {
+ emptyTwilioResponse,
+ escapeXml,
+ gatherSpeechTwilioResponse,
+ sayTwilioResponse,
+ twilioResponse,
+ type TwilioGatherSpeechResponseOptions,
+} from "#compiled/@chat-adapter/twilio/voice.js";
-/** Options for rendering a voice `<Gather input="speech">` response. */
-export interface TwilioGatherTwimlOptions {
- /** Absolute callback URL that receives the speech result. */
- readonly actionUrl: string;
- /** Prompt spoken before Twilio starts speech recognition. */
- readonly prompt: string;
- /** Twilio `<Say voice>` used for the prompt, e.g. `Polly.Joanna-Neural`. */
- readonly voice?: string;
- /** BCP 47 language used for speech recognition and the nested `<Say>` prompt. */
- readonly language?: string;
- /** Twilio `<Gather speechModel>` used for speech recognition. */
- readonly speechModel?: string;
- /** Twilio `<Gather timeout>` in seconds. */
- readonly timeoutSeconds?: number;
- /** Twilio `<Gather speechTimeout>`, such as `"auto"` or a second count string. */
- readonly speechTimeout?: string;
- /** Twilio `<Gather hints>` for expected words or phrases. */
- readonly hints?: string | readonly string[];
- /** Twilio `<Gather profanityFilter>` toggle. */
- readonly profanityFilter?: boolean;
-}
-
-/** Returns an empty TwiML response, useful for acknowledging inbound SMS without replying. */
-export function emptyTwilioResponse(): Response {
- return twimlResponse("<Response></Response>");
-}
-
-/** Returns a TwiML response that speaks `message` and then ends the call. */
-export function sayTwilioResponse(message: string): Response {
- return twimlResponse(`<Response><Say>${escapeXml(message)}</Say></Response>`);
-}
+/** Options for rendering a Twilio `<Gather input="speech">` TwiML response. */
+export type TwilioGatherTwimlOptions = TwilioGatherSpeechResponseOptions;
-/** Returns a TwiML response that asks the caller to speak and posts the transcript to `actionUrl`. */
-export function gatherSpeechTwilioResponse(options: TwilioGatherTwimlOptions): Response {
- const hints = typeof options.hints === "string" ? options.hints : options.hints?.join(",");
- const attributes = [
- `input="speech"`,
- `action="${escapeXml(options.actionUrl)}"`,
- `method="POST"`,
- `actionOnEmptyResult="true"`,
- options.language ? `language="${escapeXml(options.language)}"` : undefined,
- options.speechModel ? `speechModel="${escapeXml(options.speechModel)}"` : undefined,
- options.timeoutSeconds !== undefined ? `timeout="${options.timeoutSeconds}"` : undefined,
- options.speechTimeout ? `speechTimeout="${escapeXml(options.speechTimeout)}"` : undefined,
- hints ? `hints="${escapeXml(hints)}"` : undefined,
- options.profanityFilter !== undefined
- ? `profanityFilter="${options.profanityFilter ? "true" : "false"}"`
- : undefined,
- ]
- .filter((value): value is string => value !== undefined)
- .join(" ");
+export { emptyTwilioResponse, escapeXml, gatherSpeechTwilioResponse, sayTwilioResponse };
- const sayAttributes = [
- options.voice ? `voice="${escapeXml(options.voice)}"` : undefined,
- options.language ? `language="${escapeXml(options.language)}"` : undefined,
- ]
- .filter((value): value is string => value !== undefined)
- .join(" ");
- const sayOpen = sayAttributes ? `<Say ${sayAttributes}>` : "<Say>";
-
- return twimlResponse(
- `<Response><Gather ${attributes}>${sayOpen}${escapeXml(options.prompt)}</Say></Gather></Response>`,
- );
-}
-
-/** Wraps a TwiML string in a Twilio-compatible XML response. */
+/** Wraps a TwiML string in an XML `Response`. */
export function twimlResponse(twiml: string): Response {
- return new Response(twiml, {
- status: 200,
- headers: { "content-type": "text/xml;charset=UTF-8" },
- });
-}
-
-/** Escapes the five XML predefined entities (`&`, `<`, `>`, `"`, `'`) for safe use in TwiML element content or attribute values. Note that `'` becomes `&apos;`. */
-export function escapeXml(value: string): string {
- return value
- .replaceAll("&", "&amp;")
- .replaceAll("<", "&lt;")
- .replaceAll(">", "&gt;")
- .replaceAll('"', "&quot;")
- .replaceAll("'", "&apos;");
+ return twilioResponse(twiml);
}
diff --git a/packages/eve/src/public/channels/twilio/verify.ts b/packages/eve/src/public/channels/twilio/verify.ts
index 2f7a81255..5329b0120 100644
--- a/packages/eve/src/public/channels/twilio/verify.ts
+++ b/packages/eve/src/public/channels/twilio/verify.ts
@@ -1,79 +1,70 @@
-/**
- * Twilio inbound-webhook verification.
- *
- * Twilio signs webhook requests with `X-Twilio-Signature`. For form
- * posts, the signed payload is the exact public URL Twilio called plus
- * every POST parameter sorted by name and appended as `name + value`.
- */
-
-import { createHmac, timingSafeEqual } from "node:crypto";
+import { createHmac } from "node:crypto";
-import { createLogger } from "#internal/logging.js";
+import {
+ resolveTwilioCredential,
+ TwilioApiError,
+ type TwilioCredential,
+} from "#compiled/@chat-adapter/twilio/api.js";
+import {
+ twilioSignatureBase,
+ verifyTwilioRequest as verifyPrimitive,
+ TwilioWebhookVerificationError,
+ type TwilioVerifiedRequest,
+ type TwilioWebhookUrl,
+} from "#compiled/@chat-adapter/twilio/webhook.js";
-const log = createLogger("twilio.verify");
+/** Twilio auth token, materialized directly or from an async secret provider. */
+export type TwilioAuthToken = TwilioCredential;
-/** Auth token, materialized either directly or from an async secret provider. */
-export type TwilioAuthToken = string | (() => string | Promise<string>);
+export type { TwilioVerifiedRequest, TwilioWebhookUrl };
-/** Public URL resolver used when the runtime request URL differs from Twilio's configured URL. */
-export type TwilioWebhookUrl = string | ((request: Request) => string | Promise<string>);
-
-/**
- * Parsed and verified Twilio webhook body.
- *
- * `params` contains every form parameter Twilio sent. Signature
- * validation happens before the channel reads any business fields.
- */
-export interface TwilioVerifiedRequest {
- readonly body: string;
- readonly params: URLSearchParams;
-}
-
-/** Options for {@link verifyTwilioRequest}. */
+/** Options for verifying Twilio inbound webhooks. */
export interface TwilioVerifyOptions {
- /** Auth token used to verify the signature. When undefined, falls back to `TWILIO_AUTH_TOKEN`. */
+ /** Auth token used to verify the signature. Defaults to `TWILIO_AUTH_TOKEN`. */
readonly authToken: TwilioAuthToken | undefined;
- /** Public URL Twilio signed. Defaults to `request.url`; set this when a proxy or tunnel rewrites the URL. */
+ /** Public URL Twilio signed. Set this when a proxy or tunnel rewrites `request.url`. */
readonly webhookUrl?: TwilioWebhookUrl;
}
/** Resolves a Twilio auth token, falling back to `TWILIO_AUTH_TOKEN`. */
export async function resolveTwilioAuthToken(authToken?: TwilioAuthToken): Promise<string> {
- const source = authToken ?? process.env.TWILIO_AUTH_TOKEN;
- if (!source) throw new Error("TWILIO_AUTH_TOKEN is required.");
- return typeof source === "function" ? await source() : source;
+ try {
+ return await resolveTwilioCredential(authToken, "TWILIO_AUTH_TOKEN");
+ } catch (error) {
+ if (error instanceof TwilioApiError && error.status === 0) {
+ throw new Error("TWILIO_AUTH_TOKEN is required.");
+ }
+ throw error;
+ }
}
/**
- * Verifies an inbound Twilio webhook and returns the raw body plus parsed form params.
- *
- * Consumes the request body, so the passed `Request` cannot be re-read afterward.
- * The signed URL comes from `options.webhookUrl` (falling back to `request.url`).
- * Set `webhookUrl` when a proxy or tunnel rewrites the URL. A rewritten URL causes
- * the signed payload to differ, so the signature check fails.
+ * Verifies an inbound Twilio webhook and returns the raw body plus parsed params.
*
- * Throws when the auth token is missing, the `X-Twilio-Signature` header is absent,
- * or the computed signature does not match.
+ * This preserves Eve's existing error messages while delegating signature
+ * semantics to the Chat SDK Twilio primitive.
*/
export async function verifyTwilioRequest(
request: Request,
options: TwilioVerifyOptions,
): Promise<TwilioVerifiedRequest> {
- const body = await request.text();
- const params = new URLSearchParams(body);
- const authToken = await resolveTwilioAuthToken(options.authToken);
- const signature = request.headers.get("x-twilio-signature") ?? "";
+ const signature = request.headers.get("x-twilio-signature");
if (!signature) {
throw new Error("twilioChannel: inbound request missing X-Twilio-Signature.");
}
- const url = await resolveWebhookUrl(request, options.webhookUrl);
- const expected = signTwilioRequest({ authToken, params, url });
- if (!constantTimeCompare(expected, signature)) {
- throw new Error("twilioChannel: inbound request signature mismatch.");
+ const authToken = await resolveTwilioAuthToken(options.authToken);
+ try {
+ return await verifyPrimitive(request, {
+ authToken,
+ webhookUrl: options.webhookUrl,
+ });
+ } catch (error) {
+ if (error instanceof TwilioWebhookVerificationError) {
+ throw new Error("twilioChannel: inbound request signature mismatch.");
+ }
+ throw error;
}
-
- return { body, params };
}
/** Computes Twilio's HMAC-SHA1 request signature. */
@@ -86,34 +77,7 @@ export function signTwilioRequest(input: {
return createHmac("sha1", input.authToken).update(base).digest("base64");
}
-/** Builds the string Twilio signs for a form POST webhook. */
+/** Builds the string Twilio signs for a webhook request. */
export function buildTwilioSignatureBase(url: string, params: URLSearchParams): string {
- const entries = Array.from(params.entries()).sort(([aName, aValue], [bName, bValue]) => {
- const nameOrder = aName < bName ? -1 : aName > bName ? 1 : 0;
- if (nameOrder !== 0) return nameOrder;
- return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
- });
- let base = url;
- for (const [name, value] of entries) {
- base += `${name}${value}`;
- }
- return base;
-}
-
-async function resolveWebhookUrl(
- request: Request,
- webhookUrl: TwilioWebhookUrl | undefined,
-): Promise<string> {
- if (typeof webhookUrl === "function") return webhookUrl(request);
- return webhookUrl ?? request.url;
-}
-
-function constantTimeCompare(a: string, b: string): boolean {
- if (a.length !== b.length) return false;
- try {
- return timingSafeEqual(Buffer.from(a), Buffer.from(b));
- } catch (error) {
- log.debug("timingSafeEqual threw", { error });
- return false;
- }
+ return twilioSignatureBase(url, params);
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 72534e7f2..6e0371299 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -824,6 +824,9 @@ importers:
'@chat-adapter/state-memory':
specifier: 4.31.0
+ '@chat-adapter/twilio':
+ specifier: 4.31.0
'@clack/core':
specifier: 1.3.1
version: 1.3.1
@@ -1361,6 +1364,10 @@ packages:
resolution: {integrity: sha512-QsxWce5OaY+j980dRCfFZSIoVHtg+gOg6p4IOWVsB4vxwXFin8CNg/hd34kvnmzqizbD/tmLze0Pkq/sKC4NLg==}
engines: {node: '>=20'}
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-H3zMgpgIraKMloHDOVSslIk4d+eGhuKBkS7/X0KU//3wrR270qxMPAgRT2cK4NMsaBprEVrBrRh6Zf38gdb7Ag==}
+ engines: {node: '>=20'}
+
'@chevrotain/[email protected]':
resolution: {integrity: sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==}
@@ -13481,6 +13488,15 @@ snapshots:
- supports-color
- zod
+ dependencies:
+ '@chat-adapter/shared': 4.31.0([email protected]([email protected]))([email protected])
+ transitivePeerDependencies:
+ - ai
+ - supports-color
+ - zod
+
'@chevrotain/[email protected]': {}