@openclaw/voice-call 2026.1.29

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 (44) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +135 -0
  3. package/index.ts +497 -0
  4. package/openclaw.plugin.json +601 -0
  5. package/package.json +16 -0
  6. package/src/cli.ts +312 -0
  7. package/src/config.test.ts +204 -0
  8. package/src/config.ts +502 -0
  9. package/src/core-bridge.ts +198 -0
  10. package/src/manager/context.ts +21 -0
  11. package/src/manager/events.ts +177 -0
  12. package/src/manager/lookup.ts +33 -0
  13. package/src/manager/outbound.ts +248 -0
  14. package/src/manager/state.ts +50 -0
  15. package/src/manager/store.ts +88 -0
  16. package/src/manager/timers.ts +86 -0
  17. package/src/manager/twiml.ts +9 -0
  18. package/src/manager.test.ts +108 -0
  19. package/src/manager.ts +888 -0
  20. package/src/media-stream.test.ts +97 -0
  21. package/src/media-stream.ts +393 -0
  22. package/src/providers/base.ts +67 -0
  23. package/src/providers/index.ts +10 -0
  24. package/src/providers/mock.ts +168 -0
  25. package/src/providers/plivo.test.ts +28 -0
  26. package/src/providers/plivo.ts +504 -0
  27. package/src/providers/stt-openai-realtime.ts +311 -0
  28. package/src/providers/telnyx.ts +364 -0
  29. package/src/providers/tts-openai.ts +264 -0
  30. package/src/providers/twilio/api.ts +45 -0
  31. package/src/providers/twilio/webhook.ts +30 -0
  32. package/src/providers/twilio.test.ts +64 -0
  33. package/src/providers/twilio.ts +595 -0
  34. package/src/response-generator.ts +171 -0
  35. package/src/runtime.ts +217 -0
  36. package/src/telephony-audio.ts +88 -0
  37. package/src/telephony-tts.ts +95 -0
  38. package/src/tunnel.ts +331 -0
  39. package/src/types.ts +273 -0
  40. package/src/utils.ts +12 -0
  41. package/src/voice-mapping.ts +65 -0
  42. package/src/webhook-security.test.ts +260 -0
  43. package/src/webhook-security.ts +469 -0
  44. package/src/webhook.ts +491 -0
