@openclaw/voice-call 2026.3.13 → 2026.5.2-beta.1

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 (103) hide show
  1. package/README.md +27 -5
  2. package/api.ts +16 -0
  3. package/cli-metadata.ts +10 -0
  4. package/config-api.ts +12 -0
  5. package/index.test.ts +943 -0
  6. package/index.ts +379 -149
  7. package/openclaw.plugin.json +384 -157
  8. package/package.json +35 -5
  9. package/runtime-api.ts +20 -0
  10. package/runtime-entry.ts +1 -0
  11. package/setup-api.ts +47 -0
  12. package/src/allowlist.test.ts +18 -0
  13. package/src/cli.ts +533 -68
  14. package/src/config-compat.test.ts +120 -0
  15. package/src/config-compat.ts +227 -0
  16. package/src/config.test.ts +273 -12
  17. package/src/config.ts +355 -72
  18. package/src/core-bridge.ts +2 -147
  19. package/src/deep-merge.test.ts +40 -0
  20. package/src/gateway-continue-operation.ts +200 -0
  21. package/src/http-headers.ts +6 -3
  22. package/src/manager/context.ts +6 -5
  23. package/src/manager/events.test.ts +243 -19
  24. package/src/manager/events.ts +61 -31
  25. package/src/manager/lifecycle.ts +53 -0
  26. package/src/manager/lookup.test.ts +52 -0
  27. package/src/manager/outbound.test.ts +528 -0
  28. package/src/manager/outbound.ts +163 -57
  29. package/src/manager/store.ts +18 -6
  30. package/src/manager/timers.test.ts +129 -0
  31. package/src/manager/timers.ts +4 -3
  32. package/src/manager/twiml.test.ts +13 -0
  33. package/src/manager/twiml.ts +8 -0
  34. package/src/manager.closed-loop.test.ts +30 -12
  35. package/src/manager.inbound-allowlist.test.ts +77 -10
  36. package/src/manager.notify.test.ts +344 -20
  37. package/src/manager.restore.test.ts +95 -8
  38. package/src/manager.test-harness.ts +8 -6
  39. package/src/manager.ts +79 -5
  40. package/src/media-stream.test.ts +578 -81
  41. package/src/media-stream.ts +235 -54
  42. package/src/providers/base.ts +19 -0
  43. package/src/providers/mock.ts +7 -1
  44. package/src/providers/plivo.test.ts +50 -6
  45. package/src/providers/plivo.ts +14 -6
  46. package/src/providers/shared/call-status.ts +2 -1
  47. package/src/providers/shared/guarded-json-api.test.ts +106 -0
  48. package/src/providers/shared/guarded-json-api.ts +1 -1
  49. package/src/providers/telnyx.test.ts +178 -6
  50. package/src/providers/telnyx.ts +40 -3
  51. package/src/providers/twilio/api.test.ts +145 -0
  52. package/src/providers/twilio/api.ts +67 -16
  53. package/src/providers/twilio/twiml-policy.ts +6 -10
  54. package/src/providers/twilio/webhook.ts +1 -1
  55. package/src/providers/twilio.test.ts +425 -25
  56. package/src/providers/twilio.ts +230 -77
  57. package/src/providers/twilio.types.ts +17 -0
  58. package/src/realtime-defaults.ts +3 -0
  59. package/src/realtime-fast-context.test.ts +88 -0
  60. package/src/realtime-fast-context.ts +165 -0
  61. package/src/realtime-transcription.runtime.ts +4 -0
  62. package/src/realtime-voice.runtime.ts +5 -0
  63. package/src/response-generator.test.ts +321 -0
  64. package/src/response-generator.ts +213 -53
  65. package/src/response-model.test.ts +71 -0
  66. package/src/response-model.ts +23 -0
  67. package/src/runtime.test.ts +429 -0
  68. package/src/runtime.ts +270 -24
  69. package/src/telephony-audio.test.ts +61 -0
  70. package/src/telephony-audio.ts +1 -79
  71. package/src/telephony-tts.test.ts +133 -12
  72. package/src/telephony-tts.ts +155 -2
  73. package/src/test-fixtures.ts +28 -7
  74. package/src/tts-provider-voice.test.ts +34 -0
  75. package/src/tts-provider-voice.ts +21 -0
  76. package/src/tunnel.test.ts +166 -0
  77. package/src/tunnel.ts +1 -1
  78. package/src/types.ts +24 -37
  79. package/src/utils.test.ts +17 -0
  80. package/src/voice-mapping.test.ts +34 -0
  81. package/src/voice-mapping.ts +3 -2
  82. package/src/webhook/realtime-handler.test.ts +598 -0
  83. package/src/webhook/realtime-handler.ts +485 -0
  84. package/src/webhook/stale-call-reaper.test.ts +88 -0
  85. package/src/webhook/stale-call-reaper.ts +5 -0
  86. package/src/webhook/tailscale.test.ts +214 -0
  87. package/src/webhook/tailscale.ts +19 -5
  88. package/src/webhook-exposure.test.ts +33 -0
  89. package/src/webhook-exposure.ts +84 -0
  90. package/src/webhook-security.test.ts +172 -21
  91. package/src/webhook-security.ts +43 -29
  92. package/src/webhook.hangup-once.lifecycle.test.ts +135 -0
  93. package/src/webhook.test.ts +1145 -27
  94. package/src/webhook.ts +523 -102
  95. package/src/webhook.types.ts +5 -0
  96. package/src/websocket-test-support.ts +72 -0
  97. package/tsconfig.json +16 -0
  98. package/CHANGELOG.md +0 -121
  99. package/src/providers/index.ts +0 -10
  100. package/src/providers/stt-openai-realtime.test.ts +0 -42
  101. package/src/providers/stt-openai-realtime.ts +0 -311
  102. package/src/providers/tts-openai.test.ts +0 -43
  103. package/src/providers/tts-openai.ts +0 -221
