@kodelyth/voice-call 2026.5.42 → 2026.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/package.json +18 -6
  2. package/api.ts +0 -16
  3. package/cli-metadata.ts +0 -10
  4. package/config-api.ts +0 -12
  5. package/index.test.ts +0 -1075
  6. package/index.ts +0 -863
  7. package/runtime-api.ts +0 -20
  8. package/runtime-entry.ts +0 -1
  9. package/setup-api.ts +0 -47
  10. package/src/allowlist.test.ts +0 -18
  11. package/src/allowlist.ts +0 -19
  12. package/src/cli.test.ts +0 -12
  13. package/src/cli.ts +0 -866
  14. package/src/config-compat.test.ts +0 -130
  15. package/src/config-compat.ts +0 -227
  16. package/src/config.test.ts +0 -542
  17. package/src/config.ts +0 -883
  18. package/src/core-bridge.ts +0 -14
  19. package/src/deep-merge.test.ts +0 -40
  20. package/src/deep-merge.ts +0 -23
  21. package/src/gateway-continue-operation.ts +0 -200
  22. package/src/http-headers.test.ts +0 -16
  23. package/src/http-headers.ts +0 -15
  24. package/src/manager/context.ts +0 -50
  25. package/src/manager/events.test.ts +0 -578
  26. package/src/manager/events.ts +0 -332
  27. package/src/manager/lifecycle.ts +0 -53
  28. package/src/manager/lookup.test.ts +0 -52
  29. package/src/manager/lookup.ts +0 -35
  30. package/src/manager/outbound.test.ts +0 -629
  31. package/src/manager/outbound.ts +0 -508
  32. package/src/manager/state.ts +0 -48
  33. package/src/manager/store.ts +0 -107
  34. package/src/manager/timers.test.ts +0 -127
  35. package/src/manager/timers.ts +0 -113
  36. package/src/manager/twiml.test.ts +0 -13
  37. package/src/manager/twiml.ts +0 -17
  38. package/src/manager.closed-loop.test.ts +0 -259
  39. package/src/manager.inbound-allowlist.test.ts +0 -183
  40. package/src/manager.notify.test.ts +0 -390
  41. package/src/manager.restore.test.ts +0 -310
  42. package/src/manager.test-harness.ts +0 -127
  43. package/src/manager.ts +0 -441
  44. package/src/media-stream.test.ts +0 -953
  45. package/src/media-stream.ts +0 -876
  46. package/src/providers/base.ts +0 -99
  47. package/src/providers/mock.test.ts +0 -86
  48. package/src/providers/mock.ts +0 -185
  49. package/src/providers/plivo.test.ts +0 -93
  50. package/src/providers/plivo.ts +0 -601
  51. package/src/providers/shared/call-status.test.ts +0 -24
  52. package/src/providers/shared/call-status.ts +0 -24
  53. package/src/providers/shared/guarded-json-api.test.ts +0 -127
  54. package/src/providers/shared/guarded-json-api.ts +0 -49
  55. package/src/providers/telnyx.test.ts +0 -489
  56. package/src/providers/telnyx.ts +0 -419
  57. package/src/providers/twilio/api.test.ts +0 -184
  58. package/src/providers/twilio/api.ts +0 -100
  59. package/src/providers/twilio/twiml-policy.test.ts +0 -84
  60. package/src/providers/twilio/twiml-policy.ts +0 -87
  61. package/src/providers/twilio/webhook.ts +0 -34
  62. package/src/providers/twilio.test.ts +0 -607
  63. package/src/providers/twilio.ts +0 -861
  64. package/src/providers/twilio.types.ts +0 -17
  65. package/src/realtime-agent-context.test.ts +0 -101
  66. package/src/realtime-agent-context.ts +0 -149
  67. package/src/realtime-defaults.ts +0 -3
  68. package/src/realtime-fast-context.test.ts +0 -74
  69. package/src/realtime-fast-context.ts +0 -27
  70. package/src/realtime-transcription.runtime.ts +0 -4
  71. package/src/realtime-voice.runtime.ts +0 -5
  72. package/src/response-generator.test.ts +0 -385
  73. package/src/response-generator.ts +0 -348
  74. package/src/response-model.test.ts +0 -71
  75. package/src/response-model.ts +0 -23
  76. package/src/runtime.test.ts +0 -625
  77. package/src/runtime.ts +0 -528
  78. package/src/telephony-audio.test.ts +0 -61
  79. package/src/telephony-audio.ts +0 -12
  80. package/src/telephony-tts.test.ts +0 -196
  81. package/src/telephony-tts.ts +0 -235
  82. package/src/test-fixtures.ts +0 -82
  83. package/src/tts-provider-voice.test.ts +0 -34
  84. package/src/tts-provider-voice.ts +0 -21
  85. package/src/tunnel.test.ts +0 -173
  86. package/src/tunnel.ts +0 -314
  87. package/src/types.ts +0 -311
  88. package/src/utils.test.ts +0 -17
  89. package/src/utils.ts +0 -14
  90. package/src/voice-mapping.test.ts +0 -32
  91. package/src/voice-mapping.ts +0 -65
  92. package/src/webhook/realtime-audio-pacer.test.ts +0 -146
  93. package/src/webhook/realtime-audio-pacer.ts +0 -204
  94. package/src/webhook/realtime-handler.test.ts +0 -1450
  95. package/src/webhook/realtime-handler.ts +0 -1382
  96. package/src/webhook/stale-call-reaper.test.ts +0 -89
  97. package/src/webhook/stale-call-reaper.ts +0 -38
  98. package/src/webhook/stream-frame-adapter.test.ts +0 -187
  99. package/src/webhook/stream-frame-adapter.ts +0 -219
  100. package/src/webhook/tailscale.test.ts +0 -216
  101. package/src/webhook/tailscale.ts +0 -129
  102. package/src/webhook-exposure.test.ts +0 -33
  103. package/src/webhook-exposure.ts +0 -84
  104. package/src/webhook-security.test.ts +0 -813
  105. package/src/webhook-security.ts +0 -982
  106. package/src/webhook.hangup-once.lifecycle.test.ts +0 -179
  107. package/src/webhook.test.ts +0 -1615
  108. package/src/webhook.ts +0 -933
  109. package/src/webhook.types.ts +0 -5
  110. package/src/websocket-test-support.ts +0 -72
  111. package/tsconfig.json +0 -16
