Skip to content

Commit 6f0b4ca

Browse files
committed
refactor(voice-call): share header and guarded api helpers
1 parent 78a7ff2 commit 6f0b4ca

5 files changed

Lines changed: 76 additions & 70 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export type HttpHeaderMap = Record<string, string | string[] | undefined>;
2+
3+
export function getHeader(headers: HttpHeaderMap, name: string): string | undefined {
4+
const target = name.toLowerCase();
5+
const direct = headers[target];
6+
const value =
7+
direct ?? Object.entries(headers).find(([key]) => key.toLowerCase() === target)?.[1];
8+
if (Array.isArray(value)) {
9+
return value[0];
10+
}
11+
return value;
12+
}

‎extensions/voice-call/src/providers/plivo.ts‎

Lines changed: 11 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import crypto from "node:crypto";
2-
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk";
32
import type { PlivoConfig, WebhookSecurityConfig } from "../config.js";
3+
import { getHeader } from "../http-headers.js";
44
import type {
55
HangupCallInput,
66
InitiateCallInput,
@@ -17,6 +17,7 @@ import type {
1717
import { escapeXml } from "../voice-mapping.js";
1818
import { reconstructWebhookUrl, verifyPlivoWebhook } from "../webhook-security.js";
1919
import type { VoiceCallProvider } from "./base.js";
20+
import { guardedJsonApiRequest } from "./shared/guarded-json-api.js";
2021

2122
export interface PlivoProviderOptions {
2223
/** Override public URL origin for signature verification */
@@ -32,17 +33,6 @@ export interface PlivoProviderOptions {
3233
type PendingSpeak = { text: string; locale?: string };
3334
type PendingListen = { language?: string };
3435

35-
function getHeader(
36-
headers: Record<string, string | string[] | undefined>,
37-
name: string,
38-
): string | undefined {
39-
const value = headers[name.toLowerCase()];
40-
if (Array.isArray(value)) {
41-
return value[0];
42-
}
43-
return value;
44-
}
45-
4636
function createPlivoRequestDedupeKey(ctx: WebhookContext): string {
4737
const nonceV3 = getHeader(ctx.headers, "x-plivo-signature-v3-nonce");
4838
if (nonceV3) {
@@ -96,33 +86,19 @@ export class PlivoProvider implements VoiceCallProvider {
9686
allowNotFound?: boolean;
9787
}): Promise<T> {
9888
const { method, endpoint, body, allowNotFound } = params;
99-
const { response, release } = await fetchWithSsrFGuard({
89+
return await guardedJsonApiRequest<T>({
10090
url: `${this.baseUrl}${endpoint}`,
101-
init: {
102-
method,
103-
headers: {
104-
Authorization: `Basic ${Buffer.from(`${this.authId}:${this.authToken}`).toString("base64")}`,
105-
"Content-Type": "application/json",
106-
},
107-
body: body ? JSON.stringify(body) : undefined,
91+
method,
92+
headers: {
93+
Authorization: `Basic ${Buffer.from(`${this.authId}:${this.authToken}`).toString("base64")}`,
94+
"Content-Type": "application/json",
10895
},
109-
policy: { allowedHostnames: [this.apiHost] },
96+
body,
97+
allowNotFound,
98+
allowedHostnames: [this.apiHost],
11099
auditContext: "voice-call.plivo.api",
100+
errorPrefix: "Plivo API error",
111101
});
112-
try {
113-
if (!response.ok) {
114-
if (allowNotFound && response.status === 404) {
115-
return undefined as T;
116-
}
117-
const errorText = await response.text();
118-
throw new Error(`Plivo API error: ${response.status} ${errorText}`);
119-
}
120-
121-
const text = await response.text();
122-
return text ? (JSON.parse(text) as T) : (undefined as T);
123-
} finally {
124-
await release();
125-
}
126102
}
127103

128104
verifyWebhook(ctx: WebhookContext): WebhookVerificationResult {
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk";
2+
3+
type GuardedJsonApiRequestParams = {
4+
url: string;
5+
method: "GET" | "POST" | "DELETE" | "PUT" | "PATCH";
6+
headers: Record<string, string>;
7+
body?: Record<string, unknown>;
8+
allowNotFound?: boolean;
9+
allowedHostnames: string[];
10+
auditContext: string;
11+
errorPrefix: string;
12+
};
13+
14+
export async function guardedJsonApiRequest<T = unknown>(
15+
params: GuardedJsonApiRequestParams,
16+
): Promise<T> {
17+
const { response, release } = await fetchWithSsrFGuard({
18+
url: params.url,
19+
init: {
20+
method: params.method,
21+
headers: params.headers,
22+
body: params.body ? JSON.stringify(params.body) : undefined,
23+
},
24+
policy: { allowedHostnames: params.allowedHostnames },
25+
auditContext: params.auditContext,
26+
});
27+
28+
try {
29+
if (!response.ok) {
30+
if (params.allowNotFound && response.status === 404) {
31+
return undefined as T;
32+
}
33+
const errorText = await response.text();
34+
throw new Error(`${params.errorPrefix}: ${response.status} ${errorText}`);
35+
}
36+
37+
const text = await response.text();
38+
return text ? (JSON.parse(text) as T) : (undefined as T);
39+
} finally {
40+
await release();
41+
}
42+
}

‎extensions/voice-call/src/providers/telnyx.ts‎

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import crypto from "node:crypto";
2-
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk";
32
import type { TelnyxConfig } from "../config.js";
43
import type {
54
EndReason,
@@ -17,6 +16,7 @@ import type {
1716
} from "../types.js";
1817
import { verifyTelnyxWebhook } from "../webhook-security.js";
1918
import type { VoiceCallProvider } from "./base.js";
19+
import { guardedJsonApiRequest } from "./shared/guarded-json-api.js";
2020

2121
/**
2222
* Telnyx Voice API provider implementation.
@@ -61,33 +61,19 @@ export class TelnyxProvider implements VoiceCallProvider {
6161
body: Record<string, unknown>,
6262
options?: { allowNotFound?: boolean },
6363
): Promise<T> {
64-
const { response, release } = await fetchWithSsrFGuard({
64+
return await guardedJsonApiRequest<T>({
6565
url: `${this.baseUrl}${endpoint}`,
66-
init: {
67-
method: "POST",
68-
headers: {
69-
Authorization: `Bearer ${this.apiKey}`,
70-
"Content-Type": "application/json",
71-
},
72-
body: JSON.stringify(body),
66+
method: "POST",
67+
headers: {
68+
Authorization: `Bearer ${this.apiKey}`,
69+
"Content-Type": "application/json",
7370
},
74-
policy: { allowedHostnames: [this.apiHost] },
71+
body,
72+
allowNotFound: options?.allowNotFound,
73+
allowedHostnames: [this.apiHost],
7574
auditContext: "voice-call.telnyx.api",
75+
errorPrefix: "Telnyx API error",
7676
});
77-
try {
78-
if (!response.ok) {
79-
if (options?.allowNotFound && response.status === 404) {
80-
return undefined as T;
81-
}
82-
const errorText = await response.text();
83-
throw new Error(`Telnyx API error: ${response.status} ${errorText}`);
84-
}
85-
86-
const text = await response.text();
87-
return text ? (JSON.parse(text) as T) : (undefined as T);
88-
} finally {
89-
await release();
90-
}
9177
}
9278

9379
/**

‎extensions/voice-call/src/providers/twilio.ts‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import crypto from "node:crypto";
22
import type { TwilioConfig, WebhookSecurityConfig } from "../config.js";
3+
import { getHeader } from "../http-headers.js";
34
import type { MediaStreamHandler } from "../media-stream.js";
45
import { chunkAudio } from "../telephony-audio.js";
56
import type { TelephonyTtsProvider } from "../telephony-tts.js";
@@ -21,17 +22,6 @@ import type { VoiceCallProvider } from "./base.js";
2122
import { twilioApiRequest } from "./twilio/api.js";
2223
import { verifyTwilioProviderWebhook } from "./twilio/webhook.js";
2324

24-
function getHeader(
25-
headers: Record<string, string | string[] | undefined>,
26-
name: string,
27-
): string | undefined {
28-
const value = headers[name.toLowerCase()];
29-
if (Array.isArray(value)) {
30-
return value[0];
31-
}
32-
return value;
33-
}
34-
3525
function createTwilioRequestDedupeKey(ctx: WebhookContext, verifiedRequestKey?: string): string {
3626
if (verifiedRequestKey) {
3727
return verifiedRequestKey;

0 commit comments

Comments
 (0)