@@ -0,0 +1,214 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { beforeEach, describe, expect, it, vi } from "vitest";
3
+
4
+ const { spawnMock } = vi.hoisted(() => ({
5
+ spawnMock: vi.fn(),
6
+ }));
7
+
8
+ vi.mock("node:child_process", async () => {
9
+ const { mockNodeBuiltinModule } = await import("openclaw/plugin-sdk/test-node-mocks");
10
+ return mockNodeBuiltinModule(
11
+ () => vi.importActual<typeof import("node:child_process")>("node:child_process"),
12
+ {
13
+ spawn: spawnMock,
14
+ },
15
+ );
16
+ });
17
+
18
+ import {
19
+ cleanupTailscaleExposure,
20
+ cleanupTailscaleExposureRoute,
21
+ getTailscaleDnsName,
22
+ getTailscaleSelfInfo,
23
+ setupTailscaleExposure,
24
+ setupTailscaleExposureRoute,
25
+ } from "./tailscale.js";
26
+
27
+ function createProc(params?: { code?: number; stdout?: string }) {
28
+ const proc = new EventEmitter() as EventEmitter & {
29
+ stdout: EventEmitter;
30
+ kill: ReturnType<typeof vi.fn>;
31
+ };
32
+ proc.stdout = new EventEmitter();
33
+ proc.kill = vi.fn();
34
+ setTimeout(() => {
35
+ if (params?.stdout) {
36
+ proc.stdout.emit("data", Buffer.from(params.stdout));
37
+ }
38
+ proc.emit("close", params?.code ?? 0);
39
+ }, 0);
40
+ return proc;
41
+ }
42
+
43
+ function createErrorProc() {
44
+ const proc = new EventEmitter() as EventEmitter & {
45
+ stdout: EventEmitter;
46
+ kill: ReturnType<typeof vi.fn>;
47
+ };
48
+ proc.stdout = new EventEmitter();
49
+ proc.kill = vi.fn();
50
+ setTimeout(() => {
51
+ proc.emit("error", Object.assign(new Error("spawn tailscale ENOENT"), { code: "ENOENT" }));
52
+ }, 0);
53
+ return proc;
54
+ }
55
+
56
+ describe("voice-call tailscale helpers", () => {
57
+ beforeEach(() => {
58
+ vi.clearAllMocks();
59
+ });
60
+
61
+ it("reads dns and node id from tailscale status json", async () => {
62
+ spawnMock
63
+ .mockReturnValueOnce(
64
+ createProc({
65
+ stdout: JSON.stringify({
66
+ Self: {
67
+ DNSName: "bot.example.ts.net.",
68
+ ID: "node-123",
69
+ },
70
+ }),
71
+ }),
72
+ )
73
+ .mockReturnValueOnce(
74
+ createProc({
75
+ stdout: JSON.stringify({
76
+ Self: {
77
+ DNSName: "bot.example.ts.net.",
78
+ ID: "node-123",
79
+ },
80
+ }),
81
+ }),
82
+ );
83
+
84
+ await expect(getTailscaleSelfInfo()).resolves.toEqual({
85
+ dnsName: "bot.example.ts.net",
86
+ nodeId: "node-123",
87
+ });
88
+ await expect(getTailscaleDnsName()).resolves.toBe("bot.example.ts.net");
89
+ });
90
+
91
+ it("returns null for failing or invalid status responses", async () => {
92
+ spawnMock.mockReturnValueOnce(createProc({ code: 1, stdout: "bad" }));
93
+ await expect(getTailscaleSelfInfo()).resolves.toBeNull();
94
+
95
+ spawnMock.mockReturnValueOnce(createProc({ stdout: "{not-json" }));
96
+ await expect(getTailscaleSelfInfo()).resolves.toBeNull();
97
+ });
98
+
99
+ it("treats missing tailscale binary as unavailable instead of leaking spawn errors", async () => {
100
+ spawnMock.mockReturnValueOnce(createErrorProc());
101
+
102
+ await expect(getTailscaleSelfInfo()).resolves.toBeNull();
103
+ });
104
+
105
+ it("sets up and cleans up exposure routes with the selected mode", async () => {
106
+ spawnMock
107
+ .mockReturnValueOnce(
108
+ createProc({
109
+ stdout: JSON.stringify({ Self: { DNSName: "bot.example.ts.net." } }),
110
+ }),
111
+ )
112
+ .mockReturnValueOnce(createProc({ code: 0 }))
113
+ .mockReturnValueOnce(createProc({ code: 0 }));
114
+
115
+ await expect(
116
+ setupTailscaleExposureRoute({
117
+ mode: "serve",
118
+ path: "/voice",
119
+ localUrl: "http://127.0.0.1:8787/webhook",
120
+ }),
121
+ ).resolves.toBe("https://bot.example.ts.net/voice");
122
+
123
+ await cleanupTailscaleExposureRoute({ mode: "serve", path: "/voice" });
124
+
125
+ expect(spawnMock).toHaveBeenNthCalledWith(
126
+ 1,
127
+ "tailscale",
128
+ ["status", "--json"],
129
+ expect.objectContaining({ stdio: ["ignore", "pipe", "pipe"] }),
130
+ );
131
+ expect(spawnMock).toHaveBeenNthCalledWith(
132
+ 2,
133
+ "tailscale",
134
+ ["serve", "--bg", "--yes", "--set-path", "/voice", "http://127.0.0.1:8787/webhook"],
135
+ expect.any(Object),
136
+ );
137
+ expect(spawnMock).toHaveBeenNthCalledWith(
138
+ 3,
139
+ "tailscale",
140
+ ["serve", "off", "/voice"],
141
+ expect.any(Object),
142
+ );
143
+ });
144
+
145
+ it("returns null when setup cannot resolve dns or route activation fails", async () => {
146
+ spawnMock
147
+ .mockReturnValueOnce(createProc({ code: 1 }))
148
+ .mockReturnValueOnce(
149
+ createProc({
150
+ stdout: JSON.stringify({ Self: { DNSName: "bot.example.ts.net." } }),
151
+ }),
152
+ )
153
+ .mockReturnValueOnce(createProc({ code: 1 }));
154
+
155
+ await expect(
156
+ setupTailscaleExposureRoute({
157
+ mode: "funnel",
158
+ path: "/voice",
159
+ localUrl: "http://127.0.0.1:8787/webhook",
160
+ }),
161
+ ).resolves.toBeNull();
162
+
163
+ await expect(
164
+ setupTailscaleExposureRoute({
165
+ mode: "funnel",
166
+ path: "/voice",
167
+ localUrl: "http://127.0.0.1:8787/webhook",
168
+ }),
169
+ ).resolves.toBeNull();
170
+ });
171
+
172
+ it("maps config modes to serve or funnel and skips off", async () => {
173
+ spawnMock
174
+ .mockReturnValueOnce(
175
+ createProc({
176
+ stdout: JSON.stringify({ Self: { DNSName: "bot.example.ts.net." } }),
177
+ }),
178
+ )
179
+ .mockReturnValueOnce(createProc({ code: 0 }))
180
+ .mockReturnValueOnce(createProc({ code: 0 }));
181
+
182
+ await expect(
183
+ setupTailscaleExposure({
184
+ tailscale: { mode: "off", path: "/voice" },
185
+ serve: { port: 8787, path: "/webhook" },
186
+ } as never),
187
+ ).resolves.toBeNull();
188
+
189
+ await expect(
190
+ setupTailscaleExposure({
191
+ tailscale: { mode: "funnel", path: "/voice" },
192
+ serve: { port: 8787, path: "/webhook" },
193
+ } as never),
194
+ ).resolves.toBe("https://bot.example.ts.net/voice");
195
+
196
+ await cleanupTailscaleExposure({
197
+ tailscale: { mode: "serve", path: "/voice" },
198
+ serve: { port: 8787, path: "/webhook" },
199
+ } as never);
200
+
201
+ expect(spawnMock).toHaveBeenNthCalledWith(
202
+ 2,
203
+ "tailscale",
204
+ ["funnel", "--bg", "--yes", "--set-path", "/voice", "http://127.0.0.1:8787/webhook"],
205
+ expect.any(Object),
206
+ );
207
+ expect(spawnMock).toHaveBeenNthCalledWith(
208
+ 3,
209
+ "tailscale",
210
+ ["serve", "off", "/voice"],
211
+ expect.any(Object),
212
+ );
213
+ });
214
+ });
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import type { VoiceCallConfig } from "../config.js";
3
3
 