@@ -1,813 +0,0 @@
1
- import crypto from "node:crypto";
2
- import { describe, expect, it } from "vitest";
3
- import {
4
- verifyPlivoWebhook,
5
- verifyTelnyxWebhook,
6
- verifyTwilioWebhook,
7
- } from "./webhook-security.js";
8
-
9
- function canonicalizeBase64(input: string): string {
10
- return Buffer.from(input, "base64").toString("base64");
11
- }
12
-
13
- function plivoV2Signature(params: {
14
- authToken: string;
15
- urlNoQuery: string;
16
- nonce: string;
17
- }): string {
18
- const digest = crypto
19
- .createHmac("sha256", params.authToken)
20
- .update(params.urlNoQuery + params.nonce)
21
- .digest("base64");
22
- return canonicalizeBase64(digest);
23
- }
24
-
25
- function plivoV3Signature(params: {
26
- authToken: string;
27
- urlWithQuery: string;
28
- postBody: string;
29
- nonce: string;
30
- }): string {
31
- const u = new URL(params.urlWithQuery);
32
- const baseNoQuery = `${u.protocol}//${u.host}${u.pathname}`;
33
- const queryPairs: Array<[string, string]> = [];
34
- for (const [k, v] of u.searchParams.entries()) {
35
- queryPairs.push([k, v]);
36
- }
37
-
38
- const queryMap = new Map<string, string[]>();
39
- for (const [k, v] of queryPairs) {
40
- queryMap.set(k, (queryMap.get(k) ?? []).concat(v));
41
- }
42
-
43
- const sortedQuery = Array.from(queryMap.keys())
44
- .toSorted()
45
- .flatMap((k) => [...(queryMap.get(k) ?? [])].toSorted().map((v) => `${k}=${v}`))
46
- .join("&");
47
-
48
- const postParams = new URLSearchParams(params.postBody);
49
- const postMap = new Map<string, string[]>();
50
- for (const [k, v] of postParams.entries()) {
51
- postMap.set(k, (postMap.get(k) ?? []).concat(v));
52
- }
53
-
54
- const sortedPost = Array.from(postMap.keys())
55
- .toSorted()
56
- .flatMap((k) => [...(postMap.get(k) ?? [])].toSorted().map((v) => `${k}${v}`))
57
- .join("");
58
-
59
- const hasPost = sortedPost.length > 0;
60
- let baseUrl = baseNoQuery;
61
- if (sortedQuery.length > 0 || hasPost) {
62
- baseUrl = `${baseNoQuery}?${sortedQuery}`;
63
- }
64
- if (sortedQuery.length > 0 && hasPost) {
65
- baseUrl = `${baseUrl}.`;
66
- }
67
- baseUrl = `${baseUrl}${sortedPost}`;
68
-
69
- const digest = crypto
70
- .createHmac("sha256", params.authToken)
71
- .update(`${baseUrl}.${params.nonce}`)
72
- .digest("base64");
73
- return canonicalizeBase64(digest);
74
- }
75
-
76
- function twilioSignature(params: { authToken: string; url: string; postBody: string }): string {
77
- let dataToSign = params.url;
78
- const sortedParams = Array.from(new URLSearchParams(params.postBody).entries()).toSorted((a, b) =>
79
- a[0].localeCompare(b[0]),
80
- );
81
-
82
- for (const [key, value] of sortedParams) {
83
- dataToSign += key + value;
84
- }
85
-
86
- return crypto.createHmac("sha1", params.authToken).update(dataToSign).digest("base64");
87
- }
88
-
89
- function expectReplayResultPair(
90
- first: { ok: boolean; isReplay?: boolean; verifiedRequestKey?: string },
91
- second: { ok: boolean; isReplay?: boolean; verifiedRequestKey?: string },
92
- ) {
93
- expect(first.ok).toBe(true);
94
- expect(first.isReplay).not.toBe(true);
95
- if (!first.verifiedRequestKey) {
96
- throw new Error("verified webhook request did not produce a request key");
97
- }
98
- expect(second.ok).toBe(true);
99
- expect(second.isReplay).toBe(true);
100
- expect(second.verifiedRequestKey).toBe(first.verifiedRequestKey);
101
- }
102
-
103
- function expectAcceptedWebhookVersion(
104
- result: { ok: boolean; version?: string },
105
- version: "v2" | "v3",
106
- ) {
107
- expect(result.ok).toBe(true);
108
- expect(result.version).toBe(version);
109
- }
110
-
111
- function verifyTwilioNgrokLoopback(signature: string) {
112
- return verifyTwilioWebhook(
113
- {
114
- headers: {
115
- host: "127.0.0.1:3334",
116
- "x-forwarded-proto": "https",
117
- "x-forwarded-host": "local.ngrok-free.app",
118
- "x-twilio-signature": signature,
119
- },
120
- rawBody: "CallSid=CS123&CallStatus=completed&From=%2B15550000000",
121
- url: "http://127.0.0.1:3334/voice/webhook",
122
- method: "POST",
123
- remoteAddress: "127.0.0.1",
124
- },
125
- "test-auth-token",
126
- { allowNgrokFreeTierLoopbackBypass: true },
127
- );
128
- }
129
-
130
- function verifyTwilioSignedRequest(params: {
131
- headers: Record<string, string>;
132
- rawBody: string;
133
- authToken: string;
134
- publicUrl: string;
135
- }) {
136
- return verifyTwilioWebhook(
137
- {
138
- headers: params.headers,
139
- rawBody: params.rawBody,
140
- url: "http://local/voice/webhook?callId=abc",
141
- method: "POST",
142
- query: { callId: "abc" },
143
- },
144
- params.authToken,
145
- { publicUrl: params.publicUrl },
146
- );
147
- }
148
-
149
- function createSignedTelnyxWebhookRequest() {
150
- const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
151
- const pemPublicKey = publicKey.export({ format: "pem", type: "spki" });
152
- const timestamp = String(Math.floor(Date.now() / 1000));
153
- const rawBody = JSON.stringify({
154
- data: { event_type: "call.initiated", payload: { call_control_id: "call-1" } },
155
- nonce: crypto.randomUUID(),
156
- });
157
- const signedPayload = `${timestamp}|${rawBody}`;
158
- const signature = crypto.sign(null, Buffer.from(signedPayload), privateKey).toString("base64");
159
-
160
- return {
161
- pemPublicKey,
162
- timestamp,
163
- rawBody,
164
- signature,
165
- makeCtx(signatureValue = signature) {
166
- return {
167
- headers: {
168
- "telnyx-signature-ed25519": signatureValue,
169
- "telnyx-timestamp": timestamp,
170
- },
171
- rawBody,
172
- url: "https://example.com/voice/webhook",
173
- method: "POST" as const,
174
- };
175
- },
176
- };
177
- }
178
-
179
- const skipVerificationRequestKeyCases: Array<{
180
- name: string;
181
- prefix: RegExp;
182
- verify: () => { ok: boolean; isReplay?: boolean; verifiedRequestKey?: string };
183
- }> = [
184
- {
185
- name: "Plivo",
186
- prefix: /^plivo:skip:/,
187
- verify: () =>
188
- verifyPlivoWebhook(
189
- {
190
- headers: {},
191
- rawBody: "CallUUID=uuid&CallStatus=in-progress",
192
- url: "https://example.com/voice/webhook",
193
- method: "POST" as const,
194
- },
195
- "token",
196
- { skipVerification: true },
197
- ),
198
- },
199
- {
200
- name: "Telnyx",
201
- prefix: /^telnyx:skip:/,
202
- verify: () =>
203
- verifyTelnyxWebhook(
204
- {
205
- headers: {},
206
- rawBody: JSON.stringify({ data: { event_type: "call.initiated" } }),
207
- url: "https://example.com/voice/webhook",
208
- method: "POST" as const,
209
- },
210
- undefined,
211
- { skipVerification: true },
212
- ),
213
- },
214
- {
215
- name: "Twilio",
216
- prefix: /^twilio:skip:/,
217
- verify: () =>
218
- verifyTwilioWebhook(
219
- {
220
- headers: {},
221
- rawBody: "CallSid=CS123&CallStatus=completed",
222
- url: "https://example.com/voice/webhook",
223
- method: "POST" as const,
224
- },
225
- "token",
226
- { skipVerification: true },
227
- ),
228
- },
229
- ];
230
-
231
- describe("skip verification request keys", () => {
232
- it.each(skipVerificationRequestKeyCases)(
233
- "$name returns a stable request key when verification is skipped",
234
- ({ prefix, verify }) => {
235
- const first = verify();
236
- const second = verify();
237
-
238
- expect(first.ok).toBe(true);
239
- expect(first.verifiedRequestKey).toMatch(prefix);
240
- expect(second.verifiedRequestKey).toBe(first.verifiedRequestKey);
241
- expect(second.isReplay).toBe(true);
242
- },
243
- );
244
- });
245
-
246
- const verifiedReplayRequestCases: Array<{
247
- name: string;
248
- verifyPair: () => [
249
- { ok: boolean; isReplay?: boolean; verifiedRequestKey?: string },
250
- { ok: boolean; isReplay?: boolean; verifiedRequestKey?: string },
251
- ];
252
- }> = [
253
- {
254
- name: "Telnyx",
255
- verifyPair: () => {
256
- const request = createSignedTelnyxWebhookRequest();
257
- return [
258
- verifyTelnyxWebhook(request.makeCtx(), request.pemPublicKey),
259
- verifyTelnyxWebhook(request.makeCtx(), request.pemPublicKey),
260
- ];
261
- },
262
- },
263
- {
264
- name: "Twilio",
265
- verifyPair: () => {
266
- const authToken = "test-auth-token";
267
- const publicUrl = "https://example.com/voice/webhook";
268
- const urlWithQuery = `${publicUrl}?callId=abc`;
269
- const postBody = "CallSid=CS777&CallStatus=completed&From=%2B15550000000";
270
- const signature = twilioSignature({ authToken, url: urlWithQuery, postBody });
271
- const headers = {
272
- host: "example.com",
273
- "x-forwarded-proto": "https",
274
- "x-twilio-signature": signature,
275
- "i-twilio-idempotency-token": "idem-replay-1",
276
- };
277
-
278
- return [
279
- verifyTwilioSignedRequest({ headers, rawBody: postBody, authToken, publicUrl }),
280
- verifyTwilioSignedRequest({ headers, rawBody: postBody, authToken, publicUrl }),
281
- ];
282
- },
283
- },
284
- ];
285
-
286
- describe("verified webhook replay detection", () => {
287
- it.each(verifiedReplayRequestCases)(
288
- "$name marks replayed valid requests as replay without failing auth",
289
- ({ verifyPair }) => {
290
- const [first, second] = verifyPair();
291
- expectReplayResultPair(first, second);
292
- },
293
- );
294
- });
295
-
296
- describe("verifyPlivoWebhook", () => {
297
- it("accepts valid V2 signature", () => {
298
- const authToken = "test-auth-token";
299
- const nonce = "nonce-123";
300
-
301
- const ctxUrl = "http://local/voice/webhook?flow=answer&callId=abc";
302
- const verificationUrl = "https://example.com/voice/webhook";
303
- const signature = plivoV2Signature({
304
- authToken,
305
- urlNoQuery: verificationUrl,
306
- nonce,
307
- });
308
-
309
- const result = verifyPlivoWebhook(
310
- {
311
- headers: {
312
- host: "example.com",
313
- "x-forwarded-proto": "https",
314
- "x-plivo-signature-v2": signature,
315
- "x-plivo-signature-v2-nonce": nonce,
316
- },
317
- rawBody: "CallUUID=uuid&CallStatus=in-progress",
318
- url: ctxUrl,
319
- method: "POST",
320
- query: { flow: "answer", callId: "abc" },
321
- },
322
- authToken,
323
- );
324
-
325
- expectAcceptedWebhookVersion(result, "v2");
326
- });
327
-
328
- it("accepts valid V3 signature (including multi-signature header)", () => {
329
- const authToken = "test-auth-token";
330
- const nonce = "nonce-456";
331
-
332
- const urlWithQuery = "https://example.com/voice/webhook?flow=answer&callId=abc";
333
- const postBody = "CallUUID=uuid&CallStatus=in-progress&From=%2B15550000000";
334
-
335
- const good = plivoV3Signature({
336
- authToken,
337
- urlWithQuery,
338
- postBody,
339
- nonce,
340
- });
341
-
342
- const result = verifyPlivoWebhook(
343
- {
344
- headers: {
345
- host: "example.com",
346
- "x-forwarded-proto": "https",
347
- "x-plivo-signature-v3": `bad, ${good}`,
348
- "x-plivo-signature-v3-nonce": nonce,
349
- },
350
- rawBody: postBody,
351
- url: urlWithQuery,
352
- method: "POST",
353
- query: { flow: "answer", callId: "abc" },
354
- },
355
- authToken,
356
- );
357
-
358
- expectAcceptedWebhookVersion(result, "v3");
359
- });
360
-
361
- it("rejects missing signatures", () => {
362
- const result = verifyPlivoWebhook(
363
- {
364
- headers: { host: "example.com", "x-forwarded-proto": "https" },
365
- rawBody: "",
366
- url: "https://example.com/voice/webhook",
367
- method: "POST",
368
- },
369
- "token",
370
- );
371
-
372
- expect(result.ok).toBe(false);
373
- expect(result.reason).toMatch(/Missing Plivo signature headers/);
374
- });
375
-
376
- it("marks replayed valid V3 requests as replay without failing auth", () => {
377
- const authToken = "test-auth-token";
378
- const nonce = "nonce-replay-v3";
379
- const urlWithQuery = "https://example.com/voice/webhook?flow=answer&callId=abc";
380
- const postBody = "CallUUID=uuid&CallStatus=in-progress&From=%2B15550000000";
381
- const signature = plivoV3Signature({
382
- authToken,
383
- urlWithQuery,
384
- postBody,
385
- nonce,
386
- });
387
-
388
- const ctx = {
389
- headers: {
390
- host: "example.com",
391
- "x-forwarded-proto": "https",
392
- "x-plivo-signature-v3": signature,
393
- "x-plivo-signature-v3-nonce": nonce,
394
- },
395
- rawBody: postBody,
396
- url: urlWithQuery,
397
- method: "POST" as const,
398
- query: { flow: "answer", callId: "abc" },
399
- };
400
-
401
- const first = verifyPlivoWebhook(ctx, authToken);
402
- const second = verifyPlivoWebhook(ctx, authToken);
403
-
404
- expectReplayResultPair(first, second);
405
- });
406
-
407
- it("treats query-only V2 variants as the same verified request", () => {
408
- const authToken = "test-auth-token";
409
- const nonce = "nonce-replay-v2";
410
- const verificationUrl = "https://example.com/voice/webhook";
411
- const signature = plivoV2Signature({
412
- authToken,
413
- urlNoQuery: verificationUrl,
414
- nonce,
415
- });
416
-
417
- const baseHeaders = {
418
- host: "example.com",
419
- "x-forwarded-proto": "https",
420
- "x-plivo-signature-v2": signature,
421
- "x-plivo-signature-v2-nonce": nonce,
422
- };
423
- const rawBody = "CallUUID=uuid&CallStatus=in-progress";
424
-
425
- const first = verifyPlivoWebhook(
426
- {
427
- headers: baseHeaders,
428
- rawBody,
429
- url: `${verificationUrl}?flow=answer&callId=abc`,
430
- method: "POST",
431
- query: { flow: "answer", callId: "abc" },
432
- },
433
- authToken,
434
- );
435
- const second = verifyPlivoWebhook(
436
- {
437
- headers: baseHeaders,
438
- rawBody,
439
- url: `${verificationUrl}?flow=getinput&callId=abc`,
440
- method: "POST",
441
- query: { flow: "getinput", callId: "abc" },
442
- },
443
- authToken,
444
- );
445
-
446
- expect(first.ok).toBe(true);
447
- expect(first.verifiedRequestKey).toBeTypeOf("string");
448
- expect(first.verifiedRequestKey).not.toBe("");
449
- expect(second.ok).toBe(true);
450
- expect(second.verifiedRequestKey).toBe(first.verifiedRequestKey);
451
- expect(second.isReplay).toBe(true);
452
- });
453
-
454
- it("detects V3 replay when query parameters are reordered", () => {
455
- const authToken = "test-auth-token";
456
- const nonce = "nonce-v3-reorder";
457
- const postBody = "CallUUID=uuid&CallStatus=in-progress";
458
-
459
- const urlA = "https://example.com/voice/webhook?flow=answer&callId=abc";
460
- const urlB = "https://example.com/voice/webhook?callId=abc&flow=answer";
461
-
462
- const signatureA = plivoV3Signature({ authToken, urlWithQuery: urlA, postBody, nonce });
463
- const signatureB = plivoV3Signature({ authToken, urlWithQuery: urlB, postBody, nonce });
464
- expect(signatureA).toBe(signatureB);
465
-
466
- const first = verifyPlivoWebhook(
467
- {
468
- headers: {
469
- host: "example.com",
470
- "x-forwarded-proto": "https",
471
- "x-plivo-signature-v3": signatureA,
472
- "x-plivo-signature-v3-nonce": nonce,
473
- },
474
- rawBody: postBody,
475
- url: urlA,
476
- method: "POST",
477
- query: { flow: "answer", callId: "abc" },
478
- },
479
- authToken,
480
- );
481
-
482
- const second = verifyPlivoWebhook(
483
- {
484
- headers: {
485
- host: "example.com",
486
- "x-forwarded-proto": "https",
487
- "x-plivo-signature-v3": signatureB,
488
- "x-plivo-signature-v3-nonce": nonce,
489
- },
490
- rawBody: postBody,
491
- url: urlB,
492
- method: "POST",
493
- query: { callId: "abc", flow: "answer" },
494
- },
495
- authToken,
496
- );
497
-
498
- expectReplayResultPair(first, second);
499
- });
500
- });
501
-
502
- describe("verifyTelnyxWebhook", () => {
503
- it("treats Base64 and Base64URL signatures as the same replayed request", () => {
504
- const request = createSignedTelnyxWebhookRequest();
505
- const urlSafeSignature = request.signature
506
- .replace(/\+/g, "-")
507
- .replace(/\//g, "_")
508
- .replace(/=+$/g, "");
509
- const first = verifyTelnyxWebhook(request.makeCtx(), request.pemPublicKey);
510
- const second = verifyTelnyxWebhook(request.makeCtx(urlSafeSignature), request.pemPublicKey);
511
-
512
- expectReplayResultPair(first, second);
513
- });
514
- });
515
-
516
- describe("verifyTwilioWebhook", () => {
517
- it("uses request query when publicUrl omits it", () => {
518
- const authToken = "test-auth-token";
519
- const publicUrl = "https://example.com/voice/webhook";
520
- const urlWithQuery = `${publicUrl}?callId=abc`;
521
- const postBody = "CallSid=CS123&CallStatus=completed&From=%2B15550000000";
522
-
523
- const signature = twilioSignature({
524
- authToken,
525
- url: urlWithQuery,
526
- postBody,
527
- });
528
-
529
- const result = verifyTwilioWebhook(
530
- {
531
- headers: {
532
- host: "example.com",
533
- "x-forwarded-proto": "https",
534
- "x-twilio-signature": signature,
535
- },
536
- rawBody: postBody,
537
- url: "http://local/voice/webhook?callId=abc",
538
- method: "POST",
539
- query: { callId: "abc" },
540
- },
541
- authToken,
542
- { publicUrl },
543
- );
544
-
545
- expect(result.ok).toBe(true);
546
- });
547
-
548
- it("treats changed idempotency header as replay for identical signed requests", () => {
549
- const authToken = "test-auth-token";
550
- const publicUrl = "https://example.com/voice/webhook";
551
- const urlWithQuery = `${publicUrl}?callId=abc`;
552
- const postBody = "CallSid=CS778&CallStatus=completed&From=%2B15550000000";
553
- const signature = twilioSignature({ authToken, url: urlWithQuery, postBody });
554
-
555
- const first = verifyTwilioSignedRequest({
556
- headers: {
557
- host: "example.com",
558
- "x-forwarded-proto": "https",
559
- "x-twilio-signature": signature,
560
- "i-twilio-idempotency-token": "idem-replay-a",
561
- },
562
- rawBody: postBody,
563
- authToken,
564
- publicUrl,
565
- });
566
- const second = verifyTwilioSignedRequest({
567
- headers: {
568
- host: "example.com",
569
- "x-forwarded-proto": "https",
570
- "x-twilio-signature": signature,
571
- "i-twilio-idempotency-token": "idem-replay-b",
572
- },
573
- rawBody: postBody,
574
- authToken,
575
- publicUrl,
576
- });
577
-
578
- expectReplayResultPair(first, second);
579
- });
580
-
581
- it("rejects invalid signatures even when attacker injects forwarded host", () => {
582
- const authToken = "test-auth-token";
583
- const postBody = "CallSid=CS123&CallStatus=completed&From=%2B15550000000";
584
-
585
- const result = verifyTwilioWebhook(
586
- {
587
- headers: {
588
- host: "127.0.0.1:3334",
589
- "x-forwarded-proto": "https",
590
- "x-forwarded-host": "attacker.ngrok-free.app",
591
- "x-twilio-signature": "invalid",
592
- },
593
- rawBody: postBody,
594
- url: "http://127.0.0.1:3334/voice/webhook",
595
- method: "POST",
596
- },
597
- authToken,
598
- );
599
-
600
- expect(result.ok).toBe(false);
601
- // X-Forwarded-Host is ignored by default, so URL uses Host header
602
- expect(result.isNgrokFreeTier).toBe(false);
603
- expect(result.reason).toMatch(/Invalid signature/);
604
- });
605
-
606
- it("accepts valid signatures for ngrok free tier on loopback when compatibility mode is enabled", () => {
607
- const webhookUrl = "https://local.ngrok-free.app/voice/webhook";
608
-
609
- const signature = twilioSignature({
610
- authToken: "test-auth-token",
611
- url: webhookUrl,
612
- postBody: "CallSid=CS123&CallStatus=completed&From=%2B15550000000",
613
- });
614
-
615
- const result = verifyTwilioNgrokLoopback(signature);
616
-
617
- expect(result.ok).toBe(true);
618
- expect(result.verificationUrl).toBe(webhookUrl);
619
- });
620
-
621
- it("does not allow invalid signatures for ngrok free tier on loopback", () => {
622
- const result = verifyTwilioNgrokLoopback("invalid");
623
-
624
- expect(result.ok).toBe(false);
625
- expect(result.reason).toMatch(/Invalid signature/);
626
- expect(result.isNgrokFreeTier).toBe(true);
627
- });
628
-
629
- it("ignores attacker X-Forwarded-Host without allowedHosts or trustForwardingHeaders", () => {
630
- const authToken = "test-auth-token";
631
- const postBody = "CallSid=CS123&CallStatus=completed&From=%2B15550000000";
632
-
633
- // Attacker tries to inject their host - should be ignored
634
- const result = verifyTwilioWebhook(
635
- {
636
- headers: {
637
- host: "legitimate.example.com",
638
- "x-forwarded-host": "attacker.evil.com",
639
- "x-twilio-signature": "invalid",
640
- },
641
- rawBody: postBody,
642
- url: "http://localhost:3000/voice/webhook",
643
- method: "POST",
644
- },
645
- authToken,
646
- );
647
-
648
- expect(result.ok).toBe(false);
649
- // Attacker's host is ignored - uses Host header instead
650
- expect(result.verificationUrl).toBe("https://legitimate.example.com/voice/webhook");
651
- });
652
-
653
- it("uses X-Forwarded-Host when allowedHosts whitelist is provided", () => {
654
- const authToken = "test-auth-token";
655
- const postBody = "CallSid=CS123&CallStatus=completed&From=%2B15550000000";
656
- const webhookUrl = "https://myapp.ngrok.io/voice/webhook";
657
-
658
- const signature = twilioSignature({ authToken, url: webhookUrl, postBody });
659
-
660
- const result = verifyTwilioWebhook(
661
- {
662
- headers: {
663
- host: "localhost:3000",
664
- "x-forwarded-proto": "https",
665
- "x-forwarded-host": "myapp.ngrok.io",
666
- "x-twilio-signature": signature,
667
- },
668
- rawBody: postBody,
669
- url: "http://localhost:3000/voice/webhook",
670
- method: "POST",
671
- },
672
- authToken,
673
- { allowedHosts: ["myapp.ngrok.io"] },
674
- );
675
-
676
- expect(result.ok).toBe(true);
677
- expect(result.verificationUrl).toBe(webhookUrl);
678
- });
679
-
680
- it("verifies Twilio signatures for Cloudflare Tunnel publicUrl requests", () => {
681
- const authToken = "test-auth-token";
682
- const postBody = "CallSid=CA123&CallStatus=ringing&Direction=inbound&From=%2B15550000000";
683
- const webhookUrl = "https://oc1.example.com/voice/webhook";
684
- const signature = twilioSignature({ authToken, url: webhookUrl, postBody });
685
-
686
- const result = verifyTwilioWebhook(
687
- {
688
- headers: {
689
- host: "localhost:8765",
690
- "cf-connecting-ip": "203.0.113.42",
691
- "x-forwarded-proto": "https",
692
- "x-twilio-signature": signature,
693
- },
694
- rawBody: postBody,
695
- url: "http://localhost:8765/voice/webhook",
696
- method: "POST",
697
- remoteAddress: "127.0.0.1",
698
- },
699
- authToken,
700
- {
701
- publicUrl: webhookUrl,
702
- allowedHosts: ["oc1.example.com"],
703
- trustForwardingHeaders: true,
704
- },
705
- );
706
-
707
- expect(result.ok).toBe(true);
708
- expect(result.verificationUrl).toBe(webhookUrl);
709
- });
710
-
711
- it("rejects X-Forwarded-Host not in allowedHosts whitelist", () => {
712
- const authToken = "test-auth-token";
713
- const postBody = "CallSid=CS123&CallStatus=completed&From=%2B15550000000";
714
-
715
- const result = verifyTwilioWebhook(
716
- {
717
- headers: {
718
- host: "localhost:3000",
719
- "x-forwarded-host": "attacker.evil.com",
720
- "x-twilio-signature": "invalid",
721
- },
722
- rawBody: postBody,
723
- url: "http://localhost:3000/voice/webhook",
724
- method: "POST",
725
- },
726
- authToken,
727
- { allowedHosts: ["myapp.ngrok.io", "webhook.example.com"] },
728
- );
729
-
730
- expect(result.ok).toBe(false);
731
- // Attacker's host not in whitelist, falls back to Host header
732
- expect(result.verificationUrl).toBe("https://localhost/voice/webhook");
733
- });
734
-
735
- it("trusts forwarding headers only from trusted proxy IPs", () => {
736
- const authToken = "test-auth-token";
737
- const postBody = "CallSid=CS123&CallStatus=completed&From=%2B15550000000";
738
- const webhookUrl = "https://proxy.example.com/voice/webhook";
739
-
740
- const signature = twilioSignature({ authToken, url: webhookUrl, postBody });
741
-
742
- const result = verifyTwilioWebhook(
743
- {
744
- headers: {
745
- host: "localhost:3000",
746
- "x-forwarded-proto": "https",
747
- "x-forwarded-host": "proxy.example.com",
748
- "x-twilio-signature": signature,
749
- },
750
- rawBody: postBody,
751
- url: "http://localhost:3000/voice/webhook",
752
- method: "POST",
753
- remoteAddress: "203.0.113.10",
754
- },
755
- authToken,
756
- { trustForwardingHeaders: true, trustedProxyIPs: ["203.0.113.10"] },
757
- );
758
-
759
- expect(result.ok).toBe(true);
760
- expect(result.verificationUrl).toBe(webhookUrl);
761
- });
762
-
763
- it("ignores forwarding headers when trustedProxyIPs are set but remote IP is missing", () => {
764
- const authToken = "test-auth-token";
765
- const postBody = "CallSid=CS123&CallStatus=completed&From=%2B15550000000";
766
-
767
- const result = verifyTwilioWebhook(
768
- {
769
- headers: {
770
- host: "legitimate.example.com",
771
- "x-forwarded-proto": "https",
772
- "x-forwarded-host": "proxy.example.com",
773
- "x-twilio-signature": "invalid",
774
- },
775
- rawBody: postBody,
776
- url: "http://localhost:3000/voice/webhook",
777
- method: "POST",
778
- },
779
- authToken,
780
- { trustForwardingHeaders: true, trustedProxyIPs: ["203.0.113.10"] },
781
- );
782
-
783
- expect(result.ok).toBe(false);
784
- expect(result.verificationUrl).toBe("https://legitimate.example.com/voice/webhook");
785
- });
786
- it("succeeds when Twilio signs URL without port but server URL has port", () => {
787
- const authToken = "test-auth-token";
788
- const postBody = "CallSid=CS123&CallStatus=completed&From=%2B15550000000";
789
- // Twilio signs using URL without port.
790
- const urlWithPort = "https://example.com:8443/voice/webhook";
791
- const signedUrl = "https://example.com/voice/webhook";
792
-
793
- const signature = twilioSignature({ authToken, url: signedUrl, postBody });
794
-
795
- const result = verifyTwilioWebhook(
796
- {
797
- headers: {
798
- host: "example.com:8443",
799
- "x-twilio-signature": signature,
800
- },
801
- rawBody: postBody,
802
- url: urlWithPort,
803
- method: "POST",
804
- },
805
- authToken,
806
- { publicUrl: urlWithPort },
807
- );
808
-
809
- expect(result.ok).toBe(true);
810
- expect(result.verificationUrl).toBe(signedUrl);
811
- expect(result.verifiedRequestKey).toMatch(/^twilio:req:/);
812
- });
813
- });