Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk): send JS raw paths with a trailing or double slash again

Yudhi Armyndharis0080ca9b3377
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index 79b4d1454..25f375d93 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -404,7 +404,7 @@ try {
- **Redirects are never followed.** The transport uses `redirect: 'manual'`, so a `3xx` surfaces to the caller as an error (via `OpenWAApiError`) rather than being followed — this guarantees the `X-API-Key` header is never re-sent to a redirect target (potentially a different origin).
- **Auth and JSON headers take precedence.** Request headers are merged in the order `defaultHeaders` → per-call headers → `Content-Type: application/json` → `X-API-Key`. Both `Content-Type` and `X-API-Key` are applied last, so neither can be overridden by a caller-supplied header.
- **Path segments are percent-encoded.** Ids (session, chat, message, etc.) are encoded so a value cannot break out of its path position, while keeping the WhatsApp-safe characters `@`, `:`, and `+` readable (e.g. `[email protected]`).
-- **Empty and dot segments are refused.** An empty, `.` or `..` segment rejects with a `TypeError` and nothing is sent, because `fetch` would otherwise resolve it to the parent resource.
+- **Empty and dot segments are refused.** An empty, `.` or `..` id rejects with a `TypeError` and nothing is sent, because `fetch` would otherwise resolve it to the parent resource. A raw `request()`/`requestBytes()` path with a `.` or `..` segment rejects with a `TypeError`; a trailing or double slash in a raw path is sent as written.
- **Base-URL path prefix is preserved.** A `baseUrl` such as `https://gateway.example.com/v1` keeps its `/v1` prefix on every request; only a trailing slash is trimmed.
- **No automatic retries.** A failed request rejects immediately — the SDK does not retry, even on `429`. Wrap calls in your own backoff if you need retries.
- **Injectable transport.** Supply a custom `fetch` to wrap outbound calls with retry, logging, or observability middleware, or to run on a runtime without a global `fetch`. This is also the recommended way to unit-test without monkey-patching globals.
diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.ts
index 1cf6d0d82..dcb8d0aae 100644
--- a/sdk/javascript/src/http.ts
+++ b/sdk/javascript/src/http.ts
@@ -44,14 +44,25 @@ export interface ClientConfig {
fetch?: FetchLike;
}
+/** Stands in for an empty or dot id; encodeURIComponent output never contains it. */
+const BLANK_SEGMENT = '\u0000';
+
/**
* Percent-encode a single path segment (e.g. a chat/message id) so a value
* containing `/`, `#`, `?` or whitespace can't break out of its path position.
* WhatsApp-id characters that are already path-safe (`@`, `:`, `+`) are kept
* readable.
+ *
+ * An empty, `.` or `..` segment becomes {@link BLANK_SEGMENT}, which `send()`
+ * rejects: fetch resolves dot segments before sending, and an empty one means
+ * a required id was blank, so either would reach the parent resource instead
+ * of the intended one. Marking it here rather than throwing keeps the refusal
+ * a rejection of the returned promise, since resource methods are not async.
*/
export function encodeSegment(segment: string | number): string {
- return encodeURIComponent(String(segment)).replace(/%40/g, '@').replace(/%3A/g, ':').replace(/%2B/g, '+');
+ const text = String(segment);
+ if (text === '' || text === '.' || text === '..') return BLANK_SEGMENT;
+ return encodeURIComponent(text).replace(/%40/g, '@').replace(/%3A/g, ':').replace(/%2B/g, '+');
}
/** Build a URL with serialized query params, omitting `undefined`/`null` values. */
@@ -139,21 +150,25 @@ async function send<T>(
options: RequestOptions,
consume: (res: Response) => Promise<T>,
): Promise<T> {
+ if (options.path.includes(BLANK_SEGMENT)) {
+ throw new TypeError(`OpenWA: empty or dot path segment in ${JSON.stringify(options.path)}`);
+ }
+ const url = buildUrl(config.baseUrl, options.path, options.query);
// fetch resolves `.` and `..` segments before sending, so such a segment would reach the parent
- // resource instead of the intended one. Mirror the URL parser: it drops tab and newline, trims
- // trailing C0 controls and spaces, reads `\` as `/`, and treats %2e as a dot. An empty segment is
- // refused too: it means a required id was blank.
- const pathOnly = options.path
- .split(/[?#]/, 1)[0]
- .replace(/[\t\n\r]/g, '')
- .replace(/[\x00-\x20]+$/, '');
+ // resource instead of the intended one. Mirror the URL parser: it drops tab and newline, reads `\`
+ // as `/`, treats %2e as a dot, and trims trailing C0 controls and spaces, which end the path only
+ // when no query or fragment follows it. Empty segments, such as a trailing slash, are sent as
+ // written; a blank id is refused above.
+ const tail = url.slice(config.baseUrl.replace(/\/$/, '').length);
+ const rawPath = tail.split(/[?#]/, 1)[0];
+ let pathOnly = rawPath.replace(/[\t\n\r]/g, '');
+ if (rawPath.length === tail.length) pathOnly = pathOnly.replace(/[\x00-\x20]+$/, '');
for (const segment of pathOnly.split(/[/\\]/).slice(1)) {
const dots = segment.replace(/%2e/gi, '.');
- if (dots === '' || dots === '.' || dots === '..') {
- throw new TypeError(`OpenWA: empty or dot path segment in ${JSON.stringify(options.path)}`);
+ if (dots === '.' || dots === '..') {
+ throw new TypeError(`OpenWA: dot path segment in ${JSON.stringify(options.path)}`);
}
}
- const url = buildUrl(config.baseUrl, options.path, options.query);
const timeoutMs = toTimeoutMs(options.timeoutMs ?? config.timeoutMs);
const controller = new AbortController();
diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.ts
index f6c20bbd0..124bc2b39 100644
--- a/sdk/javascript/test/client.test.ts
+++ b/sdk/javascript/test/client.test.ts
@@ -105,6 +105,20 @@ describe('OpenWAClient', () => {
expect(t.calls).toHaveLength(2);
});
+ it('sends a raw path with a trailing slash, a double slash or only a slash as written', async () => {
+ const t = new MockTransport().passthrough({ status: 200, body: [] });
+ const c = client(t);
+ for (const path of ['/api/sessions/', '/api/sessions//x', '/']) {
+ await c.request({ method: 'GET', path });
+ expect(t.lastCall!.url).toBe(`http://localhost:2785${path}`);
+ }
+ await c.requestBytes({ method: 'GET', path: '/api/search/', query: { q: 'x' } });
+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/search/?q=x');
+ // A space before an appended query is not trailing, so `.. ` is sent as `..%20`, not as a dot segment.
+ await c.request({ method: 'GET', path: '/api/labels/.. ', query: { q: 'x' } });
+ expect(t.calls).toHaveLength(5);
+ });
+
it('serializes query params and skips null/undefined', async () => {
const t = new MockTransport().on('GET', /\/messages/, { body: [] });
await client(t).messages.list('s1', { chatId: '[email protected]', from: undefined, limit: 10 });