4
- export type TailscaleSelfInfo = {
4
+ type TailscaleSelfInfo = {
5
5
  dnsName: string | null;
6
6
  nodeId: string | null;
7
7
  };
@@ -16,18 +16,32 @@ function runTailscaleCommand(
16
16
  });
17
17
 
18
18
  let stdout = "";
19
+ let settled = false;
20
+ let timer: ReturnType<typeof setTimeout>;
21
+ const finish = (result: { code: number; stdout: string }) => {
22
+ if (settled) {
23
+ return;
24
+ }
25
+ settled = true;
26
+ clearTimeout(timer);
27
+ resolve(result);
28
+ };
29
+
19
30
  proc.stdout.on("data", (data) => {
20
31
  stdout += data;
21
32
  });
22
33
 
23
- const timer = setTimeout(() => {
34
+ timer = setTimeout(() => {
24
35
  proc.kill("SIGKILL");
25
- resolve({ code: -1, stdout: "" });
36
+ finish({ code: -1, stdout: "" });
26
37
  }, timeoutMs);
27
38
 
39
+ proc.on("error", () => {
40
+ finish({ code: -1, stdout: "" });
41
+ });
42
+
28
43
  proc.on("close", (code) => {
29
- clearTimeout(timer);
30
- resolve({ code: code ?? -1, stdout });
44
+ finish({ code: code ?? -1, stdout });
31
45
  });
32
46
  });
