Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: secrets, SDK contract & operational hardening (auth, sdk, ci, infra) (#478)
Yudhi Armyndharis18acfd358e13
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 385be010d..fc2a73906 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -91,6 +91,9 @@ jobs:- name: Build dashboardrun: cd dashboard && npm run build+ - name: Run dashboard unit tests+ run: cd dashboard && npm run test:unit+build:name: Buildruns-on: ubuntu-latestdiff --git a/.github/workflows/sdk-ci.yml b/.github/workflows/sdk-ci.ymlindex eddae6f49..89904b7b4 100644--- a/.github/workflows/sdk-ci.yml+++ b/.github/workflows/sdk-ci.yml@@ -1,15 +1,16 @@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+# Runs the JavaScript/Python/PHP client SDK suites. Path-filtered to SDK sources AND the server+# contract surfaces the SDK types mirror (DTOs + the engine interface), so a backend DTO change also+# re-runs the SDK suites and surfaces contract drift. 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']+ paths: ['sdk/**', '.github/workflows/sdk-ci.yml', 'src/**/dto/**', 'src/engine/interfaces/whatsapp-engine.interface.ts']pull_request:branches: [main, develop]- paths: ['sdk/**', '.github/workflows/sdk-ci.yml']+ paths: ['sdk/**', '.github/workflows/sdk-ci.yml', 'src/**/dto/**', 'src/engine/interfaces/whatsapp-engine.interface.ts']jobs:javascript:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a31c75533..bf70a664c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Changed++- CI now runs the dashboard unit tests, and re-runs the client-SDK suites when a server DTO or the engine interface changes (not only on SDK edits), so contract drift is caught at its source. (#478)+### Fixed- A plugin whose enable failed after it had already subscribed hooks no longer leaves stale hook registrations behind; a later successful enable could otherwise dispatch each event to the plugin more than once. (#477)@@ -15,6 +19,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The dashboard recovers from a stale lazy-loaded chunk after a redeploy with a single guarded reload instead of replacing the whole UI with the error screen; the Content-Security-Policy `img-src` now allows `blob:` so the outgoing image-attachment preview renders. (#477)- The Baileys engine's number-check (`GET /sessions/:id/contacts/check/:number`) now returns a neutral `<phone>@c.us` id, matching the whatsapp-web.js engine, instead of a raw `@s.whatsapp.net` id. (#477)- The data export/import now includes the `lid_mappings` resolution cache, so a backup/restore or a SQLite↔PostgreSQL migration no longer drops it. (#477)+- The JavaScript client SDK applies the JSON `Content-Type` and `X-API-Key` after caller-supplied headers, so they can no longer be overridden by `defaultHeaders` (matching the Python and PHP SDKs); an unfollowed redirect (HTTP status `0`) now raises a clear error instead of `OpenWA API 0`. (#478)+- The infrastructure status endpoint reports the active S3 bucket when storage is in S3 mode, instead of only the unused local media path. (#478)++### Security++- The startup banner prints the full admin API key only when it is first created; on subsequent boots the key is masked, so the live credential is not re-written to the log pipeline on every restart. (#478)+- The production secret guard now rejects a placeholder `REDIS_PASSWORD` (e.g. `changeme`); an empty/unset password is still allowed so passwordless private-network Redis continues to boot. (#478)+- The published PHP SDK package no longer ships its test suite, PHPUnit config, or `composer.lock`. (#478)## [0.7.5] - 2026-06-26diff --git a/sdk/javascript/src/errors.ts b/sdk/javascript/src/errors.tsindex 30649b83a..5a656a922 100644--- a/sdk/javascript/src/errors.ts+++ b/sdk/javascript/src/errors.ts@@ -41,6 +41,16 @@ export class OpenWAApiError extends OpenWAError {/** Build an {@link OpenWAApiError} from a fetch Response, awaiting its body. */static async fromResponse(res: Response, context: string): Promise<OpenWAApiError> {+ // An opaque unfollowed redirect (we set `redirect: 'manual'`) surfaces as status 0, not a 3xx.+ // Give it a clear message instead of "OpenWA API 0": the redirect was deliberately not followed+ // so the API key is never re-sent to the redirect target.+ if (res.status === 0) {+ return new OpenWAApiError(+ `Unexpected redirect (not followed; the API key is never re-sent to a redirect target) — ${context}`,+ 0,+ undefined,+ );+ }let body: unknown = undefined;const text = await res.text().catch(() => '');if (text) {diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.tsindex 7bdd530cc..b899d2aa4 100644--- a/sdk/javascript/src/http.ts+++ b/sdk/javascript/src/http.ts@@ -82,10 +82,13 @@ export async function request<T>(const controller = new AbortController();const timer = setTimeout(() => controller.abort(), timeoutMs);+ // Auth and JSON content-type WIN over caller-supplied defaults/per-request headers — the SDK only+ // ever sends a JSON body, and this matches the Python and PHP SDKs (which force JSON) and the+ // documented "JSON headers win" contract. Put them last so a defaultHeaders Content-Type can't clobber.const headers: Record<string, string> = {- 'Content-Type': 'application/json',...config.defaultHeaders,...options.headers,+ 'Content-Type': 'application/json','X-API-Key': config.apiKey,};diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex e216340d4..1514ba0d8 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -63,6 +63,17 @@ describe('OpenWAClient', () => {await expect(c.sessions.list()).rejects.toThrow();});+ it('surfaces a real opaque unfollowed redirect (status 0) as a clear OpenWAApiError', async () => {+ // With `redirect: 'manual'` the runtime returns an opaque response with status 0 (not a 3xx);+ // this is the actual shape the no-redirect guard produces, and it must throw a clear error.+ const opaqueRedirectFetch: FetchLike = async () => Response.error();+ const c = new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', fetch: opaqueRedirectFetch });+ const err = await c.sessions.list().catch((e: unknown) => e);+ expect(err).toBeInstanceOf(OpenWAApiError);+ expect((err as OpenWAApiError).status).toBe(0);+ expect((err as OpenWAApiError).message).toMatch(/redirect/i);+ });+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]');@@ -160,4 +171,18 @@ describe('OpenWAClient', () => {expect(t.lastCall!.headers['x-api-key']).toBe('REAL');expect(t.lastCall!.headers['x-trace']).toBe('keep');});++ it('keeps the JSON Content-Type winning over a defaultHeaders override', async () => {+ const t = new MockTransport().on('GET', '/api/sessions', { body: [] });+ const c = new OpenWAClient({+ baseUrl: 'http://x',+ apiKey: 'k',+ defaultHeaders: { 'Content-Type': 'text/plain', 'X-Trace': 'keep' },+ fetch: t.asFetch(),+ });+ await c.sessions.list();+ // JSON wins (matches the Python/PHP SDKs), but an unrelated default header is still preserved.+ expect(t.lastCall!.headers['content-type']).toBe('application/json');+ expect(t.lastCall!.headers['x-trace']).toBe('keep');+ });});diff --git a/sdk/php/.gitattributes b/sdk/php/.gitattributesnew file mode 100644index 000000000..836f2dae4--- /dev/null+++ b/sdk/php/.gitattributes@@ -0,0 +1,8 @@+# Keep the published Packagist package lean: Packagist builds its dist archive with `git archive`,+# which honors `export-ignore`, so dev-only files are excluded from what consumers download.+/tests export-ignore+/phpunit.xml export-ignore+/.phpunit.cache export-ignore+/.gitattributes export-ignore+/.gitignore export-ignore+/composer.lock export-ignorediff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.tsindex 1ec396032..4302b2910 100644--- a/src/config/bootstrap-security.spec.ts+++ b/src/config/bootstrap-security.spec.ts@@ -135,6 +135,23 @@ describe('assertNoDefaultSecretsInProduction', () => {expect(() => assertNoDefaultSecretsInProduction({ nodeEnv: 'development', allowDevApiKey: 'true' })).not.toThrow();});+ it('refuses prod with a placeholder REDIS_PASSWORD', () => {+ expect(() => assertNoDefaultSecretsInProduction({ nodeEnv: 'production', redisPassword: 'changeme' })).toThrow(+ /REDIS_PASSWORD/,+ );+ });++ it('allows prod with an empty REDIS_PASSWORD (passwordless private-network Redis is supported)', () => {+ expect(() => assertNoDefaultSecretsInProduction({ nodeEnv: 'production', redisPassword: '' })).not.toThrow();+ expect(() => assertNoDefaultSecretsInProduction({ nodeEnv: 'production' })).not.toThrow();+ });++ it('allows prod with a strong REDIS_PASSWORD', () => {+ expect(() =>+ assertNoDefaultSecretsInProduction({ nodeEnv: 'production', redisPassword: 'a-strong-unique-redis-secret' }),+ ).not.toThrow();+ });+it('allows the default sqlite + local-storage prod setup (no secrets needed)', () => {expect(() =>assertNoDefaultSecretsInProduction({ nodeEnv: 'production', databaseType: 'sqlite', storageType: 'local' }),diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.tsindex 5e75d2ad1..52db1ef48 100644--- a/src/config/bootstrap-security.ts+++ b/src/config/bootstrap-security.ts@@ -74,6 +74,8 @@ export interface SecretCheckEnv {apiMasterKey?: string;/** ALLOW_DEV_API_KEY — when 'true' it seeds the well-known public `dev-admin-key` as an ADMIN credential. */allowDevApiKey?: string;+ /** REDIS_PASSWORD — optional; passwordless private-network Redis is supported, so only a known placeholder is rejected. */+ redisPassword?: string;}/**@@ -99,6 +101,11 @@ export function assertNoDefaultSecretsInProduction(env: SecretCheckEnv): void {if (env.apiMasterKey && FORBIDDEN_PROD_SECRETS.has(env.apiMasterKey.trim().toLowerCase())) {problems.push('API_MASTER_KEY');}+ // Redis auth is optional (passwordless private-network Redis is a supported deployment), so unlike+ // DATABASE_PASSWORD this rejects only a known placeholder VALUE — never an empty/unset password.+ if (env.redisPassword && FORBIDDEN_PROD_SECRETS.has(env.redisPassword.trim().toLowerCase())) {+ problems.push('REDIS_PASSWORD');+ }// ALLOW_DEV_API_KEY=true seeds the publicly-documented `dev-admin-key` as an ADMIN credential// (when no API_MASTER_KEY is set) — never allow that opt-in to be carried into production.if (env.allowDevApiKey === 'true') {diff --git a/src/main.ts b/src/main.tsindex 861bef596..e093e0e7a 100644--- a/src/main.ts+++ b/src/main.ts@@ -124,6 +124,7 @@ async function bootstrap() {s3SecretKey: process.env.S3_SECRET_ACCESS_KEY || process.env.S3_SECRET_KEY,apiMasterKey: process.env.API_MASTER_KEY,allowDevApiKey: process.env.ALLOW_DEV_API_KEY,+ redisPassword: process.env.REDIS_PASSWORD,});// Disable Nest's default body parser so we can set an explicit size cap below.diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex caede3dcd..7cd02df82 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -3,7 +3,7 @@ import { getRepositoryToken } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { UnauthorizedException, NotFoundException } from '@nestjs/common';import { createHash, createHmac } from 'crypto';-import { AuthService, resolveSeedApiKey } from './auth.service';+import { AuthService, resolveSeedApiKey, bannerKeyLine } from './auth.service';import { ApiKey, ApiKeyRole } from './entities/api-key.entity';// Helpers@@ -62,6 +62,25 @@ describe('resolveSeedApiKey (first-boot default admin key)', () => {});});+describe('bannerKeyLine (startup banner key masking)', () => {+ const FULL = 'owa_k1_0123456789abcdef0123456789abcdef';++ it('prints the full key only when it was just created', () => {+ expect(bannerKeyLine(FULL, true)).toBe(FULL);+ });++ it('masks the key on subsequent boots — the full secret is never re-logged', () => {+ const line = bannerKeyLine(FULL, false);+ expect(line).not.toContain('0123456789abcdef'); // the secret tail must not appear+ expect(line.startsWith('owa_k1_0')).toBe(true); // a short fingerprint is fine+ expect(line).toMatch(/data\/\.api-key|dashboard/); // points the operator to the real source+ });++ it('passes a placeholder through unchanged', () => {+ expect(bannerKeyLine('(check dashboard for keys)', false)).toBe('(check dashboard for keys)');+ });+});+describe('AuthService', () => {let service: AuthService;let repository: jest.Mocked<Partial<Repository<ApiKey>>>;diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex 8afefa75f..e40d1e632 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -29,6 +29,19 @@ export function resolveSeedApiKey(): string {return `owa_k1_${randomBytes(32).toString('hex')}`;}+/**+ * The line to print for the API key in the startup banner. The full raw key is shown ONLY when it was+ * just created (first run, when the operator needs to capture it once). On every subsequent boot the+ * key is masked to a short non-secret fingerprint, so the live admin key is not re-written to the log+ * pipeline (Docker/Loki/CloudWatch) on each restart — it stays in `data/.api-key` (0600) and the+ * dashboard. A placeholder (e.g. "(check dashboard for keys)") is passed through unchanged.+ */+export function bannerKeyLine(displayKey: string, isNewKey: boolean): string {+ if (isNewKey) return displayKey;+ if (displayKey.startsWith('(')) return displayKey;+ return `${displayKey.slice(0, 8)}… (full key in data/.api-key or the dashboard)`;+}+@Injectable()export class AuthService implements OnModuleInit {private readonly logger = createLogger('AuthService');@@ -93,7 +106,7 @@ export class AuthService implements OnModuleInit {} else {this.logger.log(' 🔑 API Key:');}- this.logger.log(` ${displayKey}`);+ this.logger.log(` ${bannerKeyLine(displayKey, isNewKey)}`);this.logger.log('');this.logger.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');this.logger.log('');diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 21cf85b60..81935681f 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -672,6 +672,17 @@ describe('InfraController.getStatus storage (reads the real storage.localPath keconst status = await buildController({ 'storage.type': 'local' }).getStatus();expect(status.storage.path).toBe('./data/media');});++ it('reports the bucket in S3 mode so the active backend is visible', async () => {+ const status = await buildController({ 'storage.type': 's3', 'storage.s3.bucket': 'my-openwa-bucket' }).getStatus();+ expect(status.storage.type).toBe('s3');+ expect(status.storage.bucket).toBe('my-openwa-bucket');+ });++ it('omits bucket in local mode (no fabricated field)', async () => {+ const status = await buildController({ 'storage.type': 'local' }).getStatus();+ expect(status.storage.bucket).toBeUndefined();+ });});describe('InfraController.exportStorage keeps the export import-able and sweeps it', () => {diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex ed5b5ed50..b4fd88d3c 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -251,6 +251,9 @@ export class InfraController {// Read the key StorageService actually uses (`storage.localPath`, default `./data/media`).// The old `storage.path` key never existed, so status always reported the `./uploads` fallback.const storagePath = this.configService.get<string>('storage.localPath', './data/media');+ // In S3 mode the local path is unused; surface the bucket so the status panel shows the real+ // backend. `path` is kept (additive) so the dashboard's local-mode rendering is unchanged.+ const storageBucket = this.configService.get<string>('storage.s3.bucket');const engineType = this.configService.get<string>('engine.type', 'whatsapp-web.js');// configuration.ts nests these under engine.puppeteer.{headless,args}; the old flat@@ -268,7 +271,11 @@ export class InfraController {messages: { pending: 0, completed: 0, failed: 0 },webhooks: { pending: 0, completed: 0, failed: 0 },},- storage: { type: storageType, path: storagePath },+ storage: {+ type: storageType,+ path: storagePath,+ ...(storageType === 's3' && storageBucket ? { bucket: storageBucket } : {}),+ },engine: { type: engineType, headless: engineHeadless, sessionDataPath, browserArgs },};}