Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): tighten the SQLite database files to owner-only on boot
Yudhi Armyndharisc494d5ffdb25
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d7333222a..2c5421529 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- The SQLite database files are tightened to owner-only (`0600`, plus `-wal`/`-shm`/`-journal`) on every boot; they hold plaintext webhook/plugin secrets and were group/world-readable while sibling secret files were `0600`.- `PUT /sessions/{sessionId}/webhooks/{id}` now enforces the same 16-character webhook-secret floor as create; an empty string still clears signing.## [0.20.0] - 2026-08-16diff --git a/scripts/restore.sh b/scripts/restore.shindex c309b0bbd..25dd4e873 100755--- a/scripts/restore.sh+++ b/scripts/restore.sh@@ -271,6 +271,9 @@ if [ -f "$STAGE/main.sqlite" ]; thensnapshot_external_db "$MAIN_DB"mkdir -p "$(dirname "$MAIN_DB")"cp "$STAGE/main.sqlite" "$MAIN_DB"+ # Owner-only, matching what the app re-tightens on every boot (sqlite-file-permissions.ts);+ # cp preserves the staged mode, and a foreign-umask extraction may leave it broader.+ chmod 0600 "$MAIN_DB" 2>/dev/null || trueelselog "WARN: main.sqlite not in archive — API keys / audit log will NOT be restored"fi@@ -280,6 +283,7 @@ if [ -f "$STAGE/openwa.sqlite" ]; thensnapshot_external_db "$DATA_DB"mkdir -p "$(dirname "$DATA_DB")"cp "$STAGE/openwa.sqlite" "$DATA_DB"+ chmod 0600 "$DATA_DB" 2>/dev/null || truefiif [ -d "$STAGE/sessions" ]; thendiff --git a/src/app.module.ts b/src/app.module.tsindex e0e2aee66..8e9afeab9 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -45,6 +45,7 @@ import { PluginsApiModule } from './modules/plugins/plugins.module';import { AgentToolsModule } from './core/agent-tools/agent-tools.module';import { IntegrationModule } from './modules/integration/integration.module';import { SearchModule } from './modules/search/search.module';+import { SqlitePermissionsBoot } from './database/sqlite-file-permissions';// Only import QueueModule if explicitly enabled to avoid Redis connection errorsconst queueModules: Array<Type | DynamicModule> = [];@@ -319,5 +320,9 @@ if (dashboardServingEnabled && dashboardBuildPresent) {...mcpModules, // MCP Streamable-HTTP server (opt-in via MCP_ENABLED=true)...serveStaticModules, // Bundled dashboard SPA (production single-port setup)],+ // Runs after every DataSource has initialized (they initialize eagerly in their provider+ // factories, and onApplicationBootstrap fires after every onModuleInit), tightening the SQLite+ // files that better-sqlite3 created with umask permissions back to owner-only.+ providers: [SqlitePermissionsBoot],})export class AppModule {}diff --git a/src/database/sqlite-file-permissions.spec.ts b/src/database/sqlite-file-permissions.spec.tsnew file mode 100644index 000000000..e2e2fdcaa--- /dev/null+++ b/src/database/sqlite-file-permissions.spec.ts@@ -0,0 +1,108 @@+// The fs namespace object is frozen, so chmodSync cannot be spyOn'd; wrap it in a mock that+// delegates to the real implementation unless a test overrides one call.+jest.mock('fs', () => {+ const actual = jest.requireActual<typeof import('fs')>('fs');+ return { ...actual, chmodSync: jest.fn(actual.chmodSync) };+});++import * as fs from 'fs';+import { chmodSync, existsSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { ConfigService } from '@nestjs/config';+import { SqlitePermissionsBoot, tightenSqliteFilePermissions } from './sqlite-file-permissions';++const modeOf = (path: string): number => statSync(path).mode & 0o777;++describe('tightenSqliteFilePermissions', () => {+ let dir: string;+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'owa-sqlite-perm-'));+ });+ afterEach(() => {+ chmodSync(dir, 0o755); // a 0o500 test dir must still be cleanable+ rmSync(dir, { recursive: true, force: true });+ });++ it('tightens an existing database file and its WAL/journal sidecars to owner-only', () => {+ const db = join(dir, 'openwa.sqlite');+ writeFileSync(db, '', { mode: 0o644 });+ writeFileSync(`${db}-wal`, '', { mode: 0o644 });+ writeFileSync(`${db}-shm`, '', { mode: 0o644 });+ writeFileSync(`${db}-journal`, '', { mode: 0o644 });++ const tightened = tightenSqliteFilePermissions([db], () => undefined);++ expect(tightened).toEqual([db, `${db}-wal`, `${db}-shm`, `${db}-journal`]);+ for (const path of tightened) expect(modeOf(path)).toBe(0o600);+ });++ it('skips files that do not exist without touching anything', () => {+ expect(tightenSqliteFilePermissions([join(dir, 'absent.sqlite')], () => undefined)).toEqual([]);+ expect(existsSync(join(dir, 'absent.sqlite'))).toBe(false);+ });++ it('is best-effort: an untightenable file warns and does not throw', () => {+ const db = join(dir, 'main.sqlite');+ writeFileSync(db, '', { mode: 0o644 });+ (fs.chmodSync as jest.Mock).mockImplementationOnce(() => {+ throw new Error('EPERM: operation not permitted');+ });++ const warnings: string[] = [];+ expect(() => tightenSqliteFilePermissions([db], m => warnings.push(m))).not.toThrow();++ expect(warnings.length).toBe(1);+ expect(warnings[0]).toContain('main.sqlite');+ expect(warnings[0]).toContain('EPERM');+ });+});++describe('SqlitePermissionsBoot', () => {+ let dir: string;+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'owa-sqlite-boot-'));+ });+ afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+ });++ const configReturning = (values: Record<string, string>): ConfigService =>+ ({ get: (key: string, defaultValue?: string) => values[key] ?? defaultValue }) as unknown as ConfigService;++ it('tightens both bundled files when the data connection is SQLite', () => {+ const main = join(dir, 'main.sqlite');+ const data = join(dir, 'openwa.sqlite');+ writeFileSync(main, '', { mode: 0o644 });+ writeFileSync(data, '', { mode: 0o644 });+ const boot = new SqlitePermissionsBoot(+ configReturning({ 'database.database': main, 'dataDatabase.type': 'sqlite', 'dataDatabase.database': data }),+ );++ boot.onApplicationBootstrap();++ expect(modeOf(main)).toBe(0o600);+ expect(modeOf(data)).toBe(0o600);+ });++ it('skips the data file when the data connection is Postgres (no local file to tighten)', () => {+ const main = join(dir, 'main.sqlite');+ const data = join(dir, 'should-not-be-touched.sqlite');+ writeFileSync(main, '', { mode: 0o644 });+ writeFileSync(data, '', { mode: 0o644 });+ const boot = new SqlitePermissionsBoot(+ configReturning({ 'database.database': main, 'dataDatabase.type': 'postgres', 'dataDatabase.database': data }),+ );++ boot.onApplicationBootstrap();++ expect(modeOf(main)).toBe(0o600);+ expect(modeOf(data)).toBe(0o644);+ });++ it('falls back to the documented default paths when config supplies none', () => {+ const boot = new SqlitePermissionsBoot(configReturning({}));+ // Must not throw even when neither default file exists (e.g. a fresh checkout before first boot).+ expect(() => boot.onApplicationBootstrap()).not.toThrow();+ });+});diff --git a/src/database/sqlite-file-permissions.ts b/src/database/sqlite-file-permissions.tsnew file mode 100644index 000000000..19d298de3--- /dev/null+++ b/src/database/sqlite-file-permissions.ts@@ -0,0 +1,58 @@+import { chmodSync, existsSync } from 'fs';+import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';++// better-sqlite3 creates its database files with 0666 & umask (0644 under the usual 022), so the+// SQLite files end up group/world-readable while every sibling secret in data/ was tightened to+// 0600/0700. That matters because these files ARE secret stores: openwa.sqlite holds the webhook+// and plugin-instance HMAC secrets and session proxy URLs in plaintext. The container deployment is+// insulated (named volume, non-root user), but bare-metal and bind-mount hosts get world-readable+// secrets. Tighten on every boot, the same re-tighten-on-start posture the credential dirs use, so+// a file recreated by a restore or a copy also converges back.+const SIDECAR_SUFFIXES = ['-wal', '-shm', '-journal'] as const;++/**+ * chmod each database file (plus its WAL/rollback sidecars) to owner-only, best-effort: a failure is+ * logged and skipped, never allowed to fail the boot. Returns the paths actually tightened.+ */+export function tightenSqliteFilePermissions(paths: string[], warn: (message: string) => void): string[] {+ const tightened: string[] = [];+ for (const path of paths) {+ for (const candidate of [path, ...SIDECAR_SUFFIXES.map(suffix => `${path}${suffix}`)]) {+ if (!existsSync(candidate)) continue;+ try {+ chmodSync(candidate, 0o600);+ tightened.push(candidate);+ } catch (error) {+ warn(+ `Could not tighten ${candidate} to owner-only permissions: ` ++ `${error instanceof Error ? error.message : String(error)}`,+ );+ }+ }+ }+ return tightened;+}++/**+ * Applies the tightening to the two bundled SQLite databases once every DataSource has initialized.+ * The DataSources initialize eagerly inside their provider factories (before any lifecycle hook+ * runs), and Nest runs every onModuleInit before any onApplicationBootstrap, so both files exist by+ * the time this hook fires. The main connection is always SQLite; the data connection mirrors the+ * app.module factory's own branch (everything except postgres is the sqlite path; env.validation+ * confines DATABASE_TYPE to those two).+ */+@Injectable()+export class SqlitePermissionsBoot implements OnApplicationBootstrap {+ private readonly logger = new Logger('SqlitePermissions');++ constructor(private readonly config: ConfigService) {}++ onApplicationBootstrap(): void {+ const paths: string[] = [this.config.get<string>('database.database', './data/main.sqlite')];+ if (this.config.get<string>('dataDatabase.type', 'sqlite') !== 'postgres') {+ paths.push(this.config.get<string>('dataDatabase.database', './data/openwa.sqlite'));+ }+ tightenSqliteFilePermissions(paths, message => this.logger.warn(message));+ }+}