33
47
  }
@@ -0,0 +1,33 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { isLocalOnlyWebhookHost, isProviderUnreachableWebhookUrl } from "./webhook-exposure.js";
3
+
4
+ describe("webhook exposure host classification", () => {
5
+ it.each([
6
+ "http://[::]:3334/voice/webhook",
7
+ "http://[::1]:3334/voice/webhook",
8
+ "http://[fc00::1]/voice/webhook",
9
+ "http://[fd00::1]/voice/webhook",
10
+ "http://[::ffff:127.0.0.1]/voice/webhook",
11
+ "http://[::ffff:10.0.0.1]/voice/webhook",
12
+ "http://[::ffff:192.168.0.1]/voice/webhook",
13
+ "http://[::ffff:172.16.0.1]/voice/webhook",
14
+ "http://[fe80::1]/voice/webhook",
15
+ ])("treats local/private webhook URL %s as provider-unreachable", (url) => {
16
+ expect(isProviderUnreachableWebhookUrl(url)).toBe(true);
17
+ });
18
+
19
+ it.each([
20
+ "http://[::ffff:8.8.8.8]/voice/webhook",
21
+ "https://voice.example.com/voice/webhook",
22
+ "https://fcloud.example/voice/webhook",
23
+ ])("does not reject public webhook URL %s", (url) => {
24
+ expect(isProviderUnreachableWebhookUrl(url)).toBe(false);
25
+ });
26
+
27
+ it.each(["[::1]", "[fc00::1]", "[fd00::1]", "::ffff:7f00:1", "::ffff:a00:1", "[fe80::1]"])(
28
+ "normalizes local/private URL hostnames like %s",
29
+ (host) => {
30
+ expect(isLocalOnlyWebhookHost(host)).toBe(true);
31
+ },
32
+ );
33
+ });
@@ -0,0 +1,84 @@
1
+ import { isBlockedHostnameOrIp } from "../api.js";
2
+
3
+ type VoiceCallWebhookExposureConfig = {
4
+ provider?: string;
5
+ publicUrl?: string;
6
+ tunnel?: {
7
+ provider?: string;
8
+ };
9
+ tailscale?: {
10
+ mode?: string;
11
+ };
12
+ };
13
+
14
+ type VoiceCallWebhookExposureStatus = {
15
+ ok: boolean;
16
+ configured: boolean;
17
+ message: string;
18
+ };
19
+
20
+ export function providerRequiresPublicWebhook(providerName: string | undefined): boolean {
21
+ return providerName === "twilio" || providerName === "telnyx" || providerName === "plivo";
22
+ }
23
+
24
+ export function isLocalOnlyWebhookHost(hostname: string): boolean {
25
+ return isBlockedHostnameOrIp(hostname);
26
+ }
27
+
28
+ export function isProviderUnreachableWebhookUrl(webhookUrl: string): boolean {
29
+ try {
30
+ const parsed = new URL(webhookUrl);
31
+ return isLocalOnlyWebhookHost(parsed.hostname);
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ export function resolveWebhookExposureStatus(
38
+ config: VoiceCallWebhookExposureConfig,
39
+ ): VoiceCallWebhookExposureStatus {
40
+ if (config.provider === "mock") {
41
+ return {
42
+ ok: true,
43
+ configured: true,
44
+ message: "Mock provider does not need a public webhook",
45
+ };
46
+ }
47
+
48
+ if (config.publicUrl) {
49
+ if (isProviderUnreachableWebhookUrl(config.publicUrl)) {
50
+ return {
51
+ ok: false,
52
+ configured: true,
53
+ message: `Public webhook URL is local/private and cannot be reached by ${config.provider ?? "the provider"}: ${config.publicUrl}`,
54
+ };
55
+ }
56
+ return {
57
+ ok: true,
58
+ configured: true,
59
+ message: `Public webhook URL configured: ${config.publicUrl}`,
60
+ };
61
+ }
62
+
63
+ if (config.tunnel?.provider && config.tunnel.provider !== "none") {
64
+ return {
65
+ ok: true,
66
+ configured: true,
67
+ message: "Webhook exposure configured through tunnel",
68
+ };
69
+ }
70
+
71
+ if (config.tailscale?.mode && config.tailscale.mode !== "off") {
72
+ return {
73
+ ok: true,
74
+ configured: true,
75
+ message: "Webhook exposure configured through Tailscale",
76
+ };
77
+ }
78
+
79
+ return {
80
+ ok: false,
81
+ configured: false,
82
+ message: "Set publicUrl or configure tunnel/tailscale so the provider can reach webhooks",
83
+ };
84
+ }
@@ -92,7 +92,9 @@ function expectReplayResultPair(
92
92
  ) {
93
93
  expect(first.ok).toBe(true);
94
94
  expect(first.isReplay).toBeFalsy();
95
- expect(first.verifiedRequestKey).toBeTruthy();
95
+ if (!first.verifiedRequestKey) {
96
+ throw new Error("verified webhook request did not produce a request key");
97
+ }
96
98
  expect(second.ok).toBe(true);
97
99
  expect(second.isReplay).toBe(true);
98
100
  expect(second.verifiedRequestKey).toBe(first.verifiedRequestKey);
@@ -143,6 +145,36 @@ function verifyTwilioSignedRequest(params: {
143
145
  );
144
146
  }
145
147
 
148
+ function createSignedTelnyxWebhookRequest() {
149
+ const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
150
+ const pemPublicKey = publicKey.export({ format: "pem", type: "spki" });
151
+ const timestamp = String(Math.floor(Date.now() / 1000));
152
+ const rawBody = JSON.stringify({
153
+ data: { event_type: "call.initiated", payload: { call_control_id: "call-1" } },
154
+ nonce: crypto.randomUUID(),
155
+ });
156
+ const signedPayload = `${timestamp}|${rawBody}`;
157
+ const signature = crypto.sign(null, Buffer.from(signedPayload), privateKey).toString("base64");
158
+
159
+ return {
160
+ pemPublicKey,
161
+ timestamp,
162
+ rawBody,
163
+ signature,
164
+ makeCtx(signatureValue = signature) {
165
+ return {
166
+ headers: {
167
+ "telnyx-signature-ed25519": signatureValue,
168
+ "telnyx-timestamp": timestamp,
169
+ },
170
+ rawBody,
171
+ url: "https://example.com/voice/webhook",
172
+ method: "POST" as const,
173
+ };
174
+ },
175
+ };
176
+ }
177
+
146
178
  describe("verifyPlivoWebhook", () => {
147
179
  it("accepts valid V2 signature", () => {
148
180
  const authToken = "test-auth-token";
@@ -254,6 +286,52 @@ describe("verifyPlivoWebhook", () => {
254
286
  expectReplayResultPair(first, second);
255
287
  });
256
288
 
289
+ it("treats query-only V2 variants as the same verified request", () => {
290
+ const authToken = "test-auth-token";
291
+ const nonce = "nonce-replay-v2";
292
+ const verificationUrl = "https://example.com/voice/webhook";
293
+ const signature = plivoV2Signature({
294
+ authToken,
295
+ urlNoQuery: verificationUrl,
296
+ nonce,
297
+ });
298
+
299
+ const baseHeaders = {
300
+ host: "example.com",
301
+ "x-forwarded-proto": "https",
302
+ "x-plivo-signature-v2": signature,
303
+ "x-plivo-signature-v2-nonce": nonce,
304
+ };
305
+ const rawBody = "CallUUID=uuid&CallStatus=in-progress";
306
+
307
+ const first = verifyPlivoWebhook(
308
+ {
309
+ headers: baseHeaders,
310
+ rawBody,
311
+ url: `${verificationUrl}?flow=answer&callId=abc`,
312
+ method: "POST",
313
+ query: { flow: "answer", callId: "abc" },
314
+ },
315
+ authToken,
316
+ );
317
+ const second = verifyPlivoWebhook(
318
+ {
319
+ headers: baseHeaders,
320
+ rawBody,
321
+ url: `${verificationUrl}?flow=getinput&callId=abc`,
322
+ method: "POST",
323
+ query: { flow: "getinput", callId: "abc" },
324
+ },
325
+ authToken,
326
+ );
327
+
328
+ expect(first.ok).toBe(true);
329
+ expect(first.verifiedRequestKey).toBeDefined();
330
+ expect(second.ok).toBe(true);
331
+ expect(second.verifiedRequestKey).toBe(first.verifiedRequestKey);
332
+ expect(second.isReplay).toBe(true);
333
+ });
334
+
257
335
  it("returns a stable request key when verification is skipped", () => {
258
336
  const ctx = {
259
337
  headers: {},
@@ -269,31 +347,73 @@ describe("verifyPlivoWebhook", () => {
269
347
  expect(second.verifiedRequestKey).toBe(first.verifiedRequestKey);
270
348
  expect(second.isReplay).toBe(true);
271
349
  });
350
+
351
+ it("detects V3 replay when query parameters are reordered", () => {
352
+ const authToken = "test-auth-token";
353
+ const nonce = "nonce-v3-reorder";
354
+ const postBody = "CallUUID=uuid&CallStatus=in-progress";
355
+
356
+ const urlA = "https://example.com/voice/webhook?flow=answer&callId=abc";
357
+ const urlB = "https://example.com/voice/webhook?callId=abc&flow=answer";
358
+
359
+ const signatureA = plivoV3Signature({ authToken, urlWithQuery: urlA, postBody, nonce });
360
+ const signatureB = plivoV3Signature({ authToken, urlWithQuery: urlB, postBody, nonce });
361
+ expect(signatureA).toBe(signatureB);
362
+
363
+ const first = verifyPlivoWebhook(
364
+ {
365
+ headers: {
366
+ host: "example.com",
367
+ "x-forwarded-proto": "https",
368
+ "x-plivo-signature-v3": signatureA,
369
+ "x-plivo-signature-v3-nonce": nonce,
370
+ },
371
+ rawBody: postBody,
372
+ url: urlA,
373
+ method: "POST",
374
+ query: { flow: "answer", callId: "abc" },
375
+ },
376
+ authToken,
377
+ );
378
+
379
+ const second = verifyPlivoWebhook(
380
+ {
381
+ headers: {
382
+ host: "example.com",
383
+ "x-forwarded-proto": "https",
384
+ "x-plivo-signature-v3": signatureB,
385
+ "x-plivo-signature-v3-nonce": nonce,
386
+ },
387
+ rawBody: postBody,
388
+ url: urlB,
389
+ method: "POST",
390
+ query: { callId: "abc", flow: "answer" },
391
+ },
392
+ authToken,
393
+ );
394
+
395
+ expectReplayResultPair(first, second);
396
+ });
272
397
  });
273
398
 
274
399
  describe("verifyTelnyxWebhook", () => {
275
400
  it("marks replayed valid requests as replay without failing auth", () => {
276
- const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
277
- const pemPublicKey = publicKey.export({ format: "pem", type: "spki" }).toString();
278
- const timestamp = String(Math.floor(Date.now() / 1000));
279
- const rawBody = JSON.stringify({
280
- data: { event_type: "call.initiated", payload: { call_control_id: "call-1" } },
281
- nonce: crypto.randomUUID(),
282
- });
283
- const signedPayload = `${timestamp}|${rawBody}`;
284
- const signature = crypto.sign(null, Buffer.from(signedPayload), privateKey).toString("base64");
285
- const ctx = {
286
- headers: {
287
- "telnyx-signature-ed25519": signature,
288
- "telnyx-timestamp": timestamp,
289
- },
290
- rawBody,
291
- url: "https://example.com/voice/webhook",
292
- method: "POST" as const,
293
- };
401
+ const request = createSignedTelnyxWebhookRequest();
294
402
 
295
- const first = verifyTelnyxWebhook(ctx, pemPublicKey);
296
- const second = verifyTelnyxWebhook(ctx, pemPublicKey);
403
+ const first = verifyTelnyxWebhook(request.makeCtx(), request.pemPublicKey);
404
+ const second = verifyTelnyxWebhook(request.makeCtx(), request.pemPublicKey);
405
+
406
+ expectReplayResultPair(first, second);
407
+ });
408
+
409
+ it("treats Base64 and Base64URL signatures as the same replayed request", () => {
410
+ const request = createSignedTelnyxWebhookRequest();
411
+ const urlSafeSignature = request.signature
412
+ .replace(/\+/g, "-")
413
+ .replace(/\//g, "_")
414
+ .replace(/=+$/g, "");
415
+ const first = verifyTelnyxWebhook(request.makeCtx(), request.pemPublicKey);
416
+ const second = verifyTelnyxWebhook(request.makeCtx(urlSafeSignature), request.pemPublicKey);
297
417
 
298
418
  expectReplayResultPair(first, second);
299
419
  });
@@ -498,6 +618,37 @@ describe("verifyTwilioWebhook", () => {
498
618
  expect(result.verificationUrl).toBe(webhookUrl);
499
619
  });
500
620
 
621
+ it("verifies Twilio signatures for Cloudflare Tunnel publicUrl requests", () => {
622
+ const authToken = "test-auth-token";
623
+ const postBody = "CallSid=CA123&CallStatus=ringing&Direction=inbound&From=%2B15550000000";
624
+ const webhookUrl = "https://oc1.example.com/voice/webhook";
625
+ const signature = twilioSignature({ authToken, url: webhookUrl, postBody });
626
+
627
+ const result = verifyTwilioWebhook(
628
+ {
629
+ headers: {
630
+ host: "localhost:8765",
631
+ "cf-connecting-ip": "203.0.113.42",
632
+ "x-forwarded-proto": "https",
633
+ "x-twilio-signature": signature,
634
+ },
635
+ rawBody: postBody,
636
+ url: "http://localhost:8765/voice/webhook",
637
+ method: "POST",
638
+ remoteAddress: "127.0.0.1",
639
+ },
640
+ authToken,
641
+ {
642
+ publicUrl: webhookUrl,
643
+ allowedHosts: ["oc1.example.com"],
644
+ trustForwardingHeaders: true,
645
+ },
646
+ );
647
+
648
+ expect(result.ok).toBe(true);
649
+ expect(result.verificationUrl).toBe(webhookUrl);
650
+ });
651
+
501
652
  it("rejects X-Forwarded-Host not in allowedHosts whitelist", () => {
502
653
  const authToken = "test-auth-token";
503
654
  const postBody = "CallSid=CS123&CallStatus=completed&From=%2B15550000000";