Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk): trim the key and refuse control characters in JS and Go
Yudhi Armyndharisc6ddb3b0a0db
diff --git a/sdk/go/client.go b/sdk/go/client.goindex abe482d1b..600555297 100644--- a/sdk/go/client.go+++ b/sdk/go/client.go@@ -88,9 +88,17 @@ func New(baseURL, apiKey string, opts ...Option) (*Client, error) {if strings.TrimSpace(baseURL) == "" {return nil, errors.New("openwa: baseURL is required")}- if strings.TrimSpace(apiKey) == "" {+ // A key read from a secret file usually ends in a newline: trimmed, as the other clients do. A control+ // character left inside is refused here, by the key's name and without repeating it.+ apiKey = strings.TrimSpace(apiKey)+ if apiKey == "" {return nil, errors.New("openwa: apiKey is required")}+ for _, r := range apiKey {+ if r < 0x20 || r == 0x7f {+ return nil, errors.New("openwa: apiKey contains a control character; check for a stray newline")+ }+ }cfg := &config{baseURL: strings.TrimRight(baseURL, "/"),diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 80c463963..93f6d1e14 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -66,6 +66,33 @@ func TestNewValidation(t *testing.T) {}}+func TestNewTrimsTheKeyAndRefusesAControlCharacterWithoutRepeatingIt(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"valid":true}`}+ c, err := New("https://x", " owa_k1_test\n", WithTransport(rt))+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ if _, err := c.Auth.Validate(context.Background()); err != nil {+ t.Fatalf("Validate: %v", err)+ }+ if got := rt.lastReq.Header.Get("X-API-Key"); got != "owa_k1_test" {+ t.Fatalf("X-API-Key = %q, want the trimmed key", got)+ }+ // An inner space is part of a passphrase key.+ if _, err := New("https://x", "correct horse battery"); err != nil {+ t.Fatalf("a key with an inner space: %v", err)+ }+ for _, bad := range []string{"owa_k1_se\ncret", "owa_k1_se\x00cret", "owa_k1_se\x7fcret"} {+ _, err := New("https://x", bad)+ if err == nil {+ t.Fatalf("expected an error for %q", bad)+ }+ if strings.Contains(err.Error(), "cret") {+ t.Fatalf("the error repeats the key: %v", err)+ }+ }+}+func TestSendTextHitsCorrectPath(t *testing.T) {rt := &recordTransport{status: 200, body: `{"messageId":"m1","timestamp":123}`}c := newTestClient(t, rt)diff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.tsindex 3020c99de..ed8120d73 100644--- a/sdk/javascript/src/client.ts+++ b/sdk/javascript/src/client.ts@@ -27,7 +27,7 @@* @packageDocumentation*/-import { request, requestBytes, encodeSegment, toTimeoutMs, warnIfInsecureHttpUrl, type BinaryResponse, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';+import { request, requestBytes, encodeSegment, hasUnsendableChar, toTimeoutMs, warnIfInsecureHttpUrl, type BinaryResponse, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';import { CallsResource } from './resources/calls.js';import { MediaResource } from './resources/media.js';import { CatalogResource } from './resources/catalog.js';@@ -66,13 +66,26 @@ export class OpenWAClient {constructor(options: OpenWAClientOptions) {if (!options.baseUrl) throw new Error('OpenWAClient: baseUrl is required');- if (!options.apiKey) throw new Error('OpenWAClient: apiKey is required');+ // A key read from a secret file usually ends in a newline: trimmed, as the other clients do. A control or+ // non-Latin-1 character left inside is refused here, because fetch's own error quotes the whole value.+ const apiKey = typeof options.apiKey === 'string' ? options.apiKey.trim() : options.apiKey;+ if (!apiKey) throw new Error('OpenWAClient: apiKey is required');+ if (typeof apiKey !== 'string' || hasUnsendableChar(apiKey)) {+ throw new Error('OpenWAClient: apiKey contains a control or non-Latin-1 character; check for a stray newline');+ }+ for (const [name, value] of Object.entries(options.defaultHeaders ?? {})) {+ if (hasUnsendableChar(String(value))) {+ throw new Error(+ `OpenWAClient: defaultHeaders value for "${name}" contains a control or non-Latin-1 character; check for a stray newline`,+ );+ }+ }Object.defineProperty(this, 'config', {enumerable: false,value: {baseUrl: options.baseUrl,- apiKey: options.apiKey,+ apiKey,timeoutMs: toTimeoutMs(options.timeoutMs ?? 30000),defaultHeaders: options.defaultHeaders ?? {},// Looked up on each call rather than captured here, so a fetch installed on globalThis afterdiff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.tsindex 951cebda2..40217dcef 100644--- a/sdk/javascript/src/http.ts+++ b/sdk/javascript/src/http.ts@@ -125,6 +125,15 @@ export async function requestBytes(});}+/**+ * Whether a header value holds a character fetch cannot send: a control character other than a tab, or one+ * above U+00FF. Checked at construction so that the refusal names the header and never repeats the value,+ * which the transport's own TypeError does, and a credential would reach the application's log with it.+ */+export function hasUnsendableChar(value: string): boolean {+ return /[\u0000-\u0008\u000a-\u001f\u007f\u0100-\uffff]/.test(value);+}+/*** A timeout in milliseconds, coerced once: untyped JS config can pass a numeric string (process.env).* `0` or `Infinity` turns the timeout off, so any other value that is not a non-negative number (andiff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex eb20a6a99..e79d53e05 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -436,6 +436,51 @@ describe('OpenWAClient', () => {}});+ it('trims a key read from a file, and refuses what fetch cannot send without repeating it', async () => {+ const t = new MockTransport().on('GET', '/api/sessions', { body: [] });+ const c = new OpenWAClient({ baseUrl: 'http://x', apiKey: ' owa_k1_secret\n', fetch: t.asFetch() });+ await c.sessions.list();+ expect(t.lastCall!.headers['x-api-key']).toBe('owa_k1_secret');++ // An inner space is part of a passphrase key and is sent as it is.+ const spaced = new OpenWAClient({ baseUrl: 'http://x', apiKey: 'correct horse battery', fetch: t.asFetch() });+ await spaced.sessions.list();+ expect(t.lastCall!.headers['x-api-key']).toBe('correct horse battery');++ for (const bad of ['owa_k1_se\ncret', 'owa_k1_se\u0000cret', 'owa_k1_s\u2603cret']) {+ let message = '';+ try {+ new OpenWAClient({ baseUrl: 'http://x', apiKey: bad });+ } catch (error) {+ message = String((error as Error).message);+ }+ expect(message).toContain('apiKey');+ expect(message).not.toContain('cret');+ }+ expect(() => new OpenWAClient({ baseUrl: 'http://x', apiKey: ' \n' })).toThrow('apiKey is required');+ });++ it('refuses a default header value fetch cannot send, naming the header and not the value', () => {+ for (const [name, value] of [+ ['CF-Access-Client-Secret', 's3cret-token\nX-Injected: 1'],+ ['X-Trace', 'a\u0000b'],+ ['X-Name', 'snow\u2603'],+ ]) {+ let message = '';+ try {+ new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', defaultHeaders: { [name]: value } });+ } catch (error) {+ message = String((error as Error).message);+ }+ expect(message).toContain(`"${name}"`);+ expect(message).not.toContain(value);+ }+ // A tab, printable ASCII and a Latin-1 character are sent as before.+ expect(+ () => new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', defaultHeaders: { 'X-Trace': 'a\tb caf\u00e9' } }),+ ).not.toThrow();+ });+it('keeps X-API-Key winning over defaultHeaders', async () => {const t = new MockTransport().on('GET', '/api/sessions', { body: [] });const c = new OpenWAClient({