@@ -0,0 +1,469 @@
1
+ import crypto from "node:crypto";
2
+
3
+ import type { WebhookContext } from "./types.js";
4
+
5
+ /**
6
+ * Validate Twilio webhook signature using HMAC-SHA1.
7
+ *
8
+ * Twilio signs requests by concatenating the URL with sorted POST params,
9
+ * then computing HMAC-SHA1 with the auth token.
10
+ *
11
+ * @see https://www.twilio.com/docs/usage/webhooks/webhooks-security
12
+ */
13
+ export function validateTwilioSignature(
14
+ authToken: string,
15
+ signature: string | undefined,
16
+ url: string,
17
+ params: URLSearchParams,
18
+ ): boolean {
19
+ if (!signature) {
20
+ return false;
21
+ }
22
+
23
+ // Build the string to sign: URL + sorted params (key+value pairs)
24
+ let dataToSign = url;
25
+
26
+ // Sort params alphabetically and append key+value
27
+ const sortedParams = Array.from(params.entries()).sort((a, b) =>
28
+ a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0,
29
+ );
30
+
31
+ for (const [key, value] of sortedParams) {
32
+ dataToSign += key + value;
33
+ }
34
+
35
+ // HMAC-SHA1 with auth token, then base64 encode
36
+ const expectedSignature = crypto
37
+ .createHmac("sha1", authToken)
38
+ .update(dataToSign)
39
+ .digest("base64");
40
+
41
+ // Use timing-safe comparison to prevent timing attacks
42
+ return timingSafeEqual(signature, expectedSignature);
43
+ }
44
+
45
+ /**
46
+ * Timing-safe string comparison to prevent timing attacks.
47
+ */
48
+ function timingSafeEqual(a: string, b: string): boolean {
49
+ if (a.length !== b.length) {
50
+ // Still do comparison to maintain constant time
51
+ const dummy = Buffer.from(a);
52
+ crypto.timingSafeEqual(dummy, dummy);
53
+ return false;
54
+ }
55
+
56
+ const bufA = Buffer.from(a);
57
+ const bufB = Buffer.from(b);
58
+ return crypto.timingSafeEqual(bufA, bufB);
59
+ }
60
+
61
+ /**
62
+ * Reconstruct the public webhook URL from request headers.
63
+ *
64
+ * When behind a reverse proxy (Tailscale, nginx, ngrok), the original URL
65
+ * used by Twilio differs from the local request URL. We use standard
66
+ * forwarding headers to reconstruct it.
67
+ *
68
+ * Priority order:
69
+ * 1. X-Forwarded-Proto + X-Forwarded-Host (standard proxy headers)
70
+ * 2. X-Original-Host (nginx)
71
+ * 3. Ngrok-Forwarded-Host (ngrok specific)
72
+ * 4. Host header (direct connection)
73
+ */
74
+ export function reconstructWebhookUrl(ctx: WebhookContext): string {
75
+ const { headers } = ctx;
76
+
77
+ const proto = getHeader(headers, "x-forwarded-proto") || "https";
78
+
79
+ const forwardedHost =
80
+ getHeader(headers, "x-forwarded-host") ||
81
+ getHeader(headers, "x-original-host") ||
82
+ getHeader(headers, "ngrok-forwarded-host") ||
83
+ getHeader(headers, "host") ||
84
+ "";
85
+
86
+ // Extract path from the context URL (fallback to "/" on parse failure)
87
+ let path = "/";
88
+ try {
89
+ const parsed = new URL(ctx.url);
90
+ path = parsed.pathname + parsed.search;
91
+ } catch {
92
+ // URL parsing failed
93
+ }
94
+
95
+ // Remove port from host (ngrok URLs don't have ports)
96
+ const host = forwardedHost.split(":")[0] || forwardedHost;
97
+
98
+ return `${proto}://${host}${path}`;
99
+ }
100
+
101
+ function buildTwilioVerificationUrl(
102
+ ctx: WebhookContext,
103
+ publicUrl?: string,
104
+ ): string {
105
+ if (!publicUrl) {
106
+ return reconstructWebhookUrl(ctx);
107
+ }
108
+
109
+ try {
110
+ const base = new URL(publicUrl);
111
+ const requestUrl = new URL(ctx.url);
112
+ base.pathname = requestUrl.pathname;
113
+ base.search = requestUrl.search;
114
+ return base.toString();
115
+ } catch {
116
+ return publicUrl;
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Get a header value, handling both string and string[] types.
122
+ */
123
+ function getHeader(
124
+ headers: Record<string, string | string[] | undefined>,
125
+ name: string,
126
+ ): string | undefined {
127
+ const value = headers[name.toLowerCase()];
128
+ if (Array.isArray(value)) {
129
+ return value[0];
130
+ }
131
+ return value;
132
+ }
133
+
134
+ function isLoopbackAddress(address?: string): boolean {
135
+ if (!address) return false;
136
+ if (address === "127.0.0.1" || address === "::1") return true;
137
+ if (address.startsWith("::ffff:127.")) return true;
138
+ return false;
139
+ }
140
+
141
+ /**
142
+ * Result of Twilio webhook verification with detailed info.
143
+ */
144
+ export interface TwilioVerificationResult {
145
+ ok: boolean;
146
+ reason?: string;
147
+ /** The URL that was used for verification (for debugging) */
148
+ verificationUrl?: string;
149
+ /** Whether we're running behind ngrok free tier */
150
+ isNgrokFreeTier?: boolean;
151
+ }
152
+
153
+ /**
154
+ * Verify Twilio webhook with full context and detailed result.
155
+ *
156
+ * Handles the special case of ngrok free tier where signature validation
157
+ * may fail due to URL discrepancies (ngrok adds interstitial page handling).
158
+ */
159
+ export function verifyTwilioWebhook(
160
+ ctx: WebhookContext,
161
+ authToken: string,
162
+ options?: {
163
+ /** Override the public URL (e.g., from config) */
164
+ publicUrl?: string;
165
+ /** Allow ngrok free tier compatibility mode (loopback only, less secure) */
166
+ allowNgrokFreeTierLoopbackBypass?: boolean;
167
+ /** Skip verification entirely (only for development) */
168
+ skipVerification?: boolean;
169
+ },
170
+ ): TwilioVerificationResult {
171
+ // Allow skipping verification for development/testing
172
+ if (options?.skipVerification) {
173
+ return { ok: true, reason: "verification skipped (dev mode)" };
174
+ }
175
+
176
+ const signature = getHeader(ctx.headers, "x-twilio-signature");
177
+
178
+ if (!signature) {
179
+ return { ok: false, reason: "Missing X-Twilio-Signature header" };
180
+ }
181
+
182
+ // Reconstruct the URL Twilio used
183
+ const verificationUrl = buildTwilioVerificationUrl(ctx, options?.publicUrl);
184
+
185
+ // Parse the body as URL-encoded params
186
+ const params = new URLSearchParams(ctx.rawBody);
187
+
188
+ // Validate signature
189
+ const isValid = validateTwilioSignature(
190
+ authToken,
191
+ signature,
192
+ verificationUrl,
193
+ params,
194
+ );
195
+
196
+ if (isValid) {
197
+ return { ok: true, verificationUrl };
198
+ }
199
+
200
+ // Check if this is ngrok free tier - the URL might have different format
201
+ const isNgrokFreeTier =
202
+ verificationUrl.includes(".ngrok-free.app") ||
203
+ verificationUrl.includes(".ngrok.io");
204
+
205
+ if (
206
+ isNgrokFreeTier &&
207
+ options?.allowNgrokFreeTierLoopbackBypass &&
208
+ isLoopbackAddress(ctx.remoteAddress)
209
+ ) {
210
+ console.warn(
211
+ "[voice-call] Twilio signature validation failed (ngrok free tier compatibility, loopback only)",
212
+ );
213
+ return {
214
+ ok: true,
215
+ reason: "ngrok free tier compatibility mode (loopback only)",
216
+ verificationUrl,
217
+ isNgrokFreeTier: true,
218
+ };
219
+ }
220
+
221
+ return {
222
+ ok: false,
223
+ reason: `Invalid signature for URL: ${verificationUrl}`,
224
+ verificationUrl,
225
+ isNgrokFreeTier,
226
+ };
227
+ }
228
+
229
+ // -----------------------------------------------------------------------------
230
+ // Plivo webhook verification
231
+ // -----------------------------------------------------------------------------
232
+
233
+ /**
234
+ * Result of Plivo webhook verification with detailed info.
235
+ */
236
+ export interface PlivoVerificationResult {
237
+ ok: boolean;
238
+ reason?: string;
239
+ verificationUrl?: string;
240
+ /** Signature version used for verification */
241
+ version?: "v3" | "v2";
242
+ }
243
+
244
+ function normalizeSignatureBase64(input: string): string {
245
+ // Canonicalize base64 to match Plivo SDK behavior (decode then re-encode).
246
+ return Buffer.from(input, "base64").toString("base64");
247
+ }
248
+
249
+ function getBaseUrlNoQuery(url: string): string {
250
+ const u = new URL(url);
251
+ return `${u.protocol}//${u.host}${u.pathname}`;
252
+ }
253
+
254
+ function timingSafeEqualString(a: string, b: string): boolean {
255
+ if (a.length !== b.length) {
256
+ const dummy = Buffer.from(a);
257
+ crypto.timingSafeEqual(dummy, dummy);
258
+ return false;
259
+ }
260
+ return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
261
+ }
262
+
263
+ function validatePlivoV2Signature(params: {
264
+ authToken: string;
265
+ signature: string;
266
+ nonce: string;
267
+ url: string;
268
+ }): boolean {
269
+ const baseUrl = getBaseUrlNoQuery(params.url);
270
+ const digest = crypto
271
+ .createHmac("sha256", params.authToken)
272
+ .update(baseUrl + params.nonce)
273
+ .digest("base64");
274
+ const expected = normalizeSignatureBase64(digest);
275
+ const provided = normalizeSignatureBase64(params.signature);
276
+ return timingSafeEqualString(expected, provided);
277
+ }
278
+
279
+ type PlivoParamMap = Record<string, string[]>;
280
+
281
+ function toParamMapFromSearchParams(sp: URLSearchParams): PlivoParamMap {
282
+ const map: PlivoParamMap = {};
283
+ for (const [key, value] of sp.entries()) {
284
+ if (!map[key]) map[key] = [];
285
+ map[key].push(value);
286
+ }
287
+ return map;
288
+ }
289
+
290
+ function sortedQueryString(params: PlivoParamMap): string {
291
+ const parts: string[] = [];
292
+ for (const key of Object.keys(params).sort()) {
293
+ const values = [...params[key]].sort();
294
+ for (const value of values) {
295
+ parts.push(`${key}=${value}`);
296
+ }
297
+ }
298
+ return parts.join("&");
299
+ }
300
+
301
+ function sortedParamsString(params: PlivoParamMap): string {
302
+ const parts: string[] = [];
303
+ for (const key of Object.keys(params).sort()) {
304
+ const values = [...params[key]].sort();
305
+ for (const value of values) {
306
+ parts.push(`${key}${value}`);
307
+ }
308
+ }
309
+ return parts.join("");
310
+ }
311
+
312
+ function constructPlivoV3BaseUrl(params: {
313
+ method: "GET" | "POST";
314
+ url: string;
315
+ postParams: PlivoParamMap;
316
+ }): string {
317
+ const hasPostParams = Object.keys(params.postParams).length > 0;
318
+ const u = new URL(params.url);
319
+ const baseNoQuery = `${u.protocol}//${u.host}${u.pathname}`;
320
+
321
+ const queryMap = toParamMapFromSearchParams(u.searchParams);
322
+ const queryString = sortedQueryString(queryMap);
323
+
324
+ // In the Plivo V3 algorithm, the query portion is always sorted, and if we
325
+ // have POST params we add a '.' separator after the query string.
326
+ let baseUrl = baseNoQuery;
327
+ if (queryString.length > 0 || hasPostParams) {
328
+ baseUrl = `${baseNoQuery}?${queryString}`;
329
+ }
330
+ if (queryString.length > 0 && hasPostParams) {
331
+ baseUrl = `${baseUrl}.`;
332
+ }
333
+
334
+ if (params.method === "GET") {
335
+ return baseUrl;
336
+ }
337
+
338
+ return baseUrl + sortedParamsString(params.postParams);
339
+ }
340
+
341
+ function validatePlivoV3Signature(params: {
342
+ authToken: string;
343
+ signatureHeader: string;
344
+ nonce: string;
345
+ method: "GET" | "POST";
346
+ url: string;
347
+ postParams: PlivoParamMap;
348
+ }): boolean {
349
+ const baseUrl = constructPlivoV3BaseUrl({
350
+ method: params.method,
351
+ url: params.url,
352
+ postParams: params.postParams,
353
+ });
354
+
355
+ const hmacBase = `${baseUrl}.${params.nonce}`;
356
+ const digest = crypto
357
+ .createHmac("sha256", params.authToken)
358
+ .update(hmacBase)
359
+ .digest("base64");
360
+ const expected = normalizeSignatureBase64(digest);
361
+
362
+ // Header can contain multiple signatures separated by commas.
363
+ const provided = params.signatureHeader
364
+ .split(",")
365
+ .map((s) => s.trim())
366
+ .filter(Boolean)
367
+ .map((s) => normalizeSignatureBase64(s));
368
+
369
+ for (const sig of provided) {
370
+ if (timingSafeEqualString(expected, sig)) return true;
371
+ }
372
+ return false;
373
+ }
374
+
375
+ /**
376
+ * Verify Plivo webhooks using V3 signature if present; fall back to V2.
377
+ *
378
+ * Header names (case-insensitive; Node provides lower-case keys):
379
+ * - V3: X-Plivo-Signature-V3 / X-Plivo-Signature-V3-Nonce
380
+ * - V2: X-Plivo-Signature-V2 / X-Plivo-Signature-V2-Nonce
381
+ */
382
+ export function verifyPlivoWebhook(
383
+ ctx: WebhookContext,
384
+ authToken: string,
385
+ options?: {
386
+ /** Override the public URL origin (host) used for verification */
387
+ publicUrl?: string;
388
+ /** Skip verification entirely (only for development) */
389
+ skipVerification?: boolean;
390
+ },
391
+ ): PlivoVerificationResult {
392
+ if (options?.skipVerification) {
393
+ return { ok: true, reason: "verification skipped (dev mode)" };
394
+ }
395
+
396
+ const signatureV3 = getHeader(ctx.headers, "x-plivo-signature-v3");
397
+ const nonceV3 = getHeader(ctx.headers, "x-plivo-signature-v3-nonce");
398
+ const signatureV2 = getHeader(ctx.headers, "x-plivo-signature-v2");
399
+ const nonceV2 = getHeader(ctx.headers, "x-plivo-signature-v2-nonce");
400
+
401
+ const reconstructed = reconstructWebhookUrl(ctx);
402
+ let verificationUrl = reconstructed;
403
+ if (options?.publicUrl) {
404
+ try {
405
+ const req = new URL(reconstructed);
406
+ const base = new URL(options.publicUrl);
407
+ base.pathname = req.pathname;
408
+ base.search = req.search;
409
+ verificationUrl = base.toString();
410
+ } catch {
411
+ verificationUrl = reconstructed;
412
+ }
413
+ }
414
+
415
+ if (signatureV3 && nonceV3) {
416
+ const method =
417
+ ctx.method === "GET" || ctx.method === "POST" ? ctx.method : null;
418
+
419
+ if (!method) {
420
+ return {
421
+ ok: false,
422
+ version: "v3",
423
+ verificationUrl,
424
+ reason: `Unsupported HTTP method for Plivo V3 signature: ${ctx.method}`,
425
+ };
426
+ }
427
+
428
+ const postParams = toParamMapFromSearchParams(new URLSearchParams(ctx.rawBody));
429
+ const ok = validatePlivoV3Signature({
430
+ authToken,
431
+ signatureHeader: signatureV3,
432
+ nonce: nonceV3,
433
+ method,
434
+ url: verificationUrl,
435
+ postParams,
436
+ });
437
+ return ok
438
+ ? { ok: true, version: "v3", verificationUrl }
439
+ : {
440
+ ok: false,
441
+ version: "v3",
442
+ verificationUrl,
443
+ reason: "Invalid Plivo V3 signature",
444
+ };
445
+ }
446
+
447
+ if (signatureV2 && nonceV2) {
448
+ const ok = validatePlivoV2Signature({
449
+ authToken,
450
+ signature: signatureV2,
451
+ nonce: nonceV2,
452
+ url: verificationUrl,
453
+ });
454
+ return ok
455
+ ? { ok: true, version: "v2", verificationUrl }
456
+ : {
457
+ ok: false,
458
+ version: "v2",
459
+ verificationUrl,
460
+ reason: "Invalid Plivo V2 signature",
461
+ };
462
+ }
463
+
464
+ return {
465
+ ok: false,
466
+ reason: "Missing Plivo signature headers (V3 or V2)",
467
+ verificationUrl,
468
+ };
469
+ }