Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: reconnect stability, timestamp/env consistency, and SDK redirect alignment (#465)
Yudhi Armyndharis10323dfcc5ab
diff --git a/.github/workflows/sdk-ci.yml b/.github/workflows/sdk-ci.ymlnew file mode 100644index 000000000..eddae6f49--- /dev/null+++ b/.github/workflows/sdk-ci.yml@@ -0,0 +1,59 @@+name: SDK CI++# Runs the JavaScript/Python/PHP client SDK suites. Path-filtered to sdk/** so it only fires on SDK+# changes and never blocks an unrelated app release. The JavaScript job also builds and runs the+# dual-format packaging smoke test (require() + import() both consumable).+on:+ push:+ branches: [main, develop]+ paths: ['sdk/**', '.github/workflows/sdk-ci.yml']+ pull_request:+ branches: [main, develop]+ paths: ['sdk/**', '.github/workflows/sdk-ci.yml']++jobs:+ javascript:+ name: JavaScript SDK+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: sdk/javascript+ steps:+ - uses: actions/checkout@v6+ - uses: actions/setup-node@v6+ with:+ node-version: '22'+ cache: 'npm'+ cache-dependency-path: sdk/javascript/package-lock.json+ - run: npm ci+ - run: npm test+ - run: npm run build+ - run: npm run smoke # dual CJS+ESM consumable — must run after build++ python:+ name: Python SDK+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: sdk/python+ steps:+ - uses: actions/checkout@v6+ - uses: actions/setup-python@v5+ with:+ python-version: '3.12'+ - run: pip install -e '.[dev]'+ - run: pytest++ php:+ name: PHP SDK+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: sdk/php+ steps:+ - uses: actions/checkout@v6+ - uses: shivammathur/setup-php@v2+ with:+ php-version: '8.2'+ - run: composer install --no-interaction --no-progress+ - run: ./vendor/bin/phpunitdiff --git a/.github/workflows/split-php-sdk.yml b/.github/workflows/split-php-sdk.ymlindex 075215a56..f6d0e5789 100644--- a/.github/workflows/split-php-sdk.yml+++ b/.github/workflows/split-php-sdk.yml@@ -29,8 +29,24 @@ concurrency:cancel-in-progress: falsejobs:+ test:+ name: PHP SDK tests+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: sdk/php+ steps:+ - uses: actions/checkout@v6+ - uses: shivammathur/setup-php@v2+ with:+ php-version: '8.2'+ - run: composer install --no-interaction --no-progress+ - run: ./vendor/bin/phpunit+split:name: Mirror sdk/php -> rmyndharis/openwa-php+ # Never mirror an untested (red) SDK to Packagist dev-main.+ needs: [test]runs-on: ubuntu-lateststeps:- uses: actions/checkout@v6diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b47a8a30d..8283d49c6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- MCP server (opt-in, `MCP_ENABLED=true`): exposes a curated ~39-tool agent surface (sessions, messaging, contacts, basic group ops, webhook reads) over the Model Context Protocol at `POST /mcp`, on the existing single port. Off by default — the MCP SDK is not loaded unless enabled, and every REST route is unchanged. Tools call the existing services and reuse the same API-key auth, role, and per-session scoping as REST; reads vs writes are tiered and `MCP_READONLY=true` mounts read tools only. Destructive/privileged operations are deliberately excluded from the surface. (relates to #256; salvages result-shaping from #461 — thanks @tobiasstrebitzer)- Client SDKs: official, hand-written client libraries for the REST API in **JavaScript/TypeScript** (`@rmyndharis/openwa`), **Python** (`rmyndharis-openwa`), and **PHP** (`rmyndharis/openwa`), replacing the previous single-file stub (`sdk/`). Each exposes the same fluent resource surface — `sessions`, `messages`, `contacts`, `groups`, `chats`, `webhooks`, `labels`, `channels`, `catalog`, `status`, `templates`, `health` — over an injectable HTTP transport, with a typed error hierarchy mapping the NestJS error envelope (`401/403/404/409/429/501`) to typed exceptions and a timeout error. Request/response types mirror the server DTOs exactly. The JavaScript package ships dual CJS + ESM with bundled type declarations (consumable via both `require()` and native `import()`, guarded by a packaging smoke test); the Python package ships PEP 561 type information (`py.typed`); the PHP package is PSR-4 / Guzzle 7. Redirects are never auto-followed (so the API key is never re-sent to a redirect target), auth/JSON headers always take precedence over caller-supplied defaults, path segments are percent-encoded, and a base-URL path prefix (e.g. behind a reverse proxy) is preserved. The SDK does not retry — wrap calls with your own backoff. Published at `0.1.0` on npm (`@rmyndharis/openwa`), PyPI (`rmyndharis-openwa`), and Packagist (`rmyndharis/openwa`). (#463)+### Changed++- CI now runs the JavaScript, Python, and PHP client SDK test suites (path-filtered to `sdk/**`, including the dual-format CJS/ESM packaging smoke test), and the Packagist mirror of the PHP SDK is gated on its tests passing so a broken SDK can no longer auto-publish.++### Fixed++- Reconnection no longer stalls when a wedged browser fails to shut down: the engine teardown during an automatic reconnect is now time-bounded (10s, matching every other teardown), so a stuck Chromium can't leave a session permanently disconnected without self-healing. Affects the `whatsapp-web.js` engine; recover an already-stuck session with force-kill.+- Message timestamps are now consistently returned as a number on both SQLite and PostgreSQL. PostgreSQL previously returned the `bigint` column as a string, which broke strictly-typed SDK clients and arithmetic in non-coercing consumers.+- A blank `DATABASE_PASSWORD` forwarded by the bundled Docker Compose file is now treated as unset, so an external-PostgreSQL password saved via the dashboard is applied instead of being shadowed by the empty value (a real host/`.env` value still keeps top precedence).+- The Python and PHP SDKs now treat an unfollowed redirect (any `3xx`) as an error response, matching the JavaScript SDK. Redirects are never followed (so the API key is never re-sent to the target), which makes a `3xx` an unusable result rather than a fake success.+## [0.7.2] - 2026-06-24### Addeddiff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex 1a04fd5e2..e216340d4 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -54,6 +54,15 @@ describe('OpenWAClient', () => {expect(seenInit?.redirect).toBe('manual');});+ it('treats an unfollowed redirect (3xx) as an error', async () => {+ // Redirects are never followed, so a 3xx is not a usable response — it must throw, keeping the+ // JS transport aligned with the Python and PHP SDKs (which now also error on >= 300).+ const redirectingFetch: FetchLike = async () =>+ new Response('{"redirected":true}', { status: 302, headers: { location: 'http://evil.example/x' } });+ const c = new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', fetch: redirectingFetch });+ await expect(c.sessions.list()).rejects.toThrow();+ });+it('percent-encodes path segments but keeps @ in JIDs readable', async () => {const t = new MockTransport().on('GET', /\/history$/, { body: [] });await client(t).messages.history('s', '[email protected]');diff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.phpindex 0de83aa30..7e99bd644 100644--- a/sdk/php/src/Http/HttpExecutor.php+++ b/sdk/php/src/Http/HttpExecutor.php@@ -116,7 +116,10 @@ class HttpExecutor}$status = $response->getStatusCode();- if ($status >= 400) {+ // Treat any non-2xx as an error, including 3xx: redirects are deliberately not followed (so+ // the API key is never re-sent to the target), making an unfollowed 3xx unusable rather than+ // a success. Matches the JS (`!res.ok`) and Python (`>= 300`) transports.+ if ($status >= 300) {throw $this->buildApiException($response, $method, $path);}diff --git a/sdk/php/tests/ClientTest.php b/sdk/php/tests/ClientTest.phpindex c8576086c..ef95178f6 100644--- a/sdk/php/tests/ClientTest.php+++ b/sdk/php/tests/ClientTest.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace OpenWA\Tests;+use OpenWA\Exceptions\OpenWAApiException;use OpenWA\Exceptions\OpenWAAuthException;use OpenWA\Exceptions\OpenWANotFoundException;use OpenWA\Exceptions\OpenWATimeoutException;@@ -77,16 +78,22 @@ class ClientTest extends TestCase$this->assertStringContainsString('/v1/api/sessions', $backend->lastCall()['path']);}- public function testDoesNotFollowRedirects(): void+ public function testTreatsUnfollowedRedirectAsError(): void{- // A redirect must not be followed (which would re-send X-API-Key to the- // target origin). The 3xx body is returned and only one request is made.+ // A redirect must not be followed (which would re-send X-API-Key to the target origin).+ // An unfollowed 3xx is not a usable response, so it surfaces as an API error rather than a+ // fake success — matching the JS and Python transports. Only one request is made.$backend = new MockBackend();$backend->on(302, ['redirected' => true], ['Location' => 'http://evil.example/x']);$backend->on(200, ['followed' => true]); // only reached if a redirect were followed- $result = $backend->makeClient()->sessions->list();- $this->assertCount(1, $backend->calls());- $this->assertSame(['redirected' => true], $result);+ $threw = false;+ try {+ $backend->makeClient()->sessions->list();+ } catch (OpenWAApiException $e) {+ $threw = true;+ }+ $this->assertTrue($threw, 'an unfollowed 3xx must surface as an API error');+ $this->assertCount(1, $backend->calls()); // the redirect target was never requested}public function test204DeleteSucceedsWithNoBody(): voiddiff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.pyindex d8582b28a..7a80cf568 100644--- a/sdk/python/openwa/_http.py+++ b/sdk/python/openwa/_http.py@@ -102,7 +102,10 @@ class HttpExecutor:res = self._client.request(method, url, json=body if body is not None else None)except httpx.TimeoutException as e:raise OpenWATimeoutError(self._timeout) from e- if res.status_code >= 400:+ # Treat any non-2xx as an error, including 3xx: redirects are deliberately not followed+ # (so the API key is never re-sent to the target), which makes an unfollowed 3xx unusable+ # rather than a success. Matches the JS transport's `!res.ok`.+ if res.status_code >= 300:context = f"{method} {path}"raise OpenWAApiError.from_response(res.status_code, res.text, context)if res.status_code == 204 or not res.content:diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex ce9de92d1..761537114 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -64,10 +64,13 @@ class TestClientCore:assert result == {"ok": True}assert "a=1" in backend.last_call.url- def test_does_not_follow_redirects(self):+ def test_treats_unfollowed_redirect_as_error(self):import httpx- def handler(_req: httpx.Request) -> httpx.Response:+ calls: list[httpx.URL] = []++ def handler(req: httpx.Request) -> httpx.Response:+ calls.append(req.url)return httpx.Response(302,headers={"location": "http://evil.example/x", "content-type": "application/json"},@@ -75,8 +78,11 @@ class TestClientCore:)client = OpenWAClient(base_url="http://x", api_key="k", transport=httpx.MockTransport(handler))- # A redirect is NOT followed (which would re-send X-API-Key); the 3xx body is returned.- assert client.sessions.list() == {"redirected": True}+ # A redirect is NOT followed (which would re-send X-API-Key to the target). An unfollowed 3xx+ # is not a usable response, so it surfaces as an API error — matching the JS transport.+ with pytest.raises(OpenWAApiError):+ client.sessions.list()+ assert len(calls) == 1 # the redirect target was never requesteddef test_strips_trailing_slash(self):backend = MockBackend().on("GET", "/api/sessions", body=[])diff --git a/src/config/env-precedence.spec.ts b/src/config/env-precedence.spec.tsindex 6006eb18b..00c04376b 100644--- a/src/config/env-precedence.spec.ts+++ b/src/config/env-precedence.spec.ts@@ -2,7 +2,7 @@ import * as fs from 'fs';import * as os from 'os';import * as path from 'path';import * as dotenv from 'dotenv';-import { clearBlankEnv } from './env-precedence';+import { clearBlankEnv, BLANK_SHADOWED_ENV_KEYS } from './env-precedence';describe('clearBlankEnv', () => {it('deletes a key whose value is empty or whitespace-only', () => {@@ -56,3 +56,46 @@ describe('engine-selection env precedence (ENGINE_TYPE)', () => {expect(process.env[KEY]).toBe('whatsapp-web.js');});});++describe('blank-shadowed env keys (compose ${VAR:-} forwards the dashboard manages)', () => {+ const withGenerated = (line: string, run: (genPath: string) => void): void => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-env-pw-'));+ try {+ const genPath = path.join(dir, '.env.generated');+ fs.writeFileSync(genPath, `${line}\n`);+ run(genPath);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ };+ const KEY = 'DATABASE_PASSWORD';+ let saved: string | undefined;+ beforeEach(() => (saved = process.env[KEY]));+ afterEach(() => {+ if (saved === undefined) delete process.env[KEY];+ else process.env[KEY] = saved;+ });++ it('covers DATABASE_PASSWORD (its compose forward renders blank and the dashboard saves it)', () => {+ expect(BLANK_SHADOWED_ENV_KEYS).toContain('ENGINE_TYPE');+ expect(BLANK_SHADOWED_ENV_KEYS).toContain('DATABASE_PASSWORD');+ });++ it('lets .env.generated supply the password when the forwarded DATABASE_PASSWORD is blank', () => {+ withGenerated('DATABASE_PASSWORD=s3cret', genPath => {+ process.env[KEY] = ''; // compose `${DATABASE_PASSWORD:-}` with nothing set on the host+ clearBlankEnv(process.env, BLANK_SHADOWED_ENV_KEYS);+ dotenv.config({ path: genPath, override: false });+ expect(process.env[KEY]).toBe('s3cret');+ });+ });++ it('keeps a real host DATABASE_PASSWORD and ignores the .env.generated value', () => {+ withGenerated('DATABASE_PASSWORD=from-file', genPath => {+ process.env[KEY] = 'from-host';+ clearBlankEnv(process.env, BLANK_SHADOWED_ENV_KEYS);+ dotenv.config({ path: genPath, override: false });+ expect(process.env[KEY]).toBe('from-host');+ });+ });+});diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex eff9a459b..bd5345c17 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -9,6 +9,14 @@* pinning the default and ignoring the dashboard's selection. Clearing the blank lets the lower layers* provide the value, while a real (non-empty) value is preserved and keeps its top precedence.*/+/**+ * Keys the bundled compose forwards with `- KEY=${KEY:-}` (rendering blank when unset) AND the+ * dashboard saves to `data/.env.generated`. A blank forward of one of these would shadow the+ * dashboard's value, so each is cleared when blank. Only add a key that meets BOTH conditions —+ * `REDIS_PASSWORD`/`S3_*` are dashboard-managed but not blank-forwarded by compose, so they don't belong.+ */+export const BLANK_SHADOWED_ENV_KEYS: string[] = ['ENGINE_TYPE', 'DATABASE_PASSWORD'];+export function clearBlankEnv(env: NodeJS.ProcessEnv, keys: string[]): void {for (const key of keys) {const value = env[key];diff --git a/src/main.ts b/src/main.tsindex 624c9bbbe..9ab3bdfa1 100644--- a/src/main.ts+++ b/src/main.ts@@ -17,7 +17,7 @@ import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middlimport { AuthService } from './modules/auth/auth.service';import { Request, Response, NextFunction, json, urlencoded } from 'express';import { writeSecretFile } from './common/utils/secret-file';-import { clearBlankEnv } from './config/env-precedence';+import { clearBlankEnv, BLANK_SHADOWED_ENV_KEYS } from './config/env-precedence';import * as dotenv from 'dotenv';import * as fs from 'fs';import * as path from 'path';@@ -51,11 +51,12 @@ for (const secret of [generatedEnvPath, path.resolve(dataDir, '.api-key')]) {}}-// A compose `- ENGINE_TYPE=${ENGINE_TYPE:-}` line forwards a real operator engine choice into the-// container, but renders an empty value when none is set. An empty process.env.ENGINE_TYPE would-// still block .env / .env.generated (loaded below with override:false) from supplying one, silently-// pinning the default and ignoring the dashboard's selection — so treat a blank value as unset.-clearBlankEnv(process.env, ['ENGINE_TYPE']);+// A compose `- KEY=${KEY:-}` line forwards a real operator value into the container but renders an+// empty value when none is set. An empty process.env.KEY would still block .env / .env.generated+// (loaded below with override:false) from supplying one, silently shadowing the dashboard's saved+// value — so treat a blank value as unset for every dashboard-managed, blank-forwarded key (engine+// selection and the external-Postgres password).+clearBlankEnv(process.env, BLANK_SHADOWED_ENV_KEYS);// 2. User-managed .env (does not override real process env)if (fs.existsSync(userEnvPath)) {diff --git a/src/modules/message/entities/message.entity.spec.ts b/src/modules/message/entities/message.entity.spec.tsnew file mode 100644index 000000000..8e4c75663--- /dev/null+++ b/src/modules/message/entities/message.entity.spec.ts@@ -0,0 +1,29 @@+import { bigintToNumberTransformer } from './message.entity';++// bigint columns read back as a string on PostgreSQL but a number on SQLite; the transformer+// normalizes reads so the REST/SDK/MCP contract (always `number`) holds on both dialects.+describe('bigintToNumberTransformer (message.timestamp)', () => {+ it('coerces a PostgreSQL bigint string read to a number', () => {+ // ValueTransformer.from is typed `any`, so assert inline rather than binding to an `any` local.+ expect(bigintToNumberTransformer.from('1700000000')).toBe(1700000000);+ expect(typeof bigintToNumberTransformer.from('1700000000')).toBe('number');+ });++ it('passes a SQLite numeric read through unchanged', () => {+ expect(bigintToNumberTransformer.from(1700000000)).toBe(1700000000);+ });++ it('preserves null', () => {+ expect(bigintToNumberTransformer.from(null)).toBeNull();+ });++ it('writes values through unchanged', () => {+ expect(bigintToNumberTransformer.to(1700000000)).toBe(1700000000);+ expect(bigintToNumberTransformer.to(null)).toBeNull();+ });++ it('coerces a non-numeric read to null rather than leaking NaN (defensive)', () => {+ // A bigint column cannot actually return this; the guard keeps NaN out of the number contract.+ expect(bigintToNumberTransformer.from('not-a-number')).toBeNull();+ });+});diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex db36e1b4e..000d392b1 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -1,6 +1,23 @@-import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, Index } from 'typeorm';+import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, Index, ValueTransformer } from 'typeorm';import { jsonColumnType } from '../../../common/utils/column-types';+/**+ * A `bigint` column reads back as a string on PostgreSQL (pg avoids >2^53 precision loss) but as a+ * number on SQLite. WhatsApp epoch-seconds are far below 2^53, so coerce reads to a number for a+ * consistent REST/SDK/MCP contract (entity, DTO, all three SDKs, and dashboard declare `number`).+ * Writes pass through unchanged; null stays null.+ */+export const bigintToNumberTransformer: ValueTransformer = {+ to: (value: number | null | undefined): number | null | undefined => value,+ from: (value: string | number | null): number | null => {+ if (value == null) return null;+ const n = Number(value);+ // Defensive: a bigint column can only return null or a numeric value, so NaN is unreachable —+ // but coerce a hypothetical non-numeric read to null rather than leak NaN into the contract.+ return Number.isNaN(n) ? null : n;+ },+};+export enum MessageDirection {INCOMING = 'incoming',OUTGOING = 'outgoing',@@ -52,7 +69,7 @@ export class Message {})direction: MessageDirection;- @Column({ type: 'bigint', nullable: true })+ @Column({ type: 'bigint', nullable: true, transformer: bigintToNumberTransformer })timestamp: number;@Column({ type: jsonColumnType(), nullable: true })diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 1dad8d20e..7782f9b4f 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -481,6 +481,26 @@ describe('SessionService', () => {expect(mockEngine.destroy).toHaveBeenCalled();expect(i.engines.has('sess-uuid-1')).toBe(false);});++ it('still re-initializes when the old engine destroy() hangs (time-bounded teardown)', async () => {+ jest.useFakeTimers();+ try {+ const i = internals();+ // A wedged Chromium: destroy() never resolves — the exact condition that triggers a reconnect.+ const stuck = { destroy: jest.fn(() => new Promise<void>(() => undefined)) };+ i.engines.set('sess-uuid-1', stuck);++ const done = i.executeReconnect('sess-uuid-1', createMockSession(), reconnectState);+ await jest.advanceTimersByTimeAsync(10_000); // teardown timeout elapses++ // The hang no longer blocks reconnection: re-init proceeded instead of wedging forever.+ expect(stuck.destroy).toHaveBeenCalledTimes(1);+ expect(engineFactory.create).toHaveBeenCalled();+ await done;+ } finally {+ jest.useRealTimers();+ }+ });});describe('engine onError', () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex f1adbc6d0..31e6dcee0 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -989,10 +989,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn;}try {- // Clean up old engine+ // Clean up old engine. Time-bound the teardown: a wedged Chromium (the common reconnect+ // trigger) makes destroy() hang, and a raw await here would stall the reconnect forever —+ // the session would never re-init nor reach FAILED. teardownEngineSafely always resolves+ // (after 10s on a hang), so reconnection proceeds either way.const oldEngine = this.engines.get(id);if (oldEngine) {- await oldEngine.destroy();+ await this.teardownEngineSafely(id, oldEngine, e => e.destroy(), 'destroy');this.engines.delete(id);}@@ -1004,7 +1007,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatif (this.stoppingSessions.has(id)) {const resurrected = this.engines.get(id);if (resurrected) {- await resurrected.destroy();+ await this.teardownEngineSafely(id, resurrected, e => e.destroy(), 'destroy');this.engines.delete(id);}return;