Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

release: v0.2.2 — security hardening, reliability & metrics (#243)

Yudhi Armyndharis65022bc71e35
diff --git a/.env.example b/.env.example
index d90ca224b..5bdd00759 100644
--- a/.env.example
+++ b/.env.example
@@ -55,6 +55,13 @@ ENGINE_TYPE=whatsapp-web.js
SESSION_DATA_PATH=./data/sessions
PUPPETEER_HEADLESS=true
PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu
+# Path to a system Chromium/Chrome binary. Leave unset to use the bundled Puppeteer browser.
+# Required in the Docker image and on hosts without a bundled browser (e.g. Alpine/ARM).
+# PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
+
+# Observability — Prometheus scrape endpoint at GET /api/metrics.
+# Disabled by default; set a token to enable. Scrapers must send `Authorization: Bearer <token>`.
+# METRICS_TOKEN=change-me-to-a-long-random-string
# =============================================================================
# DATABASE
@@ -68,9 +75,15 @@ DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=openwa
DATABASE_USERNAME=openwa
-DATABASE_PASSWORD=your-secure-password
-DATABASE_SYNCHRONIZE=false # WARNING: Set false in production!
+# MUST set a strong, unique value before using Postgres — no default is shipped (M16).
+# Production refuses to start if this is empty or a known placeholder when DATABASE_TYPE=postgres.
+DATABASE_PASSWORD=
+DATABASE_SYNCHRONIZE=false # WARNING: Set false in production! (data DB)
DATABASE_LOGGING=false
+# Auth/audit (main) DB schema management. Default ON (zero-config first boot).
+# Set to "false" to manage the api_keys/audit_logs schema via the bundled main-owned
+# migration instead of synchronize (migrationsRun creates them at boot). Finding H12/M18.
+MAIN_DATABASE_SYNCHRONIZE=true
DATABASE_SSL=false # Set true for managed Postgres (Supabase, Heroku, Render, Railway)
DATABASE_SSL_REJECT_UNAUTHORIZED=true # Set false to allow self-signed certs (only when DATABASE_SSL=true)
@@ -99,8 +112,10 @@ STORAGE_LOCAL_PATH=./data/media
S3_ENDPOINT=http://localhost:9000
S3_BUCKET=openwa
S3_REGION=us-east-1
-S3_ACCESS_KEY=minioadmin
-S3_SECRET_KEY=minioadmin
+# MUST set strong, unique values before using S3/MinIO — no defaults shipped (M16).
+# Production refuses to start if these are empty/placeholder when STORAGE_TYPE=s3.
+S3_ACCESS_KEY=
+S3_SECRET_KEY=
# =============================================================================
# WEBHOOK
@@ -108,10 +123,19 @@ S3_SECRET_KEY=minioadmin
WEBHOOK_TIMEOUT=10000 # Timeout in milliseconds
WEBHOOK_MAX_RETRIES=3 # Number of retry attempts
WEBHOOK_RETRY_DELAY=5000 # Delay between retries in ms
-# Block outbound webhooks to internal/reserved addresses (SSRF protection).
-# Off by default; enable on internet-exposed deployments. When on, webhook URLs
-# resolving to loopback/private/link-local/metadata ranges are refused.
-WEBHOOK_SSRF_PROTECT=false
+# Block outbound WEBHOOK deliveries to internal/reserved addresses (SSRF
+# protection). ON by default; set to "false" only on closed networks. When on,
+# webhook URLs resolving to loopback/private/link-local/metadata ranges are
+# refused (at registration AND delivery) and redirects are not followed.
+# (Server-side media-by-URL fetches are ALWAYS SSRF-guarded, regardless of this flag.)
+WEBHOOK_SSRF_PROTECT=true
+# Comma-separated hosts/IPs allowed to bypass SSRF protection for BOTH webhooks
+# and media — escape-hatch for trusted internal targets (e.g. a localhost media
+# store or a sidecar webhook receiver).
+# SSRF_ALLOWED_HOSTS=localhost,minio
+# Server-side media-by-URL download limits:
+# MEDIA_DOWNLOAD_MAX_BYTES=52428800 # cap a remote media download (default 50 MiB)
+# MEDIA_DOWNLOAD_TIMEOUT_MS=30000 # abort a slow media download (default 30s)
# =============================================================================
# RATE LIMITING
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 824d8864e..0f6856b07 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -53,6 +53,9 @@ jobs:
- name: Run unit tests
run: npm test -- --coverage
+ - name: Run e2e smoke tests
+ run: npm run test:e2e
+
- name: Upload coverage
uses: codecov/codecov-action@v6
if: always()
@@ -79,6 +82,9 @@ jobs:
- name: Run ESLint
run: cd dashboard && npm run lint
+ - name: Check i18n parity
+ run: cd dashboard && npm run i18n:check
+
- name: Build dashboard
run: cd dashboard && npm run build
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 28847dfeb..6f3209c1b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,96 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.2.2] - 2026-06-15
+
+A security-hardening and reliability release. It tightens defaults (SSRF protection on,
+datastore secrets required, least-privilege webhook reads), closes a server-side
+request-forgery vector on media fetches and webhook deliveries, adds an optional Prometheus
+metrics endpoint, fixes headless Chromium startup in the non-root Docker image, and refreshes
+dependencies. **Please read the Upgrade notes below before upgrading from 0.2.1** — several
+defaults changed.
+
+### Added
+
+- **Prometheus metrics** at `GET /api/metrics` (session/message gauges, process stats).
+ Disabled by default; set `METRICS_TOKEN` and scrape with `Authorization: Bearer <token>`.
+
+### Security
+
+- **Webhook secrets no longer leak:** the HMAC `secret` and custom `headers` are never
+ returned from any webhook API response (responses are mapped through a scoped DTO).
+- **Media-fetch SSRF closed:** server-side `MessageMedia.fromUrl` now runs an SSRF host
+ guard + byte cap + timeout before fetching a caller-supplied URL.
+- **Redirects are not followed** on webhook deliveries or media fetches, so a `302` to an
+ internal host can't bypass the SSRF guard.
+- **Webhook SSRF protection is ON by default** and validated at registration.
+- **Docker hardening:** the socket-proxy is isolated on an `internal: true` network reachable
+ only by the API (not the dashboard); the API container runs with `cap_drop: [ALL]` (+ a
+ minimal re-add), `no-new-privileges`, a `read_only` rootfs + tmpfs, and pid/mem limits.
+- **Plugin loader** rejects a manifest `main` that escapes the plugin directory before
+ `require()`.
+- **WebSocket:** the API key is re-validated on every subscribe (a revoked key is
+ disconnected), is no longer sent in the handshake URL, and CORS uses the configured
+ allowlist instead of `*`.
+- **Production boot guard:** the app refuses to start in production with empty/placeholder
+ secrets, and the committed default datastore credentials were removed.
+- **Rate limiting** now keys on the resolved client IP instead of the proxy IP.
+
+### Changed
+
+- Webhook read routes now require an `OPERATOR`+ key.
+- Webhook `events[]` are validated against the known event types (plus `*`).
+- The six inline-body message endpoints (+ label/channel) now validate their input.
+- The `main` auth/audit DB `synchronize` is config-driven (`MAIN_DATABASE_SYNCHRONIZE`,
+ default on) with a bundled migration for `api_keys`/`audit_logs`.
+- The readiness probe (`/api/health/ready`) now performs real database checks and returns
+ 503 when a dependency is down or the app is draining; the container `HEALTHCHECK` points
+ at it.
+
+### Fixed
+
+- Message ack status UPDATE is scoped by `sessionId` (no cross-session corruption) and
+ backed by a composite index.
+- `getMessages` sanitizes `limit`/`offset` so `?limit=abc` no longer reaches the query.
+- The Postgres database name now honors `DATABASE_NAME` consistently between the runtime and
+ the migration CLI.
+- Backup/restore scripts (`scripts/backup.sh`/`restore.sh`) capture **both** databases
+ (incl. the auth DB `main.sqlite`) + sessions, so a restore preserves API keys.
+- Boot-time environment validation rejects an unknown `DATABASE_TYPE` and missing Postgres
+ credentials instead of silently coercing.
+- Message-event idempotency keys are session-scoped.
+- Response-envelope documentation corrected to the real raw-payload shape; the unused
+ interceptor/filter were removed; horizontal-scaling docs marked single-instance.
+- **Headless Chromium now starts in the Docker image as the non-root `openwa` user** — `HOME`
+ points at a writable directory, so the engine no longer dies with
+ `chrome_crashpad_handler: --database is required` on a fresh container. (closes #242)
+- Marking a 1:1 chat as read now accepts the newer `@lid` (privacy Linked ID) JID, not just
+ `@c.us`. Thanks @suraj7974 (#241).
+- Allowlisted IPv6 literals in `SSRF_ALLOWED_HOSTS` now match whether or not the entry is
+ bracketed (e.g. `[::1]` and `::1`).
+- The dashboard returns cleanly to the login screen on a `401` instead of flashing a transient
+ error toast.
+- A webhook `secret` cleared via update is normalized to "no secret" (consistent with create)
+ and is length-capped.
+
+### Dependencies
+
+- `@bull-board/{api,nestjs,express}` 7.2.1 → 8.0.0 and `@types/archiver` 7 → 8 (aligned with the
+ archiver v8 runtime), plus a batch of minor/patch bumps (NestJS 11.1.27, BullMQ 5.78.1, AWS SDK,
+ ESLint 10.5, Prettier 3.8, typescript-eslint 8.61, and a dashboard dev-tool bump).
+
+### Upgrade notes (behavior changes)
+
+- **Webhook reads now require `OPERATOR`+** — a `VIEWER` key reading webhooks gets `403`.
+- **SSRF protection defaults ON** — deployments that deliver webhooks or fetch media from
+ internal hosts must set `SSRF_ALLOWED_HOSTS` (comma-separated) or `WEBHOOK_SSRF_PROTECT=false`.
+- **Datastore secrets are now required** — there is no `openwa`/`minioadmin` default;
+ `docker compose --profile postgres/minio up` needs `DATABASE_PASSWORD` / `S3_*` set, and
+ production refuses to boot with placeholder secrets.
+- **Bull Board `?apiKey=` removed** — authenticate via `X-API-Key`/`Authorization: Bearer`.
+- New env knobs: `SSRF_ALLOWED_HOSTS`, `MEDIA_DOWNLOAD_MAX_BYTES`, `MEDIA_DOWNLOAD_TIMEOUT_MS`,
+ `MAIN_DATABASE_SYNCHRONIZE`, `SHUTDOWN_DELAY_MS`, `OPENWA_MEM_LIMIT`, `METRICS_TOKEN`.
+
## [0.2.1] - 2026-06-15
A patch release.
@@ -285,7 +375,7 @@ bugs. Backward compatible except for the two upgrade notes below.
- **PostgreSQL boot crash on `main` connection**: `AuditLog.metadata` now uses `simple-json` instead of
the dynamic `jsonColumnType()`. The `main` connection is always SQLite, so it must not switch to
`jsonb` when `DATABASE_TYPE=postgres`. Fixes `DataTypeNotSupportedError: Data type "jsonb" in
- "AuditLog.metadata" is not supported by "sqlite" database`.
+"AuditLog.metadata" is not supported by "sqlite" database`.
- **Operator env vars ignored**: `data/.env.generated` no longer overrides `process.env` or project
`.env`. Loading order is now `process env > .env > data/.env.generated`, so values from Docker /
shell / systemd take precedence over Dashboard-saved config.
diff --git a/Dockerfile b/Dockerfile
index 29c90deef..16bf7c236 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -75,6 +75,13 @@ COPY --from=builder /app/dist ./dist
RUN mkdir -p ./data/sessions ./data/media && \
chown -R openwa:openwa /app
+# The non-root openwa user has no home of its own (created with `useradd -r`, no -m), so $HOME
+# defaults to "/", which is not writable. Newer Chromium spawns chrome_crashpad_handler, which
+# needs a writable HOME-derived crash-dump dir or the browser fails to launch ("--database is
+# required"). Point HOME at the openwa-owned data dir so the engine starts under `docker run`,
+# Kubernetes, etc. (compose overrides this with HOME=/tmp on its read-only rootfs). See #242.
+ENV HOME=/app/data
+
# Copy entrypoint: runs as root to fix named-volume ownership, then drops to openwa via gosu
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
@@ -84,7 +91,7 @@ EXPOSE 2785
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
- CMD curl -f http://localhost:2785/api/health || exit 1
+ CMD curl -f http://localhost:2785/api/health/ready || exit 1
# dumb-init is PID 1 and handles signal forwarding.
# It execs docker-entrypoint.sh (as root), which fixes volume ownership and
diff --git a/README.md b/README.md
index 628afcb22..8dde07176 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,8 @@
</p>
<p align="center">
- <img src="https://img.shields.io/badge/version-0.2.1-blue.svg" alt="Version"/>
+ <a href="https://github.com/rmyndharis/OpenWA/actions/workflows/ci.yml"><img src="https://github.com/rmyndharis/OpenWA/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI"/></a>
+ <img src="https://img.shields.io/badge/version-0.2.2-blue.svg" alt="Version"/>
<img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License"/>
<img src="https://img.shields.io/badge/node-22_LTS-brightgreen.svg" alt="Node"/>
<img src="https://img.shields.io/badge/NestJS-11.x-red.svg" alt="NestJS"/>
diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json
index c0247b86a..0af2887d4 100644
--- a/dashboard/package-lock.json
+++ b/dashboard/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "dashboard",
- "version": "0.2.1",
+ "version": "0.2.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dashboard",
- "version": "0.2.1",
+ "version": "0.2.2",
"dependencies": {
"@tanstack/react-query": "^5.101.0",
"@tanstack/react-table": "^8.21.3",
@@ -27,7 +27,7 @@
"@vitejs/plugin-react": "^6.0.0",
"eslint": "^10.5.0",
"eslint-plugin-react-hooks": "^7.1.1",
- "eslint-plugin-react-refresh": "^0.5.1",
+ "eslint-plugin-react-refresh": "^0.5.3",
"globals": "^17.6.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.61.0",
@@ -1575,9 +1575,9 @@
}
},
"node_modules/eslint-plugin-react-refresh": {
- "version": "0.5.2",
- "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.2.tgz",
- "integrity": "sha512-hmgTH57GfzoTFjVN0yBwTggnsVUF2tcqi7RJZHqi9lIezSs4eFyAMktA68YD4r5kNw1mxyY4dmkyoFDb3FIqrA==",
+ "version": "0.5.3",
+ "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.3.tgz",
+ "integrity": "sha512-5EMmLCV98Pi4o/f/3DP/v/tNqLHMIc9I8LKClNDWhZ9JTho89/kQcitCXQBMG7sAfVRK0Ie3T2EDOzp1YXYiVA==",
"dev": true,
"license": "MIT",
"peerDependencies": {
diff --git a/dashboard/package.json b/dashboard/package.json
index 3ced3e810..3c62bbb2f 100644
--- a/dashboard/package.json
+++ b/dashboard/package.json
@@ -1,13 +1,14 @@
{
"name": "dashboard",
"private": true,
- "version": "0.2.1",
+ "version": "0.2.2",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "i18n:check": "node scripts/check-i18n-parity.mjs"
},
"dependencies": {
"@tanstack/react-query": "^5.101.0",
@@ -29,7 +30,7 @@
"@vitejs/plugin-react": "^6.0.0",
"eslint": "^10.5.0",
"eslint-plugin-react-hooks": "^7.1.1",
- "eslint-plugin-react-refresh": "^0.5.1",
+ "eslint-plugin-react-refresh": "^0.5.3",
"globals": "^17.6.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.61.0",
diff --git a/dashboard/scripts/check-i18n-parity.mjs b/dashboard/scripts/check-i18n-parity.mjs
new file mode 100644
index 000000000..e9a459327
--- /dev/null
+++ b/dashboard/scripts/check-i18n-parity.mjs
@@ -0,0 +1,70 @@
+#!/usr/bin/env node
+/**
+ * i18n locale parity check.
+ *
+ * Loads the reference locale (en.json) and every other locale in
+ * src/i18n/locales, then asserts that every nested key path present in
+ * en.json also exists in each locale. Prints the missing key paths per
+ * locale and exits non-zero if any are missing.
+ *
+ * Wire into CI with: `npm run i18n:check`
+ */
+import { readdirSync, readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const LOCALES_DIR = join(__dirname, '..', 'src', 'i18n', 'locales');
+const REFERENCE = 'en.json';
+
+/** Flatten a nested object into a Set of dot-separated key paths (leaf keys only). */
+function flatten(obj, prefix = '', out = new Set()) {
+ for (const [key, value] of Object.entries(obj)) {
+ const path = prefix ? `${prefix}.${key}` : key;
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
+ flatten(value, path, out);
+ } else {
+ out.add(path);
+ }
+ }
+ return out;
+}
+
+function load(file) {
+ return JSON.parse(readFileSync(join(LOCALES_DIR, file), 'utf8'));
+}
+
+const reference = flatten(load(REFERENCE));
+const localeFiles = readdirSync(LOCALES_DIR)
+ .filter((f) => f.endsWith('.json') && f !== REFERENCE)
+ .sort();
+
+let hasErrors = false;
+
+for (const file of localeFiles) {
+ const keys = flatten(load(file));
+ const missing = [...reference].filter((k) => !keys.has(k)).sort();
+ const extra = [...keys].filter((k) => !reference.has(k)).sort();
+
+ if (missing.length > 0) {
+ hasErrors = true;
+ console.error(`\n[FAIL] ${file}: missing ${missing.length} key(s) present in ${REFERENCE}:`);
+ for (const k of missing) console.error(` - ${k}`);
+ } else {
+ console.log(`[OK] ${file}: all ${reference.size} keys present`);
+ }
+
+ if (extra.length > 0) {
+ // Extra keys are a warning, not a hard failure: they do not break i18n parity
+ // against the reference, but they signal drift worth cleaning up.
+ console.warn(`[WARN] ${file}: ${extra.length} extra key(s) not in ${REFERENCE}:`);
+ for (const k of extra) console.warn(` ~ ${k}`);
+ }
+}
+
+if (hasErrors) {
+ console.error('\ni18n parity check FAILED.');
+ process.exit(1);
+}
+
+console.log('\ni18n parity check passed.');
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index f4cb7fd25..4e0a1a77e 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -6,6 +6,7 @@ import { Layout } from './components/Layout';
import { ToastProvider } from './components/Toast';
import { RoleProvider, useRole, type UserRole } from './hooks/useRole';
import { ErrorBoundary } from './components/ErrorBoundary';
+import { API_BASE_URL } from './services/api';
import './App.css';
const Login = lazy(() => import('./pages/Login').then(m => ({ default: m.Login })));
@@ -42,7 +43,7 @@ function AppContent() {
// Fetch the role from API
try {
- const response = await fetch('/api/auth/validate', {
+ const response = await fetch(`${API_BASE_URL}/auth/validate`, {
method: 'POST',
headers: { 'X-API-Key': key },
});
@@ -69,7 +70,7 @@ function AppContent() {
useEffect(() => {
if (!savedKey) return;
- fetch('/api/auth/validate', {
+ fetch(`${API_BASE_URL}/auth/validate`, {
method: 'POST',
headers: { 'X-API-Key': savedKey },
})
diff --git a/dashboard/src/components/Layout.tsx b/dashboard/src/components/Layout.tsx
index 90de18a94..7eb396b4f 100644
--- a/dashboard/src/components/Layout.tsx
+++ b/dashboard/src/components/Layout.tsx
@@ -38,7 +38,8 @@ const allNavItems = [
{ to: '/webhooks', icon: Webhook, key: 'webhooks' as const, adminOnly: false },
{ to: '/api-keys', icon: Key, key: 'apiKeys' as const, adminOnly: true },
{ to: '/message-tester', icon: Send, key: 'messageTester' as const, adminOnly: false },
- { to: '/infrastructure', icon: Server, key: 'infrastructure' as const, adminOnly: false },
+ // Backend /infra/* is ADMIN-only; hide the nav item from non-admins (UX + defense-in-depth).
+ { to: '/infrastructure', icon: Server, key: 'infrastructure' as const, adminOnly: true },
{ to: '/plugins', icon: Puzzle, key: 'plugins' as const, adminOnly: true },
{ to: '/logs', icon: FileText, key: 'logs' as const, adminOnly: false },
];
diff --git a/dashboard/src/hooks/useWebSocket.ts b/dashboard/src/hooks/useWebSocket.ts
index 387d16ebf..e3f9712d4 100644
--- a/dashboard/src/hooks/useWebSocket.ts
+++ b/dashboard/src/hooks/useWebSocket.ts
@@ -76,6 +76,9 @@ const SOCKET_URL = import.meta.env.VITE_WS_URL || window.location.origin;
export function useWebSocket(events: WebSocketEvents = {}) {
const socketRef = useRef<Socket | null>(null);
const [isConnected, setIsConnected] = useState(false);
+ // True once Socket.IO exhausts its reconnection attempts and permanently gives up — lets the
+ // UI show a "connection lost" indicator + a manual retry instead of silently going stale.
+ const [connectionFailed, setConnectionFailed] = useState(false);
const connect = useCallback(() => {
if (socketRef.current?.connected) return;
@@ -93,19 +96,19 @@ export function useWebSocket(events: WebSocketEvents = {}) {
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
+ // Send the key via `auth` (and a header for proxies). NOT via `query` — a key in the
+ // handshake URL leaks into access logs / Referer. The gateway reads auth first.
auth: {
apiKey,
},
extraHeaders: {
'X-API-Key': apiKey,
},
- query: {
- apiKey,
- },
});
socketRef.current.on('connect', () => {
setIsConnected(true);
+ setConnectionFailed(false);
});
socketRef.current.on('disconnect', () => {
@@ -115,8 +118,24 @@ export function useWebSocket(events: WebSocketEvents = {}) {
socketRef.current.on('connect_error', error => {
console.warn('[WebSocket] Connection error:', error.message);
});
+
+ // `reconnect_failed` is emitted on the Manager once all reconnectionAttempts are exhausted.
+ socketRef.current.io.on('reconnect_failed', () => {
+ console.warn('[WebSocket] Reconnection failed after max attempts');
+ setConnectionFailed(true);
+ });
}, []);
+ // Manual retry after the socket permanently gave up: tear down the dead socket and reconnect.
+ const reconnect = useCallback(() => {
+ setConnectionFailed(false);
+ if (socketRef.current) {
+ socketRef.current.disconnect();
+ socketRef.current = null;
+ }
+ connect();
+ }, [connect]);
+
const subscribe = useCallback((sessionId: string, eventsList: string[]) => {
if (socketRef.current?.connected) {
socketRef.current.emit('message', {
@@ -214,5 +233,5 @@ export function useWebSocket(events: WebSocketEvents = {}) {
};
}, [events]);
- return { isConnected, subscribe, unsubscribe };
+ return { isConnected, connectionFailed, reconnect, subscribe, unsubscribe };
}
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 81b5b72a2..8b81a9bb8 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -37,7 +37,6 @@
"language": "اللغة",
"english": "English",
"hebrew": "עברית",
- "arabic": "العربية",
"back": "رجوع",
"next": "التالي",
"previous": "السابق",
@@ -57,6 +56,7 @@
"nav": {
"dashboard": "لوحة التحكم",
"sessions": "الجلسات",
+ "chats": "المحادثات",
"webhooks": "الويب هوك",
"apiKeys": "مفاتيح API",
"messageTester": "اختبار الرسائل",
@@ -64,6 +64,48 @@
"plugins": "الإضافات",
"logs": "السجلات"
},
+ "chats": {
+ "subtitle": "أرسل ورد على رسائل واتساب في الوقت الفعلي",
+ "noSessionsTitle": "لا توجد جلسات متصلة",
+ "noSessionsDesc": "يرجى أولاً توصيل جلسة واتساب من قائمة <1>الجلسات</1> لاستخدام ميزة المحادثة.",
+ "sessionLabel": "جلسة واتساب",
+ "noPhone": "لا يوجد هاتف",
+ "searchPlaceholder": "البحث في المحادثات...",
+ "loadingChats": "جارٍ تحميل المحادثات...",
+ "empty": "لا توجد محادثات",
+ "noMessageYet": "لا توجد رسائل بعد",
+ "loadingMessages": "جارٍ تحميل الرسائل...",
+ "noMessagesInChat": "لا توجد رسائل بعد. أرسل الرسالة الأولى للبدء!",
+ "downloadDocument": "تنزيل المستند",
+ "actions": {
+ "reply": "رد",
+ "react": "تفاعل",
+ "delete": "حذف الرسالة"
+ },
+ "replyingTo": "الرد على {{name}}",
+ "you": "أنت",
+ "youPrefix": "أنت: ",
+ "yesterday": "أمس",
+ "attachTitle": "إرسال ملف / صورة",
+ "emojiTitle": "اختيار إيموجي",
+ "captionPlaceholder": "أضف تعليقاً...",
+ "messagePlaceholder": "اكتب رسالة...",
+ "noPermission": "ليس لديك إذن لإرسال الرسائل",
+ "send": "إرسال",
+ "placeholderTitle": "ابدأ المراسلة",
+ "placeholderDesc": "اختر محادثة نشطة من الشريط الجانبي الأيسر لبدء قراءة وإرسال رسائل واتساب.",
+ "deleteConfirm": "حذف هذه الرسالة للجميع؟",
+ "messageDeleted": "🚫 تم حذف هذه الرسالة",
+ "errors": {
+ "loadSessions": "فشل تحميل الجلسات",
+ "loadChats": "فشل تحميل المحادثات",
+ "loadMessages": "فشل تحميل الرسائل",
+ "markRead": "فشل تعليم المحادثة كمقروءة",
+ "send": "فشل إرسال الرسالة",
+ "react": "فشل التفاعل مع الرسالة",
+ "delete": "فشل حذف الرسالة"
+ }
+ },
"errorBoundary": {
"title": "حدث خطأ ما",
"description": "واجهت لوحة التحكم خطأً غير متوقع.",
@@ -187,12 +229,15 @@
"readyTitle": "الجلسة جاهزة",
"readyDesc": "جلسة واتساب متصلة الآن",
"disconnectedTitle": "انقطع اتصال الجلسة",
- "disconnectedDesc": "انقطع اتصال جلسة واتساب"
+ "disconnectedDesc": "انقطع اتصال جلسة واتساب",
+ "failedTitle": "فشلت الجلسة",
+ "failedDesc": "فشل بدء جلسة واتساب. افتح الجلسة لمعرفة السبب."
},
"card": {
"phone": "الهاتف",
"sessionId": "معرّف الجلسة",
- "lastActive": "آخر نشاط"
+ "lastActive": "آخر نشاط",
+ "error": "خطأ"
}
},
"webhooks": {
@@ -476,7 +521,6 @@
"engineCard": "محرك واتساب النشط",
"running": "يعمل",
"supportedFeatures": "الميزات المدعومة:",
- "more": "+{{count}} أخرى",
"builtIn": "مدمج",
"noDescription": "لا يوجد وصف متاح",
"required": "مطلوب",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 7ad3a63c6..873ec8396 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -37,8 +37,6 @@
"language": "Langue",
"english": "English",
"hebrew": "עברית",
- "telugu": "తెలుగు",
- "french": "Français",
"back": "Retour",
"next": "Suivant",
"previous": "Précédent",
@@ -58,6 +56,7 @@
"nav": {
"dashboard": "Tableau de bord",
"sessions": "Sessions",
+ "chats": "Discussions",
"webhooks": "Webhooks",
"apiKeys": "Clés API",
"messageTester": "Testeur de messages",
@@ -65,6 +64,48 @@
"plugins": "Plugins",
"logs": "Journaux"
},
+ "chats": {
+ "subtitle": "Envoyez et répondez aux messages WhatsApp en temps réel",
+ "noSessionsTitle": "Aucune session connectée",
+ "noSessionsDesc": "Veuillez d'abord connecter une session WhatsApp depuis le menu <1>Sessions</1> pour utiliser la fonction de discussion.",
+ "sessionLabel": "Session WhatsApp",
+ "noPhone": "Aucun téléphone",
+ "searchPlaceholder": "Rechercher des discussions...",
+ "loadingChats": "Chargement des discussions...",
+ "empty": "Aucune discussion",
+ "noMessageYet": "Aucun message pour le moment",
+ "loadingMessages": "Chargement des messages...",
+ "noMessagesInChat": "Aucun message pour le moment. Envoyez le premier message pour commencer !",
+ "downloadDocument": "Télécharger le document",
+ "actions": {
+ "reply": "Répondre",
+ "react": "Réagir",
+ "delete": "Supprimer le message"
+ },
+ "replyingTo": "Réponse à {{name}}",
+ "you": "Vous",
+ "youPrefix": "Vous : ",
+ "yesterday": "Hier",
+ "attachTitle": "Envoyer un fichier / une image",
+ "emojiTitle": "Choisir un emoji",
+ "captionPlaceholder": "Ajouter une légende...",
+ "messagePlaceholder": "Tapez un message...",
+ "noPermission": "Vous n'avez pas la permission d'envoyer des messages",
+ "send": "Envoyer",
+ "placeholderTitle": "Commencer à discuter",
+ "placeholderDesc": "Sélectionnez une discussion active dans la barre latérale gauche pour commencer à lire et envoyer des messages WhatsApp.",
+ "deleteConfirm": "Supprimer ce message pour tout le monde ?",
+ "messageDeleted": "🚫 Ce message a été supprimé",
+ "errors": {
+ "loadSessions": "Échec du chargement des sessions",
+ "loadChats": "Échec du chargement des discussions",
+ "loadMessages": "Échec du chargement des messages",
+ "markRead": "Échec du marquage de la discussion comme lue",
+ "send": "Échec de l'envoi du message",
+ "react": "Échec de la réaction au message",
+ "delete": "Échec de la suppression du message"
+ }
+ },
"errorBoundary": {
"title": "Une erreur est survenue",
"description": "Le tableau de bord a rencontré une erreur inattendue.",
@@ -188,12 +229,15 @@
"readyTitle": "Session prête",
"readyDesc": "La session WhatsApp est maintenant connectée",
"disconnectedTitle": "Session déconnectée",
- "disconnectedDesc": "La session WhatsApp a été déconnectée"
+ "disconnectedDesc": "La session WhatsApp a été déconnectée",
+ "failedTitle": "Échec de la session",
+ "failedDesc": "Le démarrage de la session WhatsApp a échoué. Ouvrez la session pour en voir la raison."
},
"card": {
"phone": "Téléphone",
"sessionId": "ID de session",
- "lastActive": "Dernière activité"
+ "lastActive": "Dernière activité",
+ "error": "Erreur"
}
},
"webhooks": {
@@ -403,6 +447,8 @@
"poolSize": "Taille du pool",
"ssl": "Connexion SSL",
"sslDesc": "Activer TLS/SSL pour des connexions sécurisées à la base de données",
+ "sslRejectUnauthorized": "Vérifier le certificat SSL",
+ "sslRejectUnauthorizedDesc": "Rejeter les certificats auto-signés ou non valides. Désactivez cette option pour les bases Postgres gérées avec des certificats auto-signés (Supabase, Heroku, Render, Railway).",
"migrationsTitle": "Migrations de base de données",
"migrationsStatus": "Le schéma est auto-synchronisé avec TypeORM",
"migrationsHint": "Les migrations sont gérées automatiquement. Utilisez la CLI pour les migrations manuelles."
@@ -475,7 +521,6 @@
"engineCard": "Moteur WhatsApp actif",
"running": "En cours d'exécution",
"supportedFeatures": "Fonctionnalités supportées :",
- "more": "+{{count}} de plus",
"builtIn": "Intégré",
"noDescription": "Aucune description disponible",
"required": "Requis",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index b17b2a3a2..c93e33c89 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -37,7 +37,6 @@
"language": "Lingua",
"english": "Inglese",
"hebrew": "עברית",
- "italian": "Italiano",
"back": "Indietro",
"next": "Avanti",
"previous": "Precedente",
@@ -57,6 +56,7 @@
"nav": {
"dashboard": "Dashboard",
"sessions": "Sessioni",
+ "chats": "Chat",
"webhooks": "Webhook",
"apiKeys": "Chiavi API",
"messageTester": "Tester Messaggi",
@@ -64,6 +64,48 @@
"plugins": "Plugin",
"logs": "Log"
},
+ "chats": {
+ "subtitle": "Invia e rispondi ai messaggi WhatsApp in tempo reale",
+ "noSessionsTitle": "Nessuna sessione connessa",
+ "noSessionsDesc": "Per utilizzare la funzione chat, connetti prima una sessione WhatsApp dal menu <1>Sessioni</1>.",
+ "sessionLabel": "Sessione WhatsApp",
+ "noPhone": "Nessun telefono",
+ "searchPlaceholder": "Cerca chat...",
+ "loadingChats": "Caricamento chat...",
+ "empty": "Nessuna chat",
+ "noMessageYet": "Ancora nessun messaggio",
+ "loadingMessages": "Caricamento messaggi...",
+ "noMessagesInChat": "Ancora nessun messaggio. Invia il primo messaggio per iniziare!",
+ "downloadDocument": "Scarica documento",
+ "actions": {
+ "reply": "Rispondi",
+ "react": "Reagisci",
+ "delete": "Elimina messaggio"
+ },
+ "replyingTo": "Risposta a {{name}}",
+ "you": "Tu",
+ "youPrefix": "Tu: ",
+ "yesterday": "Ieri",
+ "attachTitle": "Invia file / immagine",
+ "emojiTitle": "Scegli emoji",
+ "captionPlaceholder": "Aggiungi una didascalia...",
+ "messagePlaceholder": "Scrivi un messaggio...",
+ "noPermission": "Non hai il permesso di inviare messaggi",
+ "send": "Invia",
+ "placeholderTitle": "Inizia a messaggiare",
+ "placeholderDesc": "Seleziona una chat attiva dalla barra laterale a sinistra per iniziare a leggere e inviare messaggi WhatsApp.",
+ "deleteConfirm": "Eliminare questo messaggio per tutti?",
+ "messageDeleted": "🚫 Questo messaggio è stato eliminato",
+ "errors": {
+ "loadSessions": "Impossibile caricare le sessioni",
+ "loadChats": "Impossibile caricare le chat",
+ "loadMessages": "Impossibile caricare i messaggi",
+ "markRead": "Impossibile contrassegnare la chat come letta",
+ "send": "Impossibile inviare il messaggio",
+ "react": "Impossibile reagire al messaggio",
+ "delete": "Impossibile eliminare il messaggio"
+ }
+ },
"errorBoundary": {
"title": "Qualcosa è andato storto",
"description": "La dashboard ha riscontrato un errore imprevisto.",
@@ -187,12 +229,15 @@
"readyTitle": "Sessione Pronta",
"readyDesc": "La sessione WhatsApp è ora connessa",
"disconnectedTitle": "Sessione Disconnessa",
- "disconnectedDesc": "La sessione WhatsApp è stata disconnessa"
+ "disconnectedDesc": "La sessione WhatsApp è stata disconnessa",
+ "failedTitle": "Sessione Fallita",
+ "failedDesc": "Avvio della sessione WhatsApp non riuscito. Apri la sessione per vedere il motivo."
},
"card": {
"phone": "Telefono",
"sessionId": "ID Sessione",
- "lastActive": "Ultima Attività"
+ "lastActive": "Ultima Attività",
+ "error": "Errore"
}
},
"webhooks": {
@@ -476,7 +521,6 @@
"engineCard": "Motore WhatsApp Attivo",
"running": "In esecuzione",
"supportedFeatures": "Funzionalità Supportate:",
- "more": "+altri {{count}}",
"builtIn": "Integrato",
"noDescription": "Nessuna descrizione disponibile",
"required": "Richiesto",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 47835e91d..458b32ab6 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -37,8 +37,6 @@
"language": "భాష",
"english": "English",
"hebrew": "עברית",
- "telugu": "తెలుగు",
- "french": "Français",
"back": "వెనుకకు",
"next": "తరువాత",
"previous": "మునుపటి",
@@ -58,6 +56,7 @@
"nav": {
"dashboard": "డ్యాష్‌బోర్డ్",
"sessions": "సెషన్స్",
+ "chats": "చాట్‌లు",
"webhooks": "వెబ్‌హుక్స్",
"apiKeys": "API కీలు",
"messageTester": "మెసేజ్ టెస్టర్",
@@ -65,6 +64,48 @@
"plugins": "ప్లగిన్స్",
"logs": "లాగ్స్"
},
+ "chats": {
+ "subtitle": "వాట్సాప్ సందేశాలను నిజ-సమయంలో పంపండి మరియు ప్రత్యుత్తరం ఇవ్వండి",
+ "noSessionsTitle": "కనెక్ట్ అయిన సెషన్లు లేవు",
+ "noSessionsDesc": "చాట్ ఫీచర్‌ను ఉపయోగించడానికి దయచేసి ముందుగా <1>సెషన్స్</1> మెను నుండి ఒక వాట్సాప్ సెషన్‌ను కనెక్ట్ చేయండి.",
+ "sessionLabel": "వాట్సాప్ సెషన్",
+ "noPhone": "ఫోన్ లేదు",
+ "searchPlaceholder": "చాట్‌ల కోసం వెతకండి...",
+ "loadingChats": "చాట్‌లను లోడ్ చేస్తోంది...",
+ "empty": "చాట్‌లు లేవు",
+ "noMessageYet": "ఇంకా సందేశాలు లేవు",
+ "loadingMessages": "సందేశాలను లోడ్ చేస్తోంది...",
+ "noMessagesInChat": "ఇంకా సందేశాలు లేవు. ప్రారంభించడానికి మొదటి సందేశాన్ని పంపండి!",
+ "downloadDocument": "డాక్యుమెంట్‌ను డౌన్‌లోడ్ చేయి",
+ "actions": {
+ "reply": "ప్రత్యుత్తరం",
+ "react": "ప్రతిస్పందించు",
+ "delete": "సందేశాన్ని తొలగించు"
+ },
+ "replyingTo": "{{name}} కు ప్రత్యుత్తరం ఇస్తోంది",
+ "you": "మీరు",
+ "youPrefix": "మీరు: ",
+ "yesterday": "నిన్న",
+ "attachTitle": "ఫైల్ / చిత్రాన్ని పంపు",
+ "emojiTitle": "ఎమోజీని ఎంచుకోండి",
+ "captionPlaceholder": "క్యాప్షన్ జోడించండి...",
+ "messagePlaceholder": "ఒక సందేశాన్ని టైప్ చేయండి...",
+ "noPermission": "సందేశాలను పంపడానికి మీకు అనుమతి లేదు",
+ "send": "పంపు",
+ "placeholderTitle": "మెసేజింగ్ ప్రారంభించండి",
+ "placeholderDesc": "వాట్సాప్ సందేశాలను చదవడం మరియు పంపడం ప్రారంభించడానికి ఎడమ సైడ్‌బార్ నుండి ఒక యాక్టివ్ చాట్‌ను ఎంచుకోండి.",
+ "deleteConfirm": "ఈ సందేశాన్ని అందరి కోసం తొలగించాలా?",
+ "messageDeleted": "🚫 ఈ సందేశం తొలగించబడింది",
+ "errors": {
+ "loadSessions": "సెషన్లను లోడ్ చేయడం విఫలమైంది",
+ "loadChats": "చాట్‌లను లోడ్ చేయడం విఫలమైంది",
+ "loadMessages": "సందేశాలను లోడ్ చేయడం విఫలమైంది",
+ "markRead": "చాట్‌ను చదివినట్లుగా గుర్తించడం విఫలమైంది",
+ "send": "సందేశాన్ని పంపడం విఫలమైంది",
+ "react": "సందేశానికి ప్రతిస్పందించడం విఫలమైంది",
+ "delete": "సందేశాన్ని తొలగించడం విఫలమైంది"
+ }
+ },
"errorBoundary": {
"title": "ఏదో తప్పు జరిగింది",
"description": "డ్యాష్‌బోర్డ్‌లో ఊహించని లోపం ఎదురైంది.",
@@ -188,12 +229,15 @@
"readyTitle": "సెషన్ సిద్ధంగా ఉంది",
"readyDesc": "వాట్సాప్ సెషన్ ఇప్పుడు కనెక్ట్ అయింది",
"disconnectedTitle": "సెషన్ డిస్‌కనెక్ట్ అయింది",
- "disconnectedDesc": "వాట్సాప్ సెషన్ డిస్‌కనెక్ట్ చేయబడింది"
+ "disconnectedDesc": "వాట్సాప్ సెషన్ డిస్‌కనెక్ట్ చేయబడింది",
+ "failedTitle": "సెషన్ విఫలమైంది",
+ "failedDesc": "వాట్సాప్ సెషన్ ప్రారంభం కావడం విఫలమైంది. కారణాన్ని చూడటానికి సెషన్‌ను తెరవండి."
},
"card": {
"phone": "ఫోన్",
"sessionId": "సెషన్ ID",
- "lastActive": "చివరిసారి యాక్టివ్"
+ "lastActive": "చివరిసారి యాక్టివ్",
+ "error": "లోపం"
}
},
"webhooks": {
@@ -403,6 +447,8 @@
"poolSize": "పూల్ సైజు",
"ssl": "SSL కనెక్షన్",
"sslDesc": "సురక్షిత డేటాబేస్ కనెక్షన్ల కోసం TLS/SSLని ప్రారంభించండి",
+ "sslRejectUnauthorized": "SSL సర్టిఫికేట్‌ను ధృవీకరించు",
+ "sslRejectUnauthorizedDesc": "స్వీయ-సంతకం చేసిన లేదా చెల్లని సర్టిఫికేట్‌లను తిరస్కరించండి. స్వీయ-సంతకం చేసిన సర్టిఫికేట్‌లతో నిర్వహించబడే Postgres (Supabase, Heroku, Render, Railway) కోసం దీన్ని ఆఫ్ చేయండి.",
"migrationsTitle": "డేటాబేస్ మైగ్రేషన్స్",
"migrationsStatus": "స్కీమా TypeORM తో స్వయంచాలకంగా సమకాలీకరించబడింది",
"migrationsHint": "మైగ్రేషన్స్ స్వయంచాలకంగా నిర్వహించబడతాయి. మాన్యువల్ మైగ్రేషన్స్ కోసం CLIని ఉపయోగించండి."
@@ -475,7 +521,6 @@
"engineCard": "యాక్టివ్ వాట్సాప్ ఇంజిన్",
"running": "నడుస్తోంది",
"supportedFeatures": "మద్దతు ఉన్న ఫీచర్లు:",
- "more": "+ఇంకా {{count}}",
"builtIn": "ఇన్-బిల్ట్",
"noDescription": "ఎలాంటి వివరణ అందుబాటులో లేదు",
"required": "అవసరం",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 867f511be..cb4b751f7 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -56,6 +56,7 @@
"nav": {
"dashboard": "仪表盘",
"sessions": "会话",
+ "chats": "聊天",
"webhooks": "Webhooks",
"apiKeys": "API 密钥",
"messageTester": "消息测试器",
@@ -63,6 +64,48 @@
"plugins": "插件",
"logs": "日志"
},
+ "chats": {
+ "subtitle": "实时发送和回复 WhatsApp 消息",
+ "noSessionsTitle": "没有已连接的会话",
+ "noSessionsDesc": "请先从 <1>会话</1> 菜单连接一个 WhatsApp 会话,才能使用聊天功能。",
+ "sessionLabel": "WhatsApp 会话",
+ "noPhone": "无电话",
+ "searchPlaceholder": "搜索聊天...",
+ "loadingChats": "正在加载聊天...",
+ "empty": "没有聊天",
+ "noMessageYet": "暂无消息",
+ "loadingMessages": "正在加载消息...",
+ "noMessagesInChat": "暂无消息。发送第一条消息即可开始!",
+ "downloadDocument": "下载文档",
+ "actions": {
+ "reply": "回复",
+ "react": "回应",
+ "delete": "删除消息"
+ },
+ "replyingTo": "正在回复 {{name}}",
+ "you": "你",
+ "youPrefix": "你:",
+ "yesterday": "昨天",
+ "attachTitle": "发送文件 / 图片",
+ "emojiTitle": "选择表情",
+ "captionPlaceholder": "添加说明文字...",
+ "messagePlaceholder": "输入消息...",
+ "noPermission": "你没有发送消息的权限",
+ "send": "发送",
+ "placeholderTitle": "开始聊天",
+ "placeholderDesc": "从左侧边栏选择一个活跃聊天,即可开始阅读和发送 WhatsApp 消息。",
+ "deleteConfirm": "为所有人删除此消息?",
+ "messageDeleted": "🚫 此消息已被删除",
+ "errors": {
+ "loadSessions": "加载会话失败",
+ "loadChats": "加载聊天失败",
+ "loadMessages": "加载消息失败",
+ "markRead": "将聊天标记为已读失败",
+ "send": "发送消息失败",
+ "react": "回应消息失败",
+ "delete": "删除消息失败"
+ }
+ },
"errorBoundary": {
"title": "出了点问题",
"description": "仪表盘遇到意外错误。",
@@ -186,12 +229,15 @@
"readyTitle": "会话就绪",
"readyDesc": "WhatsApp 会话现已连接",
"disconnectedTitle": "会话已断开",
- "disconnectedDesc": "WhatsApp 会话已断开连接"
+ "disconnectedDesc": "WhatsApp 会话已断开连接",
+ "failedTitle": "会话失败",
+ "failedDesc": "WhatsApp 会话启动失败。打开该会话以查看原因。"
},
"card": {
"phone": "电话",
"sessionId": "会话 ID",
- "lastActive": "上次活跃"
+ "lastActive": "上次活跃",
+ "error": "错误"
}
},
"webhooks": {
@@ -475,7 +521,6 @@
"engineCard": "当前 WhatsApp 引擎",
"running": "运行中",
"supportedFeatures": "支持的功能:",
- "more": "+{{count}} 更多",
"builtIn": "内置",
"noDescription": "没有可用描述",
"required": "必需",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index f513d60d2..9434b5e72 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -56,6 +56,7 @@
"nav": {
"dashboard": "控制面板",
"sessions": "工作階段",
+ "chats": "聊天",
"webhooks": "Webhooks",
"apiKeys": "API 金鑰",
"messageTester": "訊息測試器",
@@ -63,6 +64,48 @@
"plugins": "外掛",
"logs": "記錄"
},
+ "chats": {
+ "subtitle": "即時傳送和回覆 WhatsApp 訊息",
+ "noSessionsTitle": "沒有已連線的工作階段",
+ "noSessionsDesc": "請先從 <1>工作階段</1> 選單連線一個 WhatsApp 工作階段,才能使用聊天功能。",
+ "sessionLabel": "WhatsApp 工作階段",
+ "noPhone": "沒有電話",
+ "searchPlaceholder": "搜尋聊天...",
+ "loadingChats": "正在載入聊天...",
+ "empty": "沒有聊天",
+ "noMessageYet": "尚無訊息",
+ "loadingMessages": "正在載入訊息...",
+ "noMessagesInChat": "尚無訊息。傳送第一則訊息即可開始!",
+ "downloadDocument": "下載文件",
+ "actions": {
+ "reply": "回覆",
+ "react": "回應",
+ "delete": "刪除訊息"
+ },
+ "replyingTo": "正在回覆 {{name}}",
+ "you": "你",
+ "youPrefix": "你:",
+ "yesterday": "昨天",
+ "attachTitle": "傳送檔案 / 圖片",
+ "emojiTitle": "選擇表情符號",
+ "captionPlaceholder": "新增說明文字...",
+ "messagePlaceholder": "輸入訊息...",
+ "noPermission": "你沒有傳送訊息的權限",
+ "send": "傳送",
+ "placeholderTitle": "開始聊天",
+ "placeholderDesc": "從左側邊欄選擇一個活躍聊天,即可開始閱讀和傳送 WhatsApp 訊息。",
+ "deleteConfirm": "為所有人刪除此訊息?",
+ "messageDeleted": "🚫 此訊息已被刪除",
+ "errors": {
+ "loadSessions": "載入工作階段失敗",
+ "loadChats": "載入聊天失敗",
+ "loadMessages": "載入訊息失敗",
+ "markRead": "將聊天標記為已讀失敗",
+ "send": "傳送訊息失敗",
+ "react": "回應訊息失敗",
+ "delete": "刪除訊息失敗"
+ }
+ },
"errorBoundary": {
"title": "發生問題",
"description": "控制面板遇到未預期的錯誤。",
@@ -186,12 +229,15 @@
"readyTitle": "工作階段就緒",
"readyDesc": "WhatsApp 工作階段現已連線",
"disconnectedTitle": "工作階段已中斷連線",
- "disconnectedDesc": "WhatsApp 工作階段已中斷連線"
+ "disconnectedDesc": "WhatsApp 工作階段已中斷連線",
+ "failedTitle": "工作階段失敗",
+ "failedDesc": "WhatsApp 工作階段啟動失敗。開啟該工作階段以查看原因。"
},
"card": {
"phone": "電話",
"sessionId": "工作階段 ID",
- "lastActive": "上次活躍"
+ "lastActive": "上次活躍",
+ "error": "錯誤"
}
},
"webhooks": {
@@ -475,7 +521,6 @@
"engineCard": "目前 WhatsApp 引擎",
"running": "執行中",
"supportedFeatures": "支援功能:",
- "more": "+{{count}} 更多",
"builtIn": "內置",
"noDescription": "沒有可用描述",
"required": "必需",
diff --git a/dashboard/src/pages/ApiKeys.tsx b/dashboard/src/pages/ApiKeys.tsx
index a7a9db361..5bfa577b2 100644
--- a/dashboard/src/pages/ApiKeys.tsx
+++ b/dashboard/src/pages/ApiKeys.tsx
@@ -151,13 +151,8 @@ export function ApiKeys() {
const apiKey = info.row.original;
return (
<span className="actions-cell">
- <button
- className="icon-btn"
- onClick={() => copyToClipboard(apiKey.keyPrefix, apiKey.id)}
- title={t('apiKeys.actions.copy')}
- >
- {copied === apiKey.id ? <Check size={16} /> : <Copy size={16} />}
- </button>
+ {/* No per-row copy: the full key only exists once (post-creation modal); the row
+ only has the prefix, so a copy button here could only copy a useless fragment. */}
{apiKey.isActive && (
<button
className="icon-btn"
@@ -179,7 +174,7 @@ export function ApiKeys() {
},
}),
],
- [visibleKeys, copied, t],
+ [visibleKeys, t],
);
const table = useReactTable({
diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.css
index eca635685..17627c734 100644
--- a/dashboard/src/pages/Chats.css
+++ b/dashboard/src/pages/Chats.css
@@ -510,6 +510,23 @@
color: #ea580c;
}
+/* Real-time connection-lost banner */
+.chats-reconnect-banner {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.5rem 0.75rem;
+ margin-bottom: 0.75rem;
+ border-radius: 6px;
+ background: rgba(234, 88, 12, 0.1);
+ color: #ea580c;
+ font-size: 0.875rem;
+}
+
+.chats-reconnect-banner button {
+ margin-left: auto;
+}
+
/* =============================================================================
ATTACHMENT PREVIEW & EMOJI PICKER
============================================================================= */
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 7a53875f9..48afaf5ee 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -273,7 +273,7 @@ export function Chats() {
[selectedSessionId],
);
- const { isConnected, subscribe, unsubscribe } = useWebSocket({
+ const { isConnected, connectionFailed, reconnect, subscribe, unsubscribe } = useWebSocket({
onMessage: handleIncomingMessage,
onMessageAck: handleIncomingMessageAck,
onMessageReaction: handleIncomingMessageReaction,
@@ -573,6 +573,18 @@ export function Chats() {
<div className="chats-page">
<PageHeader title={t('nav.chats')} subtitle={t('chats.subtitle')} />
+ {/* Real-time connection permanently dropped — let the user re-establish it instead of
+ silently showing stale chats. */}
+ {connectionFailed && (
+ <div className="chats-reconnect-banner" role="alert">
+ <AlertCircle size={16} />
+ <span>{t('common.disconnected')}</span>
+ <button className="btn-secondary" onClick={reconnect}>
+ {t('common.refresh')}
+ </button>
+ </div>
+ )}
+
{loadingSessions ? (
<div className="chats-loading-container">
<Loader2 className="animate-spin" size={32} />
diff --git a/dashboard/src/pages/Login.tsx b/dashboard/src/pages/Login.tsx
index 516f48e55..d3e909e62 100644
--- a/dashboard/src/pages/Login.tsx
+++ b/dashboard/src/pages/Login.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { Eye, EyeOff, Languages } from 'lucide-react';
import { GithubIcon } from '../components/GithubIcon';
import { languageOptions, resolveSupportedLanguage, type SupportedLanguage } from '../i18n';
+import { API_BASE_URL } from '../services/api';
import './Login.css';
interface LoginProps {
@@ -31,7 +32,7 @@ export function Login({ onLogin }: LoginProps) {
setError('');
try {
- const response = await fetch('/api/auth/validate', {
+ const response = await fetch(`${API_BASE_URL}/auth/validate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
diff --git a/dashboard/src/pages/Logs.tsx b/dashboard/src/pages/Logs.tsx
index 0678d3fa4..722b30266 100644
--- a/dashboard/src/pages/Logs.tsx
+++ b/dashboard/src/pages/Logs.tsx
@@ -31,6 +31,52 @@ export function Logs() {
const formatTimestamp = (date: string) => new Date(date).toLocaleString();
+ // Export the currently loaded (and filtered) logs to a CSV download. Client-side only —
+ // it exports what the page already has, not the whole audit history.
+ const handleExportCsv = () => {
+ if (filteredLogs.length === 0) return;
+ const headers = [
+ 'timestamp',
+ 'action',
+ 'severity',
+ 'session',
+ 'apiKey',
+ 'ip',
+ 'method',
+ 'path',
+ 'statusCode',
+ 'errorMessage',
+ ];
+ const escape = (value: unknown): string => {
+ const s = value === undefined || value === null ? '' : String(value);
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
+ };
+ const rows = filteredLogs.map(log =>
+ [
+ log.createdAt,
+ log.action,
+ log.severity,
+ log.sessionName || log.sessionId || '',
+ log.apiKeyName || log.apiKeyId || '',
+ log.ipAddress,
+ log.method,
+ log.path,
+ log.statusCode,
+ log.errorMessage,
+ ]
+ .map(escape)
+ .join(','),
+ );
+ const csv = [headers.join(','), ...rows].join('\n');
+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `openwa-logs-${new Date().toISOString().slice(0, 10)}.csv`;
+ a.click();
+ URL.revokeObjectURL(url);
+ };
+
if (loading && logs.length === 0) {
return (
<div
@@ -48,7 +94,7 @@ export function Logs() {
title={t('logs.title')}
subtitle={t('logs.subtitle')}
actions={
- <button className="btn-secondary">
+ <button className="btn-secondary" onClick={handleExportCsv} disabled={filteredLogs.length === 0}>
<Download size={18} />
{t('logs.exportCsv')}
</button>
diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsx
index a595e79d3..c30285510 100644
--- a/dashboard/src/pages/Plugins.tsx
+++ b/dashboard/src/pages/Plugins.tsx
@@ -17,7 +17,7 @@ import {
Zap,
X,
} from 'lucide-react';
-import { pluginsApi } from '../services/api';
+import { pluginsApi, infraApi } from '../services/api';
import type { Plugin } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import {
@@ -118,6 +118,16 @@ export default function Plugins() {
const handleSaveConfig = async () => {
setSavingConfig(true);
try {
+ // Persist the engine section to the backend (.env.generated via PUT /infra/config).
+ // The engine `type` isn't a savable field (only whatsapp-web.js exists); the backend
+ // maps these to PUPPETEER_HEADLESS / SESSION_DATA_PATH / PUPPETEER_ARGS.
+ await infraApi.saveConfig({
+ engine: {
+ headless: engineConfig.headless,
+ sessionDataPath: engineConfig.sessionDataPath,
+ browserArgs: engineConfig.browserArgs,
+ },
+ });
toast.success(t('plugins.toasts.savedTitle'), t('plugins.toasts.savedDesc'));
setShowConfigModal(false);
} catch (err) {
diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsx
index 877c76dd8..d49e28bd1 100644
--- a/dashboard/src/pages/Webhooks.tsx
+++ b/dashboard/src/pages/Webhooks.tsx
@@ -25,12 +25,21 @@ import {
import { PageHeader } from '../components/PageHeader';
import './Webhooks.css';
+// Must stay aligned with the backend WEBHOOK_EVENTS: the API now rejects unknown
+// event names, so offering e.g. the never-emitted 'session.connected' would 400 on save.
const availableEventNames = [
'message.received',
'message.sent',
- 'session.connected',
- 'session.disconnected',
+ 'message.ack',
+ 'message.failed',
+ 'message.revoked',
+ 'session.status',
'session.qr',
+ 'session.authenticated',
+ 'session.disconnected',
+ 'group.join',
+ 'group.leave',
+ 'group.update',
'*',
] as const;
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index e670425ec..10d7ae5ad 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -8,7 +8,9 @@
// `VITE_API_URL=https://gateway.example.com` — and the '/api' prefix is appended here.
// Previously VITE_API_URL was documented but never read, so the dashboard always called
// same-origin '/api' and a split deployment failed with "Invalid API Key" (#91).
-const API_BASE_URL = `${(import.meta.env.VITE_API_URL ?? '').replace(/\/+$/, '')}/api`;
+// Exported so direct fetches (e.g. auth/validate in Login.tsx / App.tsx) honor VITE_API_URL
+// too — otherwise split-origin deployments break. Empty VITE_API_URL → '/api'.
+export const API_BASE_URL = `${(import.meta.env.VITE_API_URL ?? '').replace(/\/+$/, '')}/api`;
// =============================================================================
// Types
@@ -235,6 +237,18 @@ async function request<T>(endpoint: string, options: RequestInit = {}): Promise<
const response = await fetch(url, { ...options, headers });
+ if (response.status === 401) {
+ // The stored API key is invalid/expired/revoked — clear it and return to login
+ // so the user isn't stuck on a dashboard that 401s every request.
+ sessionStorage.removeItem('openwa_api_key');
+ if (typeof window !== 'undefined') {
+ window.location.assign('/');
+ // The page is navigating away — halt this request's promise chain so callers neither
+ // throw the generic error below (flashing a toast) nor receive an undefined payload.
+ return new Promise<T>(() => {});
+ }
+ }
+
if (!response.ok) {
const error = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(error.message || `HTTP ${response.status}`);
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index a59cb4827..c881b2ced 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -1,4 +1,11 @@
-# OpenWA - Docker Compose for Development
+# OpenWA - Local smoke / quick-start compose (L22)
+#
+# This builds and runs the PRODUCTION image (same Dockerfile) against a local SQLite DB
+# with a bind-mounted ./data — it is a single-container local smoke test, NOT a
+# hot-reload development environment (there is no source mount or `start:dev`).
+# DATABASE_SYNCHRONIZE=true keeps the SQLite schema zero-config for local use; the
+# production compose (docker-compose.yml) never forces synchronize (it defaults to false).
+#
# Quick Start: docker compose -f docker-compose.dev.yml up -d
services:
@@ -8,11 +15,28 @@ services:
context: .
dockerfile: Dockerfile
container_name: openwa-api
+ # Container hardening (finding H7) — same posture as production (same Dockerfile/entrypoint).
+ security_opt:
+ - 'no-new-privileges:true'
+ cap_drop:
+ - ALL
+ cap_add:
+ - CHOWN
+ - DAC_OVERRIDE
+ - FOWNER
+ - SETGID
+ - SETUID
+ read_only: true
+ tmpfs:
+ - /tmp
+ pids_limit: 512
+ mem_limit: ${OPENWA_MEM_LIMIT:-2g}
ports:
- '127.0.0.1:2785:2785'
environment:
- NODE_ENV=development
- PORT=2785
+ - HOME=/tmp
- DATABASE_TYPE=sqlite
- DATABASE_NAME=/app/data/openwa.sqlite
- DATABASE_SYNCHRONIZE=true
@@ -29,7 +53,7 @@ services:
- ./data:/app/data
restart: unless-stopped
healthcheck:
- test: ['CMD', 'curl', '-f', 'http://localhost:2785/api/health']
+ test: ['CMD', 'curl', '-f', 'http://localhost:2785/api/health/ready']
interval: 30s
timeout: 10s
retries: 3
diff --git a/docker-compose.yml b/docker-compose.yml
index ca401305f..c082f4f4b 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -7,6 +7,11 @@ services:
image: tecnativa/docker-socket-proxy
container_name: openwa-docker-proxy
restart: unless-stopped
+ # Only on the isolated internal network — reachable solely by openwa-api, NOT the
+ # dashboard or any other peer (finding H6). `internal: true` also denies the proxy
+ # outbound access; it only needs the locally-mounted docker socket.
+ networks:
+ - internal-docker
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
environment:
@@ -28,6 +33,8 @@ services:
container_name: openwa-traefik
profiles: ['with-proxy', 'full']
restart: unless-stopped
+ networks:
+ - openwa-network
ports:
- '127.0.0.1:${DASHBOARD_PORT:-2886}:80'
- '127.0.0.1:8080:8080' # Traefik dashboard
@@ -45,6 +52,34 @@ services:
dockerfile: Dockerfile
container_name: openwa-api
restart: unless-stopped
+ # App network for datastores/traefik/dashboard + the isolated network to reach
+ # docker-proxy (DOCKER_HOST). createService() in docker.service.ts attaches
+ # orchestrated containers to the literal `openwa-network`, so its name is fixed.
+ networks:
+ - openwa-network
+ - internal-docker
+ # Container hardening (finding H7): Chromium runs with --no-sandbox, so the
+ # container itself is the confinement boundary. cap_drop ALL + a minimal re-add
+ # ONLY for the root entrypoint's chown + gosu privilege-drop; once gosu setuids to
+ # the openwa user the node/Chromium process keeps NO effective capabilities.
+ # read_only rootfs (Chromium's profile lives on the writable /app/data volume;
+ # HOME=/tmp + tmpfs absorb stray writes). no-new-privileges blocks setuid escalation.
+ # NOTE: requires a live single-session smoke (Chromium must launch) before merge.
+ security_opt:
+ - 'no-new-privileges:true'
+ cap_drop:
+ - ALL
+ cap_add:
+ - CHOWN # entrypoint: chown -R openwa /app/data on the named volume
+ - DAC_OVERRIDE # entrypoint: chown across pre-existing files
+ - FOWNER
+ - SETGID # gosu: drop to the openwa group
+ - SETUID # gosu: drop to the openwa user
+ read_only: true
+ tmpfs:
+ - /tmp
+ pids_limit: 512
+ mem_limit: ${OPENWA_MEM_LIMIT:-2g} # tune up for many concurrent sessions
ports:
- '127.0.0.1:${API_PORT:-2785}:2785'
expose:
@@ -52,6 +87,8 @@ services:
environment:
# Core
- NODE_ENV=${NODE_ENV:-production}
+ # Writable HOME on tmpfs so Chromium's HOME-relative writes don't hit the read_only rootfs
+ - HOME=/tmp
- PORT=2785
- LOG_LEVEL=${LOG_LEVEL:-info}
# Database
@@ -60,7 +97,9 @@ services:
- DATABASE_HOST=${DATABASE_HOST:-postgres}
- DATABASE_PORT=${DATABASE_PORT:-5432}
- DATABASE_USERNAME=${DATABASE_USERNAME:-openwa}
- - DATABASE_PASSWORD=${DATABASE_PASSWORD:-openwa}
+ # No committed default secret (M16). Empty for the default sqlite setup; the
+ # postgres service requires it (:?) when that profile is active.
+ - DATABASE_PASSWORD=${DATABASE_PASSWORD:-}
- DATABASE_SYNCHRONIZE=${DATABASE_SYNCHRONIZE:-false}
# Engine
- ENGINE_TYPE=${ENGINE_TYPE:-whatsapp-web.js}
@@ -71,8 +110,8 @@ services:
- STORAGE_TYPE=${STORAGE_TYPE:-local}
- STORAGE_LOCAL_PATH=/app/data/media
- S3_ENDPOINT=${S3_ENDPOINT:-http://minio:9000}
- - S3_ACCESS_KEY=${S3_ACCESS_KEY:-minioadmin}
- - S3_SECRET_KEY=${S3_SECRET_KEY:-minioadmin}
+ - S3_ACCESS_KEY=${S3_ACCESS_KEY:-}
+ - S3_SECRET_KEY=${S3_SECRET_KEY:-}
- S3_BUCKET=${S3_BUCKET:-openwa}
# Redis
- REDIS_ENABLED=${REDIS_ENABLED:-false}
@@ -110,7 +149,7 @@ services:
'CMD',
'node',
'-e',
- "require('http').get('http://localhost:2785/api/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1))",
+ "require('http').get('http://localhost:2785/api/health/ready', (r) => process.exit(r.statusCode === 200 ? 0 : 1))",
]
interval: 30s
timeout: 10s
@@ -128,6 +167,9 @@ services:
container_name: openwa-dashboard
profiles: ['with-dashboard', 'full']
restart: unless-stopped
+ # App network only — the dashboard must NOT be able to reach docker-proxy:2375 (H6).
+ networks:
+ - openwa-network
expose:
- '80'
depends_on:
@@ -142,9 +184,16 @@ services:
container_name: openwa-postgres
profiles: ['postgres']
restart: unless-stopped
+ networks:
+ - openwa-network
+ security_opt:
+ - 'no-new-privileges:true'
environment:
POSTGRES_USER: ${DATABASE_USERNAME:-openwa}
- POSTGRES_PASSWORD: ${DATABASE_PASSWORD:-openwa}
+ # M16: no committed default secret. Empty unless the operator sets it; the postgres
+ # image refuses to initialize with an empty password (clear fail-fast), and the app's
+ # production boot guard rejects empty/placeholder secrets before startup.
+ POSTGRES_PASSWORD: ${DATABASE_PASSWORD:-}
POSTGRES_DB: ${DATABASE_NAME:-openwa}
volumes:
- postgres-data:/var/lib/postgresql/data
@@ -163,6 +212,10 @@ services:
container_name: openwa-redis
profiles: ['redis']
restart: unless-stopped
+ networks:
+ - openwa-network
+ security_opt:
+ - 'no-new-privileges:true'
command: redis-server --appendonly yes
volumes:
- redis-data:/data
@@ -181,10 +234,16 @@ services:
container_name: openwa-minio
profiles: ['minio']
restart: unless-stopped
+ networks:
+ - openwa-network
+ security_opt:
+ - 'no-new-privileges:true'
command: server /data --console-address ":9001"
environment:
- MINIO_ROOT_USER: ${S3_ACCESS_KEY:-minioadmin}
- MINIO_ROOT_PASSWORD: ${S3_SECRET_KEY:-minioadmin}
+ # M16: no committed default creds. MinIO refuses to start with empty root creds
+ # (clear fail-fast); the app's production boot guard rejects empty/placeholder secrets.
+ MINIO_ROOT_USER: ${S3_ACCESS_KEY:-}
+ MINIO_ROOT_PASSWORD: ${S3_SECRET_KEY:-}
volumes:
- minio-data:/data
ports:
@@ -210,5 +269,12 @@ volumes:
driver: local
networks:
- default:
+ # Application network — datastores, traefik, dashboard, and openwa-api. Keep the
+ # name `openwa-network`: docker.service.ts attaches orchestrated containers to it by literal name.
+ openwa-network:
name: openwa-network
+ # Isolated network for the Docker socket proxy. `internal: true` means no external
+ # connectivity; only openwa-api joins it, so nothing else can reach docker-proxy:2375.
+ internal-docker:
+ name: openwa-internal-docker
+ internal: true
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.md
index 4a791828b..dc496c6d5 100644
--- a/docs/03-system-architecture.md
+++ b/docs/03-system-architecture.md
@@ -76,7 +76,12 @@ sequenceDiagram
## 3.2 Pluggable Architecture Philosophy
-OpenWA is designed with a **Pluggable Architecture** that allows infrastructure components to be swapped without changing application code. This enables flexible deployments ranging from minimal single-session bots to enterprise-scale multi-tenant platforms.
+OpenWA is designed with a **Pluggable Architecture** that allows infrastructure components to be swapped without changing application code. This enables flexible deployments ranging from minimal single-session bots to larger single-node, multi-session installs.
+
+> **Note — single-instance:** the live WhatsApp engine layer is stateful and held in-process
+> (an in-memory `Map` in `SessionService`). OpenWA currently runs as **one API instance per
+> session-data volume**; horizontal scaling across multiple API replicas is a future design
+> (not implemented). See [13 - Horizontal Scaling](13-horizontal-scaling.md).
### Design Philosophy
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index a654b756d..70e0a1208 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -75,20 +75,14 @@ curl -X POST http://localhost:2785/api/auth/api-keys \
**Response:**
```json
{
- "success": true,
- "data": {
- "id": "2a8f41e3-3b9a-4a1d-b6d0-b9910df8f0be",
- "name": "n8n Integration",
- "keyPrefix": "owa_k1_abcd",
- "role": "operator",
- "isActive": true,
- "usageCount": 0,
- "createdAt": "2026-02-02T10:30:00.000Z",
- "apiKey": "owa_k1_abcd1234..."
- },
- "meta": {
- "timestamp": "2026-02-02T10:30:00.000Z"
- }
+ "id": "2a8f41e3-3b9a-4a1d-b6d0-b9910df8f0be",
+ "name": "n8n Integration",
+ "keyPrefix": "owa_k1_abcd",
+ "role": "operator",
+ "isActive": true,
+ "usageCount": 0,
+ "createdAt": "2026-02-02T10:30:00.000Z",
+ "apiKey": "owa_k1_abcd1234..."
}
```
@@ -106,41 +100,48 @@ curl -X POST http://localhost:2785/api/auth/api-keys \
## 6.2 Response Format
+> **OpenWA returns the raw handler payload directly — there is NO `{success, data, meta}`
+> envelope.** A resource endpoint returns that resource object; a list endpoint returns a
+> bare array. Read fields directly (`response.id`, not `response.data.id`). Errors use the
+> NestJS default shape with the HTTP status in the status line.
+>
+> *(The response examples elsewhere in this document predate this and may still show the
+> old wrapper; the shape described here is authoritative — see [the H8 finding](../_docs/2026-06-15-security-architecture-audit.md).)*
+
### Success Response
+A successful request returns the resource (or array) as-is:
+
```json
{
- "success": true,
- "data": {},
- "meta": {
- "timestamp": "2025-02-02T10:00:00.000Z",
- "requestId": "550e8400-e29b-41d4-a716-446655440000",
- "version": "0.1.0"
- }
+ "id": "550e8400-e29b-41d4-a716-446655440000",
+ "name": "my-session",
+ "status": "READY"
}
```
+List endpoints return a bare array:
+
+```json
+[
+ { "id": "…", "name": "session-a" },
+ { "id": "…", "name": "session-b" }
+]
+```
+
### Error Response
+Errors use the NestJS default shape (the HTTP status is on the status line, not in a `code` field):
+
```json
{
- "success": false,
- "error": {
- "code": "ERROR_CODE",
- "message": "Human readable message",
- "details": {}
- },
- "meta": {
- "timestamp": "2025-02-02T10:00:00.000Z",
- "requestId": "550e8400-e29b-41d4-a716-446655440000"
- }
+ "statusCode": 404,
+ "message": "Webhook with id 'x' not found",
+ "error": "Not Found"
}
```
-### Request ID Convention
-
-- Recommended format: `req_<epoch_ms>` (example: `req_1706868000000`).
-- `X-Request-ID` is returned in `meta.requestId` when provided by the client.
+Validation errors (`statusCode: 400`) return `message` as an array of field-level strings.
### Timestamp Conventions
@@ -414,14 +415,11 @@ POST /api/sessions
**Response (201 Created):**
```json
{
- "success": true,
- "data": {
- "id": "sess_abc123",
- "name": "my-bot",
- "status": "INITIALIZING",
- "qr": null,
- "createdAt": "2025-02-02T10:00:00.000Z"
- }
+ "id": "sess_abc123",
+ "name": "my-bot",
+ "status": "INITIALIZING",
+ "qr": null,
+ "createdAt": "2025-02-02T10:00:00.000Z"
}
```
@@ -442,24 +440,15 @@ GET /api/sessions
**Response (200 OK):**
```json
-{
- "success": true,
- "data": [
- {
- "id": "sess_abc123",
- "name": "my-bot",
- "status": "CONNECTED",
- "phoneNumber": "628123456789",
- "createdAt": "2025-02-02T10:00:00.000Z"
- }
- ],
- "pagination": {
- "page": 1,
- "limit": 20,
- "total": 1,
- "totalPages": 1
+[
+ {
+ "id": "sess_abc123",
+ "name": "my-bot",
+ "status": "CONNECTED",
+ "phoneNumber": "628123456789",
+ "createdAt": "2025-02-02T10:00:00.000Z"
}
-}
+]
```
---
@@ -473,17 +462,14 @@ GET /api/sessions/:sessionId
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "id": "sess_abc123",
- "name": "my-bot",
- "status": "CONNECTED",
- "phoneNumber": "628123456789",
- "pushName": "My Bot",
- "platform": "android",
- "connectedAt": "2025-02-02T10:05:00.000Z",
- "createdAt": "2025-02-02T10:00:00.000Z"
- }
+ "id": "sess_abc123",
+ "name": "my-bot",
+ "status": "CONNECTED",
+ "phoneNumber": "628123456789",
+ "pushName": "My Bot",
+ "platform": "android",
+ "connectedAt": "2025-02-02T10:05:00.000Z",
+ "createdAt": "2025-02-02T10:00:00.000Z"
}
```
@@ -524,11 +510,8 @@ GET /api/sessions/:sessionId/qr
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "code": "2@ABC123...",
- "image": "data:image/png;base64,..."
- }
+ "code": "2@ABC123...",
+ "image": "data:image/png;base64,..."
}
```
@@ -543,10 +526,7 @@ DELETE /api/sessions/:sessionId
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "message": "Session deleted successfully"
- }
+ "message": "Session deleted successfully"
}
```
@@ -561,10 +541,7 @@ POST /api/sessions/:sessionId/logout
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "message": "Session logged out successfully"
- }
+ "message": "Session logged out successfully"
}
```
@@ -602,12 +579,9 @@ POST /api/sessions/:sessionId/messages/send-text
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "messageId": "[email protected]_3EB0ABC123",
- "status": "sent",
- "timestamp": "2025-02-02T10:00:00.000Z"
- }
+ "messageId": "[email protected]_3EB0ABC123",
+ "status": "sent",
+ "timestamp": "2025-02-02T10:00:00.000Z"
}
```
@@ -644,12 +618,9 @@ POST /api/sessions/:sessionId/messages/send-image
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "messageId": "[email protected]_3EB0ABC124",
- "status": "sent",
- "timestamp": "2025-02-02T10:00:00.000Z"
- }
+ "messageId": "[email protected]_3EB0ABC124",
+ "status": "sent",
+ "timestamp": "2025-02-02T10:00:00.000Z"
}
```
@@ -824,14 +795,11 @@ POST /api/sessions/:sessionId/messages/send-bulk
**Response (202 Accepted):**
```json
{
- "success": true,
- "data": {
- "batchId": "batch_abc123xyz",
- "status": "processing",
- "totalMessages": 2,
- "estimatedCompletionTime": "2025-02-02T10:05:00.000Z",
- "statusUrl": "/api/sessions/sess_abc123/messages/batch/batch_abc123xyz"
- }
+ "batchId": "batch_abc123xyz",
+ "status": "processing",
+ "totalMessages": 2,
+ "estimatedCompletionTime": "2025-02-02T10:05:00.000Z",
+ "statusUrl": "/api/sessions/sess_abc123/messages/batch/batch_abc123xyz"
}
```
@@ -846,34 +814,31 @@ GET /api/sessions/:sessionId/messages/batch/:batchId
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "batchId": "batch_abc123xyz",
- "status": "completed",
- "progress": {
- "total": 100,
- "sent": 95,
- "failed": 5,
- "pending": 0
+ "batchId": "batch_abc123xyz",
+ "status": "completed",
+ "progress": {
+ "total": 100,
+ "sent": 95,
+ "failed": 5,
+ "pending": 0
+ },
+ "results": [
+ {
+ "chatId": "[email protected]",
+ "status": "sent",
+ "messageId": "[email protected]_3EB0ABC123"
},
- "results": [
- {
- "chatId": "[email protected]",
- "status": "sent",
- "messageId": "[email protected]_3EB0ABC123"
- },
- {
- "chatId": "[email protected]",
- "status": "failed",
- "error": {
- "code": "MESSAGE_NUMBER_NOT_ON_WHATSAPP",
- "message": "Number not registered on WhatsApp"
- }
+ {
+ "chatId": "[email protected]",
+ "status": "failed",
+ "error": {
+ "code": "MESSAGE_NUMBER_NOT_ON_WHATSAPP",
+ "message": "Number not registered on WhatsApp"
}
- ],
- "startedAt": "2025-02-02T10:00:00.000Z",
- "completedAt": "2025-02-02T10:08:30.000Z"
- }
+ }
+ ],
+ "startedAt": "2025-02-02T10:00:00.000Z",
+ "completedAt": "2025-02-02T10:08:30.000Z"
}
```
@@ -888,16 +853,13 @@ POST /api/sessions/:sessionId/messages/batch/:batchId/cancel
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "batchId": "batch_abc123xyz",
- "status": "cancelled",
- "progress": {
- "total": 100,
- "sent": 45,
- "failed": 2,
- "cancelled": 53
- }
+ "batchId": "batch_abc123xyz",
+ "status": "cancelled",
+ "progress": {
+ "total": 100,
+ "sent": 45,
+ "failed": 2,
+ "cancelled": 53
}
}
```
@@ -918,22 +880,19 @@ GET /api/sessions/:sessionId/chats/:chatId/messages
**Response (200 OK):**
```json
-{
- "success": true,
- "data": [
- {
- "id": "[email protected]_3EB0ABC123",
- "from": "[email protected]",
- "body": "Hello!",
- "type": "chat",
- "waTimestamp": 1706868000,
- "timestamp": "2025-02-02T10:00:00.000Z",
- "fromMe": false,
- "hasMedia": false
- }
- ]
-}
+[
+ {
+ "id": "[email protected]_3EB0ABC123",
+ "from": "[email protected]",
+ "body": "Hello!",
+ "type": "chat",
+ "waTimestamp": 1706868000,
+ "timestamp": "2025-02-02T10:00:00.000Z",
+ "fromMe": false,
+ "hasMedia": false
+ }
+]
```
---
@@ -979,11 +938,8 @@ POST /api/sessions/:sessionId/messages/send-template
**Response (201 Created):**
```json
{
- "success": true,
- "data": {
- "messageId": "[email protected]_3EB0ABC123",
- "timestamp": "2025-02-02T10:00:00.000Z"
- }
+ "messageId": "[email protected]_3EB0ABC123",
+ "timestamp": "2025-02-02T10:00:00.000Z"
}
```
@@ -1032,17 +988,14 @@ When rendered, the header, body, and footer are joined with blank lines.
**Response (201 Created):**
```json
{
- "success": true,
- "data": {
- "id": "b1c2d3e4-f5a6-7890-bcde-f01234567890",
- "sessionId": "sess_abc123",
- "name": "order-confirmation",
- "body": "Hi {{customer}}, your order {{orderId}} has shipped.",
- "header": "OpenWA Store",
- "footer": "Reply STOP to unsubscribe.",
- "createdAt": "2025-02-02T10:00:00.000Z",
- "updatedAt": "2025-02-02T10:00:00.000Z"
- }
+ "id": "b1c2d3e4-f5a6-7890-bcde-f01234567890",
+ "sessionId": "sess_abc123",
+ "name": "order-confirmation",
+ "body": "Hi {{customer}}, your order {{orderId}} has shipped.",
+ "header": "OpenWA Store",
+ "footer": "Reply STOP to unsubscribe.",
+ "createdAt": "2025-02-02T10:00:00.000Z",
+ "updatedAt": "2025-02-02T10:00:00.000Z"
}
```
@@ -1098,18 +1051,15 @@ GET /api/sessions/:sessionId/contacts
**Response (200 OK):**
```json
-{
- "success": true,
- "data": [
- {
- "name": "John Doe",
- "pushName": "John",
- "isMyContact": true,
- "isBlocked": false
- }
- ]
-}
+[
+ {
+ "name": "John Doe",
+ "pushName": "John",
+ "isMyContact": true,
+ "isBlocked": false
+ }
+]
```
---
@@ -1123,11 +1073,8 @@ GET /api/sessions/:sessionId/contacts/check/:phone
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "exists": true,
- "chatId": "[email protected]"
- }
+ "exists": true,
+ "chatId": "[email protected]"
}
```
@@ -1142,10 +1089,7 @@ GET /api/sessions/:sessionId/contacts/:contactId/profile-picture
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "url": "https://pps.whatsapp.net/..."
- }
+ "url": "https://pps.whatsapp.net/..."
}
```
@@ -1161,18 +1105,15 @@ GET /api/sessions/:sessionId/groups
**Response (200 OK):**
```json
-{
- "success": true,
- "data": [
- {
- "name": "Family Group",
- "description": "Family chat",
- "participantsCount": 10,
- "createdAt": "2024-01-01T00:00:00.000Z"
- }
- ]
-}
+[
+ {
+ "name": "Family Group",
+ "description": "Family chat",
+ "participantsCount": 10,
+ "createdAt": "2024-01-01T00:00:00.000Z"
+ }
+]
```
---
@@ -1186,21 +1127,18 @@ GET /api/sessions/:sessionId/groups/:groupId
**Response (200 OK):**
```json
{
- "success": true,
- "data": {
- "name": "Family Group",
- "description": "Family chat",
- "owner": "[email protected]",
- "participants": [
- {
- "isAdmin": true,
- "isSuperAdmin": true
- }
- ],
- "createdAt": "2024-01-01T00:00:00.000Z"
- }
+ "name": "Family Group",
+ "description": "Family chat",
+ "owner": "[email protected]",
+ "participants": [
+ {
+ "isAdmin": true,
+ "isSuperAdmin": true
+ }
+ ],
+ "createdAt": "2024-01-01T00:00:00.000Z"
}
```
@@ -1253,14 +1191,11 @@ POST /api/sessions/:sessionId/webhooks
**Response (201 Created):**
```json
{
- "success": true,
- "data": {
- "id": "wh_xyz789",
- "url": "https://your-server.com/webhook",
- "events": ["message.received", "message.sent"],
- "active": true,
- "createdAt": "2025-02-02T10:00:00.000Z"
- }
+ "id": "wh_xyz789",
+ "url": "https://your-server.com/webhook",
+ "events": ["message.received", "message.sent"],
+ "active": true,
+ "createdAt": "2025-02-02T10:00:00.000Z"
}
```
@@ -1298,30 +1233,23 @@ GET /health
}
```
-The basic endpoint is public. The detailed endpoint requires an API key.
+The basic endpoint is public.
-#### Detailed Health Check
+#### Readiness / Liveness
```http
-GET /health/detailed
+GET /api/health/ready
+GET /api/health/live
```
+`/api/health/ready` reports whether the service is ready to receive traffic;
+`/api/health/live` reports process liveness. (There is no `/health/detailed` route.)
+
**Response (200 OK):**
```json
{
"status": "ok",
- "version": "0.1.0",
- "uptime": 3600,
- "timestamp": "2026-02-02T10:30:00Z",
- "checks": {
- "database": "ok",
- "redis": "ok",
- "sessions": {
- "total": 5,
- "connected": 4,
- "disconnected": 1
- }
- }
+ "details": { "database": { "status": "up" } }
}
```
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index a291631ca..002d801a9 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -1,5 +1,12 @@
# 10 - DevOps & Infrastructure
+> **⚠️ Conceptual reference (M9).** Some examples here predate the shipped runtime and may not
+> match it exactly. The **authoritative** sources are the repo's `Dockerfile`, `docker-compose.yml`
+> (Docker socket-proxy threat model, gosu non-root drop, loopback-bound datastores, container
+> hardening), and `.env.example` (canonical env var names). Where this doc and those disagree,
+> the files win. In particular: the API master key env is `API_MASTER_KEY`, datastores have no
+> default credentials, and production migrations use `npm run migration:run:prod`.
+
## 10.1 Infrastructure Overview
```mermaid
@@ -105,7 +112,9 @@ services:
- NODE_ENV=development
- DATABASE_URL=postgresql://openwa:openwa@postgres:5432/openwa
- REDIS_URL=redis://redis:6379
- - API_KEY_MASTER=dev-master-key
+ # The env var is API_MASTER_KEY (not API_KEY_MASTER); never hardcode a key — set a
+ # strong secret. Production refuses to boot with a placeholder/default (M9/M16).
+ - API_MASTER_KEY=
volumes:
- ./:/app
- /app/node_modules
diff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.md
index 842cafe3e..d5cdb9003 100644
--- a/docs/11-operational-runbooks.md
+++ b/docs/11-operational-runbooks.md
@@ -414,7 +414,9 @@ docker compose down
docker compose pull
# 7. Run database migrations (if any)
-docker compose run --rm openwa npm run migration:run
+# Use migration:run:prod in the production image — `migration:run` needs ts-node + the TS
+# source, both stripped from the prod image by `npm ci --omit=dev` (M13).
+docker compose run --rm openwa npm run migration:run:prod
# 8. Start services
docker compose up -d
@@ -456,15 +458,14 @@ docker compose down
# 2. Revert docker-compose.yml to previous version
-# 3. Restore database
-cp $BACKUP_DIR/openwa.db ./data/
+# 3. Restore from the pre-upgrade backup (both DBs + sessions)
+./scripts/restore.sh "$BACKUP_FILE"
# 4. Start with old version
docker compose up -d
-# 5. Verify rollback
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/health/detailed | jq '.version'
+# 5. Verify rollback (note: readiness is at /api/health/ready)
+curl -H "X-API-Key: $API_KEY" http://localhost:2785/api/health
```
---
@@ -481,78 +482,37 @@ curl -H "X-API-Key: $API_KEY" \
**Steps:**
+Use the repo's `scripts/backup.sh`. It captures **everything** required to restore a
+working install — critically including `main.sqlite`, the auth (API-key) + audit DB,
+which an earlier version of this runbook omitted (a "successful" backup that could not
+restore authentication):
+
```bash
-#!/bin/bash
-# scripts/backup.sh
-
-set -e
-
-DATE=$(date +%Y%m%d-%H%M%S)
-BACKUP_DIR="/backups/openwa/$DATE"
-RETENTION_DAYS=30
-
-echo "Starting backup to $BACKUP_DIR"
-
-# Create backup directory
-mkdir -p "$BACKUP_DIR"
-
-# 1. Backup database
-if [ "$DATABASE_ADAPTER" = "postgresql" ]; then
- echo "Backing up PostgreSQL..."
- docker compose exec -T postgres pg_dump -U postgres openwa > "$BACKUP_DIR/database.sql"
-else
- echo "Backing up SQLite..."
- # Use SQLite online backup
- docker compose exec openwa sqlite3 /app/data/openwa.db ".backup /tmp/backup.db"
- docker cp openwa:/tmp/backup.db "$BACKUP_DIR/openwa.db"
-fi
-
-# 2. Backup auth sessions
-echo "Backing up auth sessions..."
-cp -r ./data/.wwebjs_auth "$BACKUP_DIR/"
-
-# 3. Backup configuration
-echo "Backing up configuration..."
-cp .env "$BACKUP_DIR/"
-cp docker-compose.yml "$BACKUP_DIR/"
-
-# 4. Backup media (optional, can be large)
-if [ "$BACKUP_MEDIA" = "true" ]; then
- echo "Backing up media..."
- cp -r ./data/media "$BACKUP_DIR/"
-fi
-
-# 5. Create archive
-echo "Creating archive..."
-tar -czf "$BACKUP_DIR.tar.gz" -C "/backups/openwa" "$DATE"
-rm -rf "$BACKUP_DIR"
-
-# 6. Cleanup old backups
-echo "Cleaning up old backups..."
-find /backups/openwa -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete
-
-# 7. Verify backup
-echo "Verifying backup..."
-tar -tzf "$BACKUP_DIR.tar.gz" > /dev/null
-
-echo "Backup completed: $BACKUP_DIR.tar.gz"
-echo "Size: $(du -h "$BACKUP_DIR.tar.gz" | cut -f1)"
+# scripts/backup.sh captures:
+# - main.sqlite — auth (API keys) + audit log (ALWAYS SQLite)
+# - openwa.sqlite — user data (or a pg_dump when DATABASE_TYPE=postgres)
+# - sessions/ — WhatsApp LocalAuth session data
+# - media/ — local media (skipped automatically when STORAGE_TYPE=s3)
+
+# Run from the repo root (operates on the data dir, default ./data):
+./scripts/backup.sh
+
+# Customize via environment:
+OPENWA_DATA_DIR=/srv/openwa/data \
+ BACKUP_DIR=/backups/openwa \
+ DATABASE_TYPE=postgres DATABASE_URL=postgres://user:pass@host:5432/openwa \
+ ./scripts/backup.sh
```
+> The data directory is a Docker **named volume** (`openwa-data`) in the production
+> compose. Run the script where that volume is mounted — e.g. point `OPENWA_DATA_DIR`
+> at the volume's mountpoint, or run it inside a container with `/app/data` mounted.
+
**Verification:**
```bash
-# List backup contents
-tar -tzf $BACKUP_DIR.tar.gz
-
-# Check backup size
-du -h $BACKUP_DIR.tar.gz
-
-# Test restore to temp location
-mkdir /tmp/restore-test
-tar -xzf $BACKUP_DIR.tar.gz -C /tmp/restore-test
-ls -la /tmp/restore-test/
-rm -rf /tmp/restore-test
+# The archive MUST contain main.sqlite (auth/audit), the data store, and sessions/
+tar -tzf ./backups/openwa-backup-*.tar.gz
```
---
@@ -570,75 +530,30 @@ rm -rf /tmp/restore-test
**Steps:**
-```bash
-#!/bin/bash
-# scripts/restore.sh
-
-BACKUP_FILE=$1
+Use the repo's `scripts/restore.sh`. It restores **both** databases (`main.sqlite`
+auth/audit + the data store) and the WhatsApp `sessions/`, and snapshots the current
+data dir first so a bad restore can be undone:
-if [ -z "$BACKUP_FILE" ]; then
- echo "Usage: ./restore.sh <backup-file.tar.gz>"
- exit 1
-fi
-
-echo "WARNING: This will overwrite current data!"
-read -p "Continue? (yes/no): " CONFIRM
-if [ "$CONFIRM" != "yes" ]; then
- exit 0
-fi
-
-set -e
-
-# 1. Stop services
-echo "Stopping services..."
+```bash
+# 1. Stop the app (so files are quiescent)
docker compose down
-# 2. Extract backup
-echo "Extracting backup..."
-RESTORE_DIR="/tmp/restore-$(date +%s)"
-mkdir -p "$RESTORE_DIR"
-tar -xzf "$BACKUP_FILE" -C "$RESTORE_DIR"
-
-# 3. Restore database
-if [ -f "$RESTORE_DIR/*/database.sql" ]; then
- echo "Restoring PostgreSQL..."
- docker compose up -d postgres
- sleep 10
- docker compose exec -T postgres psql -U postgres openwa < "$RESTORE_DIR"/*/database.sql
-elif [ -f "$RESTORE_DIR/*/openwa.db" ]; then
- echo "Restoring SQLite..."
- cp "$RESTORE_DIR"/*/openwa.db ./data/
-fi
-
-# 4. Restore auth sessions
-echo "Restoring auth sessions..."
-rm -rf ./data/.wwebjs_auth
-cp -r "$RESTORE_DIR"/*/.wwebjs_auth ./data/
-
-# 5. Restore configuration (optional - review first)
-echo "Configuration files in backup:"
-ls -la "$RESTORE_DIR"/*/.env "$RESTORE_DIR"/*/docker-compose.yml
-read -p "Restore configuration? (yes/no): " RESTORE_CONFIG
-if [ "$RESTORE_CONFIG" = "yes" ]; then
- cp "$RESTORE_DIR"/*/.env .
- cp "$RESTORE_DIR"/*/docker-compose.yml .
-fi
-
-# 6. Start services
-echo "Starting services..."
-docker compose up -d
+# 2. Restore from an archive produced by scripts/backup.sh
+# (operates on the data dir, default ./data; override with OPENWA_DATA_DIR)
+./scripts/restore.sh ./backups/openwa-backup-<timestamp>.tar.gz
-# 7. Wait for health
-echo "Waiting for health check..."
-sleep 30
-curl http://localhost:2785/health
-
-# 8. Cleanup
-rm -rf "$RESTORE_DIR"
+# 3. (Postgres only) the archive contains database.sql — import it manually:
+# psql "$DATABASE_URL" < ./data/database.sql
-echo "Restore completed!"
+# 4. Start the app and CONFIRM an existing API key still authenticates
+docker compose up -d
+curl -s -H "X-API-Key: <an-existing-key>" http://localhost:2785/api/auth/validate
```
+> Restoring `main.sqlite` is the whole point: it carries the API keys and audit log.
+> If a restore leaves you unable to authenticate, the backup that produced the archive
+> did not capture `main.sqlite` — re-run `scripts/backup.sh` (which always does).
+
**Verification:**
```bash
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index 5c786f665..e043b495b 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -1,6 +1,22 @@
# 13 - Horizontal Scaling Guide
-This guide explains how to deploy OpenWA in a horizontally scaled environment for high availability and increased capacity.
+> ## ⚠️ DESIGN REFERENCE ONLY — NOT IMPLEMENTED
+>
+> **OpenWA is currently a single-process, single-instance application.** Live WhatsApp
+> engine state (browser + WebSocket + reconnect/error state) lives in an in-memory `Map`
+> in `SessionService`; there is **no** DB-backed session registry, **no** node-claim/lease,
+> and **no** Socket.IO Redis adapter (findings H1/H11).
+>
+> **Supported topology:** exactly **one** API instance per session-data volume. Running
+> multiple replicas against a shared session volume — as the multi-node examples below
+> describe — will cause **two browsers to write the same WhatsApp LocalAuth directory and
+> corrupt the session** (forced logout / ban), especially with `AUTO_START_SESSIONS=true`.
+>
+> Everything in this guide (session-claim, node affinity, `replicas: 3`) is a **future
+> design sketch**, retained for planning. Until it is implemented, deploy with
+> **`replicas: 1`** for the OpenWA API service.
+
+This guide explains a *proposed* design for deploying OpenWA in a horizontally scaled environment for high availability and increased capacity.
## 13.1 Architecture Overview
@@ -78,7 +94,7 @@ function getNodeForSession(sessionId: string, nodes: string[]): string {
### Strategy 3: Session Claim
-Each node "claims" sessions on startup and releases them on shutdown.
+Each node "claims" sessions on startup and releases them on shutdown. **(Not implemented — no claim/lease logic exists in code; this is the design target.)**
## 13.3 Docker Swarm Deployment
@@ -91,7 +107,7 @@ services:
openwa:
image: ghcr.io/rmyndharis/openwa:0.2.0
deploy:
- replicas: 3
+ replicas: 1 # MUST stay 1 until session-claim is implemented — multiple replicas on one session volume corrupt WhatsApp auth (H1/H11)
update_config:
parallelism: 1
delay: 30s
@@ -250,7 +266,7 @@ metadata:
namespace: openwa
spec:
serviceName: openwa
- replicas: 3
+ replicas: 1 # MUST stay 1 until session-claim is implemented (H1/H11) — see the warning at the top of this guide
selector:
matchLabels:
app: openwa
diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.md
index f84cb8c5e..0031bb928 100644
--- a/docs/14-migration-guide.md
+++ b/docs/14-migration-guide.md
@@ -750,7 +750,7 @@ docker run --rm \
-v $(pwd)/data:/app/data \
-e DATABASE_URL=sqlite:///app/data/openwa.db \
ghcr.io/rmyndharis/openwa:0.2.0 \
- npm run migration:run
+ npm run migration:run:prod # the prod image strips ts-node/TS source — use :prod (M13)
# 4. Migrate configuration
echo "⚙️ Migrating configuration..."
diff --git a/docs/15-project-roadmap.md b/docs/15-project-roadmap.md
index 2410bcc40..a10760be0 100644
--- a/docs/15-project-roadmap.md
+++ b/docs/15-project-roadmap.md
@@ -24,13 +24,16 @@ timeline
: Community tools
: Stable release
- section v0.2.0 - Developer Tools
- Q2 2026 : JavaScript/Node.js SDK
- : Python SDK
+ section v0.2.0 - i18n, Real-time & Hardening (Released)
+ Jun 2026 : Multi-locale dashboard (i18n)
+ : Real-time Chats view
+ : Webhook delivery-state & templates
+ : Security & container hardening
+
+ section v0.3.0 - SDK & Observability
+ Q3 2026 : JavaScript/Node.js & Python SDK
: Docs Site
-
- section v0.3.0 - Observability
- Q3 2026 : Prometheus Metrics
+ : Prometheus Metrics
: Grafana Dashboard
section v1.0.0 - Enterprise
@@ -40,14 +43,17 @@ timeline
### Release Summary
-| Version | Focus | Status |
-| ------- | --------------------------- | ----------- |
-| v0.0.1 | MVP - Basic API | ✅ Released |
-| v0.0.2 | Production Ready | ✅ Released |
-| v0.1.0 | Initial Stable Release | ✅ Released |
-| v0.2.0 | SDK & Developer Tools | 📋 Planned |
-| v0.3.0 | Performance & Observability | 📋 Planned |
-| v1.0.0 | Enterprise Ready | 📋 Planned |
+| Version | Focus | Status |
+| ------- | -------------------------------------- | ----------- |
+| v0.0.1 | MVP - Basic API | ✅ Released |
+| v0.0.2 | Production Ready | ✅ Released |
+| v0.1.0 | Initial Stable Release | ✅ Released |
+| v0.1.7 | Maintenance & fixes | ✅ Released |
+| v0.1.8 | Maintenance & fixes | ✅ Released |
+| v0.2.0 | i18n, Real-time Chats & Hardening | ✅ Released |
+| v0.2.1 | Dashboard split-origin fix | ✅ Released |
+| v0.3.0 | SDK, Developer Tools & Observability | 📋 Planned |
+| v1.0.0 | Enterprise Ready | 📋 Planned |
### Risk Buffer
@@ -82,7 +88,8 @@ Examples:
0.0.2 - Production Ready (Multi-session, Dashboard)
0.1.0 - Initial Stable Release (Full features)
0.1.1 - Bug fix for QR timeout
-0.2.0 - SDK & Developer Tools
+0.2.0 - i18n, Real-time Chats, Webhook Delivery-state & Hardening
+0.3.0 - SDK & Developer Tools
1.0.0 - Enterprise Ready
2.0.0 - Breaking API changes
```
@@ -448,9 +455,11 @@ v0.1.0 Release Package:
└── Release automation
```
-## 15.6 Future Roadmap (v0.2.0+)
+## 15.6 Future Roadmap (v0.3.0+)
> **Note:** Version 0.1.0 is the initial stable release including all features from Phases 1-3.
+> Versions 0.1.7, 0.1.8, 0.2.0, and 0.2.1 have since shipped (see the CHANGELOG); v0.3.0
+> onward is forward-looking.
```mermaid
flowchart LR
@@ -462,13 +471,13 @@ flowchart LR
V002[v0.0.2 - Production Ready<br/>Multi-session & Dashboard]
end
- subgraph Current["✅ Current Release"]
+ subgraph Stable["✅ Released"]
V010[v0.1.0 - Initial Stable Release<br/>All Core Features]
+ V020[v0.2.0 - i18n, Real-time Chats,<br/>Webhook Delivery-state & Hardening]
end
subgraph v0.x["v0.x Series - Enhancements"]
- V020[v0.2.0 - SDK & Developer Tools]
- V030[v0.3.0 - Performance & Observability]
+ V030[v0.3.0 - SDK, Developer Tools & Observability]
end
subgraph v1.x["v1.x Series - Enterprise"]
@@ -476,10 +485,21 @@ flowchart LR
V11[v1.1.0 - Multi-engine Support]
end
- Phase1 --> Phase2 --> Current --> v0.x --> v1.x
+ Phase1 --> Phase2 --> Stable --> v0.x --> v1.x
```
-### v0.2.0 - SDK & Developer Tools
+### v0.2.0 - i18n, Real-time Chats, Webhook Delivery-state & Hardening (Released)
+
+| Feature | Priority | Status |
+| -------------------------------- | -------- | ------ |
+| Multi-locale dashboard (i18n) | P1 | ✅ |
+| Real-time Chats view (WebSocket) | P1 | ✅ |
+| Message templates | P1 | ✅ |
+| Webhook delivery-state tracking | P1 | ✅ |
+| Security & API surface hardening | P0 | ✅ |
+| Container / Podman hardening | P1 | ✅ |
+
+### v0.3.0 - SDK, Developer Tools & Observability
| Feature | Priority | Description |
| ---------------------- | -------- | ------------------------------- |
@@ -490,7 +510,7 @@ flowchart LR
| Video Tutorials | P2 | Getting started video series |
| Example Projects | P1 | Real-world integration examples |
-### v0.3.0 - Performance & Observability
+**Performance & Observability**
| Feature | Priority | Description |
| ---------------------- | -------- | -------------------------------- |
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index c61e1a5fe..8081789ab 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -49,9 +49,9 @@ flowchart TB
end
```
-1. **Isolation** - Plugins cannot compromise the core system
+1. **Isolation** - _Planned, NOT enforced._ Plugins currently run in-process with full Node privileges (`require()`), guarded only by a path-containment check. **Load only trusted plugins** until sandboxed (vm2/worker) execution ships.
2. **Extensibility** - Easy to add new features
-3. **Safety** - Permission-based access control
+3. **Safety** - Permission-based access control (planned; not yet enforced)
4. **Performance** - Lazy loading, minimal overhead
## 19.2 Plugin Types
diff --git a/docs/README.md b/docs/README.md
index be7c52304..002cfde40 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -16,7 +16,7 @@
</p>
<p align="center">
- <img src="https://img.shields.io/badge/version-0.2.1-blue.svg" alt="Version"/>
+ <img src="https://img.shields.io/badge/version-0.2.2-blue.svg" alt="Version"/>
<img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License"/>
<img src="https://img.shields.io/badge/node-22_LTS-brightgreen.svg" alt="Node"/>
<img src="https://img.shields.io/badge/NestJS-11.x-red.svg" alt="NestJS"/>
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 4e9f8271c..e97dd8062 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -32,4 +32,36 @@ export default tseslint.config(
"prettier/prettier": ["error", { endOfLine: "auto" }],
},
},
+ {
+ // Architecture guard (M1): HTTP controllers must go through a per-capability service and
+ // never reach for the raw WhatsApp engine. This keeps the "session not started" guard,
+ // error mapping, and business rules behind the service boundary instead of leaking into
+ // controllers. `.getEngine(` (not `.getEngines()`) and the `IWhatsAppEngine` type are banned.
+ files: ['**/*.controller.ts'],
+ rules: {
+ 'no-restricted-syntax': [
+ 'error',
+ {
+ selector: "CallExpression[callee.property.name='getEngine']",
+ message:
+ 'Controllers must not call getEngine(). Add a method to the capability service (e.g. GroupService) and call that instead (M1).',
+ },
+ ],
+ 'no-restricted-imports': [
+ 'error',
+ {
+ patterns: [
+ {
+ // Only the engine abstraction itself is banned — data shapes (e.g. ChatSummary)
+ // that happen to live in the same file remain importable by controllers.
+ group: ['**/engine/interfaces/whatsapp-engine.interface'],
+ importNames: ['IWhatsAppEngine'],
+ message:
+ 'Controllers must not import IWhatsAppEngine. Keep engine types behind a capability service (M1).',
+ },
+ ],
+ },
+ ],
+ },
+ },
);
diff --git a/package-lock.json b/package-lock.json
index 0a15a5117..9f624cb74 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,31 +1,31 @@
{
"name": "openwa",
- "version": "0.2.1",
+ "version": "0.2.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openwa",
- "version": "0.2.1",
+ "version": "0.2.2",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
- "@aws-sdk/client-s3": "^3.1063.0",
- "@bull-board/api": "^7.2.1",
- "@bull-board/express": "^7.2.1",
- "@bull-board/nestjs": "^7.2.1",
+ "@aws-sdk/client-s3": "^3.1068.0",
+ "@bull-board/api": "^8.0.0",
+ "@bull-board/express": "^8.0.0",
+ "@bull-board/nestjs": "^8.0.0",
"@nestjs-modules/ioredis": "^2.0.2",
"@nestjs/bullmq": "^11.0.4",
- "@nestjs/common": "^11.1.25",
+ "@nestjs/common": "^11.1.27",
"@nestjs/config": "^4.0.2",
- "@nestjs/core": "^11.1.25",
- "@nestjs/platform-express": "^11.1.25",
- "@nestjs/platform-socket.io": "^11.1.25",
+ "@nestjs/core": "^11.1.27",
+ "@nestjs/platform-express": "^11.1.27",
+ "@nestjs/platform-socket.io": "^11.1.27",
"@nestjs/swagger": "^11.4.4",
"@nestjs/throttler": "^6.5.0",
"@nestjs/typeorm": "^11.0.0",
"archiver": "^8.0.0",
- "bullmq": "^5.78.0",
+ "bullmq": "^5.78.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"dockerode": "^5.0.0",
@@ -45,25 +45,25 @@
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^10.0.1",
- "@nestjs/cli": "^11.0.22",
+ "@nestjs/cli": "^11.0.23",
"@nestjs/schematics": "^11.0.0",
- "@nestjs/testing": "^11.1.25",
- "@types/archiver": "^7.0.0",
+ "@nestjs/testing": "^11.1.27",
+ "@types/archiver": "^8.0.0",
"@types/dockerode": "^4.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
- "@types/node": "^25.9.2",
+ "@types/node": "^25.9.3",
"@types/qrcode": "^1.5.5",
"@types/supertest": "^6.0.2",
"@types/tar-stream": "^3.1.4",
"@types/uuid": "^11.0.0",
"concurrently": "^10.0.3",
- "eslint": "^10.4.1",
+ "eslint": "^10.5.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.5.6",
"globals": "^17.6.0",
"jest": "^30.4.2",
- "prettier": "^3.4.2",
+ "prettier": "^3.8.4",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.4.11",
@@ -71,7 +71,7 @@
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
- "typescript-eslint": "^8.60.1"
+ "typescript-eslint": "^8.61.0"
}
},
"node_modules/@angular-devkit/core": {
@@ -388,16 +388,16 @@
}
},
"node_modules/@aws-sdk/checksums": {
- "version": "3.1000.2",
- "resolved": "https://registry.npmjs.org/@aws-sdk/checksums/-/checksums-3.1000.2.tgz",
- "integrity": "sha512-PIha+kauTbp6IRmOpYktPTrlfrrSqDVixvhO/EUOFOf62DPX81CaJoHJreuA1m9HYpSKyXf99BKjU1dvJPeUfw==",
+ "version": "3.1000.5",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/checksums/-/checksums-3.1000.5.tgz",
+ "integrity": "sha512-zOXUUnilC6lgCsQtp77p/QNPmRlTES9Xi6tlDwbR6kfC/kz5PCzZckgHWm5z+8DskdwuMAbFDq61x3zr10GEEQ==",
"license": "Apache-2.0",
"dependencies": {
"@aws-crypto/crc32": "5.2.0",
"@aws-crypto/crc32c": "5.2.0",
"@aws-crypto/util": "5.2.0",
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/types": "^4.14.3",
"tslib": "^2.6.2"
@@ -407,20 +407,20 @@
}
},
"node_modules/@aws-sdk/client-s3": {
- "version": "3.1063.0",
- "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.1063.0.tgz",
- "integrity": "sha512-ETn+vvmZVK1MmOZwVBXmWANpmD5iTbzojIqyEIoZ86qo+8oWy35S8QyQNE/ZDI+WHgMU1dS+VSYbpRl1QkEySg==",
+ "version": "3.1068.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.1068.0.tgz",
+ "integrity": "sha512-lFgaIpxZvloNbJvQ337YPdMXhzI2zJdDw13nATVGnkAGNoNPx4ksD84AQAcuW75hsaaMaIuNmXU9sSx6+FTirA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-crypto/sha1-browser": "5.2.0",
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/credential-provider-node": "^3.972.52",
- "@aws-sdk/middleware-flexible-checksums": "^3.974.27",
- "@aws-sdk/middleware-sdk-s3": "^3.972.48",
- "@aws-sdk/signature-v4-multi-region": "^3.996.32",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/credential-provider-node": "^3.972.55",
+ "@aws-sdk/middleware-flexible-checksums": "^3.974.30",
+ "@aws-sdk/middleware-sdk-s3": "^3.972.51",
+ "@aws-sdk/signature-v4-multi-region": "^3.996.34",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/fetch-http-handler": "^5.4.6",
"@smithy/node-http-handler": "^4.7.6",
@@ -432,13 +432,13 @@
}
},
"node_modules/@aws-sdk/core": {
- "version": "3.974.18",
- "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.974.18.tgz",
- "integrity": "sha512-JDYCPI0j7zGrzXTDFsLB346cxss7J/AxH7+O0MzWlqppJBEyB9Qe6TQXRL6iwLUo/xZkNv9KFmBL2hqElmwW0g==",
+ "version": "3.974.20",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.974.20.tgz",
+ "integrity": "sha512-7sDi2B2N3mc3nf1nz6FyEx/FCrJ1N1QnBmraHHQNabFaeAh2IaOOLml48/rHOD1bICHgTRkbBgNTvUzEr5Z35g==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/types": "^3.973.11",
- "@aws-sdk/xml-builder": "^3.972.28",
+ "@aws-sdk/types": "^3.973.12",
+ "@aws-sdk/xml-builder": "^3.972.29",
"@aws/lambda-invoke-store": "^0.2.2",
"@smithy/core": "^3.24.6",
"@smithy/signature-v4": "^5.4.6",
@@ -451,13 +451,13 @@
}
},
"node_modules/@aws-sdk/credential-provider-env": {
- "version": "3.972.44",
- "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.44.tgz",
- "integrity": "sha512-3hKJVrZ7bqXzDAXCQp+OaQ1ASN+vWstaNuEH418wQVl//cRZhqhfR9Bjk1qIWmgUGe8/D3gdO73PgidRj378EQ==",
+ "version": "3.972.46",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.46.tgz",
+ "integrity": "sha512-+GPXVS2srMOlH74S+SmC1gVuP2TvUZ0siuC0onKO93q+udP+M72dmY8wJfVQ5CX9z/9X5A1HHwz5yRIGBtskvQ==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/types": "^4.14.3",
"tslib": "^2.6.2"
@@ -467,13 +467,13 @@
}
},
"node_modules/@aws-sdk/credential-provider-http": {
- "version": "3.972.46",
- "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.46.tgz",
- "integrity": "sha512-VhwC9pGAZHhiQ2xSViyOPDFqvr9aRxGCAXZtADsUhU3R65nad7y//CwynE6mQnWNR+suRlqE79W36IVayL+m1g==",
+ "version": "3.972.48",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.48.tgz",
+ "integrity": "sha512-fA5loSdlocacRxyUXtpoHSMuk5rsIKRDzQYVMnMxjcmFeZshaJlJ8lymy/hYKji6sne/UmNGj5pxuEs6kq/Qcg==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/fetch-http-handler": "^5.4.6",
"@smithy/node-http-handler": "^4.7.6",
@@ -485,20 +485,20 @@
}
},
"node_modules/@aws-sdk/credential-provider-ini": {
- "version": "3.972.50",
- "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.972.50.tgz",
- "integrity": "sha512-09Xi6ovxiK42+De/qBGF71sT5F2bWgYM+1fFyDwSOpy1xpsQ5R/naIu7MVDpH6Dic36QNc8dAv4KADtMGK2JYg==",
+ "version": "3.972.53",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.972.53.tgz",
+ "integrity": "sha512-ZfdhIOR41q8TcWEnUac+gCOb+O2LBWdHLmjedXpXz4IEFW2ppNuFcm6p0sMTavpM+zD5TYfpH5Gp7guRyqSgsQ==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/credential-provider-env": "^3.972.44",
- "@aws-sdk/credential-provider-http": "^3.972.46",
- "@aws-sdk/credential-provider-login": "^3.972.49",
- "@aws-sdk/credential-provider-process": "^3.972.44",
- "@aws-sdk/credential-provider-sso": "^3.972.49",
- "@aws-sdk/credential-provider-web-identity": "^3.972.49",
- "@aws-sdk/nested-clients": "^3.997.17",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/credential-provider-env": "^3.972.46",
+ "@aws-sdk/credential-provider-http": "^3.972.48",
+ "@aws-sdk/credential-provider-login": "^3.972.52",
+ "@aws-sdk/credential-provider-process": "^3.972.46",
+ "@aws-sdk/credential-provider-sso": "^3.972.52",
+ "@aws-sdk/credential-provider-web-identity": "^3.972.52",
+ "@aws-sdk/nested-clients": "^3.997.20",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/credential-provider-imds": "^4.3.7",
"@smithy/types": "^4.14.3",
@@ -509,14 +509,14 @@
}
},
"node_modules/@aws-sdk/credential-provider-login": {
- "version": "3.972.49",
- "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.49.tgz",
- "integrity": "sha512-EfJF/1Fh9mI4pZyoheU2RY9xUhTcugIZNkD63+orXMkYj/QXacJNbKVDUK90Yv5hE+aX+rt9J/EZ9Qr3vKOa7g==",
+ "version": "3.972.52",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.52.tgz",
+ "integrity": "sha512-9hu2oR0qH7Fst5Tzdx+UWxm+w5zCXtErTLtOOW5hwwQc170CLwOeniRxyFY6s9mHfGEfC5zFukNBdKBwJR8mhQ==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/nested-clients": "^3.997.17",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/nested-clients": "^3.997.20",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/types": "^4.14.3",
"tslib": "^2.6.2"
@@ -526,18 +526,18 @@
}
},
"node_modules/@aws-sdk/credential-provider-node": {
- "version": "3.972.52",
- "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.52.tgz",
- "integrity": "sha512-7QX+PbyiWBEOVipJq8Nke/TqXT6lAPLE7fvTaopa39/IVWuLfS+Fzdy71sZJONf/mLGgmtj6aU17+REw3+aRrw==",
+ "version": "3.972.55",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.55.tgz",
+ "integrity": "sha512-zMGLa/dhESVqmCD7mmIFFKSwSFrJGScvCXcjvBZEVOOMauFS5JRQvLTMukFpMEFWiV6dTAlsen2ATDBulLPtbg==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/credential-provider-env": "^3.972.44",
- "@aws-sdk/credential-provider-http": "^3.972.46",
- "@aws-sdk/credential-provider-ini": "^3.972.50",
- "@aws-sdk/credential-provider-process": "^3.972.44",
- "@aws-sdk/credential-provider-sso": "^3.972.49",
- "@aws-sdk/credential-provider-web-identity": "^3.972.49",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/credential-provider-env": "^3.972.46",
+ "@aws-sdk/credential-provider-http": "^3.972.48",
+ "@aws-sdk/credential-provider-ini": "^3.972.53",
+ "@aws-sdk/credential-provider-process": "^3.972.46",
+ "@aws-sdk/credential-provider-sso": "^3.972.52",
+ "@aws-sdk/credential-provider-web-identity": "^3.972.52",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/credential-provider-imds": "^4.3.7",
"@smithy/types": "^4.14.3",
@@ -548,13 +548,13 @@
}
},
"node_modules/@aws-sdk/credential-provider-process": {
- "version": "3.972.44",
- "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.44.tgz",
- "integrity": "sha512-V+UUhZpRP7QDRhi+qgBDisM9tUBnYmMje8Bk77A6MZsfeGeGdMsQXmaHP1CDYFcept0o/Rz5g2Y0TMeVlG9dzg==",
+ "version": "3.972.46",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.46.tgz",
+ "integrity": "sha512-VUoNFBIjWrUN8NbFiQiuxQEgFjvziAlBRPK+ddh27aj65gk0BYu6bLZnrdrNZwpW6vAihtSUtEMQ1PUJ32QRPA==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/types": "^4.14.3",
"tslib": "^2.6.2"
@@ -564,15 +564,15 @@
}
},
"node_modules/@aws-sdk/credential-provider-sso": {
- "version": "3.972.49",
- "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.972.49.tgz",
- "integrity": "sha512-9QqOYGuh5tZ76OzaT68kwI78AH+5lS/uZGGvkfxb3fc8FzRrIz2jOufNTliEBEeSAwmgK2rWLNsK+IB3zbtNPA==",
+ "version": "3.972.52",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.972.52.tgz",
+ "integrity": "sha512-nb2/n4o/HQf+FVpVbZe9vCTFngmuDoIsltMgLAtjixaKzvzhB4J8WSDFyWgnErgLHk55ctWH+I4PU+LIHhyffg==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/nested-clients": "^3.997.17",
- "@aws-sdk/token-providers": "3.1063.0",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/nested-clients": "^3.997.20",
+ "@aws-sdk/token-providers": "3.1066.0",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/types": "^4.14.3",
"tslib": "^2.6.2"
@@ -582,14 +582,14 @@
}
},
"node_modules/@aws-sdk/credential-provider-web-identity": {
- "version": "3.972.49",
- "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.49.tgz",
- "integrity": "sha512-IYx1lN38MnnPXv+NBLpuATu0cZakbZ321TAfjW+aVkw7HIJF38YnEwdeEO55MSl3pl7hIX1IvvnD6EmnAzmAJw==",
+ "version": "3.972.52",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.52.tgz",
+ "integrity": "sha512-lKj6aRSGbqLmpYmM24bY7a1Xmfcq2vkE3hv8CSPYfc1yCu0BPu/XEJ1L4Fm61MsU6ULLNSG8UGsffNoFUBjESA==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/nested-clients": "^3.997.17",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/nested-clients": "^3.997.20",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/types": "^4.14.3",
"tslib": "^2.6.2"
@@ -599,12 +599,12 @@
}
},
"node_modules/@aws-sdk/middleware-flexible-checksums": {
- "version": "3.974.27",
- "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-flexible-checksums/-/middleware-flexible-checksums-3.974.27.tgz",
- "integrity": "sha512-bZqezPLdllFC4VAeV/f+EIc/hz56ab3TD/+4zNCgOgmG5ZHAE5dMHrX1gtTwdcQXbPr3KR7x3zTC3zuCTE6+ng==",
+ "version": "3.974.30",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-flexible-checksums/-/middleware-flexible-checksums-3.974.30.tgz",
+ "integrity": "sha512-OaIhub+3yTgfFWPzKO8OzOZFIMUoJaiS5v67y3spQg7SoULGoMx4jKVBbE+uhnzkiZXQ+rEDS0RqrK4/aD1yJw==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/checksums": "^3.1000.2",
+ "@aws-sdk/checksums": "^3.1000.5",
"tslib": "^2.6.2"
},
"engines": {
@@ -612,14 +612,14 @@
}
},
"node_modules/@aws-sdk/middleware-sdk-s3": {
- "version": "3.972.48",
- "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.972.48.tgz",
- "integrity": "sha512-MRTqx8wD/T3REt6LTT3/yN8rrp6+xIHrbUekkDYJTYWVch70mwtdJBovR4qKJz1jIPlbN+9R/Sn6R04BfsglzA==",
+ "version": "3.972.51",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.972.51.tgz",
+ "integrity": "sha512-keQgcIUTcHL0Qn7guhsuLaxQU36r9norCrxgaPH4DNCwon4TPtXdI/UdYuycl9vj3Dlwc3YR1dfL3U+6iIwJ6w==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/signature-v4-multi-region": "^3.996.32",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/signature-v4-multi-region": "^3.996.34",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/types": "^4.14.3",
"tslib": "^2.6.2"
@@ -629,16 +629,16 @@
}
},
"node_modules/@aws-sdk/nested-clients": {
- "version": "3.997.17",
- "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.17.tgz",
- "integrity": "sha512-lDRgraoTfKRawUyc176Ow93mrNrOho/x+EoK4C+lKU+vKkHWhNhzvSMVAx0WEJUJoeQxxDN5ZdKMfiGEyNejig==",
+ "version": "3.997.20",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.20.tgz",
+ "integrity": "sha512-IYJuLpXp2DEILVQpQOy0PMpkftv0AHEOCn52o0atyOaumA0CdWQ3klPyXdViGYLbNpESsVFMVybvHUeZAuiGxA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/signature-v4-multi-region": "^3.996.32",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/signature-v4-multi-region": "^3.996.34",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/fetch-http-handler": "^5.4.6",
"@smithy/node-http-handler": "^4.7.6",
@@ -650,12 +650,12 @@
}
},
"node_modules/@aws-sdk/signature-v4-multi-region": {
- "version": "3.996.32",
- "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.32.tgz",
- "integrity": "sha512-llvApLcsWtmRFhG2wT3WIp1CmDeRaIYutqty1ZZXoMzK7TiJ6MOLOimk9eXUS8PwgG4ew4pa4QAbt0lfhn++1w==",
+ "version": "3.996.34",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.34.tgz",
+ "integrity": "sha512-mx1L5qlumSOt/nKM3BFaHE2HVkWwz0i4Bw0pyYO42FfX/FeLlo8YI6csC0gSPprEk6fTIqI+CZN9RwUwKd5krQ==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/signature-v4": "^5.4.6",
"@smithy/types": "^4.14.3",
"tslib": "^2.6.2"
@@ -665,14 +665,14 @@
}
},
"node_modules/@aws-sdk/token-providers": {
- "version": "3.1063.0",
- "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1063.0.tgz",
- "integrity": "sha512-nYDaWWdzjKiDP5xj8k4oUgcYd4WPgzfAOgdU5vJsaqH/07Dfvm7ffisHCFJ+NEl7kUC9JEIUxh0kznvenbo3NQ==",
+ "version": "3.1066.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1066.0.tgz",
+ "integrity": "sha512-UqEUJq7dqa44hneLDUcX7UJy95cg8YqEWyakRpvIPnrNS3Mq+UlQHgCDGu5pvwAPtlIW4qcYbvW6reG6++FyvA==",
"license": "Apache-2.0",
"dependencies": {
- "@aws-sdk/core": "^3.974.18",
- "@aws-sdk/nested-clients": "^3.997.17",
- "@aws-sdk/types": "^3.973.11",
+ "@aws-sdk/core": "^3.974.20",
+ "@aws-sdk/nested-clients": "^3.997.20",
+ "@aws-sdk/types": "^3.973.12",
"@smithy/core": "^3.24.6",
"@smithy/types": "^4.14.3",
"tslib": "^2.6.2"
@@ -682,9 +682,9 @@
}
},
"node_modules/@aws-sdk/types": {
- "version": "3.973.11",
- "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.973.11.tgz",
- "integrity": "sha512-YjS0qFuECClRh4qhEyW8XagW0fwEPBeZ1cfsW/gU73Kh/ExFILxbzxOfPCmzF/2DwEvhvsHYt0b0qnvStwKYrg==",
+ "version": "3.973.12",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.973.12.tgz",
+ "integrity": "sha512-43ajd1NF0RMgX5k0hxCNUyEdrtFUsb2aHT2QvpktSC/2Eyb2Jr/JPVqdp0XIoaHWikZJq5tNWSLO6kB5q2eMCA==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/types": "^4.14.3",
@@ -707,9 +707,9 @@
}
},
"node_modules/@aws-sdk/xml-builder": {
- "version": "3.972.28",
- "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.28.tgz",
- "integrity": "sha512-lI/l3c/vPvsxmspzV63NfS3x9q4CkMmdhJy4QiM+NThAufVkDvi/PZZQ6xETnICL0UD7jI808pY83gllf86RFg==",
+ "version": "3.972.29",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.29.tgz",
+ "integrity": "sha512-fk0niuGFxfi8yIJuMVM4mhwObkiQSuwZFj3tAPrLVx64Pk3BkrEIpqjzHKY4hKoEBUD6Jg/S74Zj9jy+5F3DnQ==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/types": "^4.14.3",
@@ -1261,37 +1261,37 @@
}
},
"node_modules/@bull-board/api": {
- "version": "7.2.1",
- "resolved": "https://registry.npmjs.org/@bull-board/api/-/api-7.2.1.tgz",
- "integrity": "sha512-ldRG4POJLHf6oDrbDA7AsbTKliBmV4eySlwdUAumiRDtfvtbRSdXGE4Md2uPDova1r/ck7ExEe1+pHEQAZElqw==",
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/@bull-board/api/-/api-8.0.0.tgz",
+ "integrity": "sha512-GYXJNJclgm9H5Tt/tmuNWfjyF2BuygMwl8xrRIfxxOTgcK4SB8zNUPveTcHGAOoKKtPDVotHNZCBRrFCcOAXMA==",
"license": "MIT",
"peer": true,
"dependencies": {
"redis-info": "^3.1.0"
},
"peerDependencies": {
- "@bull-board/ui": "7.2.1"
+ "@bull-board/ui": "8.0.0"
}
},
"node_modules/@bull-board/express": {
- "version": "7.2.1",
- "resolved": "https://registry.npmjs.org/@bull-board/express/-/express-7.2.1.tgz",
- "integrity": "sha512-tBr/xV5letzKYPRGRkilTQZmfoCoy3mCuUo4M2dDoDKOhbrF360mK5v9/rIcSgYSyI9c7BgEgrve80LhmexNxQ==",
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/@bull-board/express/-/express-8.0.0.tgz",
+ "integrity": "sha512-NYMzcJNSnQBhVuQuxUyGvJ5U6HymuDoDN+jAX17/CN7xjEhDEGeW5twICiv4ZzWjyAdHS0T9wVyFhL7aSwjRBg==",
"license": "MIT",
"dependencies": {
- "@bull-board/api": "7.2.1",
- "@bull-board/ui": "7.2.1",
+ "@bull-board/api": "8.0.0",
+ "@bull-board/ui": "8.0.0",
"ejs": "^6.0.1",
"express": "^5.2.1"
}
},
"node_modules/@bull-board/nestjs": {
- "version": "7.2.1",
- "resolved": "https://registry.npmjs.org/@bull-board/nestjs/-/nestjs-7.2.1.tgz",
- "integrity": "sha512-Uq2Z3+0ORgHJSw4TDV1kBrHdksRnK8CZdda63hrStduPnvKHPBxIZUGNfBN/vL08UqizpNkjFmNyNXiHOgf0LQ==",
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/@bull-board/nestjs/-/nestjs-8.0.0.tgz",
+ "integrity": "sha512-oi5aX0yBau05QD8XfRyDrjHaCU1IWGwU9UP4niTVtSWeyPrgJ1S1Zb2vEtG+A2sUs+zc5GVgjmXUszYCWTfitA==",
"license": "MIT",
"peerDependencies": {
- "@bull-board/api": "^7.2.1",
+ "@bull-board/api": "^8.0.0",
"@nestjs/bull-shared": "^10.0.0 || ^11.0.0",
"@nestjs/common": "^9.0.0 || ^10.0.0 || ^11.0.0",
"@nestjs/core": "^9.0.0 || ^10.0.0 || ^11.0.0",
@@ -1300,13 +1300,13 @@
}
},
"node_modules/@bull-board/ui": {
- "version": "7.2.1",
- "resolved": "https://registry.npmjs.org/@bull-board/ui/-/ui-7.2.1.tgz",
- "integrity": "sha512-O4ykrXrl2UJNHnhJrCvJxrw1ar+DlUBgyZUeZ8Ci+Ne5Wbq6rBv1gfpQH54/eu3IFbLso0S/kjc6WUGb2HPqZw==",
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/@bull-board/ui/-/ui-8.0.0.tgz",
+ "integrity": "sha512-X/F256CmpBj9oj+fK2wOzjygkhTtjgWnc3f/SxPiUs3rQFvgYCplJLEaURh13J+Tpq46/1drAxq4Ukt4e5LelA==",
"license": "MIT",
"peer": true,
"dependencies": {
- "@bull-board/api": "7.2.1"
+ "@bull-board/api": "8.0.0"
}
},
"node_modules/@colors/colors": {
@@ -2919,9 +2919,9 @@
}
},
"node_modules/@nestjs/cli": {
- "version": "11.0.22",
- "resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-11.0.22.tgz",
- "integrity": "sha512-KuMosDSsMM0qlfYiBBRbIvCavYh77kFXDJVXqvd2rJOuhsAS+sYaujXPl/KTIiVlS7WCUvcGeQl6Ek2nY17org==",
+ "version": "11.0.23",
+ "resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-11.0.23.tgz",
+ "integrity": "sha512-2V0Bf5jz0KXhUZk3eJi9GljIyqH04otwsE/mYLbqJR+X0iiYx+6bkNJ2Qz28uHNFj1cpHgimf9xDzHkqarie0g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -3045,9 +3045,9 @@
}
},
"node_modules/@nestjs/common": {
- "version": "11.1.25",
- "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.25.tgz",
- "integrity": "sha512-eObNI89zpPEHQWr9BxD5yQe6hcDjzT6sj/jng1tWBL4GXEgZzrVYOnFA4pzk1ZvDNHa3z7GD2Yy0Z06Ihv9y6g==",
+ "version": "11.1.27",
+ "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.27.tgz",
+ "integrity": "sha512-kEGSzqM2lWr4whh4Ubflw+oPZSEzxvRMu9WL+LveZploJWTjec5bBlCiRVlVzTPg2kIwBiLwWSvCCW7Wnin1gg==",
"license": "MIT",
"peer": true,
"dependencies": {
@@ -3092,9 +3092,9 @@
}
},
"node_modules/@nestjs/core": {
- "version": "11.1.25",
- "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.25.tgz",
- "integrity": "sha512-tkpoJlSB1CPGWHzEw3AyiUZhazngzhzKw14DbF9Rb5Ny50GP0zV6diTFkahob+HqzDDVjK/2DTt41OMFa4lK5w==",
+ "version": "11.1.27",
+ "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.27.tgz",
+ "integrity": "sha512-K6DX7hcqmZdeXkv7tsPakKBRCgqL19a4mtbX4FluY0hWtFdtPKp6lbe+lb8gWPfvLdbOWr/CPScn7BSjBX+Ecg==",
"license": "MIT",
"peer": true,
"dependencies": {
@@ -3152,9 +3152,9 @@
}
},
"node_modules/@nestjs/platform-express": {
- "version": "11.1.25",
- "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.25.tgz",
- "integrity": "sha512-a4f4WIGG8oCF4lwh7SlVOZXif0EwC4fsM/JZY5/X7OkHd8rp7Dxnx+sB2lwKAtnP6A29os/IPdH2Rll+wVJ6Qg==",
+ "version": "11.1.27",
+ "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.27.tgz",
+ "integrity": "sha512-0ZFhz6H6EdGh4xQVbUNwjoAwBuz73P7FvUAl67h9CTdMqQlJDaQYJApBv8pKfVZ1fGjMCbl0m9DcC6pXaZPWSQ==",
"license": "MIT",
"peer": true,
"dependencies": {
@@ -3174,9 +3174,9 @@
}
},
"node_modules/@nestjs/platform-socket.io": {
- "version": "11.1.25",
- "resolved": "https://registry.npmjs.org/@nestjs/platform-socket.io/-/platform-socket.io-11.1.25.tgz",
- "integrity": "sha512-MyiT4F5VexHVxw2YUbb3rE5a45q1jb1cfC4cChIZRxhVp2S/Pe3R7TIBliQedm+Ysr23L7EACOsCsPtZ/g+TDg==",
+ "version": "11.1.27",
+ "resolved": "https://registry.npmjs.org/@nestjs/platform-socket.io/-/platform-socket.io-11.1.27.tgz",
+ "integrity": "sha512-xgpLzaIDGOCC6xOAtHnRAz8sqieFgGxxu3MN5ID026Jt6oeL3efp29N5QHhPr7UlqBfy/Jd02uj0POkZq6Au3Q==",
"license": "MIT",
"peer": true,
"dependencies": {
@@ -3321,9 +3321,9 @@
}
},
"node_modules/@nestjs/testing": {
- "version": "11.1.25",
- "resolved": "https://registry.npmjs.org/@nestjs/testing/-/testing-11.1.25.tgz",
- "integrity": "sha512-rvTXbeT6e2IMMShT7aKtbjSE3i3nbS8hejszpjQd5IR1Sh674U/KJ8EioqyI01vcGDbph2fopdzRMsyaeZuyPg==",
+ "version": "11.1.27",
+ "resolved": "https://registry.npmjs.org/@nestjs/testing/-/testing-11.1.27.tgz",
+ "integrity": "sha512-I35po13UHZZeGenLWJ3QYwh77RsLau5RcFKWBZ4waVHeARpwjtC7v7n7lGh98swLQdGmZgTnbvKaZ0B5dsUIKA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -3411,9 +3411,9 @@
}
},
"node_modules/@nodable/entities": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.1.tgz",
- "integrity": "sha512-Pig3HxDIoMgjdEH8OCf/dkcTmLFjJRjWuq8jSnklu284/TKOPibSRERmOykiwmyXTtv61mP+44f3GMx0tLAyjg==",
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.2.0.tgz",
+ "integrity": "sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg==",
"funding": [
{
"type": "github",
@@ -3615,13 +3615,13 @@
}
},
"node_modules/@smithy/core": {
- "version": "3.24.6",
- "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.24.6.tgz",
- "integrity": "sha512-wBXDRup6UU97VKyaiRo8AssnfStPtG0oAAfpq/bC0a1YYau8pM86YB4kM6ccoVi1mS8l/UHbn9oDM+7uozr/ug==",
+ "version": "3.24.7",
+ "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.24.7.tgz",
+ "integrity": "sha512-KoUi4M1f3BG6kzN1FnCwL7oyFptTbyBJKjR6yhSib+JHRdUmM1o+VwsFtJ66NZCkCzVfJMWRHJNo0R0jznp0Pg==",
"license": "Apache-2.0",
"dependencies": {
"@aws-crypto/crc32": "5.2.0",
- "@smithy/types": "^4.14.3",
+ "@smithy/types": "^4.14.4",
"tslib": "^2.6.2"
},
"engines": {
@@ -3629,13 +3629,13 @@
}
},
"node_modules/@smithy/credential-provider-imds": {
- "version": "4.3.8",
- "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.3.8.tgz",
- "integrity": "sha512-5cAM+KZC02sTqDt6NaLXyu50M/GNMd1eTzDVR8Lb0BBsVtu7RWHo47VPPEEv1vt3Yub6uzr+M5FHC+GtoT0USg==",
+ "version": "4.3.9",
+ "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.3.9.tgz",
+ "integrity": "sha512-ZlfJ/4Fa3jYb+3eaohPfG9utX9HmdhFNcFtpoGAhUhdynAOmGXtmigbi7eEiONKM+ykHw8RwKuDEb85Lx7t7fA==",
"license": "Apache-2.0",
"dependencies": {
- "@smithy/core": "^3.24.6",
- "@smithy/types": "^4.14.3",
+ "@smithy/core": "^3.24.7",
+ "@smithy/types": "^4.14.4",
"tslib": "^2.6.2"
},
"engines": {
@@ -3643,13 +3643,13 @@
}
},
"node_modules/@smithy/fetch-http-handler": {
- "version": "5.4.6",
- "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.4.6.tgz",
- "integrity": "sha512-FEwEYJ1jlBKdhe9TPzfghEi1bP55ZeEImlDkEa62bBBYzUcnB6RUCyuiS2mqKt6ZVjUbBgcNhzfIctH+Hevx9g==",
+ "version": "5.4.7",
+ "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.4.7.tgz",
+ "integrity": "sha512-NslaM2ir0N2hisDmzXLstPaVINZheh8SokyOC++kzFPloZucL2R7Y7bS57mSzx/1Fc/fqmn7twjkeezTTrV0EA==",
"license": "Apache-2.0",
"dependencies": {
- "@smithy/core": "^3.24.6",
- "@smithy/types": "^4.14.3",
+ "@smithy/core": "^3.24.7",
+ "@smithy/types": "^4.14.4",
"tslib": "^2.6.2"
},
"engines": {
@@ -3669,13 +3669,13 @@
}
},
"node_modules/@smithy/node-http-handler": {
- "version": "4.7.7",
- "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.7.7.tgz",
- "integrity": "sha512-ZAFvHXrEk6K180EVhmZVg8GU5pUH5BSFqRs27JW3j1qEFx9YyYwWFx17x/MHcjALYimGAji7qEOlF1++be+G5A==",
+ "version": "4.7.8",
+ "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.7.8.tgz",
+ "integrity": "sha512-f+DbsWUwSbtMu1a/j8Y93KiU1SRg9nyzfjereqn1BJ33QOTUXxdlYvVXMhAYl1vuR1Kmna5aIJe09KSIfyFNYw==",
"license": "Apache-2.0",
"dependencies": {
- "@smithy/core": "^3.24.6",
- "@smithy/types": "^4.14.3",
+ "@smithy/core": "^3.24.7",
+ "@smithy/types": "^4.14.4",
"tslib": "^2.6.2"
},
"engines": {
@@ -3683,13 +3683,13 @@
}
},
"node_modules/@smithy/signature-v4": {
- "version": "5.4.6",
- "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.4.6.tgz",
- "integrity": "sha512-Ojg4B6oIDlIr1R86xCDJt1zJWnYa0VINmqdjfe9qxWjdRivHalZ3iSlQgVqYbW0MdpFOC5XfHEWsnbmdnpIILQ==",
+ "version": "5.4.7",
+ "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.4.7.tgz",
+ "integrity": "sha512-LwQZazFayImv+IOm0S0enoLeUJwmAlhGC5O6YCcLWezyu08dF46GOxPOq35OpBIHkgd7OvNvBStIFwVNyrvoBw==",
"license": "Apache-2.0",
"dependencies": {
- "@smithy/core": "^3.24.6",
- "@smithy/types": "^4.14.3",
+ "@smithy/core": "^3.24.7",
+ "@smithy/types": "^4.14.4",
"tslib": "^2.6.2"
},
"engines": {
@@ -3697,9 +3697,9 @@
}
},
"node_modules/@smithy/types": {
- "version": "4.14.3",
- "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.14.3.tgz",
- "integrity": "sha512-YupL0ZWmFtJexUN2cHzkvvF/b9pKrtAIfT1o7/oY/Ppu8IYeZ+lDPM5vZdQJaSeA132dJCqojjGC9NhXeF71VQ==",
+ "version": "4.14.4",
+ "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.14.4.tgz",
+ "integrity": "sha512-B2S9+UGm1+/pHkcx3ZoLVX1a+pmSk8rqxRR+ZsNqZaJ5q9FWX9AFGQVM4qG5+OBeQUZVy99HY8HqW8gK/wgXzQ==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
@@ -3825,12 +3825,13 @@
}
},
"node_modules/@types/archiver": {
- "version": "7.0.0",
- "resolved": "https://registry.npmjs.org/@types/archiver/-/archiver-7.0.0.tgz",
- "integrity": "sha512-/3vwGwx9n+mCQdYZ2IKGGHEFL30I96UgBlk8EtRDDFQ9uxM1l4O5Ci6r00EMAkiDaTqD9DQ6nVrWRICnBPtzzg==",
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/@types/archiver/-/archiver-8.0.0.tgz",
+ "integrity": "sha512-YpXPbEuv9+eUIPPQWUPahj3cvs9isWRuF+J4z+KbdYVDO3rWorWQFxUVHnwPu2AgKwvgpki5F2VMX0Xx+mX45A==",
"dev": true,
"license": "MIT",
"dependencies": {
+ "@types/node": "*",
"@types/readdir-glob": "*"
}
},
@@ -4061,9 +4062,9 @@
"license": "MIT"
},
"node_modules/@types/node": {
- "version": "25.9.2",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.2.tgz",
- "integrity": "sha512-G05zqtJhcDLb8uslf5EjCxXg9G1KQxiV8OS0R26IC//Eoyitzqe8z37I7cqvnZlrlSfgocQRfSn/AHBZJJFyGw==",
+ "version": "25.9.3",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.3.tgz",
+ "integrity": "sha512-603BddQMv3pUcr4U2dhujk83N2tTDVr/34wII2B6bJy6g+8WD6yUb11jszNs0gdi4PesVWl7ABt8nYMVpnLUcg==",
"license": "MIT",
"peer": true,
"dependencies": {
@@ -4247,17 +4248,17 @@
}
},
"node_modules/@typescript-eslint/eslint-plugin": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.60.1.tgz",
- "integrity": "sha512-JQ4S5GB0tfjO8BuJ4fcX+HodkzJjYBV+7OJ+wLygaX7OGQ7FudyHL4NSCA6ob+w3Yn+5MkKIozOwQhXeM7opVg==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.61.0.tgz",
+ "integrity": "sha512-bFNvl9ZczlVb+wR2Akszf3gHfKVj/8WanXaGJ3UstTA7brNKg0cNdk6X1Psu5V7MZ2oQtzZKOEzIUehaoxbDGw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/regexpp": "^4.12.2",
- "@typescript-eslint/scope-manager": "8.60.1",
- "@typescript-eslint/type-utils": "8.60.1",
- "@typescript-eslint/utils": "8.60.1",
- "@typescript-eslint/visitor-keys": "8.60.1",
+ "@typescript-eslint/scope-manager": "8.61.0",
+ "@typescript-eslint/type-utils": "8.61.0",
+ "@typescript-eslint/utils": "8.61.0",
+ "@typescript-eslint/visitor-keys": "8.61.0",
"ignore": "^7.0.5",
"natural-compare": "^1.4.0",
"ts-api-utils": "^2.5.0"
@@ -4270,7 +4271,7 @@
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
- "@typescript-eslint/parser": "^8.60.1",
+ "@typescript-eslint/parser": "^8.61.0",
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
"typescript": ">=4.8.4 <6.1.0"
}
@@ -4286,17 +4287,17 @@
}
},
"node_modules/@typescript-eslint/parser": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.60.1.tgz",
- "integrity": "sha512-A0M6ua6H252bVjPvvtSgl2QA4+ET9S5Mtkb2GDyTxIhH/C4qDItT7RQNO5PhMC6NXGYXOR9dIalcDDgBKT7oFA==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.61.0.tgz",
+ "integrity": "sha512-5B7PfA2e1NQGCnDHd/0lW7W3gvp3d59Ryw54FYO8Uswxo9f6ikw3AZV+Xj/TvpImmpsiYyUqAfhC6kJID1jF6w==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
- "@typescript-eslint/scope-manager": "8.60.1",
- "@typescript-eslint/types": "8.60.1",
- "@typescript-eslint/typescript-estree": "8.60.1",
- "@typescript-eslint/visitor-keys": "8.60.1",
+ "@typescript-eslint/scope-manager": "8.61.0",
+ "@typescript-eslint/types": "8.61.0",
+ "@typescript-eslint/typescript-estree": "8.61.0",
+ "@typescript-eslint/visitor-keys": "8.61.0",
"debug": "^4.4.3"
},
"engines": {
@@ -4312,14 +4313,14 @@
}
},
"node_modules/@typescript-eslint/project-service": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.60.1.tgz",
- "integrity": "sha512-eXkTH2bxmXlqD1RnOPmLZ9ZM9D3VwSx04JOwBnP9RQ+yUA5a2Mu7SfW8uaV2Aon53NJzZlZYuX7tn91Izf+xaw==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.61.0.tgz",
+ "integrity": "sha512-DV42F7MLJO6Rax7SK1yg43tcnEfGUrurSpSxKuVX+a3RCTzBlH3fuxprrOJXKCJGAaw82xXocikJ0uQaqwXgGA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/tsconfig-utils": "^8.60.1",
- "@typescript-eslint/types": "^8.60.1",
+ "@typescript-eslint/tsconfig-utils": "^8.61.0",
+ "@typescript-eslint/types": "^8.61.0",
"debug": "^4.4.3"
},
"engines": {
@@ -4334,14 +4335,14 @@
}
},
"node_modules/@typescript-eslint/scope-manager": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.60.1.tgz",
- "integrity": "sha512-gvI5OQoptnxQnchOirukCuQ55svJSTuD/4k5+pC267xyBtYry748R9/c3tYUzb/iE6RZfllRz2lVulLCHkTm4w==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.61.0.tgz",
+ "integrity": "sha512-IWdXFHFSb6mlC3HPc7QsLDm5zYEbUla6trDEHf32D3/dnuUyXd87plScSNXSbm0/RxMvObpI17sv/EDTGrGZkA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/types": "8.60.1",
- "@typescript-eslint/visitor-keys": "8.60.1"
+ "@typescript-eslint/types": "8.61.0",
+ "@typescript-eslint/visitor-keys": "8.61.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -4352,9 +4353,9 @@
}
},
"node_modules/@typescript-eslint/tsconfig-utils": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.60.1.tgz",
- "integrity": "sha512-nh8w4qAteiKuZu3pSSzG/yGKpw0OlkrKnzFmbVRenKaD4qc+7i1GrmZaLVkr8rk4uipiPGMOW4YsM6WmKZ5CvA==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.61.0.tgz",
+ "integrity": "sha512-O5Amvdv9ztMpxpf+vmFULGG78IE6Qwdr3bCGvqwG4nwc9H2qXkOYJJnRbRHyMkQTjv1d03olqwwwzHLMqpFePQ==",
"dev": true,
"license": "MIT",
"engines": {
@@ -4369,15 +4370,15 @@
}
},
"node_modules/@typescript-eslint/type-utils": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.60.1.tgz",
- "integrity": "sha512-sdwTrpjosW7ANQYJ39ZBF1ZyEMEGVB2UsikrserVM/30a/F1dTLnu9bGxEdosugyu5caigjLrR2qiD11asjI1A==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.61.0.tgz",
+ "integrity": "sha512-TuBiQYIkd97yBfInHCTKVYMbX4kvEmpOEuixIuzCU9p8BGT1SfyyO0d0IfDMbPIHcjn/hWnusUX5e8v5Xg+X8A==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/types": "8.60.1",
- "@typescript-eslint/typescript-estree": "8.60.1",
- "@typescript-eslint/utils": "8.60.1",
+ "@typescript-eslint/types": "8.61.0",
+ "@typescript-eslint/typescript-estree": "8.61.0",
+ "@typescript-eslint/utils": "8.61.0",
"debug": "^4.4.3",
"ts-api-utils": "^2.5.0"
},
@@ -4394,9 +4395,9 @@
}
},
"node_modules/@typescript-eslint/types": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.60.1.tgz",
- "integrity": "sha512-4h0tY8ppCkdCzcrl2YM5M3my0xsE1Tf8om3owEu5oPWmXwkKRmk0j0LGDzYBGUcAlesEbxBhazqu/K4cu3Ug7w==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.61.0.tgz",
+ "integrity": "sha512-9QTQpZ5Iin4CdIodfbDQFSeiSJKidgYJYug1P9CC2xWgUTvlmixViqDZNciMjwLBZyJnG4tGmPl97rVAFb1AJg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -4408,16 +4409,16 @@
}
},
"node_modules/@typescript-eslint/typescript-estree": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.60.1.tgz",
- "integrity": "sha512-alpRkfG8hlVE5kdJW2GkfgDgXxold3e8e4l6EnmhRmRLbekgAPCCGDVD++sABy9FcgPFroq+uFcCSM1vR57Cew==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.61.0.tgz",
+ "integrity": "sha512-42zatd5qSvvcV1JdDBCLxYRznvP4eIHpPoZXdkPFnAmanA4FuZ5dibSnCBggY8hQnqajPpoGjXFdZ7fIJKQnlA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/project-service": "8.60.1",
- "@typescript-eslint/tsconfig-utils": "8.60.1",
- "@typescript-eslint/types": "8.60.1",
- "@typescript-eslint/visitor-keys": "8.60.1",
+ "@typescript-eslint/project-service": "8.61.0",
+ "@typescript-eslint/tsconfig-utils": "8.61.0",
+ "@typescript-eslint/types": "8.61.0",
+ "@typescript-eslint/visitor-keys": "8.61.0",
"debug": "^4.4.3",
"minimatch": "^10.2.2",
"semver": "^7.7.3",
@@ -4475,16 +4476,16 @@
}
},
"node_modules/@typescript-eslint/utils": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.60.1.tgz",
- "integrity": "sha512-h2MPBLoNtjc3qZWfY3Tl51yPorQ2McHn8pJfcMNTcIvrrZrr90Ykffit0yjrPFWQcRcUxzH20+6OcVdW4yHtUg==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.61.0.tgz",
+ "integrity": "sha512-3bzFt7ImFMW/jVYwJamDoe/dMOdFLSC6pom6rRjdh4SZJEYupyMzem8e7vKZLclLfpHjlwSAXOUxtKxGXUiLqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.9.1",
- "@typescript-eslint/scope-manager": "8.60.1",
- "@typescript-eslint/types": "8.60.1",
- "@typescript-eslint/typescript-estree": "8.60.1"
+ "@typescript-eslint/scope-manager": "8.61.0",
+ "@typescript-eslint/types": "8.61.0",
+ "@typescript-eslint/typescript-estree": "8.61.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -4499,13 +4500,13 @@
}
},
"node_modules/@typescript-eslint/visitor-keys": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.60.1.tgz",
- "integrity": "sha512-EbGRQg4FhrmwLodl+t3JNAnXHWVr9Vp+Zl1QBZVPY4ByfkzIT8cX3K6QWODHtkIZqqJVEWvhHSx3v5PDHsaQag==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.61.0.tgz",
+ "integrity": "sha512-QVLZu3ZPQEE+HICQyAMZ2yLQhxf0meY/wx6Hx14YcTNj13JB3qHlX3lJ02L3fLGHgERRH71kvYDwiXIguT3AjQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/types": "8.60.1",
+ "@typescript-eslint/types": "8.61.0",
"eslint-visitor-keys": "^5.0.0"
},
"engines": {
@@ -5268,6 +5269,18 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/anynum": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/anynum/-/anynum-1.0.0.tgz",
+ "integrity": "sha512-xjR9/zBVnUOP6ztMIIgShjsxui80nQUQH+5xJnvrYLs+90bF25/KJqaAi8mk+B4RDtX1Nspi6fmp4YTEts8SfA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/NaturalIntelligence"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/app-root-path": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/app-root-path/-/app-root-path-3.1.0.tgz",
@@ -6033,9 +6046,9 @@
}
},
"node_modules/bullmq": {
- "version": "5.78.0",
- "resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.78.0.tgz",
- "integrity": "sha512-tT9jJmbobk9ueEfFc22egLmgwCcMGgOjZ5Y1cvgczBPv1JUmC7iHQVbQtqku2YBE5dE9uzdVpxIrBvL/YAjGwA==",
+ "version": "5.78.1",
+ "resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.78.1.tgz",
+ "integrity": "sha512-zD5IT+qMqbMgPFPdL9FwnZka1bz6nckM+5lXj4N0vsXqdzoVO6wizmXpwsg/4GnHmXJsL7XOKeWA64tYUdPrOA==",
"license": "MIT",
"peer": true,
"dependencies": {
@@ -6043,7 +6056,7 @@
"ioredis": "5.10.1",
"msgpackr": "2.0.2",
"node-abort-controller": "3.1.1",
- "semver": "7.8.0",
+ "semver": "7.8.1",
"tslib": "2.8.1"
},
"engines": {
@@ -7755,12 +7768,15 @@
}
},
"node_modules/eslint": {
- "version": "10.4.1",
- "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.4.1.tgz",
- "integrity": "sha512-AyIKhnOBuOAdueD7RB3xB+YeAWScb9jHsJBgH2Hcde8InP5JYhqrRR6iTMHyTEwgENK54Cp44e4v8BwNhsuHuw==",
+ "version": "10.5.0",
+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.5.0.tgz",
+ "integrity": "sha512-1y+7C+vi12bUK1IpZeaV3gsH9fHLBmPvYmPx42pvT/E9yG0IC8g3PUZZgp0+JLJl7ZDK0flc2gc+Aw9dpCvIsQ==",
"dev": true,
"license": "MIT",
"peer": true,
+ "workspaces": [
+ "packages/*"
+ ],
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.2",
@@ -12171,9 +12187,9 @@
}
},
"node_modules/prettier": {
- "version": "3.8.3",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.3.tgz",
- "integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==",
+ "version": "3.8.4",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.4.tgz",
+ "integrity": "sha512-N2MylSdi48+5N/6S5j+maeHbUSIzzZ5uOcX5Hm4QpV8Dkb1HFjfAKTKX6yNPJQD9AhcT3ifHNB66tWTTJDi11Q==",
"dev": true,
"license": "MIT",
"peer": true,
@@ -13067,9 +13083,9 @@
}
},
"node_modules/semver": {
- "version": "7.8.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz",
- "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==",
+ "version": "7.8.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.1.tgz",
+ "integrity": "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -13780,16 +13796,19 @@
}
},
"node_modules/strnum": {
- "version": "2.3.0",
- "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.3.0.tgz",
- "integrity": "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q==",
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.4.0.tgz",
+ "integrity": "sha512-sHrVyWWdq28RbhjuJdZsA1SnGRJV6NiXbk6AXBxDOsgAcA+lmpUZCYjOdLBxkXMwis6RRe7dlZt4VlIWFVzkmg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
- "license": "MIT"
+ "license": "MIT",
+ "dependencies": {
+ "anynum": "^1.0.0"
+ }
},
"node_modules/strtok3": {
"version": "10.3.5",
@@ -14841,16 +14860,16 @@
}
},
"node_modules/typescript-eslint": {
- "version": "8.60.1",
- "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.60.1.tgz",
- "integrity": "sha512-6m5hkkRAp8lKvhVpcprAIn5KkehQEh+47oHH2VGnExEh7dhNxXlg6GPAOIu6TxbVQxhebrJDvjl3020ooiWCMA==",
+ "version": "8.61.0",
+ "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.61.0.tgz",
+ "integrity": "sha512-8y31Rd0eGTrDKqhy6vT0HtzhN+YLjQizwX3aA3hPXP/ynSfnrBXcQY5IzsP9/DM7+klX4IUncZZjkchP0z+rUw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/eslint-plugin": "8.60.1",
- "@typescript-eslint/parser": "8.60.1",
- "@typescript-eslint/typescript-estree": "8.60.1",
- "@typescript-eslint/utils": "8.60.1"
+ "@typescript-eslint/eslint-plugin": "8.61.0",
+ "@typescript-eslint/parser": "8.61.0",
+ "@typescript-eslint/typescript-estree": "8.61.0",
+ "@typescript-eslint/utils": "8.61.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
diff --git a/package.json b/package.json
index c952015c2..dad34e307 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "openwa",
- "version": "0.2.1",
+ "version": "0.2.2",
"description": "Open Source WhatsApp API Gateway - Free, Self-Hosted HTTP API for WhatsApp",
"author": "Yudhi Armyndharis & OpenWA Contributors",
"private": true,
@@ -36,22 +36,22 @@
"migration:show:prod": "npm run typeorm:prod -- migration:show -d dist/database/data-source.js"
},
"dependencies": {
- "@aws-sdk/client-s3": "^3.1063.0",
- "@bull-board/api": "^7.2.1",
- "@bull-board/express": "^7.2.1",
- "@bull-board/nestjs": "^7.2.1",
+ "@aws-sdk/client-s3": "^3.1068.0",
+ "@bull-board/api": "^8.0.0",
+ "@bull-board/express": "^8.0.0",
+ "@bull-board/nestjs": "^8.0.0",
"@nestjs-modules/ioredis": "^2.0.2",
"@nestjs/bullmq": "^11.0.4",
- "@nestjs/common": "^11.1.25",
+ "@nestjs/common": "^11.1.27",
"@nestjs/config": "^4.0.2",
- "@nestjs/core": "^11.1.25",
- "@nestjs/platform-express": "^11.1.25",
- "@nestjs/platform-socket.io": "^11.1.25",
+ "@nestjs/core": "^11.1.27",
+ "@nestjs/platform-express": "^11.1.27",
+ "@nestjs/platform-socket.io": "^11.1.27",
"@nestjs/swagger": "^11.4.4",
"@nestjs/throttler": "^6.5.0",
"@nestjs/typeorm": "^11.0.0",
"archiver": "^8.0.0",
- "bullmq": "^5.78.0",
+ "bullmq": "^5.78.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"dockerode": "^5.0.0",
@@ -71,25 +71,25 @@
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^10.0.1",
- "@nestjs/cli": "^11.0.22",
+ "@nestjs/cli": "^11.0.23",
"@nestjs/schematics": "^11.0.0",
- "@nestjs/testing": "^11.1.25",
- "@types/archiver": "^7.0.0",
+ "@nestjs/testing": "^11.1.27",
+ "@types/archiver": "^8.0.0",
"@types/dockerode": "^4.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
- "@types/node": "^25.9.2",
+ "@types/node": "^25.9.3",
"@types/qrcode": "^1.5.5",
"@types/supertest": "^6.0.2",
"@types/tar-stream": "^3.1.4",
"@types/uuid": "^11.0.0",
"concurrently": "^10.0.3",
- "eslint": "^10.4.1",
+ "eslint": "^10.5.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.5.6",
"globals": "^17.6.0",
"jest": "^30.4.2",
- "prettier": "^3.4.2",
+ "prettier": "^3.8.4",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.4.11",
@@ -97,7 +97,7 @@
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
- "typescript-eslint": "^8.60.1"
+ "typescript-eslint": "^8.61.0"
},
"jest": {
"moduleFileExtensions": [
@@ -116,10 +116,22 @@
"coverageDirectory": "../coverage",
"coverageThreshold": {
"global": {
- "branches": 10,
- "functions": 12,
- "lines": 15,
- "statements": 15
+ "branches": 30,
+ "functions": 30,
+ "lines": 33,
+ "statements": 33
+ },
+ "./src/common/security/": {
+ "branches": 85,
+ "functions": 95,
+ "lines": 90,
+ "statements": 90
+ },
+ "./src/modules/auth/": {
+ "branches": 30,
+ "functions": 50,
+ "lines": 45,
+ "statements": 45
}
},
"testEnvironment": "node"
diff --git a/scripts/backup.sh b/scripts/backup.sh
new file mode 100755
index 000000000..79d6fa9bf
--- /dev/null
+++ b/scripts/backup.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+#
+# OpenWA backup.
+#
+# Captures EVERYTHING needed to restore a working install:
+# - main.sqlite — auth (API keys) + audit log, ALWAYS SQLite (see app.module.ts)
+# - data store — openwa.sqlite (SQLite) OR a pg_dump (when DATABASE_TYPE=postgres)
+# - sessions/ — WhatsApp LocalAuth session data
+# - media/ — locally-stored media (skipped automatically when using S3)
+#
+# The previous runbook backed up the wrong file (openwa.db) and omitted main.sqlite,
+# so a "successful" backup silently lost every API key and all audit history.
+#
+# Usage:
+# ./scripts/backup.sh
+# Environment:
+# OPENWA_DATA_DIR data directory (default: ./data)
+# BACKUP_DIR where archives are written (default: ./backups)
+# DATABASE_TYPE sqlite (default) | postgres
+# For postgres: DATABASE_URL, or DATABASE_HOST/PORT/USERNAME/PASSWORD/NAME
+#
+set -euo pipefail
+
+DATA_DIR="${OPENWA_DATA_DIR:-./data}"
+BACKUP_DIR="${BACKUP_DIR:-./backups}"
+DATABASE_TYPE="${DATABASE_TYPE:-sqlite}"
+TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
+
+MAIN_DB="$DATA_DIR/main.sqlite"
+DATA_DB="$DATA_DIR/openwa.sqlite"
+SESSIONS_DIR="$DATA_DIR/sessions"
+MEDIA_DIR="$DATA_DIR/media"
+
+log() { echo "[backup] $*"; }
+
+STAGE="$(mktemp -d)"
+trap 'rm -rf "$STAGE"' EXIT
+
+# Online SQLite backup (consistent without stopping the app) when sqlite3 is present,
+# else a plain copy with a warning.
+backup_sqlite() {
+ src="$1"
+ dest="$2"
+ if [ ! -f "$src" ]; then
+ log "WARN: $src not found — skipping"
+ return 0
+ fi
+ if command -v sqlite3 >/dev/null 2>&1; then
+ sqlite3 "$src" ".backup '$dest'"
+ else
+ log "WARN: sqlite3 not found — plain-copying $src (stop the app first for a consistent copy)"
+ cp "$src" "$dest"
+ fi
+}
+
+log "Backing up auth/audit DB (main.sqlite) — the API-key + audit store"
+backup_sqlite "$MAIN_DB" "$STAGE/main.sqlite"
+
+if [ "$DATABASE_TYPE" = "postgres" ]; then
+ log "Backing up data store via pg_dump"
+ if ! command -v pg_dump >/dev/null 2>&1; then
+ log "ERROR: DATABASE_TYPE=postgres but pg_dump is not installed"
+ exit 1
+ fi
+ if [ -n "${DATABASE_URL:-}" ]; then
+ pg_dump "$DATABASE_URL" >"$STAGE/database.sql"
+ else
+ PGPASSWORD="${DATABASE_PASSWORD:-}" pg_dump \
+ -h "${DATABASE_HOST:-localhost}" \
+ -p "${DATABASE_PORT:-5432}" \
+ -U "${DATABASE_USERNAME:-openwa}" \
+ "${DATABASE_NAME:-openwa}" >"$STAGE/database.sql"
+ fi
+else
+ log "Backing up data store (openwa.sqlite)"
+ backup_sqlite "$DATA_DB" "$STAGE/openwa.sqlite"
+fi
+
+if [ -d "$SESSIONS_DIR" ]; then
+ log "Backing up WhatsApp sessions"
+ cp -r "$SESSIONS_DIR" "$STAGE/sessions"
+else
+ log "WARN: $SESSIONS_DIR not found — skipping sessions"
+fi
+
+if [ -d "$MEDIA_DIR" ]; then
+ log "Backing up local media"
+ cp -r "$MEDIA_DIR" "$STAGE/media"
+fi
+
+mkdir -p "$BACKUP_DIR"
+ARCHIVE="$BACKUP_DIR/openwa-backup-$TIMESTAMP.tar.gz"
+tar -czf "$ARCHIVE" -C "$STAGE" .
+
+log "Backup complete: $ARCHIVE"
+log "Contents:"
+tar -tzf "$ARCHIVE" | sed 's/^/[backup] /'
diff --git a/scripts/restore.sh b/scripts/restore.sh
new file mode 100755
index 000000000..0545ee3f1
--- /dev/null
+++ b/scripts/restore.sh
@@ -0,0 +1,73 @@
+#!/usr/bin/env bash
+#
+# OpenWA restore.
+#
+# Restores BOTH databases (auth/audit + data) and the WhatsApp sessions from an
+# archive produced by scripts/backup.sh, so API keys and audit history survive.
+#
+# Usage:
+# ./scripts/restore.sh <backup-archive.tar.gz>
+# Environment:
+# OPENWA_DATA_DIR data directory to restore into (default: ./data)
+#
+# Stop the OpenWA app before restoring. A snapshot of the current data dir is taken
+# first so a bad restore can be undone.
+#
+set -euo pipefail
+
+ARCHIVE="${1:-}"
+DATA_DIR="${OPENWA_DATA_DIR:-./data}"
+
+log() { echo "[restore] $*"; }
+
+if [ -z "$ARCHIVE" ] || [ ! -f "$ARCHIVE" ]; then
+ echo "Usage: $0 <backup-archive.tar.gz>" >&2
+ exit 1
+fi
+
+STAGE="$(mktemp -d)"
+trap 'rm -rf "$STAGE"' EXIT
+
+log "Extracting $ARCHIVE"
+tar -xzf "$ARCHIVE" -C "$STAGE"
+
+# Safety snapshot of whatever is there now.
+if [ -d "$DATA_DIR" ] && [ -n "$(ls -A "$DATA_DIR" 2>/dev/null || true)" ]; then
+ SAFETY="${DATA_DIR%/}.pre-restore-$(date +%Y%m%d-%H%M%S)"
+ log "Snapshotting current data dir -> $SAFETY"
+ cp -r "$DATA_DIR" "$SAFETY"
+fi
+
+mkdir -p "$DATA_DIR"
+
+if [ -f "$STAGE/main.sqlite" ]; then
+ log "Restoring auth/audit DB (main.sqlite)"
+ cp "$STAGE/main.sqlite" "$DATA_DIR/main.sqlite"
+else
+ log "WARN: main.sqlite not in archive — API keys / audit log will NOT be restored"
+fi
+
+if [ -f "$STAGE/openwa.sqlite" ]; then
+ log "Restoring data store (openwa.sqlite)"
+ cp "$STAGE/openwa.sqlite" "$DATA_DIR/openwa.sqlite"
+fi
+
+if [ -d "$STAGE/sessions" ]; then
+ log "Restoring WhatsApp sessions"
+ rm -rf "$DATA_DIR/sessions"
+ cp -r "$STAGE/sessions" "$DATA_DIR/sessions"
+fi
+
+if [ -d "$STAGE/media" ]; then
+ log "Restoring local media"
+ rm -rf "$DATA_DIR/media"
+ cp -r "$STAGE/media" "$DATA_DIR/media"
+fi
+
+if [ -f "$STAGE/database.sql" ]; then
+ cp "$STAGE/database.sql" "$DATA_DIR/database.sql"
+ log "Postgres dump present — import it manually into your Postgres instance:"
+ log " psql \"\$DATABASE_URL\" < $DATA_DIR/database.sql"
+fi
+
+log "Restore complete. Start the app and confirm an existing API key still authenticates."
diff --git a/src/app.module.ts b/src/app.module.ts
index 1a625dd51..7266e5ec4 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -3,6 +3,7 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ThrottlerModule } from '@nestjs/throttler';
import configuration from './config/configuration';
+import { validateEnv } from './config/env.validation';
import { SessionModule } from './modules/session/session.module';
import { MessageModule } from './modules/message/message.module';
import { TemplateModule } from './modules/template/template.module';
@@ -22,6 +23,7 @@ import { ChannelModule } from './modules/channel/channel.module';
import { CacheModule } from './common/cache';
import { StorageModule } from './common/storage/storage.module';
import { StatsModule } from './modules/stats/stats.module';
+import { MetricsModule } from './modules/metrics/metrics.module';
import { StatusModule } from './modules/status/status.module';
import { CatalogModule } from './modules/catalog/catalog.module';
import { HooksModule } from './core/hooks';
@@ -44,6 +46,7 @@ if (process.env.QUEUE_ENABLED === 'true') {
ConfigModule.forRoot({
isGlobal: true,
load: [configuration],
+ validate: validateEnv,
}),
// Main Database (always SQLite - boot config)
@@ -51,13 +54,26 @@ if (process.env.QUEUE_ENABLED === 'true') {
name: 'main',
imports: [ConfigModule],
inject: [ConfigService],
- useFactory: (configService: ConfigService) => ({
- type: 'sqlite' as const,
- database: configService.get<string>('database.database', './data/main.sqlite'),
- entities: [__dirname + '/modules/auth/**/*.entity{.ts,.js}', __dirname + '/modules/audit/**/*.entity{.ts,.js}'],
- synchronize: true,
- logging: configService.get<boolean>('database.logging', false),
- }),
+ useFactory: (configService: ConfigService) => {
+ // Default ON for zero-config first boot. When disabled
+ // (MAIN_DATABASE_SYNCHRONIZE=false), the main-owned migrations create the
+ // api_keys/audit_logs schema instead — never both at once.
+ const synchronize = configService.get<boolean>('database.synchronize', true);
+ return {
+ type: 'sqlite' as const,
+ database: configService.get<string>('database.database', './data/main.sqlite'),
+ entities: [
+ __dirname + '/modules/auth/**/*.entity{.ts,.js}',
+ __dirname + '/modules/audit/**/*.entity{.ts,.js}',
+ ],
+ // Dedicated migrations dir for the main connection only (must NOT run the
+ // data-connection migrations, which target session/webhook/message tables).
+ migrations: [__dirname + '/database/migrations-main/*{.ts,.js}'],
+ synchronize,
+ migrationsRun: !synchronize,
+ logging: configService.get<boolean>('database.logging', false),
+ };
+ },
}),
// Data Storage Database (pluggable - user data)
@@ -86,7 +102,7 @@ if (process.env.QUEUE_ENABLED === 'true') {
port: configService.get<number>('dataDatabase.port'),
username: configService.get<string>('dataDatabase.username'),
password: configService.get<string>('dataDatabase.password'),
- database: 'openwa',
+ database: configService.get<string>('dataDatabase.name', 'openwa'),
ssl: configService.get<boolean>('dataDatabase.ssl', false)
? {
@@ -166,6 +182,7 @@ if (process.env.QUEUE_ENABLED === 'true') {
LabelModule, // Phase 3: Labels Management
ChannelModule, // Phase 3: Channels/Newsletter
StatsModule, // Phase 3: Statistics Dashboard
+ MetricsModule, // Prometheus /api/metrics
StatusModule, // Phase 3: Status/Stories API
CatalogModule, // Phase 3: Catalog API (WhatsApp Business)
PluginsApiModule, // Phase 5: Plugins API
diff --git a/src/common/filters/http-exception.filter.ts b/src/common/filters/http-exception.filter.ts
deleted file mode 100644
index 9e95048c7..000000000
--- a/src/common/filters/http-exception.filter.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
-import { Response, Request } from 'express';
-import { ApiResponse } from '../interfaces/response.interface';
-
-@Catch()
-export class HttpExceptionFilter implements ExceptionFilter {
- catch(exception: unknown, host: ArgumentsHost) {
- const ctx = host.switchToHttp();
- const response = ctx.getResponse<Response>();
- const request = ctx.getRequest<Request>();
-
- let status = HttpStatus.INTERNAL_SERVER_ERROR;
- let code = 'INTERNAL_ERROR';
- let message = 'An unexpected error occurred';
- let details: Record<string, unknown> | undefined;
-
- if (exception instanceof HttpException) {
- status = exception.getStatus();
- const exceptionResponse = exception.getResponse();
-
- if (typeof exceptionResponse === 'string') {
- message = exceptionResponse;
- } else if (typeof exceptionResponse === 'object' && exceptionResponse !== null) {
- const resp = exceptionResponse as {
- message?: string | string[];
- error?: string;
- details?: Record<string, unknown>;
- };
- message = typeof resp.message === 'string' ? resp.message : message;
- code = resp.error || this.getErrorCode(status);
- details = resp.details;
-
- // Handle validation errors
- if (Array.isArray(resp.message)) {
- message = 'Validation failed';
- details = { errors: resp.message };
- }
- }
-
- // Only set code from status if not already set from response
- if (code === 'INTERNAL_ERROR') {
- code = this.getErrorCode(status);
- }
- } else if (exception instanceof Error) {
- message = exception.message;
- }
-
- const errorResponse: ApiResponse = {
- success: false,
- error: {
- code,
- message,
- details,
- },
- meta: {
- timestamp: new Date().toISOString(),
- requestId: request.headers['x-request-id'] as string,
- },
- };
-
- response.status(status).json(errorResponse);
- }
-
- private getErrorCode(status: number): string {
- switch (status) {
- case 400:
- return 'BAD_REQUEST';
- case 401:
- return 'UNAUTHORIZED';
- case 403:
- return 'FORBIDDEN';
- case 404:
- return 'NOT_FOUND';
- case 409:
- return 'CONFLICT';
- case 422:
- return 'VALIDATION_ERROR';
- case 429:
- return 'TOO_MANY_REQUESTS';
- default:
- return 'INTERNAL_ERROR';
- }
- }
-}
diff --git a/src/common/interceptors/response.interceptor.ts b/src/common/interceptors/response.interceptor.ts
deleted file mode 100644
index a6d1fafc7..000000000
--- a/src/common/interceptors/response.interceptor.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
-import { Observable } from 'rxjs';
-import { map } from 'rxjs/operators';
-import { Request } from 'express';
-import { ApiResponse } from '../interfaces/response.interface';
-
-@Injectable()
-export class ResponseInterceptor<T> implements NestInterceptor<T, ApiResponse<T>> {
- intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponse<T>> {
- const request = context.switchToHttp().getRequest<Request>();
- const requestId = (request.headers['x-request-id'] as string) || undefined;
-
- return next.handle().pipe(
- map(data => ({
- success: true,
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- data,
- meta: {
- timestamp: new Date().toISOString(),
- requestId,
- },
- })),
- );
- }
-}
diff --git a/src/common/interfaces/response.interface.ts b/src/common/interfaces/response.interface.ts
deleted file mode 100644
index d518bf36e..000000000
--- a/src/common/interfaces/response.interface.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-// Common response interface for all API endpoints
-
-export interface ApiResponse<T = any> {
- success: boolean;
- data?: T;
- error?: ApiError;
- meta?: ApiMeta;
-}
-
-export interface ApiError {
- code: string;
- message: string;
- details?: Record<string, any>;
-}
-
-export interface ApiMeta {
- timestamp: string;
- requestId?: string;
-}
-
-export interface PaginatedResponse<T = any> extends ApiResponse<T[]> {
- pagination?: {
- page: number;
- limit: number;
- total: number;
- totalPages: number;
- };
-}
diff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.ts
index 26f00c5bf..098366a91 100644
--- a/src/common/security/bull-board-auth.middleware.spec.ts
+++ b/src/common/security/bull-board-auth.middleware.spec.ts
@@ -48,14 +48,18 @@ describe('BullBoardAuthMiddleware', () => {
expect(authService.validateApiKey).toHaveBeenCalledWith('admin', '127.0.0.1');
});
- it('accepts a Bearer token and the ?apiKey query param', async () => {
+ it('accepts a Bearer token', async () => {
authService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.ADMIN });
authService.hasPermission.mockReturnValue(true);
await mw.use(reqWith({ authorization: 'Bearer abc' }), res, jest.fn());
expect(authService.validateApiKey).toHaveBeenCalledWith('abc', '127.0.0.1');
+ });
- await mw.use(reqWith({}, { apiKey: 'qkey' }), res, jest.fn());
- expect(authService.validateApiKey).toHaveBeenLastCalledWith('qkey', '127.0.0.1');
+ it('rejects an ?apiKey query param (no key in the URL)', async () => {
+ const next = jest.fn();
+ await mw.use(reqWith({}, { apiKey: 'qkey' }), res, next);
+ expect(next).toHaveBeenCalledWith(expect.any(UnauthorizedException));
+ expect(authService.validateApiKey).not.toHaveBeenCalled();
});
});
diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.ts
index ca71d1151..6c95897ad 100644
--- a/src/common/security/bull-board-auth.middleware.ts
+++ b/src/common/security/bull-board-auth.middleware.ts
@@ -9,8 +9,10 @@ import { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';
* Bull Board is mounted as raw Express middleware by @bull-board/nestjs, so the
* global ApiKeyGuard — which only runs on Nest controller handlers — does not
* cover it. This middleware requires a valid ADMIN-role API key, supplied via
- * the X-API-Key header, an Authorization: Bearer token, or an ?apiKey query
- * param (the latter for direct browser access).
+ * the X-API-Key header or an Authorization: Bearer token.
+ *
+ * The ?apiKey query-string fallback was removed: an ADMIN key in the
+ * URL leaks into proxy/access logs, browser history, bookmarks, and the Referer header.
*/
@Injectable()
export class BullBoardAuthMiddleware implements NestMiddleware {
@@ -42,9 +44,7 @@ export class BullBoardAuthMiddleware implements NestMiddleware {
const authHeader = req.headers['authorization'];
if (authHeader?.startsWith('Bearer ')) return authHeader.slice(7);
- const queryKey = req.query?.apiKey;
- if (typeof queryKey === 'string' && queryKey) return queryKey;
-
+ // No ?apiKey query fallback — an admin key in the URL leaks into logs/history.
return undefined;
}
diff --git a/src/common/security/proxy-aware-throttler.guard.spec.ts b/src/common/security/proxy-aware-throttler.guard.spec.ts
new file mode 100644
index 000000000..5bc4fa953
--- /dev/null
+++ b/src/common/security/proxy-aware-throttler.guard.spec.ts
@@ -0,0 +1,49 @@
+import { ProxyAwareThrottlerGuard } from './proxy-aware-throttler.guard';
+
+/**
+ * Regression lock: the throttler must bucket on the resolved client IP, not the
+ * proxy IP — so one abusive client cannot rate-limit everyone behind a reverse proxy.
+ */
+describe('ProxyAwareThrottlerGuard.getTracker', () => {
+ const orig = process.env.TRUSTED_PROXIES;
+
+ // getTracker uses only process.env + the pure resolveClientIp (no `this`), so we can
+ // invoke it on a prototype instance without the throttler's storage/reflector deps.
+ const guard = Object.create(ProxyAwareThrottlerGuard.prototype) as ProxyAwareThrottlerGuard;
+ const track = (req: unknown): Promise<string> =>
+ (guard as unknown as { getTracker(r: unknown): Promise<string> }).getTracker(req);
+
+ const reqFrom = (socketIp: string, xff?: string): unknown => ({
+ ip: socketIp,
+ socket: { remoteAddress: socketIp },
+ headers: xff ? { 'x-forwarded-for': xff } : {},
+ });
+
+ afterEach(() => {
+ if (orig === undefined) delete process.env.TRUSTED_PROXIES;
+ else process.env.TRUSTED_PROXIES = orig;
+ });
+
+ it('with no trusted proxies, keys on the socket IP and ignores a spoofed XFF', async () => {
+ delete process.env.TRUSTED_PROXIES;
+ expect(await track(reqFrom('203.0.113.9', '1.1.1.1'))).toBe('203.0.113.9');
+ });
+
+ it('with a trusted proxy peer, keys on the real forwarded client IP', async () => {
+ process.env.TRUSTED_PROXIES = '172.18.0.0/16';
+ expect(await track(reqFrom('172.18.0.5', '203.0.113.9'))).toBe('203.0.113.9');
+ });
+
+ it('gives two distinct forwarded clients independent buckets', async () => {
+ process.env.TRUSTED_PROXIES = '172.18.0.0/16';
+ const a = await track(reqFrom('172.18.0.5', '203.0.113.9'));
+ const b = await track(reqFrom('172.18.0.5', '198.51.100.7'));
+ expect(a).not.toBe(b);
+ });
+
+ it('ignores XFF from an untrusted peer (anti-spoof)', async () => {
+ process.env.TRUSTED_PROXIES = '172.18.0.0/16';
+ // peer 203.0.113.9 is NOT a trusted proxy → its XFF is ignored, key on the socket IP
+ expect(await track(reqFrom('203.0.113.9', '10.0.0.1'))).toBe('203.0.113.9');
+ });
+});
diff --git a/src/common/security/proxy-aware-throttler.guard.ts b/src/common/security/proxy-aware-throttler.guard.ts
new file mode 100644
index 000000000..aa49c5961
--- /dev/null
+++ b/src/common/security/proxy-aware-throttler.guard.ts
@@ -0,0 +1,25 @@
+import { Injectable } from '@nestjs/common';
+import { ThrottlerGuard } from '@nestjs/throttler';
+import { resolveClientIp, RequestLike } from '../utils/ip';
+
+/**
+ * Rate-limit bucket keyed on the resolved client IP.
+ *
+ * The stock ThrottlerGuard keys on `req.ip`, which — behind the documented reverse
+ * proxy with Express `trust proxy` disabled — resolves to the proxy for every client,
+ * so all traffic shares ONE bucket and a single abuser rate-limits everyone (self-DoS).
+ *
+ * This reuses the same trusted-proxy-aware resolution as ApiKeyGuard: with no
+ * TRUSTED_PROXIES configured it falls back to the socket IP (no behavior change and no
+ * XFF-spoofing risk); with trusted proxies it keys on the real forwarded client IP.
+ */
+@Injectable()
+export class ProxyAwareThrottlerGuard extends ThrottlerGuard {
+ protected getTracker(req: Record<string, unknown>): Promise<string> {
+ const trustedProxies = (process.env.TRUSTED_PROXIES || '')
+ .split(',')
+ .map(proxy => proxy.trim())
+ .filter(Boolean);
+ return Promise.resolve(resolveClientIp(req as unknown as RequestLike, trustedProxies));
+ }
+}
diff --git a/src/common/security/security.middleware.ts b/src/common/security/security.middleware.ts
deleted file mode 100644
index e333c3a89..000000000
--- a/src/common/security/security.middleware.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import { Injectable, NestMiddleware } from '@nestjs/common';
-import { Request, Response, NextFunction } from 'express';
-import { randomUUID } from 'crypto';
-
-/**
- * Security middleware for request tracking and security headers
- * Phase 3 Security Audit
- */
-@Injectable()
-export class SecurityMiddleware implements NestMiddleware {
- use(req: Request, res: Response, next: NextFunction): void {
- // Generate or use existing request ID for tracing
- const requestId = (req.headers['x-request-id'] as string) || randomUUID();
- req.headers['x-request-id'] = requestId;
- res.setHeader('X-Request-ID', requestId);
-
- // Add additional security headers
- res.setHeader('X-Content-Type-Options', 'nosniff');
- res.setHeader('X-Frame-Options', 'DENY');
- res.setHeader('X-XSS-Protection', '1; mode=block');
-
- // Remove server header to avoid fingerprinting
- res.removeHeader('X-Powered-By');
-
- next();
- }
-}
-
-/**
- * Sanitize input strings to prevent XSS and injection attacks
- */
-export function sanitizeString(input: string): string {
- if (typeof input !== 'string') return input;
-
- return input
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&#x27;')
- .replace(/\//g, '&#x2F;')
- .replace(/\\/g, '&#x5C;')
- .replace(/`/g, '&#x60;');
-}
-
-/**
- * Validate that a string matches safe patterns
- */
-export function isValidSessionName(name: string): boolean {
- // Only allow alphanumeric, hyphens, underscores, 3-50 chars
- return /^[a-zA-Z0-9_-]{3,50}$/.test(name);
-}
-
-/**
- * Validate WhatsApp chat ID format
- */
-export function isValidChatId(chatId: string): boolean {
- // Format: <phone>@c.us (individual) or <id>@g.us (group)
- return /^\d+@(c\.us|g\.us)$/.test(chatId);
-}
-
-/**
- * Validate phone number format
- */
-export function isValidPhoneNumber(phone: string): boolean {
- // 10-15 digits
- return /^\d{10,15}$/.test(phone);
-}
-
-/**
- * Mask sensitive data for logging
- */
-export function maskSensitiveData(data: string, visibleChars: number = 4): string {
- if (!data || data.length <= visibleChars) return '***';
- return data.substring(0, visibleChars) + '*'.repeat(Math.min(data.length - visibleChars, 8));
-}
-
-/**
- * Security configuration constants
- */
-export const SecurityConfig = {
- // Rate limiting defaults
- rateLimit: {
- short: { ttl: 1000, limit: 10 },
- medium: { ttl: 60000, limit: 100 },
- long: { ttl: 3600000, limit: 1000 },
- },
-
- // Input validation limits
- inputLimits: {
- maxTextLength: 65536,
- maxSessionNameLength: 50,
- maxUrlLength: 2048,
- maxArrayItems: 100,
- },
-
- // Session limits
- sessionLimits: {
- maxSessionsPerInstance: 100,
- sessionIdleTimeout: 86400000, // 24 hours
- qrCodeTimeout: 120000, // 2 minutes
- },
-
- // API key configuration
- apiKey: {
- prefix: 'owa_k1_',
- hashAlgorithm: 'sha256',
- randomBytes: 32,
- prefixLength: 12,
- },
-} as const;
diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.ts
index 2c2c2bb5d..42b11edf7 100644
--- a/src/common/security/ssrf-guard.spec.ts
+++ b/src/common/security/ssrf-guard.spec.ts
@@ -1,4 +1,10 @@
-import { isBlockedAddress, assertSafeWebhookUrl, SsrfBlockedError, isSsrfProtectionEnabled } from './ssrf-guard';
+import {
+ isBlockedAddress,
+ assertSafeFetchUrl,
+ assertNoRedirect,
+ SsrfBlockedError,
+ isSsrfProtectionEnabled,
+} from './ssrf-guard';
describe('isBlockedAddress', () => {
it.each([
@@ -32,29 +38,80 @@ describe('isBlockedAddress', () => {
});
});
-describe('assertSafeWebhookUrl', () => {
+describe('assertSafeFetchUrl', () => {
it('rejects a non-http(s) scheme', async () => {
- await expect(assertSafeWebhookUrl('ftp://example.com/hook')).rejects.toThrow(SsrfBlockedError);
+ await expect(assertSafeFetchUrl('ftp://example.com/hook')).rejects.toThrow(SsrfBlockedError);
});
it('rejects a literal loopback IPv4 host', async () => {
- await expect(assertSafeWebhookUrl('http://127.0.0.1/hook')).rejects.toThrow(SsrfBlockedError);
+ await expect(assertSafeFetchUrl('http://127.0.0.1/hook')).rejects.toThrow(SsrfBlockedError);
});
it('rejects the cloud metadata IP', async () => {
- await expect(assertSafeWebhookUrl('http://169.254.169.254/latest/meta-data')).rejects.toThrow(SsrfBlockedError);
+ await expect(assertSafeFetchUrl('http://169.254.169.254/latest/meta-data')).rejects.toThrow(SsrfBlockedError);
});
it('rejects a literal IPv6 loopback host', async () => {
- await expect(assertSafeWebhookUrl('http://[::1]:8080/hook')).rejects.toThrow(SsrfBlockedError);
+ await expect(assertSafeFetchUrl('http://[::1]:8080/hook')).rejects.toThrow(SsrfBlockedError);
});
it('rejects a hostname that resolves to loopback (localhost)', async () => {
- await expect(assertSafeWebhookUrl('http://localhost:9999/hook')).rejects.toThrow(SsrfBlockedError);
+ await expect(assertSafeFetchUrl('http://localhost:9999/hook')).rejects.toThrow(SsrfBlockedError);
});
it('allows a public literal IP', async () => {
- await expect(assertSafeWebhookUrl('https://8.8.8.8/hook')).resolves.toBeUndefined();
+ await expect(assertSafeFetchUrl('https://8.8.8.8/hook')).resolves.toBeUndefined();
+ });
+});
+
+describe('assertSafeFetchUrl — SSRF_ALLOWED_HOSTS escape-hatch', () => {
+ const orig = process.env.SSRF_ALLOWED_HOSTS;
+ afterEach(() => {
+ if (orig === undefined) delete process.env.SSRF_ALLOWED_HOSTS;
+ else process.env.SSRF_ALLOWED_HOSTS = orig;
+ });
+
+ it('allows an internal host that is explicitly allowlisted (case-insensitive)', async () => {
+ process.env.SSRF_ALLOWED_HOSTS = 'Localhost, minio';
+ await expect(assertSafeFetchUrl('http://localhost:9000/bucket/x.png')).resolves.toBeUndefined();
+ await expect(assertSafeFetchUrl('http://minio:9000/x.png')).resolves.toBeUndefined();
+ });
+
+ it('still blocks internal hosts that are NOT allowlisted', async () => {
+ process.env.SSRF_ALLOWED_HOSTS = 'minio';
+ await expect(assertSafeFetchUrl('http://127.0.0.1/x.png')).rejects.toThrow(SsrfBlockedError);
+ });
+
+ it('allows an allowlisted literal internal IP', async () => {
+ process.env.SSRF_ALLOWED_HOSTS = '10.0.0.5';
+ await expect(assertSafeFetchUrl('http://10.0.0.5/x.png')).resolves.toBeUndefined();
+ });
+
+ it('allows an allowlisted IPv6 literal whether or not it is bracketed', async () => {
+ // The URL hostname is compared bracket-stripped, so a bracketed allowlist entry
+ // (as copy-pasted from a URL) must still match.
+ process.env.SSRF_ALLOWED_HOSTS = '[::1]';
+ await expect(assertSafeFetchUrl('http://[::1]:8080/hook')).resolves.toBeUndefined();
+
+ process.env.SSRF_ALLOWED_HOSTS = '::1';
+ await expect(assertSafeFetchUrl('http://[::1]:8080/hook')).resolves.toBeUndefined();
+ });
+});
+
+describe('assertNoRedirect (redirect bypass)', () => {
+ it('throws on an undici opaqueredirect response', () => {
+ expect(() => assertNoRedirect({ status: 0, type: 'opaqueredirect' }, 'http://evil.example')).toThrow(
+ SsrfBlockedError,
+ );
+ });
+
+ it('throws on a 3xx status (node-fetch manual)', () => {
+ expect(() => assertNoRedirect({ status: 302 }, 'http://evil.example')).toThrow(SsrfBlockedError);
+ expect(() => assertNoRedirect({ status: 301 }, 'http://evil.example')).toThrow(SsrfBlockedError);
+ });
+
+ it('passes a normal 2xx response', () => {
+ expect(() => assertNoRedirect({ status: 200, type: 'basic' }, 'http://ok.example')).not.toThrow();
});
});
@@ -64,10 +121,12 @@ describe('isSsrfProtectionEnabled', () => {
process.env.WEBHOOK_SSRF_PROTECT = orig;
});
- it('is off by default and on only when explicitly "true"', () => {
+ it('is ON by default and off only when explicitly "false"', () => {
delete process.env.WEBHOOK_SSRF_PROTECT;
- expect(isSsrfProtectionEnabled()).toBe(false);
+ expect(isSsrfProtectionEnabled()).toBe(true);
process.env.WEBHOOK_SSRF_PROTECT = 'true';
expect(isSsrfProtectionEnabled()).toBe(true);
+ process.env.WEBHOOK_SSRF_PROTECT = 'false';
+ expect(isSsrfProtectionEnabled()).toBe(false);
});
});
diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.ts
index 15f878c43..945075270 100644
--- a/src/common/security/ssrf-guard.ts
+++ b/src/common/security/ssrf-guard.ts
@@ -1,7 +1,7 @@
import { isIPv4, isIPv6 } from 'net';
import { lookup } from 'dns/promises';
-/** Thrown when an outbound webhook URL is blocked by the SSRF guard. */
+/** Thrown when an outbound URL is blocked by the SSRF guard. */
export class SsrfBlockedError extends Error {
constructor(message: string) {
super(message);
@@ -9,9 +9,35 @@ export class SsrfBlockedError extends Error {
}
}
-/** Opt-in: outbound webhook SSRF protection is only active when WEBHOOK_SSRF_PROTECT=true. */
+/**
+ * Outbound webhook SSRF protection. Default ON; disable only with an explicit
+ * WEBHOOK_SSRF_PROTECT=false (e.g. a closed network that delivers to internal sidecars — prefer
+ * the SSRF_ALLOWED_HOSTS escape-hatch instead of disabling protection wholesale).
+ */
export function isSsrfProtectionEnabled(): boolean {
- return process.env.WEBHOOK_SSRF_PROTECT === 'true';
+ return process.env.WEBHOOK_SSRF_PROTECT !== 'false';
+}
+
+/**
+ * Escape-hatch for self-hosted topologies that intentionally fetch from / deliver to
+ * internal hosts (e.g. a localhost media store or a sidecar webhook receiver).
+ * `SSRF_ALLOWED_HOSTS` is a comma-separated list of hostnames and/or IP literals that
+ * bypass the block. Matched case-insensitively against the URL hostname.
+ */
+function getAllowedHosts(): Set<string> {
+ return new Set(
+ (process.env.SSRF_ALLOWED_HOSTS ?? '')
+ .split(',')
+ // Strip IPv6 brackets so an entry copied from a URL (e.g. "[::1]") matches the
+ // bracket-stripped url.hostname we compare against below.
+ .map(h =>
+ h
+ .trim()
+ .replace(/^\[|\]$/g, '')
+ .toLowerCase(),
+ )
+ .filter(Boolean),
+ );
}
function ipv4ToInt(ip: string): number {
@@ -81,37 +107,55 @@ export function isBlockedAddress(ip: string): boolean {
}
/**
- * Resolves an outbound webhook URL and throws SsrfBlockedError if its scheme is not
+ * Reject a response obtained with `redirect: 'manual'` that turned out to be a redirect.
+ * The pre-fetch SSRF check only validates the original URL, so a followed 3xx to an
+ * internal host would bypass it. We never follow redirects on guarded
+ * fetches; a redirect is treated as a delivery failure.
+ */
+export function assertNoRedirect(response: { status: number; type?: string }, url: string): void {
+ if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {
+ throw new SsrfBlockedError(`Refusing to follow redirect from ${url}`);
+ }
+}
+
+/**
+ * Resolves an outbound URL and throws SsrfBlockedError if its scheme is not
* http(s) or if the host (literal or any DNS-resolved address) is internal/reserved.
+ * Guards both webhook delivery and server-side media fetches. Hosts named in
+ * `SSRF_ALLOWED_HOSTS` are allowed through (escape-hatch for trusted internal targets).
*/
-export async function assertSafeWebhookUrl(rawUrl: string): Promise<void> {
+export async function assertSafeFetchUrl(rawUrl: string): Promise<void> {
let url: URL;
try {
url = new URL(rawUrl);
} catch {
- throw new SsrfBlockedError(`Invalid webhook URL: ${rawUrl}`);
+ throw new SsrfBlockedError(`Invalid URL: ${rawUrl}`);
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
- throw new SsrfBlockedError(`Blocked webhook URL scheme: ${url.protocol}`);
+ throw new SsrfBlockedError(`Blocked URL scheme: ${url.protocol}`);
}
const host = url.hostname.replace(/^\[|\]$/g, ''); // strip IPv6 brackets
+ if (getAllowedHosts().has(host.toLowerCase())) {
+ return; // explicitly allowlisted internal target
+ }
+
if (isIPv4(host) || isIPv6(host)) {
if (isBlockedAddress(host)) {
- throw new SsrfBlockedError(`Blocked internal webhook address: ${host}`);
+ throw new SsrfBlockedError(`Blocked internal address: ${host}`);
}
return;
}
const resolved = await lookup(host, { all: true });
if (resolved.length === 0) {
- throw new SsrfBlockedError(`Could not resolve webhook host: ${host}`);
+ throw new SsrfBlockedError(`Could not resolve host: ${host}`);
}
for (const { address } of resolved) {
if (isBlockedAddress(address)) {
- throw new SsrfBlockedError(`Webhook host ${host} resolves to a blocked internal address: ${address}`);
+ throw new SsrfBlockedError(`Host ${host} resolves to a blocked internal address: ${address}`);
}
}
}
diff --git a/src/common/services/shutdown.service.spec.ts b/src/common/services/shutdown.service.spec.ts
new file mode 100644
index 000000000..d3c6618ee
--- /dev/null
+++ b/src/common/services/shutdown.service.spec.ts
@@ -0,0 +1,20 @@
+import { ShutdownService } from './shutdown.service';
+
+/**
+ * Regression lock: shutdown must flip a draining flag the readiness probe can
+ * read, so the LB stops routing before teardown. (shutdown() itself calls process.exit
+ * and is not invoked here.)
+ */
+describe('ShutdownService (draining flag)', () => {
+ it('is not draining initially', () => {
+ expect(new ShutdownService().isShuttingDown()).toBe(false);
+ });
+
+ it('markShuttingDown flips the flag and is idempotent', () => {
+ const svc = new ShutdownService();
+ svc.markShuttingDown();
+ expect(svc.isShuttingDown()).toBe(true);
+ svc.markShuttingDown(); // no throw, stays true
+ expect(svc.isShuttingDown()).toBe(true);
+ });
+});
diff --git a/src/common/services/shutdown.service.ts b/src/common/services/shutdown.service.ts
index 6a135d745..cde9d5f77 100644
--- a/src/common/services/shutdown.service.ts
+++ b/src/common/services/shutdown.service.ts
@@ -1,10 +1,15 @@
import { Injectable } from '@nestjs/common';
import { createLogger } from './logger.service';
+/** Default grace before teardown; capped so a misconfigured value can't exceed a typical SIGKILL window. */
+const DEFAULT_SHUTDOWN_DELAY_MS = 3000;
+const MAX_SHUTDOWN_DELAY_MS = 30_000;
+
@Injectable()
export class ShutdownService {
private readonly logger = createLogger('ShutdownService');
private destroyCallback: (() => Promise<void>) | null = null;
+ private shuttingDown = false;
/**
* Set the shutdown callback (called from main.ts after app creation)
@@ -14,10 +19,30 @@ export class ShutdownService {
}
/**
- * Trigger graceful shutdown with optional delay
+ * True once shutdown has begun. The readiness probe reports 503 while draining so the
+ * load balancer / orchestrator stops routing NEW traffic before teardown.
+ */
+ isShuttingDown(): boolean {
+ return this.shuttingDown;
+ }
+
+ /** Flip the draining flag (idempotent). Safe to call synchronously from a signal handler. */
+ markShuttingDown(): void {
+ if (!this.shuttingDown) {
+ this.shuttingDown = true;
+ this.logger.log('Entering draining state — readiness now reports 503');
+ }
+ }
+
+ /**
+ * Trigger graceful shutdown after a bounded grace window. Readiness flips to 503 first
+ * (drain), then after the delay the teardown callback runs and the process exits.
*/
- shutdown(delayMs = 3000): void {
- this.logger.log('Graceful shutdown requested', { delayMs });
+ shutdown(delayMs?: number): void {
+ this.markShuttingDown();
+
+ const delay = Math.min(delayMs ?? this.resolveDelay(), MAX_SHUTDOWN_DELAY_MS);
+ this.logger.log('Graceful shutdown requested', { delayMs: delay });
setTimeout(() => {
this.logger.log('Initiating shutdown...');
@@ -33,6 +58,13 @@ export class ShutdownService {
}
};
void doShutdown();
- }, delayMs);
+ }, delay);
+ }
+
+ /** Bounded, configurable grace (SHUTDOWN_DELAY_MS); default 3s, capped at 30s. */
+ private resolveDelay(): number {
+ const parsed = Number.parseInt(process.env.SHUTDOWN_DELAY_MS ?? '', 10);
+ if (!Number.isInteger(parsed) || parsed < 0) return DEFAULT_SHUTDOWN_DELAY_MS;
+ return parsed;
}
}
diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.ts
index 876708cca..7569e028c 100644
--- a/src/common/storage/storage.service.ts
+++ b/src/common/storage/storage.service.ts
@@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';
-import * as archiver from 'archiver';
+import { TarArchive } from 'archiver';
import * as tar from 'tar-stream';
import { createGunzip } from 'zlib';
import { Readable, PassThrough } from 'stream';
@@ -157,7 +157,7 @@ export class StorageService {
const files = await this.listFiles();
const output = new PassThrough();
- const archive = archiver.default('tar', {
+ const archive = new TarArchive({
gzip: true,
gzipOptions: { level: 6 },
});
diff --git a/src/common/utils/ip.ts b/src/common/utils/ip.ts
index 8f1bee54c..817228042 100644
--- a/src/common/utils/ip.ts
+++ b/src/common/utils/ip.ts
@@ -9,6 +9,54 @@ export function normalizeIp(ip: string): string {
return match ? match[1] : ip;
}
+/** Minimal request shape needed for client-IP resolution (framework-agnostic). */
+export interface RequestLike {
+ ip?: string;
+ socket?: { remoteAddress?: string };
+ headers: Record<string, string | string[] | undefined>;
+}
+
+/**
+ * Resolve the real client IP. X-Forwarded-For is client-controllable, so it is only
+ * honored when the request actually arrives from a configured trusted proxy. With no
+ * trusted proxies, the direct socket address is used (prevents XFF spoofing). Shared by
+ * ApiKeyGuard (allowedIps whitelist) and the throttler (per-client rate-limit bucket).
+ */
+export function resolveClientIp(req: RequestLike, trustedProxies: string[]): string {
+ const socketIp = normalizeIp(req.socket?.remoteAddress || req.ip || '');
+
+ if (!trustedProxies || trustedProxies.length === 0) {
+ return socketIp;
+ }
+
+ const isTrusted = (ip: string): boolean => trustedProxies.some(proxy => ipMatches(ip, proxy));
+
+ // Only trust the forwarded chain if the immediate peer is a trusted proxy.
+ if (!isTrusted(socketIp)) {
+ return socketIp;
+ }
+
+ const forwarded = req.headers['x-forwarded-for'];
+ if (!forwarded) {
+ return socketIp;
+ }
+
+ const hops = (Array.isArray(forwarded) ? forwarded.join(',') : forwarded)
+ .split(',')
+ .map(hop => normalizeIp(hop.trim()))
+ .filter(Boolean);
+
+ // Walk right-to-left and return the first hop that is not a trusted proxy:
+ // the closest address the trusted infrastructure actually observed.
+ for (let i = hops.length - 1; i >= 0; i--) {
+ if (!isTrusted(hops[i])) {
+ return hops[i];
+ }
+ }
+
+ return socketIp;
+}
+
function ipv4ToInt(ip: string): number | null {
const parts = ip.split('.');
if (parts.length !== 4) return null;
diff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.ts
index 5890d2d98..6f80ba986 100644
--- a/src/config/bootstrap-security.spec.ts
+++ b/src/config/bootstrap-security.spec.ts
@@ -1,4 +1,9 @@
-import { resolveCorsPolicy, isSwaggerEnabled, resolveBodyLimit } from './bootstrap-security';
+import {
+ resolveCorsPolicy,
+ isSwaggerEnabled,
+ resolveBodyLimit,
+ assertNoDefaultSecretsInProduction,
+} from './bootstrap-security';
describe('resolveCorsPolicy', () => {
it('defaults to wildcard in development, without credentials', () => {
@@ -58,3 +63,77 @@ describe('resolveBodyLimit', () => {
expect(resolveBodyLimit('5mb')).toBe('5mb');
});
});
+
+describe('assertNoDefaultSecretsInProduction', () => {
+ it('is a no-op outside production, even with default secrets', () => {
+ expect(() =>
+ assertNoDefaultSecretsInProduction({
+ nodeEnv: 'development',
+ databaseType: 'postgres',
+ databasePassword: 'openwa',
+ storageType: 's3',
+ s3AccessKey: 'minioadmin',
+ s3SecretKey: 'minioadmin',
+ }),
+ ).not.toThrow();
+ });
+
+ it('refuses prod with a default Postgres password', () => {
+ expect(() =>
+ assertNoDefaultSecretsInProduction({
+ nodeEnv: 'production',
+ databaseType: 'postgres',
+ databasePassword: 'openwa',
+ }),
+ ).toThrow(/DATABASE_PASSWORD/);
+ });
+
+ it('refuses prod with an empty Postgres password', () => {
+ expect(() =>
+ assertNoDefaultSecretsInProduction({ nodeEnv: 'production', databaseType: 'postgres', databasePassword: '' }),
+ ).toThrow(/DATABASE_PASSWORD/);
+ });
+
+ it('refuses prod with default MinIO/S3 credentials', () => {
+ expect(() =>
+ assertNoDefaultSecretsInProduction({
+ nodeEnv: 'production',
+ storageType: 's3',
+ s3AccessKey: 'minioadmin',
+ s3SecretKey: 'minioadmin',
+ }),
+ ).toThrow(/S3_ACCESS_KEY, S3_SECRET_KEY/);
+ });
+
+ it('refuses prod with a placeholder API_MASTER_KEY', () => {
+ expect(() => assertNoDefaultSecretsInProduction({ nodeEnv: 'production', apiMasterKey: 'dev-master-key' })).toThrow(
+ /API_MASTER_KEY/,
+ );
+ });
+
+ it('allows the default sqlite + local-storage prod setup (no secrets needed)', () => {
+ expect(() =>
+ assertNoDefaultSecretsInProduction({ nodeEnv: 'production', databaseType: 'sqlite', storageType: 'local' }),
+ ).not.toThrow();
+ });
+
+ it('allows prod with strong, unique secrets', () => {
+ expect(() =>
+ assertNoDefaultSecretsInProduction({
+ nodeEnv: 'production',
+ databaseType: 'postgres',
+ databasePassword: 'Xy7$kP2qLm9wRt4z',
+ storageType: 's3',
+ s3AccessKey: 'AKIA-not-default-123',
+ s3SecretKey: 'long-random-secret-value-098',
+ }),
+ ).not.toThrow();
+ });
+
+ it('does not check the DB password when using sqlite', () => {
+ // DATABASE_PASSWORD is irrelevant for sqlite, so a leftover default must not block boot.
+ expect(() =>
+ assertNoDefaultSecretsInProduction({ nodeEnv: 'production', databaseType: 'sqlite', databasePassword: 'openwa' }),
+ ).not.toThrow();
+ });
+});
diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.ts
index d5dcbb11e..0d6e220b9 100644
--- a/src/config/bootstrap-security.ts
+++ b/src/config/bootstrap-security.ts
@@ -43,3 +43,58 @@ export function resolveBodyLimit(bodySizeEnv?: string): string {
const trimmed = bodySizeEnv?.trim();
return trimmed ? trimmed : '25mb';
}
+
+/** Known weak/default/placeholder secret values that must never reach production. */
+const FORBIDDEN_PROD_SECRETS = new Set([
+ 'openwa',
+ 'minioadmin',
+ 'your-secure-password',
+ 'dev-master-key',
+ 'changeme',
+ 'change-me',
+ 'password',
+ 'secret',
+ 'admin',
+]);
+
+export interface SecretCheckEnv {
+ nodeEnv?: string;
+ databaseType?: string;
+ databasePassword?: string;
+ storageType?: string;
+ s3AccessKey?: string;
+ s3SecretKey?: string;
+ apiMasterKey?: string;
+}
+
+/**
+ * Refuse to boot in production when a required secret is empty or a known default/
+ * placeholder. Only secrets actually in use are checked: the DB password
+ * when DATABASE_TYPE=postgres, the S3 keys when STORAGE_TYPE=s3, and API_MASTER_KEY
+ * whenever it is set. Throws with the offending var names so the operator can fix them.
+ */
+export function assertNoDefaultSecretsInProduction(env: SecretCheckEnv): void {
+ if (env.nodeEnv !== 'production') return;
+
+ const isWeak = (value?: string): boolean => !value || FORBIDDEN_PROD_SECRETS.has(value.trim().toLowerCase());
+ const problems: string[] = [];
+
+ if (env.databaseType === 'postgres' && isWeak(env.databasePassword)) {
+ problems.push('DATABASE_PASSWORD');
+ }
+ if (env.storageType === 's3') {
+ if (isWeak(env.s3AccessKey)) problems.push('S3_ACCESS_KEY');
+ if (isWeak(env.s3SecretKey)) problems.push('S3_SECRET_KEY');
+ }
+ // API_MASTER_KEY is optional, but if provided it must not be a known default.
+ if (env.apiMasterKey && FORBIDDEN_PROD_SECRETS.has(env.apiMasterKey.trim().toLowerCase())) {
+ problems.push('API_MASTER_KEY');
+ }
+
+ if (problems.length > 0) {
+ throw new Error(
+ `Refusing to start in production: insecure or default value for ${problems.join(', ')}. ` +
+ 'Set strong, unique secrets (see .env.example).',
+ );
+ }
+}
diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.ts
new file mode 100644
index 000000000..98b5c7f67
--- /dev/null
+++ b/src/config/configuration.spec.ts
@@ -0,0 +1,37 @@
+import configuration from './configuration';
+
+describe('configuration — main DB synchronize', () => {
+ const orig = process.env.MAIN_DATABASE_SYNCHRONIZE;
+
+ afterEach(() => {
+ if (orig === undefined) delete process.env.MAIN_DATABASE_SYNCHRONIZE;
+ else process.env.MAIN_DATABASE_SYNCHRONIZE = orig;
+ });
+
+ it('defaults main synchronize ON (zero-config first boot)', () => {
+ delete process.env.MAIN_DATABASE_SYNCHRONIZE;
+ expect(configuration().database.synchronize).toBe(true);
+ });
+
+ it('disables synchronize only when MAIN_DATABASE_SYNCHRONIZE="false"', () => {
+ process.env.MAIN_DATABASE_SYNCHRONIZE = 'false';
+ expect(configuration().database.synchronize).toBe(false);
+ process.env.MAIN_DATABASE_SYNCHRONIZE = 'true';
+ expect(configuration().database.synchronize).toBe(true);
+ });
+});
+
+describe('configuration — Postgres database name', () => {
+ const orig = process.env.DATABASE_NAME;
+ afterEach(() => {
+ if (orig === undefined) delete process.env.DATABASE_NAME;
+ else process.env.DATABASE_NAME = orig;
+ });
+
+ it('resolves dataDatabase.name from DATABASE_NAME (matches the migration CLI), default openwa', () => {
+ delete process.env.DATABASE_NAME;
+ expect(configuration().dataDatabase.name).toBe('openwa');
+ process.env.DATABASE_NAME = 'prod_db';
+ expect(configuration().dataDatabase.name).toBe('prod_db');
+ });
+});
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index 09abd9525..f08c9b35b 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -22,7 +22,10 @@ export default () => ({
database: {
type: 'sqlite' as const,
database: './data/main.sqlite',
- synchronize: true,
+ // Schema management for the auth/audit DB. Default ON (zero-config first boot).
+ // Set MAIN_DATABASE_SYNCHRONIZE=false to manage schema via the main-owned migrations
+ // instead (migrationsRun then creates api_keys/audit_logs).
+ synchronize: process.env.MAIN_DATABASE_SYNCHRONIZE !== 'false',
logging: process.env.DATABASE_LOGGING === 'true',
},
@@ -31,6 +34,10 @@ export default () => ({
type: process.env.DATABASE_TYPE || 'sqlite',
// SQLite path (used when type is sqlite)
database: process.env.DATABASE_NAME || './data/openwa.sqlite',
+ // Postgres database NAME (used when type is postgres). Resolved from the same
+ // DATABASE_NAME env as the migration CLI (data-source.ts) so the runtime factory and
+ // migrations never target different databases. Distinct sqlite-vs-pg defaults.
+ name: process.env.DATABASE_NAME || 'openwa',
// PostgreSQL/MySQL connection (used when type is postgres/mysql)
host: process.env.DATABASE_HOST || 'localhost',
port: parseInt(process.env.DATABASE_PORT || '5432', 10),
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
new file mode 100644
index 000000000..ee0ca3249
--- /dev/null
+++ b/src/config/env.validation.spec.ts
@@ -0,0 +1,26 @@
+import { validateEnv } from './env.validation';
+
+/** Regression locks for boot-time env validation (no silent coercion). */
+describe('validateEnv', () => {
+ it('passes the zero-config default (sqlite, no pg vars)', () => {
+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite' })).not.toThrow();
+ expect(() => validateEnv({})).not.toThrow();
+ });
+
+ it('rejects a DATABASE_TYPE typo instead of silently falling back to SQLite', () => {
+ expect(() => validateEnv({ DATABASE_TYPE: 'postgre' })).toThrow(/DATABASE_TYPE/);
+ });
+
+ it('requires host/username/password when DATABASE_TYPE=postgres', () => {
+ expect(() => validateEnv({ DATABASE_TYPE: 'postgres' })).toThrow(/DATABASE_PASSWORD/);
+ expect(() =>
+ validateEnv({ DATABASE_TYPE: 'postgres', DATABASE_HOST: 'db', DATABASE_USERNAME: 'u', DATABASE_PASSWORD: 'p' }),
+ ).not.toThrow();
+ });
+
+ it('rejects a non-integer / out-of-range port', () => {
+ expect(() => validateEnv({ DATABASE_PORT: 'abc' })).toThrow(/DATABASE_PORT/);
+ expect(() => validateEnv({ PORT: '70000' })).toThrow(/PORT/);
+ expect(() => validateEnv({ PORT: '2785' })).not.toThrow();
+ });
+});
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
new file mode 100644
index 000000000..de17d8b1c
--- /dev/null
+++ b/src/config/env.validation.ts
@@ -0,0 +1,50 @@
+type EnvConfig = Record<string, unknown>;
+
+/**
+ * Fail-fast environment validation. Wired as ConfigModule's `validate`
+ * callback so a misconfigured deployment is rejected at BOOT instead of silently
+ * coercing (e.g. a `DATABASE_TYPE=postgre` typo falling back to SQLite) or failing on
+ * the first query. Hand-rolled to avoid adding a `joi` dependency; same guarantees:
+ * - DATABASE_TYPE must be a known value (no silent SQLite fallback on a typo)
+ * - Postgres requires host/username/password
+ * - PORT / DATABASE_PORT / REDIS_PORT must be valid integer ports
+ */
+export function validateEnv(config: EnvConfig): EnvConfig {
+ const errors: string[] = [];
+
+ const str = (key: string): string | undefined => {
+ const value = config[key];
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
+ };
+
+ const dbType = str('DATABASE_TYPE');
+ if (dbType && dbType !== 'sqlite' && dbType !== 'postgres') {
+ errors.push(`DATABASE_TYPE must be "sqlite" or "postgres" (got "${dbType}")`);
+ }
+
+ if (dbType === 'postgres') {
+ for (const key of ['DATABASE_HOST', 'DATABASE_USERNAME', 'DATABASE_PASSWORD']) {
+ if (!str(key)) {
+ errors.push(`${key} is required when DATABASE_TYPE=postgres`);
+ }
+ }
+ }
+
+ const checkPort = (key: string): void => {
+ const raw = str(key);
+ if (raw === undefined) return;
+ const n = Number(raw);
+ if (!Number.isInteger(n) || n < 1 || n > 65535) {
+ errors.push(`${key} must be an integer port in [1, 65535] (got "${raw}")`);
+ }
+ };
+ checkPort('PORT');
+ checkPort('DATABASE_PORT');
+ checkPort('REDIS_PORT');
+
+ if (errors.length > 0) {
+ throw new Error(`Invalid environment configuration:\n - ${errors.join('\n - ')}`);
+ }
+
+ return config;
+}
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
new file mode 100644
index 000000000..9b370eff1
--- /dev/null
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -0,0 +1,26 @@
+import * as path from 'path';
+import { resolvePluginMainPath } from './plugin-loader.service';
+
+/** Regression lock: a plugin's manifest.main must not escape its plugin directory. */
+describe('resolvePluginMainPath', () => {
+ const dir = '/app/data/plugins';
+
+ it('allows a normal entry inside the plugin directory', () => {
+ expect(resolvePluginMainPath(dir, 'my-plugin', 'index.js')).toBe(path.resolve(dir, 'my-plugin', 'index.js'));
+ expect(resolvePluginMainPath(dir, 'my-plugin', 'dist/main.js')).toBe(
+ path.resolve(dir, 'my-plugin', 'dist/main.js'),
+ );
+ });
+
+ it('rejects a path-traversal escape (../../)', () => {
+ expect(() => resolvePluginMainPath(dir, 'my-plugin', '../../etc/passwd')).toThrow(/escapes/);
+ });
+
+ it('rejects an absolute path', () => {
+ expect(() => resolvePluginMainPath(dir, 'my-plugin', '/etc/passwd')).toThrow(/escapes/);
+ });
+
+ it('rejects climbing into a sibling plugin', () => {
+ expect(() => resolvePluginMainPath(dir, 'my-plugin', '../other-plugin/evil.js')).toThrow(/escapes/);
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 2117d146f..db4bd6cc9 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -15,6 +15,20 @@ import {
} from './plugin.interfaces';
import { PluginStorageService } from './plugin-storage.service';
+/**
+ * Resolve a plugin's `main` entry to an absolute path, asserting it stays inside
+ * <pluginsDir>/<pluginId>. `main` comes from a user-supplied manifest, so a
+ * value like '../../etc/passwd' (or an absolute path) must be rejected BEFORE require().
+ */
+export function resolvePluginMainPath(pluginsDir: string, pluginId: string, main: string): string {
+ const base = path.resolve(pluginsDir, pluginId);
+ const mainPath = path.resolve(base, main);
+ if (mainPath !== base && !mainPath.startsWith(base + path.sep)) {
+ throw new Error(`Plugin ${pluginId} main path escapes the plugin directory`);
+ }
+ return mainPath;
+}
+
@Injectable()
export class PluginLoaderService implements OnModuleInit {
private readonly logger = createLogger('PluginLoaderService');
@@ -134,7 +148,8 @@ export class PluginLoaderService implements OnModuleInit {
// Load the plugin instance if not already loaded
if (!plugin.instance) {
- const mainPath = path.join(this.pluginsDir, pluginId, plugin.manifest.main);
+ // Containment guard: reject a manifest.main that escapes the plugin dir.
+ const mainPath = resolvePluginMainPath(this.pluginsDir, pluginId, plugin.manifest.main);
// Dynamic require for user plugins
// eslint-disable-next-line @typescript-eslint/no-require-imports
const pluginModule = require(mainPath) as { default?: new () => IPlugin };
diff --git a/src/database/migrations-main/1779900000000-CreateAuthAuditTables.ts b/src/database/migrations-main/1779900000000-CreateAuthAuditTables.ts
new file mode 100644
index 000000000..561f582a2
--- /dev/null
+++ b/src/database/migrations-main/1779900000000-CreateAuthAuditTables.ts
@@ -0,0 +1,70 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Creates the `api_keys` (auth) and `audit_logs` tables on the **main** connection.
+ * The main connection was previously schema-managed only by
+ * `synchronize: true`, with no migrations — so turning synchronize off would leave a
+ * fresh install with no `api_keys` table and total auth failure at boot.
+ *
+ * This migration is what the `main` connection runs when `MAIN_DATABASE_SYNCHRONIZE=false`
+ * (`migrationsRun: !synchronize`). The main DB is always SQLite (boot config). `IF NOT EXISTS`
+ * makes it idempotent so it is also safe to adopt on a DB previously created by synchronize.
+ */
+export class CreateAuthAuditTables1779900000000 implements MigrationInterface {
+ name = 'CreateAuthAuditTables1779900000000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `CREATE TABLE IF NOT EXISTS "api_keys" (` +
+ `"id" varchar PRIMARY KEY NOT NULL, ` +
+ `"name" varchar(100) NOT NULL, ` +
+ `"keyHash" varchar(64) NOT NULL, ` +
+ `"keyPrefix" varchar(12) NOT NULL, ` +
+ `"role" varchar(20) NOT NULL DEFAULT ('operator'), ` +
+ `"allowedIps" text, ` +
+ `"allowedSessions" text, ` +
+ `"isActive" boolean NOT NULL DEFAULT (1), ` +
+ `"expiresAt" datetime, ` +
+ `"lastUsedAt" datetime, ` +
+ `"usageCount" integer NOT NULL DEFAULT (0), ` +
+ `"createdAt" datetime NOT NULL DEFAULT (datetime('now')), ` +
+ `"updatedAt" datetime NOT NULL DEFAULT (datetime('now'))` +
+ `)`,
+ );
+ await queryRunner.query(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_api_keys_keyHash" ON "api_keys" ("keyHash")`);
+
+ await queryRunner.query(
+ `CREATE TABLE IF NOT EXISTS "audit_logs" (` +
+ `"id" varchar PRIMARY KEY NOT NULL, ` +
+ `"action" varchar(50) NOT NULL, ` +
+ `"severity" varchar(10) NOT NULL DEFAULT ('info'), ` +
+ `"apiKeyId" varchar(36), ` +
+ `"apiKeyName" varchar(100), ` +
+ `"sessionId" varchar(36), ` +
+ `"sessionName" varchar(100), ` +
+ `"ipAddress" varchar(45), ` +
+ `"userAgent" varchar(500), ` +
+ `"method" varchar(10), ` +
+ `"path" varchar(500), ` +
+ `"statusCode" integer, ` +
+ `"metadata" text, ` +
+ `"errorMessage" text, ` +
+ `"createdAt" datetime NOT NULL DEFAULT (datetime('now'))` +
+ `)`,
+ );
+ await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_audit_logs_action" ON "audit_logs" ("action")`);
+ await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_audit_logs_apiKeyId" ON "audit_logs" ("apiKeyId")`);
+ await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_audit_logs_sessionId" ON "audit_logs" ("sessionId")`);
+ await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_audit_logs_createdAt" ON "audit_logs" ("createdAt")`);
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_audit_logs_createdAt"`);
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_audit_logs_sessionId"`);
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_audit_logs_apiKeyId"`);
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_audit_logs_action"`);
+ await queryRunner.query(`DROP TABLE IF EXISTS "audit_logs"`);
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_api_keys_keyHash"`);
+ await queryRunner.query(`DROP TABLE IF EXISTS "api_keys"`);
+ }
+}
diff --git a/src/database/migrations-main/__tests__/1779900000000-CreateAuthAuditTables.spec.ts b/src/database/migrations-main/__tests__/1779900000000-CreateAuthAuditTables.spec.ts
new file mode 100644
index 000000000..07210cce5
--- /dev/null
+++ b/src/database/migrations-main/__tests__/1779900000000-CreateAuthAuditTables.spec.ts
@@ -0,0 +1,70 @@
+import { DataSource } from 'typeorm';
+import { CreateAuthAuditTables1779900000000 } from '../1779900000000-CreateAuthAuditTables';
+
+/**
+ * Regression lock: the main-connection migration must create the
+ * api_keys + audit_logs schema so that running with MAIN_DATABASE_SYNCHRONIZE=false
+ * does NOT leave a fresh install without an auth table (total auth failure at boot).
+ */
+describe('CreateAuthAuditTables migration', () => {
+ let ds: DataSource;
+
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'sqlite', database: ':memory:', entities: [], synchronize: false });
+ await ds.initialize();
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ it('creates api_keys + audit_logs (so auth works without synchronize)', async () => {
+ const qr = ds.createQueryRunner();
+ await new CreateAuthAuditTables1779900000000().up(qr);
+
+ const tables = (await qr.query("SELECT name FROM sqlite_master WHERE type='table'")) as Array<{ name: string }>;
+ const names = tables.map(t => t.name);
+ expect(names).toContain('api_keys');
+ expect(names).toContain('audit_logs');
+
+ const indexes = (await qr.query(
+ "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='api_keys'",
+ )) as Array<{ name: string }>;
+ expect(indexes.some(i => i.name === 'IDX_api_keys_keyHash')).toBe(true);
+
+ // An API key row inserts and gets its column defaults — i.e. auth can read/write it.
+ await qr.query("INSERT INTO api_keys (id, name, keyHash, keyPrefix) VALUES ('1', 'k', 'hash', 'pref')");
+ const rows = (await qr.query("SELECT role, isActive, usageCount FROM api_keys WHERE id = '1'")) as Array<{
+ role: string;
+ isActive: number;
+ usageCount: number;
+ }>;
+ expect(rows[0].role).toBe('operator');
+ expect(rows[0].usageCount).toBe(0);
+
+ await qr.release();
+ });
+
+ it('is idempotent (safe to run on a DB that already has the tables)', async () => {
+ const qr = ds.createQueryRunner();
+ const migration = new CreateAuthAuditTables1779900000000();
+ await migration.up(qr);
+ // running again must NOT throw (CREATE TABLE IF NOT EXISTS)
+ await expect(migration.up(qr)).resolves.not.toThrow();
+ await qr.release();
+ });
+
+ it('down() drops both tables', async () => {
+ const qr = ds.createQueryRunner();
+ const migration = new CreateAuthAuditTables1779900000000();
+ await migration.up(qr);
+ await migration.down(qr);
+
+ const tables = (await qr.query("SELECT name FROM sqlite_master WHERE type='table'")) as Array<{ name: string }>;
+ const names = tables.map(t => t.name);
+ expect(names).not.toContain('api_keys');
+ expect(names).not.toContain('audit_logs');
+
+ await qr.release();
+ });
+});
diff --git a/src/database/migrations/1779900100000-AddMessageSessionWaIndex.ts b/src/database/migrations/1779900100000-AddMessageSessionWaIndex.ts
new file mode 100644
index 000000000..376be433b
--- /dev/null
+++ b/src/database/migrations/1779900100000-AddMessageSessionWaIndex.ts
@@ -0,0 +1,22 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Composite index on messages(sessionId, waMessageId) for the ack-driven status UPDATE.
+ * Without it, every WhatsApp ack scans the entire (hot) messages table.
+ *
+ * Runs on the `data` connection. `IF NOT EXISTS` keeps it portable + idempotent across
+ * SQLite and Postgres, and safe on a DB where `synchronize` already created the index.
+ */
+export class AddMessageSessionWaIndex1779900100000 implements MigrationInterface {
+ name = 'AddMessageSessionWaIndex1779900100000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `CREATE INDEX IF NOT EXISTS "IDX_messages_sessionId_waMessageId" ON "messages" ("sessionId", "waMessageId")`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_messages_sessionId_waMessageId"`);
+ }
+}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 1004ea80c..47be6c4e3 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1,5 +1,7 @@
-import { WhatsAppWebJsAdapter, extractLinkedParentJID } from './whatsapp-web-js.adapter';
+import { MessageMedia } from 'whatsapp-web.js';
+import { WhatsAppWebJsAdapter, extractLinkedParentJID, loadRemoteMedia } from './whatsapp-web-js.adapter';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
+import { SsrfBlockedError } from '../../common/security/ssrf-guard';
describe('extractLinkedParentJID (#201)', () => {
it('returns null when no metadata is provided', () => {
@@ -37,6 +39,54 @@ describe('extractLinkedParentJID (#201)', () => {
});
});
+describe('loadRemoteMedia — media-fetch SSRF guard + cap + timeout', () => {
+ let fromUrlSpy: jest.SpyInstance;
+
+ beforeEach(() => {
+ fromUrlSpy = jest
+ .spyOn(MessageMedia, 'fromUrl')
+ .mockResolvedValue(new MessageMedia('image/png', 'ZmFrZQ==', 'x.png'));
+ });
+
+ afterEach(() => {
+ fromUrlSpy.mockRestore();
+ delete process.env.SSRF_ALLOWED_HOSTS;
+ });
+
+ it('blocks an internal/loopback URL BEFORE any fetch (no outbound socket)', async () => {
+ await expect(loadRemoteMedia('http://127.0.0.1/x.png')).rejects.toBeInstanceOf(SsrfBlockedError);
+ expect(fromUrlSpy).not.toHaveBeenCalled();
+ });
+
+ it('blocks the cloud-metadata IP before fetching', async () => {
+ await expect(loadRemoteMedia('http://169.254.169.254/latest/meta-data/x.png')).rejects.toBeInstanceOf(
+ SsrfBlockedError,
+ );
+ expect(fromUrlSpy).not.toHaveBeenCalled();
+ });
+
+ it('fetches a public URL with a byte cap and an abort-timeout signal', async () => {
+ await loadRemoteMedia('https://8.8.8.8/x.png');
+
+ expect(fromUrlSpy).toHaveBeenCalledTimes(1);
+ const [url, options] = fromUrlSpy.mock.calls[0] as [
+ string,
+ { reqOptions: { size: number; signal: unknown; redirect: string } },
+ ];
+ expect(url).toBe('https://8.8.8.8/x.png');
+ expect(typeof options.reqOptions.size).toBe('number');
+ expect(options.reqOptions.size).toBeGreaterThan(0);
+ expect(options.reqOptions.signal).toBeInstanceOf(AbortSignal);
+ expect(options.reqOptions.redirect).toBe('error'); // never follow redirects
+ });
+
+ it('honors the SSRF_ALLOWED_HOSTS escape-hatch for trusted internal media stores', async () => {
+ process.env.SSRF_ALLOWED_HOSTS = 'minio';
+ await loadRemoteMedia('http://minio:9000/bucket/x.png');
+ expect(fromUrlSpy).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('WhatsAppWebJsAdapter readiness guard (#100)', () => {
const newAdapter = (): WhatsAppWebJsAdapter =>
new WhatsAppWebJsAdapter({ sessionId: 'sess-1', sessionDataPath: './data/sessions', puppeteer: {} });
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 88fd52c8a..fa0e781f8 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -32,6 +32,7 @@ import {
} from '../interfaces/whatsapp-engine.interface';
import { createLogger } from '../../common/services/logger.service';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
+import { assertSafeFetchUrl } from '../../common/security/ssrf-guard';
import {
GroupChat,
GroupMetadataRaw,
@@ -42,6 +43,36 @@ import {
} from '../types/whatsapp-web-js.types';
import { buildIncomingMessageBase } from './message-mapper';
+/** Default cap on a server-side media download: 50 MiB (overridable via MEDIA_DOWNLOAD_MAX_BYTES). */
+const DEFAULT_MEDIA_MAX_BYTES = 50 * 1024 * 1024;
+/** Default timeout for a server-side media download: 30s (overridable via MEDIA_DOWNLOAD_TIMEOUT_MS). */
+const DEFAULT_MEDIA_TIMEOUT_MS = 30_000;
+
+function positiveIntFromEnv(name: string, fallback: number): number {
+ const parsed = Number.parseInt(process.env[name] ?? '', 10);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
+}
+
+/**
+ * Fetch remote media for sending, with an SSRF host guard, a byte cap, and a timeout.
+ * The guard runs BEFORE any network call, so an internal/reserved URL throws `SsrfBlockedError`
+ * and no outbound socket is opened. The byte cap (node-fetch `size`) and `AbortSignal` timeout
+ * bound memory use and hang time. `unsafeMime` is left at its default (false) to preserve the
+ * existing MIME-detection behavior.
+ */
+export async function loadRemoteMedia(url: string): Promise<MessageMedia> {
+ await assertSafeFetchUrl(url);
+ return MessageMedia.fromUrl(url, {
+ reqOptions: {
+ size: positiveIntFromEnv('MEDIA_DOWNLOAD_MAX_BYTES', DEFAULT_MEDIA_MAX_BYTES),
+ signal: AbortSignal.timeout(positiveIntFromEnv('MEDIA_DOWNLOAD_TIMEOUT_MS', DEFAULT_MEDIA_TIMEOUT_MS)),
+ // Never follow redirects: the SSRF guard only validated the original host, so a
+ // followed 3xx could reach an internal target. node-fetch rejects on redirect.
+ redirect: 'error',
+ },
+ });
+}
+
export interface WhatsAppWebJsConfig {
sessionId: string;
sessionDataPath: string;
@@ -402,7 +433,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
if (typeof media.data === 'string') {
if (media.data.startsWith('http://') || media.data.startsWith('https://')) {
// URL
- messageMedia = await MessageMedia.fromUrl(media.data);
+ messageMedia = await loadRemoteMedia(media.data);
} else {
// Base64
messageMedia = new MessageMedia(media.mimetype, media.data, media.filename);
@@ -531,7 +562,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
if (typeof media.data === 'string') {
if (media.data.startsWith('http://') || media.data.startsWith('https://')) {
- messageMedia = await MessageMedia.fromUrl(media.data);
+ messageMedia = await loadRemoteMedia(media.data);
} else {
messageMedia = new MessageMedia(media.mimetype, media.data, media.filename);
}
diff --git a/src/main.ts b/src/main.ts
index 5ef450d09..01b5fccba 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -5,7 +5,12 @@ import helmet from 'helmet';
import { AppModule } from './app.module';
import { ShutdownService } from './common/services/shutdown.service';
import { createSwaggerConfig } from './config/swagger.config';
-import { resolveCorsPolicy, isSwaggerEnabled, resolveBodyLimit } from './config/bootstrap-security';
+import {
+ resolveCorsPolicy,
+ isSwaggerEnabled,
+ resolveBodyLimit,
+ assertNoDefaultSecretsInProduction,
+} from './config/bootstrap-security';
import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';
import { AuthService } from './modules/auth/auth.service';
import { Request, Response, NextFunction, json, urlencoded } from 'express';
@@ -70,6 +75,17 @@ STORAGE_PATH=./data/media
}
async function bootstrap() {
+ // Fail fast: never start production with default/placeholder secrets.
+ assertNoDefaultSecretsInProduction({
+ nodeEnv: process.env.NODE_ENV,
+ databaseType: process.env.DATABASE_TYPE,
+ databasePassword: process.env.DATABASE_PASSWORD,
+ storageType: process.env.STORAGE_TYPE,
+ s3AccessKey: process.env.S3_ACCESS_KEY,
+ s3SecretKey: process.env.S3_SECRET_KEY,
+ apiMasterKey: process.env.API_MASTER_KEY,
+ });
+
// Disable Nest's default body parser so we can set an explicit size cap below.
const app = await NestFactory.create(AppModule, { bodyParser: false });
@@ -88,7 +104,14 @@ async function bootstrap() {
await app.close();
});
- // Enhanced Security Headers (Phase 3 Security Audit)
+ // On a termination signal, flip readiness to 503 immediately so the load
+ // balancer/orchestrator stops routing new traffic. This only sets a flag — NestJS's
+ // own shutdown hooks (enabled above) still perform the actual app.close()/teardown.
+ for (const signal of ['SIGTERM', 'SIGINT'] as const) {
+ process.on(signal, () => shutdownService.markShuttingDown());
+ }
+
+ // Enhanced Security Headers
app.use(
helmet({
contentSecurityPolicy: {
@@ -115,7 +138,7 @@ async function bootstrap() {
}),
);
- // CORS Configuration (Phase 3 Security Audit; #221 hardening)
+ // CORS Configuration (#221 hardening)
const corsPolicy = resolveCorsPolicy(process.env.CORS_ORIGINS, process.env.NODE_ENV);
if (process.env.NODE_ENV === 'production' && corsPolicy.origins.length === 0 && !corsPolicy.allowAnyOrigin) {
console.warn(
diff --git a/src/modules/auth/auth-validate.controller.ts b/src/modules/auth/auth-validate.controller.ts
index bc2798317..71c5c6ba5 100644
--- a/src/modules/auth/auth-validate.controller.ts
+++ b/src/modules/auth/auth-validate.controller.ts
@@ -17,6 +17,10 @@ export class AuthValidateController {
@ApiResponse({ status: 200, description: 'API key is valid' })
@ApiResponse({ status: 401, description: 'Invalid or missing API key' })
async validate(@Headers('x-api-key') apiKey?: string): Promise<{ valid: boolean; role?: string }> {
+ // This route is behind the global API-key guard, so in normal operation only a valid key
+ // reaches this handler (a missing/invalid key 401s first) and the `valid:false` branches
+ // below are unreachable. They are retained as defense-in-depth in case the guard
+ // config ever changes — they are cheap and keep the endpoint safe to expose directly.
if (!apiKey) {
return { valid: false };
}
diff --git a/src/modules/auth/auth.module.ts b/src/modules/auth/auth.module.ts
index 6ac0e25f7..441baa16f 100644
--- a/src/modules/auth/auth.module.ts
+++ b/src/modules/auth/auth.module.ts
@@ -1,12 +1,12 @@
import { Module, Global } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { APP_GUARD } from '@nestjs/core';
-import { ThrottlerGuard } from '@nestjs/throttler';
import { ApiKey } from './entities/api-key.entity';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { AuthValidateController } from './auth-validate.controller';
import { ApiKeyGuard } from './guards/api-key.guard';
+import { ProxyAwareThrottlerGuard } from '../../common/security/proxy-aware-throttler.guard';
@Global()
@Module({
@@ -16,7 +16,7 @@ import { ApiKeyGuard } from './guards/api-key.guard';
AuthService,
{
provide: APP_GUARD,
- useClass: ThrottlerGuard,
+ useClass: ProxyAwareThrottlerGuard,
},
{
provide: APP_GUARD,
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.ts
index be26566c6..16edfdca4 100644
--- a/src/modules/auth/auth.service.spec.ts
+++ b/src/modules/auth/auth.service.spec.ts
@@ -224,6 +224,33 @@ describe('AuthService', () => {
expect(result.lastUsedAt).toBeDefined();
});
+ it('coalesces the usage-stat write within the throttle window', async () => {
+ const rawKey = 'recent-key';
+ const key = createMockApiKey({ keyHash: hashKey(rawKey), lastUsedAt: new Date(), usageCount: 5 });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+
+ const result = await service.validateApiKey(rawKey);
+
+ expect(repository.save).not.toHaveBeenCalled(); // throttled — no DB write this request
+ expect(result.usageCount).toBe(6); // but the count is still reflected in-memory
+ expect(result.lastUsedAt).toBeDefined();
+ });
+
+ it('flushes the usage-stat write once the throttle window has elapsed', async () => {
+ const rawKey = 'stale-key';
+ const key = createMockApiKey({
+ keyHash: hashKey(rawKey),
+ lastUsedAt: new Date(Date.now() - 5 * 60_000),
+ usageCount: 5,
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+
+ await service.validateApiKey(rawKey);
+
+ expect(repository.save).toHaveBeenCalled(); // persisted after the window
+ });
+
it('should throw UnauthorizedException for invalid key', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(null);
diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts
index 409008621..03ca81a76 100644
--- a/src/modules/auth/auth.service.ts
+++ b/src/modules/auth/auth.service.ts
@@ -31,6 +31,11 @@ export function resolveSeedApiKey(): string {
export class AuthService implements OnModuleInit {
private readonly logger = createLogger('AuthService');
+ /** Coalesce per-request usage-stat writes to at most one DB write per key per window. */
+ private static readonly STAT_FLUSH_INTERVAL_MS = 60_000;
+ /** keyId -> usage increments observed but not yet persisted (flushed on the next windowed write). */
+ private readonly pendingUsage = new Map<string, number>();
+
constructor(
@InjectRepository(ApiKey, 'main')
private readonly apiKeyRepository: Repository<ApiKey>,
@@ -159,6 +164,8 @@ export class AuthService implements OnModuleInit {
async delete(id: string): Promise<void> {
const apiKey = await this.findOne(id);
+ // Drop any un-flushed usage accumulator so a deleted key leaves nothing behind in the Map.
+ this.pendingUsage.delete(id);
await this.apiKeyRepository.remove(apiKey);
this.logger.log(`API key deleted: ${apiKey.name}`, {
keyId: id,
@@ -168,6 +175,9 @@ export class AuthService implements OnModuleInit {
async revoke(id: string): Promise<ApiKey> {
const apiKey = await this.findOne(id);
+ // A revoked key fails validation before its next flush, so its accumulator would orphan —
+ // drop it here.
+ this.pendingUsage.delete(id);
apiKey.isActive = false;
return this.apiKeyRepository.save(apiKey);
}
@@ -210,10 +220,23 @@ export class AuthService implements OnModuleInit {
}
}
- // Update usage stats
+ // Update usage stats — coalesced. Validation above is unchanged/synchronous; only
+ // the stat WRITE is throttled to at most once per key per window. usageCount stays
+ // accurate via an in-memory accumulator; the returned object reflects the true count.
+ const pending = (this.pendingUsage.get(apiKey.id) ?? 0) + 1;
+ const previousLastUsedAt = apiKey.lastUsedAt;
apiKey.lastUsedAt = new Date();
- apiKey.usageCount += 1;
- await this.apiKeyRepository.save(apiKey);
+ apiKey.usageCount += pending; // DB value + all not-yet-persisted increments (incl. this request)
+
+ const due =
+ !previousLastUsedAt ||
+ apiKey.lastUsedAt.getTime() - previousLastUsedAt.getTime() >= AuthService.STAT_FLUSH_INTERVAL_MS;
+ if (due) {
+ this.pendingUsage.delete(apiKey.id);
+ await this.apiKeyRepository.save(apiKey);
+ } else {
+ this.pendingUsage.set(apiKey.id, pending);
+ }
return apiKey;
}
@@ -223,7 +246,7 @@ export class AuthService implements OnModuleInit {
}
private isIpAllowed(clientIp: string, allowedIps: string[]): boolean {
- // Phase 3 Security Audit: Support both exact match and CIDR notation
+ // Support both exact match and CIDR notation
for (const entry of allowedIps) {
if (entry.includes('/')) {
// CIDR notation (e.g., "10.0.0.0/24")
diff --git a/src/modules/auth/entities/api-key.entity.ts b/src/modules/auth/entities/api-key.entity.ts
index 22c70d50b..27469143c 100644
--- a/src/modules/auth/entities/api-key.entity.ts
+++ b/src/modules/auth/entities/api-key.entity.ts
@@ -18,7 +18,9 @@ export class ApiKey {
@Column({ type: 'varchar', length: 64 })
keyHash: string;
- @Column({ type: 'varchar', length: 8 })
+ // 12 to fit the 12-char prefix that auth.service writes (was varchar(8); harmless on the
+ // hardcoded-SQLite `main` connection, but kept consistent with the code).
+ @Column({ type: 'varchar', length: 12 })
keyPrefix: string;
@Column({
diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.ts
index a53a8fcd9..4d3d136be 100644
--- a/src/modules/auth/guards/api-key.guard.ts
+++ b/src/modules/auth/guards/api-key.guard.ts
@@ -5,7 +5,7 @@ import { Request } from 'express';
import { AuthService } from '../auth.service';
import { ApiKeyRole } from '../entities/api-key.entity';
import { REQUIRED_ROLE_KEY, PUBLIC_KEY } from '../decorators/auth.decorators';
-import { ipMatches, normalizeIp } from '../../../common/utils/ip';
+import { resolveClientIp } from '../../../common/utils/ip';
@Injectable()
export class ApiKeyGuard implements CanActivate {
@@ -75,38 +75,7 @@ export class ApiKeyGuard implements CanActivate {
* direct socket address is used — preventing IP-whitelist spoofing.
*/
private getClientIp(request: Request): string {
- const socketIp = normalizeIp(request.socket?.remoteAddress || request.ip || '');
const trustedProxies = this.configService.get<string[]>('security.trustedProxies') ?? [];
-
- if (trustedProxies.length === 0) {
- return socketIp;
- }
-
- const isTrusted = (ip: string): boolean => trustedProxies.some(proxy => ipMatches(ip, proxy));
-
- // Only trust the forwarded chain if the immediate peer is a trusted proxy.
- if (!isTrusted(socketIp)) {
- return socketIp;
- }
-
- const forwarded = request.headers['x-forwarded-for'];
- if (!forwarded) {
- return socketIp;
- }
-
- const hops = (Array.isArray(forwarded) ? forwarded.join(',') : forwarded)
- .split(',')
- .map(hop => normalizeIp(hop.trim()))
- .filter(Boolean);
-
- // Walk right-to-left and return the first hop that is not a trusted proxy:
- // the closest address the trusted infrastructure actually observed.
- for (let i = hops.length - 1; i >= 0; i--) {
- if (!isTrusted(hops[i])) {
- return hops[i];
- }
- }
-
- return socketIp;
+ return resolveClientIp(request, trustedProxies);
}
}
diff --git a/src/modules/channel/channel.controller.ts b/src/modules/channel/channel.controller.ts
index 459f0addb..734b01af5 100644
--- a/src/modules/channel/channel.controller.ts
+++ b/src/modules/channel/channel.controller.ts
@@ -1,29 +1,12 @@
-import {
- Controller,
- Get,
- Post,
- Delete,
- Param,
- Body,
- Query,
- BadRequestException,
- NotFoundException,
-} from '@nestjs/common';
+import { Controller, Get, Post, Delete, Param, Body, Query } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody, ApiQuery } from '@nestjs/swagger';
-import { SessionService } from '../session/session.service';
+import { ChannelService } from './channel.service';
+import { SubscribeChannelDto } from './dto/subscribe-channel.dto';
@ApiTags('channels')
@Controller('sessions/:sessionId/channels')
export class ChannelController {
- constructor(private readonly sessionService: SessionService) {}
-
- private getEngine(sessionId: string) {
- const engine = this.sessionService.getEngine(sessionId);
- if (!engine) {
- throw new BadRequestException('Session is not started');
- }
- return engine;
- }
+ constructor(private readonly channelService: ChannelService) {}
@Get()
@ApiOperation({ summary: 'Get all subscribed channels/newsletters' })
@@ -34,8 +17,7 @@ export class ChannelController {
})
@ApiResponse({ status: 400, description: 'Session not ready' })
async findAll(@Param('sessionId') sessionId: string) {
- const engine = this.getEngine(sessionId);
- return engine.getSubscribedChannels();
+ return this.channelService.getSubscribedChannels(sessionId);
}
@Get(':channelId')
@@ -48,12 +30,7 @@ export class ChannelController {
})
@ApiResponse({ status: 404, description: 'Channel not found' })
async findOne(@Param('sessionId') sessionId: string, @Param('channelId') channelId: string) {
- const engine = this.getEngine(sessionId);
- const channel = await engine.getChannelById(channelId);
- if (!channel) {
- throw new NotFoundException(`Channel ${channelId} not found`);
- }
- return channel;
+ return this.channelService.getChannelById(sessionId, channelId);
}
@Get(':channelId/messages')
@@ -70,8 +47,7 @@ export class ChannelController {
@Param('channelId') channelId: string,
@Query('limit') limit?: string,
) {
- const engine = this.getEngine(sessionId);
- return engine.getChannelMessages(channelId, limit ? parseInt(limit, 10) : undefined);
+ return this.channelService.getChannelMessages(sessionId, channelId, limit ? parseInt(limit, 10) : undefined);
}
@Post('subscribe')
@@ -94,9 +70,8 @@ export class ChannelController {
status: 201,
description: 'Successfully subscribed to channel',
})
- async subscribe(@Param('sessionId') sessionId: string, @Body() body: { inviteCode: string }) {
- const engine = this.getEngine(sessionId);
- return engine.subscribeToChannel(body.inviteCode);
+ async subscribe(@Param('sessionId') sessionId: string, @Body() body: SubscribeChannelDto) {
+ return this.channelService.subscribeToChannel(sessionId, body.inviteCode);
}
@Delete(':channelId')
@@ -108,8 +83,7 @@ export class ChannelController {
description: 'Successfully unsubscribed from channel',
})
async unsubscribe(@Param('sessionId') sessionId: string, @Param('channelId') channelId: string) {
- const engine = this.getEngine(sessionId);
- await engine.unsubscribeFromChannel(channelId);
+ await this.channelService.unsubscribeFromChannel(sessionId, channelId);
return { success: true };
}
}
diff --git a/src/modules/channel/channel.module.ts b/src/modules/channel/channel.module.ts
index 543374e32..2d9f926f9 100644
--- a/src/modules/channel/channel.module.ts
+++ b/src/modules/channel/channel.module.ts
@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { ChannelController } from './channel.controller';
+import { ChannelService } from './channel.service';
import { SessionModule } from '../session/session.module';
@Module({
imports: [SessionModule],
controllers: [ChannelController],
+ providers: [ChannelService],
})
export class ChannelModule {}
diff --git a/src/modules/channel/channel.service.spec.ts b/src/modules/channel/channel.service.spec.ts
new file mode 100644
index 000000000..6279337f1
--- /dev/null
+++ b/src/modules/channel/channel.service.spec.ts
@@ -0,0 +1,26 @@
+import { BadRequestException, NotFoundException } from '@nestjs/common';
+import { ChannelService } from './channel.service';
+import { SessionService } from '../session/session.service';
+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+
+describe('ChannelService', () => {
+ const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {
+ const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;
+ return new ChannelService(sessionService);
+ };
+
+ it('throws 400 when the session is not started', () => {
+ expect(() => makeService(undefined).getSubscribedChannels('s1')).toThrow(BadRequestException);
+ });
+
+ it('maps a missing channel to 404', async () => {
+ const svc = makeService({ getChannelById: jest.fn().mockResolvedValue(null) });
+ await expect(svc.getChannelById('s1', 'ch404')).rejects.toBeInstanceOf(NotFoundException);
+ });
+
+ it('forwards an optional message limit to the engine', async () => {
+ const getChannelMessages = jest.fn().mockResolvedValue([]);
+ await makeService({ getChannelMessages }).getChannelMessages('s1', 'ch1', 25);
+ expect(getChannelMessages).toHaveBeenCalledWith('ch1', 25);
+ });
+});
diff --git a/src/modules/channel/channel.service.ts b/src/modules/channel/channel.service.ts
new file mode 100644
index 000000000..1196d517e
--- /dev/null
+++ b/src/modules/channel/channel.service.ts
@@ -0,0 +1,44 @@
+import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
+import { SessionService } from '../session/session.service';
+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+
+/**
+ * Owns engine access for channel/newsletter operations so the "session not started" guard
+ * and channel business rules (not-found mapping) live behind the service boundary.
+ */
+@Injectable()
+export class ChannelService {
+ constructor(private readonly sessionService: SessionService) {}
+
+ private getEngine(sessionId: string): IWhatsAppEngine {
+ const engine = this.sessionService.getEngine(sessionId);
+ if (!engine) {
+ throw new BadRequestException('Session is not started');
+ }
+ return engine;
+ }
+
+ getSubscribedChannels(sessionId: string) {
+ return this.getEngine(sessionId).getSubscribedChannels();
+ }
+
+ async getChannelById(sessionId: string, channelId: string) {
+ const channel = await this.getEngine(sessionId).getChannelById(channelId);
+ if (!channel) {
+ throw new NotFoundException(`Channel ${channelId} not found`);
+ }
+ return channel;
+ }
+
+ getChannelMessages(sessionId: string, channelId: string, limit?: number) {
+ return this.getEngine(sessionId).getChannelMessages(channelId, limit);
+ }
+
+ subscribeToChannel(sessionId: string, inviteCode: string) {
+ return this.getEngine(sessionId).subscribeToChannel(inviteCode);
+ }
+
+ unsubscribeFromChannel(sessionId: string, channelId: string) {
+ return this.getEngine(sessionId).unsubscribeFromChannel(channelId);
+ }
+}
diff --git a/src/modules/channel/dto/subscribe-channel.dto.ts b/src/modules/channel/dto/subscribe-channel.dto.ts
new file mode 100644
index 000000000..00930c2f9
--- /dev/null
+++ b/src/modules/channel/dto/subscribe-channel.dto.ts
@@ -0,0 +1,10 @@
+import { ApiProperty } from '@nestjs/swagger';
+import { IsString, IsNotEmpty } from 'class-validator';
+
+/** Validated body for subscribing to a channel (was an inline @Body literal). */
+export class SubscribeChannelDto {
+ @ApiProperty({ description: 'Channel invite code' })
+ @IsString()
+ @IsNotEmpty()
+ inviteCode: string;
+}
diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.ts
index cf65f916f..129ba2668 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -1,21 +1,11 @@
-import {
- Controller,
- Get,
- Post,
- Delete,
- Param,
- HttpCode,
- HttpStatus,
- BadRequestException,
- NotFoundException,
-} from '@nestjs/common';
+import { Controller, Get, Post, Delete, Param, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';
-import { SessionService } from '../session/session.service';
+import { ContactService } from './contact.service';
@ApiTags('contacts')
@Controller('sessions/:sessionId/contacts')
export class ContactController {
- constructor(private readonly sessionService: SessionService) {}
+ constructor(private readonly contactService: ContactService) {}
@Get()
@ApiOperation({ summary: 'Get all contacts for a session' })
@@ -27,11 +17,7 @@ export class ContactController {
@ApiResponse({ status: 400, description: 'Session not ready' })
@ApiResponse({ status: 404, description: 'Session not found' })
async findAll(@Param('sessionId') sessionId: string) {
- const engine = this.sessionService.getEngine(sessionId);
- if (!engine) {
- throw new BadRequestException('Session is not started');
- }
- return engine.getContacts();
+ return this.contactService.getContacts(sessionId);
}
@Get(':contactId')
@@ -44,15 +30,7 @@ export class ContactController {
})
@ApiResponse({ status: 404, description: 'Contact not found' })
async findOne(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {
- const engine = this.sessionService.getEngine(sessionId);
- if (!engine) {
- throw new BadRequestException('Session is not started');
- }
- const contact = await engine.getContactById(contactId);
- if (!contact) {
- throw new NotFoundException(`Contact ${contactId} not found`);
- }
- return contact;
+ return this.contactService.getContactById(sessionId, contactId);
}
@Get('check/:number')
@@ -64,11 +42,7 @@ export class ContactController {
description: 'Number existence check result',
})
async checkNumber(@Param('sessionId') sessionId: string, @Param('number') number: string) {
- const engine = this.sessionService.getEngine(sessionId);
- if (!engine) {
- throw new BadRequestException('Session is not started');
- }
- const exists = await engine.checkNumberExists(number);
+ const exists = await this.contactService.checkNumberExists(sessionId, number);
return {
number,
exists,
@@ -87,11 +61,7 @@ export class ContactController {
description: 'Profile picture URL',
})
async getProfilePicture(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {
- const engine = this.sessionService.getEngine(sessionId);
- if (!engine) {
- throw new BadRequestException('Session is not started');
- }
- const url = await engine.getProfilePicture(contactId);
+ const url = await this.contactService.getProfilePicture(sessionId, contactId);
return { url };
}
@@ -105,11 +75,7 @@ export class ContactController {
description: 'Contact blocked',
})
async blockContact(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {
- const engine = this.sessionService.getEngine(sessionId);
- if (!engine) {
- throw new BadRequestException('Session is not started');
- }
- await engine.blockContact(contactId);
+ await this.contactService.blockContact(sessionId, contactId);
return { success: true, message: 'Contact blocked' };
}
@@ -122,11 +88,7 @@ export class ContactController {
description: 'Contact unblocked',
})
async unblockContact(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {
- const engine = this.sessionService.getEngine(sessionId);
- if (!engine) {
- throw new BadRequestException('Session is not started');
- }
- await engine.unblockContact(contactId);
+ await this.contactService.unblockContact(sessionId, contactId);
return { success: true, message: 'Contact unblocked' };
}
}
diff --git a/src/modules/contact/contact.module.ts b/src/modules/contact/contact.module.ts
index 820780a11..5cdf56c08 100644
--- a/src/modules/contact/contact.module.ts
+++ b/src/modules/contact/contact.module.ts
@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { ContactController } from './contact.controller';
+import { ContactService } from './contact.service';
import { SessionModule } from '../session/session.module';
@Module({
imports: [SessionModule],
controllers: [ContactController],
+ providers: [ContactService],
})
export class ContactModule {}
diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.ts
new file mode 100644
index 000000000..910e04f1c
--- /dev/null
+++ b/src/modules/contact/contact.service.spec.ts
@@ -0,0 +1,26 @@
+import { BadRequestException, NotFoundException } from '@nestjs/common';
+import { ContactService } from './contact.service';
+import { SessionService } from '../session/session.service';
+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+
+describe('ContactService', () => {
+ const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {
+ const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;
+ return new ContactService(sessionService);
+ };
+
+ it('throws 400 when the session is not started', () => {
+ expect(() => makeService(undefined).getContacts('s1')).toThrow(BadRequestException);
+ });
+
+ it('maps a missing contact to 404', async () => {
+ const svc = makeService({ getContactById: jest.fn().mockResolvedValue(null) });
+ await expect(svc.getContactById('s1', 'c404')).rejects.toBeInstanceOf(NotFoundException);
+ });
+
+ it('delegates checkNumberExists to the engine', async () => {
+ const checkNumberExists = jest.fn().mockResolvedValue(true);
+ await expect(makeService({ checkNumberExists }).checkNumberExists('s1', '628123')).resolves.toBe(true);
+ expect(checkNumberExists).toHaveBeenCalledWith('628123');
+ });
+});
diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.ts
new file mode 100644
index 000000000..6e35df53c
--- /dev/null
+++ b/src/modules/contact/contact.service.ts
@@ -0,0 +1,48 @@
+import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
+import { SessionService } from '../session/session.service';
+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+
+/**
+ * Owns engine access for contact operations so the "session not started" guard and
+ * contact business rules (not-found mapping) live behind the service boundary.
+ */
+@Injectable()
+export class ContactService {
+ constructor(private readonly sessionService: SessionService) {}
+
+ private getEngine(sessionId: string): IWhatsAppEngine {
+ const engine = this.sessionService.getEngine(sessionId);
+ if (!engine) {
+ throw new BadRequestException('Session is not started');
+ }
+ return engine;
+ }
+
+ getContacts(sessionId: string) {
+ return this.getEngine(sessionId).getContacts();
+ }
+
+ async getContactById(sessionId: string, contactId: string) {
+ const contact = await this.getEngine(sessionId).getContactById(contactId);
+ if (!contact) {
+ throw new NotFoundException(`Contact ${contactId} not found`);
+ }
+ return contact;
+ }
+
+ checkNumberExists(sessionId: string, number: string) {
+ return this.getEngine(sessionId).checkNumberExists(number);
+ }
+
+ getProfilePicture(sessionId: string, contactId: string) {
+ return this.getEngine(sessionId).getProfilePicture(contactId);
+ }
+
+ blockContact(sessionId: string, contactId: string) {
+ return this.getEngine(sessionId).blockContact(contactId);
+ }
+
+ unblockContact(sessionId: string, contactId: string) {
+ return this.getEngine(sessionId).unblockContact(contactId);
+ }
+}
diff --git a/src/modules/docker/compose-network.spec.ts b/src/modules/docker/compose-network.spec.ts
new file mode 100644
index 000000000..1330fa3f9
--- /dev/null
+++ b/src/modules/docker/compose-network.spec.ts
@@ -0,0 +1,34 @@
+import { readFileSync } from 'fs';
+import { join } from 'path';
+// js-yaml has no bundled types here; require + cast (matches the repo's plugin-loader pattern).
+// eslint-disable-next-line @typescript-eslint/no-require-imports
+const yaml = require('js-yaml') as { load: (src: string) => unknown };
+
+interface ComposeFile {
+ services: Record<string, { networks?: string[] }>;
+ networks: Record<string, { internal?: boolean }>;
+}
+
+/**
+ * Regression lock: the Docker socket proxy must live on a dedicated
+ * internal network that the dashboard (and other untrusted peers) cannot reach.
+ */
+describe('docker-compose network segmentation', () => {
+ const compose = yaml.load(readFileSync(join(__dirname, '../../../docker-compose.yml'), 'utf8')) as ComposeFile;
+
+ it('declares an internal-only network for the docker socket proxy', () => {
+ expect(compose.networks['internal-docker'].internal).toBe(true);
+ });
+
+ it('puts docker-proxy ONLY on the internal network (not the shared app network)', () => {
+ expect(compose.services['docker-proxy'].networks).toEqual(['internal-docker']);
+ });
+
+ it('keeps the dashboard OFF the internal docker network (cannot reach docker-proxy:2375)', () => {
+ expect(compose.services['dashboard'].networks ?? []).not.toContain('internal-docker');
+ });
+
+ it('lets openwa-api reach the proxy via the internal network', () => {
+ expect(compose.services['openwa-api'].networks).toContain('internal-docker');
+ });
+});
diff --git a/src/modules/docker/traefik-config.spec.ts b/src/modules/docker/traefik-config.spec.ts
new file mode 100644
index 000000000..02a7a19a9
--- /dev/null
+++ b/src/modules/docker/traefik-config.spec.ts
@@ -0,0 +1,23 @@
+import { readFileSync } from 'fs';
+import { join } from 'path';
+// js-yaml has no bundled types here; require + cast (matches the repo's plugin-loader pattern).
+// eslint-disable-next-line @typescript-eslint/no-require-imports
+const yaml = require('js-yaml') as { load: (src: string) => unknown };
+
+interface TraefikConfig {
+ api?: { insecure?: boolean };
+ entryPoints?: Record<string, { address?: string }>;
+}
+
+/** Regression lock: the Traefik dashboard must not be served insecurely + TLS exists. */
+describe('traefik static config', () => {
+ const cfg = yaml.load(readFileSync(join(__dirname, '../../../traefik/traefik.yml'), 'utf8')) as TraefikConfig;
+
+ it('does not enable the insecure API dashboard', () => {
+ expect(cfg.api?.insecure).toBe(false);
+ });
+
+ it('defines a TLS (websecure) entrypoint', () => {
+ expect(cfg.entryPoints?.websecure?.address).toBe(':443');
+ });
+});
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.ts
index 1f355bb92..390ebbbd2 100644
--- a/src/modules/events/events.gateway.spec.ts
+++ b/src/modules/events/events.gateway.spec.ts
@@ -1,4 +1,7 @@
-import { isSessionSubscriptionAllowed } from './events.gateway';
+import { Socket } from 'socket.io';
+import { EventsGateway, isSessionSubscriptionAllowed } from './events.gateway';
+import { AuthService } from '../auth/auth.service';
+import type { WSClientMessage, WSErrorResponse, WSSubscribedResponse } from './dto/ws-messages.dto';
describe('isSessionSubscriptionAllowed (WS session-scope enforcement)', () => {
it('allows an unrestricted key (null allowedSessions) to subscribe to anything, including *', () => {
@@ -22,3 +25,84 @@ describe('isSessionSubscriptionAllowed (WS session-scope enforcement)', () => {
expect(isSessionSubscriptionAllowed(['sess-1'], 'sess-2')).toBe(false);
});
});
+
+interface MockSocket {
+ id: string;
+ handshake: { headers: Record<string, string>; query: Record<string, string>; auth: { apiKey?: string } };
+ data: Record<string, unknown>;
+ emit: jest.Mock;
+ disconnect: jest.Mock;
+ join: jest.Mock;
+ rooms: Set<string>;
+}
+
+describe('EventsGateway connection auth + subscribe re-validation', () => {
+ let gateway: EventsGateway;
+ let authService: { validateApiKey: jest.Mock };
+
+ const makeSocket = (auth: { apiKey?: string } = {}): MockSocket => ({
+ id: 'sock-1',
+ handshake: { headers: {}, query: {}, auth },
+ data: {},
+ emit: jest.fn(),
+ disconnect: jest.fn(),
+ join: jest.fn(),
+ rooms: new Set<string>(),
+ });
+ const asSocket = (s: MockSocket): Socket => s as unknown as Socket;
+ const subscribeMsg = (sessionId: string, events: string[]): WSClientMessage =>
+ ({ type: 'subscribe', sessionId, events, requestId: 'r1' }) as unknown as WSClientMessage;
+
+ beforeEach(() => {
+ authService = { validateApiKey: jest.fn() };
+ gateway = new EventsGateway(authService as unknown as AuthService);
+ });
+
+ it('rejects a connection with no API key (and never calls validate)', async () => {
+ const sock = makeSocket({});
+ await gateway.handleConnection(asSocket(sock));
+ expect(sock.disconnect).toHaveBeenCalled();
+ expect(authService.validateApiKey).not.toHaveBeenCalled();
+ });
+
+ it('rejects a connection with an invalid API key', async () => {
+ authService.validateApiKey.mockResolvedValue(null);
+ const sock = makeSocket({ apiKey: 'bad' });
+ await gateway.handleConnection(asSocket(sock));
+ expect(sock.disconnect).toHaveBeenCalled();
+ });
+
+ it('accepts a valid key via handshake.auth and stores the raw key for re-validation', async () => {
+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });
+ const sock = makeSocket({ apiKey: 'good' });
+ await gateway.handleConnection(asSocket(sock));
+ expect(sock.disconnect).not.toHaveBeenCalled();
+ expect(sock.data.rawApiKey).toBe('good');
+ });
+
+ it('re-validates on subscribe and disconnects a key revoked after connect', async () => {
+ authService.validateApiKey.mockResolvedValueOnce({ name: 'k', allowedSessions: null }); // connect
+ const sock = makeSocket({ apiKey: 'good' });
+ await gateway.handleConnection(asSocket(sock));
+
+ authService.validateApiKey.mockResolvedValueOnce(null); // revoked on the subscribe re-check
+ const res = (await gateway.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['*']))) as WSErrorResponse;
+
+ expect(sock.disconnect).toHaveBeenCalled();
+ expect(res.code).toBe('UNAUTHORIZED');
+ });
+
+ it('allows subscribe when the key still re-validates', async () => {
+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });
+ const sock = makeSocket({ apiKey: 'good' });
+ await gateway.handleConnection(asSocket(sock));
+
+ const res = (await gateway.handleMessage(
+ asSocket(sock),
+ subscribeMsg('sess-1', ['session.status']),
+ )) as WSSubscribedResponse;
+
+ expect(res.type).toBe('subscribed');
+ expect(sock.join).toHaveBeenCalled();
+ });
+});
diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.ts
index 555104a6d..9db8cd605 100644
--- a/src/modules/events/events.gateway.ts
+++ b/src/modules/events/events.gateway.ts
@@ -11,6 +11,17 @@ import {
import { Server, Socket } from 'socket.io';
import { Logger } from '@nestjs/common';
import { AuthService } from '../auth/auth.service';
+import { resolveCorsPolicy } from '../../config/bootstrap-security';
+
+/**
+ * WebSocket CORS origin: reuse the HTTP CORS policy instead of a hardcoded '*'.
+ * Dev → allow any origin; production → the configured CORS_ORIGINS allowlist (or none).
+ * Read from process.env at module load (real env vars apply; same-origin is unaffected).
+ */
+function resolveWsCorsOrigin(): boolean | string[] {
+ const policy = resolveCorsPolicy(process.env.CORS_ORIGINS, process.env.NODE_ENV);
+ return policy.allowAnyOrigin ? true : policy.origins;
+}
import type {
WSClientMessage,
WSSubscribeRequest,
@@ -42,7 +53,7 @@ export function isSessionSubscriptionAllowed(allowedSessions: string[] | null |
@WebSocketGateway({
cors: {
- origin: '*', // In production, restrict this
+ origin: resolveWsCorsOrigin(),
},
namespace: '/events',
})
@@ -59,8 +70,13 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
}
async handleConnection(client: Socket) {
- // Extract API key from header or query param
- const apiKey = (client.handshake.headers['x-api-key'] as string) || (client.handshake.query.apiKey as string);
+ // Prefer Socket.IO's `auth` field (not logged in URLs), then the header; the query
+ // param is a deprecated transition fallback (the key leaks into access logs).
+ const handshakeAuth = client.handshake.auth as { apiKey?: string } | undefined;
+ const apiKey =
+ handshakeAuth?.apiKey ||
+ (client.handshake.headers['x-api-key'] as string) ||
+ (client.handshake.query.apiKey as string);
if (!apiKey) {
this.logger.warn(`Client ${client.id} rejected: No API key provided`);
@@ -78,8 +94,10 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
return;
}
- // Store API key info on socket for later use
- (client.data as { apiKey: unknown }).apiKey = validKey;
+ // Store the validated key AND the raw key — the raw key lets handleSubscribe
+ // RE-validate on each subscription so a key revoked mid-connection is caught.
+ (client.data as { apiKey: unknown; rawApiKey: string }).apiKey = validKey;
+ (client.data as { rawApiKey: string }).rawApiKey = apiKey;
this.logger.log(`Client connected: ${client.id} (key: ${validKey.name})`);
} catch (error) {
this.logger.warn(`Client ${client.id} rejected: Auth error`, {
@@ -112,7 +130,10 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
}
}
- private handleSubscribe(client: Socket, message: WSSubscribeRequest): WSSubscribedResponse | WSErrorResponse {
+ private async handleSubscribe(
+ client: Socket,
+ message: WSSubscribeRequest,
+ ): Promise<WSSubscribedResponse | WSErrorResponse> {
const { sessionId, events, requestId } = message;
// Validate sessionId
@@ -120,11 +141,24 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
return this.createError('INVALID_SESSION', 'sessionId is required', requestId);
}
- // Enforce per-key session scope: a key restricted to specific sessions must not
- // subscribe to '*' or to a session outside its allowlist (prevents cross-tenant
- // event leakage — #221).
- const subscriberKey = (client.data as { apiKey?: { allowedSessions?: string[] | null } }).apiKey;
- if (!isSessionSubscriptionAllowed(subscriberKey?.allowedSessions, sessionId)) {
+ // Re-validate the API key on every subscribe: a long-lived socket whose key was
+ // revoked/expired after connect must not be able to keep opening new subscriptions.
+ const rawApiKey = (client.data as { rawApiKey?: string }).rawApiKey;
+ let subscriberKey: { allowedSessions?: string[] | null } | null;
+ try {
+ subscriberKey = rawApiKey ? await this.authService.validateApiKey(rawApiKey) : null;
+ } catch {
+ subscriberKey = null;
+ }
+ if (!subscriberKey) {
+ client.emit('message', this.createError('UNAUTHORIZED', 'API key is no longer valid', requestId));
+ client.disconnect();
+ return this.createError('UNAUTHORIZED', 'API key is no longer valid', requestId);
+ }
+
+ // Enforce per-key session scope against the FRESH key: a key restricted to specific
+ // sessions must not subscribe to '*' or a session outside its allowlist (#221).
+ if (!isSessionSubscriptionAllowed(subscriberKey.allowedSessions, sessionId)) {
return this.createError('FORBIDDEN_SESSION', 'API key is not authorized for this session', requestId);
}
diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.ts
index 5ed99ce84..81ce054df 100644
--- a/src/modules/group/group.controller.ts
+++ b/src/modules/group/group.controller.ts
@@ -1,32 +1,19 @@
-import {
- Controller,
- Get,
- Post,
- Put,
- Delete,
- Param,
- Body,
- HttpCode,
- HttpStatus,
- BadRequestException,
- NotFoundException,
-} from '@nestjs/common';
+import { Controller, Get, Post, Put, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';
-import { SessionService } from '../session/session.service';
+import { GroupService } from './group.service';
import { CreateGroupDto, ParticipantsDto, GroupSubjectDto, GroupDescriptionDto } from './dto/group.dto';
@ApiTags('groups')
@Controller('sessions/:sessionId/groups')
export class GroupController {
- constructor(private readonly sessionService: SessionService) {}
+ constructor(private readonly groupService: GroupService) {}
@Get()
@ApiOperation({ summary: 'Get all groups for a session' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiResponse({ status: 200, description: 'List of groups' })
async findAll(@Param('sessionId') sessionId: string) {
- const engine = this.getEngine(sessionId);
- return engine.getGroups();
+ return this.groupService.getGroups(sessionId);
}
@Get(':groupId')
@@ -36,12 +23,7 @@ export class GroupController {
@ApiResponse({ status: 200, description: 'Group details with participants' })
@ApiResponse({ status: 404, description: 'Group not found' })
async findOne(@Param('sessionId') sessionId: string, @Param('groupId') groupId: string) {
- const engine = this.getEngine(sessionId);
- const group = await engine.getGroupInfo(groupId);
- if (!group) {
- throw new NotFoundException(`Group ${groupId} not found`);
- }
- return group;
+ return this.groupService.getGroupInfo(sessionId, groupId);
}
@Post()
@@ -50,8 +32,7 @@ export class GroupController {
@ApiBody({ type: CreateGroupDto })
@ApiResponse({ status: 201, description: 'Group created' })
async create(@Param('sessionId') sessionId: string, @Body() dto: CreateGroupDto) {
- const engine = this.getEngine(sessionId);
- return engine.createGroup(dto.name, dto.participants);
+ return this.groupService.createGroup(sessionId, dto.name, dto.participants);
}
@Post(':groupId/participants')
@@ -66,8 +47,7 @@ export class GroupController {
@Param('groupId') groupId: string,
@Body() dto: ParticipantsDto,
) {
- const engine = this.getEngine(sessionId);
- await engine.addParticipants(groupId, dto.participants);
+ await this.groupService.addParticipants(sessionId, groupId, dto.participants);
return { success: true, message: 'Participants added' };
}
@@ -82,8 +62,7 @@ export class GroupController {
@Param('groupId') groupId: string,
@Body() dto: ParticipantsDto,
) {
- const engine = this.getEngine(sessionId);
- await engine.removeParticipants(groupId, dto.participants);
+ await this.groupService.removeParticipants(sessionId, groupId, dto.participants);
return { success: true, message: 'Participants removed' };
}
@@ -99,8 +78,7 @@ export class GroupController {
@Param('groupId') groupId: string,
@Body() dto: ParticipantsDto,
) {
- const engine = this.getEngine(sessionId);
- await engine.promoteParticipants(groupId, dto.participants);
+ await this.groupService.promoteParticipants(sessionId, groupId, dto.participants);
return { success: true, message: 'Participants promoted to admin' };
}
@@ -116,8 +94,7 @@ export class GroupController {
@Param('groupId') groupId: string,
@Body() dto: ParticipantsDto,
) {
- const engine = this.getEngine(sessionId);
- await engine.demoteParticipants(groupId, dto.participants);
+ await this.groupService.demoteParticipants(sessionId, groupId, dto.participants);
return { success: true, message: 'Participants demoted from admin' };
}
@@ -132,8 +109,7 @@ export class GroupController {
@Param('groupId') groupId: string,
@Body() dto: GroupSubjectDto,
) {
- const engine = this.getEngine(sessionId);
- await engine.setGroupSubject(groupId, dto.subject);
+ await this.groupService.setGroupSubject(sessionId, groupId, dto.subject);
return { success: true, message: 'Group subject updated' };
}
@@ -148,8 +124,7 @@ export class GroupController {
@Param('groupId') groupId: string,
@Body() dto: GroupDescriptionDto,
) {
- const engine = this.getEngine(sessionId);
- await engine.setGroupDescription(groupId, dto.description);
+ await this.groupService.setGroupDescription(sessionId, groupId, dto.description);
return { success: true, message: 'Group description updated' };
}
@@ -160,8 +135,7 @@ export class GroupController {
@ApiResponse({ status: 200, description: 'Left the group' })
@HttpCode(HttpStatus.OK)
async leave(@Param('sessionId') sessionId: string, @Param('groupId') groupId: string) {
- const engine = this.getEngine(sessionId);
- await engine.leaveGroup(groupId);
+ await this.groupService.leaveGroup(sessionId, groupId);
return { success: true, message: 'Left the group' };
}
@@ -173,8 +147,7 @@ export class GroupController {
@ApiParam({ name: 'groupId', description: 'Group ID' })
@ApiResponse({ status: 200, description: 'Group invite code' })
async getInviteCode(@Param('sessionId') sessionId: string, @Param('groupId') groupId: string) {
- const engine = this.getEngine(sessionId);
- const inviteCode = await engine.getGroupInviteCode(groupId);
+ const inviteCode = await this.groupService.getGroupInviteCode(sessionId, groupId);
return {
inviteCode,
inviteLink: `https://chat.whatsapp.com/${inviteCode}`,
@@ -188,20 +161,11 @@ export class GroupController {
@ApiParam({ name: 'groupId', description: 'Group ID' })
@ApiResponse({ status: 200, description: 'New invite code generated' })
async revokeInviteCode(@Param('sessionId') sessionId: string, @Param('groupId') groupId: string) {
- const engine = this.getEngine(sessionId);
- const newCode = await engine.revokeGroupInviteCode(groupId);
+ const newCode = await this.groupService.revokeGroupInviteCode(sessionId, groupId);
return {
inviteCode: newCode,
inviteLink: `https://chat.whatsapp.com/${newCode}`,
message: 'Invite code revoked and new one generated',
};
}
-
- private getEngine(sessionId: string) {
- const engine = this.sessionService.getEngine(sessionId);
- if (!engine) {
- throw new BadRequestException('Session is not started');
- }
- return engine;
- }
}
diff --git a/src/modules/group/group.module.ts b/src/modules/group/group.module.ts
index 422c802ff..c9574a2d8 100644
--- a/src/modules/group/group.module.ts
+++ b/src/modules/group/group.module.ts
@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { GroupController } from './group.controller';
+import { GroupService } from './group.service';
import { SessionModule } from '../session/session.module';
@Module({
imports: [SessionModule],
controllers: [GroupController],
+ providers: [GroupService],
})
export class GroupModule {}
diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.ts
new file mode 100644
index 000000000..6afe294cb
--- /dev/null
+++ b/src/modules/group/group.service.spec.ts
@@ -0,0 +1,43 @@
+import { BadRequestException, NotFoundException } from '@nestjs/common';
+import { GroupService } from './group.service';
+import { SessionService } from '../session/session.service';
+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+
+describe('GroupService', () => {
+ const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {
+ const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;
+ return new GroupService(sessionService);
+ };
+
+ it('throws 400 "Session is not started" when the engine is missing (guard preserved)', () => {
+ // The guard throws synchronously; the controller methods are `async`, so this still surfaces
+ // as a rejected promise → 400 at the HTTP layer.
+ const svc = makeService(undefined);
+ expect(() => svc.getGroups('s1')).toThrow(BadRequestException);
+ expect(() => svc.getGroups('s1')).toThrow('Session is not started');
+ });
+
+ it('delegates getGroups to the engine when the session is started', async () => {
+ const getGroups = jest.fn().mockResolvedValue([{ id: 'g1' }]);
+ const svc = makeService({ getGroups });
+ await expect(svc.getGroups('s1')).resolves.toEqual([{ id: 'g1' }]);
+ expect(getGroups).toHaveBeenCalledTimes(1);
+ });
+
+ it('maps a missing group to 404 (business rule lives in the service)', async () => {
+ const svc = makeService({ getGroupInfo: jest.fn().mockResolvedValue(null) });
+ await expect(svc.getGroupInfo('s1', 'g404')).rejects.toBeInstanceOf(NotFoundException);
+ });
+
+ it('returns the group when found', async () => {
+ const svc = makeService({ getGroupInfo: jest.fn().mockResolvedValue({ id: 'g1', name: 'G' }) });
+ await expect(svc.getGroupInfo('s1', 'g1')).resolves.toEqual({ id: 'g1', name: 'G' });
+ });
+
+ it('passes participant lists straight through to the engine', async () => {
+ const addParticipants = jest.fn().mockResolvedValue(undefined);
+ const svc = makeService({ addParticipants });
+ await svc.addParticipants('s1', 'g1', ['[email protected]', '[email protected]']);
+ expect(addParticipants).toHaveBeenCalledWith('g1', ['[email protected]', '[email protected]']);
+ });
+});
diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.ts
new file mode 100644
index 000000000..39c5f40e3
--- /dev/null
+++ b/src/modules/group/group.service.ts
@@ -0,0 +1,73 @@
+import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
+import { SessionService } from '../session/session.service';
+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+
+/**
+ * Owns engine access for group operations. Controllers depend on this service instead of
+ * reaching for the raw `IWhatsAppEngine` via `sessionService.getEngine`, so the "session not
+ * started" guard and group-level business rules (e.g. not-found mapping) live in one place.
+ */
+@Injectable()
+export class GroupService {
+ constructor(private readonly sessionService: SessionService) {}
+
+ private getEngine(sessionId: string): IWhatsAppEngine {
+ const engine = this.sessionService.getEngine(sessionId);
+ if (!engine) {
+ throw new BadRequestException('Session is not started');
+ }
+ return engine;
+ }
+
+ getGroups(sessionId: string) {
+ return this.getEngine(sessionId).getGroups();
+ }
+
+ async getGroupInfo(sessionId: string, groupId: string) {
+ const group = await this.getEngine(sessionId).getGroupInfo(groupId);
+ if (!group) {
+ throw new NotFoundException(`Group ${groupId} not found`);
+ }
+ return group;
+ }
+
+ createGroup(sessionId: string, name: string, participants: string[]) {
+ return this.getEngine(sessionId).createGroup(name, participants);
+ }
+
+ addParticipants(sessionId: string, groupId: string, participants: string[]) {
+ return this.getEngine(sessionId).addParticipants(groupId, participants);
+ }
+
+ removeParticipants(sessionId: string, groupId: string, participants: string[]) {
+ return this.getEngine(sessionId).removeParticipants(groupId, participants);
+ }
+
+ promoteParticipants(sessionId: string, groupId: string, participants: string[]) {
+ return this.getEngine(sessionId).promoteParticipants(groupId, participants);
+ }
+
+ demoteParticipants(sessionId: string, groupId: string, participants: string[]) {
+ return this.getEngine(sessionId).demoteParticipants(groupId, participants);
+ }
+
+ setGroupSubject(sessionId: string, groupId: string, subject: string) {
+ return this.getEngine(sessionId).setGroupSubject(groupId, subject);
+ }
+
+ setGroupDescription(sessionId: string, groupId: string, description: string) {
+ return this.getEngine(sessionId).setGroupDescription(groupId, description);
+ }
+
+ leaveGroup(sessionId: string, groupId: string) {
+ return this.getEngine(sessionId).leaveGroup(groupId);
+ }
+
+ getGroupInviteCode(sessionId: string, groupId: string) {
+ return this.getEngine(sessionId).getGroupInviteCode(groupId);
+ }
+
+ revokeGroupInviteCode(sessionId: string, groupId: string) {
+ return this.getEngine(sessionId).revokeGroupInviteCode(groupId);
+ }
+}
diff --git a/src/modules/health/health.controller.spec.ts b/src/modules/health/health.controller.spec.ts
index f0cac40a9..cc3c2cfe5 100644
--- a/src/modules/health/health.controller.spec.ts
+++ b/src/modules/health/health.controller.spec.ts
@@ -1,39 +1,77 @@
import { Test, TestingModule } from '@nestjs/testing';
+import { getDataSourceToken } from '@nestjs/typeorm';
+import { ServiceUnavailableException } from '@nestjs/common';
import { HealthController } from './health.controller';
+import { ShutdownService } from '../../common/services/shutdown.service';
describe('HealthController', () => {
let controller: HealthController;
+ const mainQuery = jest.fn();
+ const dataQuery = jest.fn();
+ const isShuttingDown = jest.fn();
beforeEach(async () => {
+ mainQuery.mockResolvedValue([{ '1': 1 }]);
+ dataQuery.mockResolvedValue([{ '1': 1 }]);
+ isShuttingDown.mockReturnValue(false);
+
const module: TestingModule = await Test.createTestingModule({
controllers: [HealthController],
+ providers: [
+ { provide: getDataSourceToken('main'), useValue: { query: mainQuery } },
+ { provide: getDataSourceToken('data'), useValue: { query: dataQuery } },
+ { provide: ShutdownService, useValue: { isShuttingDown } },
+ ],
}).compile();
controller = module.get<HealthController>(HealthController);
});
+ afterEach(() => {
+ mainQuery.mockReset();
+ dataQuery.mockReset();
+ isShuttingDown.mockReset();
+ });
+
describe('check', () => {
- it('should return ok status', () => {
+ it('returns ok with a timestamp (static)', () => {
const result = controller.check();
-
expect(result.status).toBe('ok');
expect(result.timestamp).toBeDefined();
});
});
describe('liveness', () => {
- it('should return ok status for liveness probe', () => {
- const result = controller.liveness();
-
- expect(result.status).toBe('ok');
+ it('returns ok (static — does not probe dependencies)', () => {
+ expect(controller.liveness().status).toBe('ok');
});
});
describe('readiness', () => {
- it('should return ok status for readiness probe', () => {
- const result = controller.readiness();
-
+ it('returns ok when both databases respond', async () => {
+ const result = await controller.readiness();
expect(result.status).toBe('ok');
+ expect(result.details.mainDatabase.status).toBe('up');
+ expect(result.details.dataDatabase.status).toBe('up');
+ expect(mainQuery).toHaveBeenCalledWith('SELECT 1');
+ expect(dataQuery).toHaveBeenCalledWith('SELECT 1');
+ });
+
+ it('throws 503 when the data database is down', async () => {
+ dataQuery.mockRejectedValue(new Error('connection refused'));
+ await expect(controller.readiness()).rejects.toBeInstanceOf(ServiceUnavailableException);
+ });
+
+ it('throws 503 when the main (auth/audit) database is down', async () => {
+ mainQuery.mockRejectedValue(new Error('disk I/O error'));
+ await expect(controller.readiness()).rejects.toBeInstanceOf(ServiceUnavailableException);
+ });
+
+ it('throws 503 while draining, without even probing the DBs', async () => {
+ isShuttingDown.mockReturnValue(true);
+ await expect(controller.readiness()).rejects.toBeInstanceOf(ServiceUnavailableException);
+ expect(mainQuery).not.toHaveBeenCalled();
+ expect(dataQuery).not.toHaveBeenCalled();
});
});
});
diff --git a/src/modules/health/health.controller.ts b/src/modules/health/health.controller.ts
index 79e299475..0bd97114d 100644
--- a/src/modules/health/health.controller.ts
+++ b/src/modules/health/health.controller.ts
@@ -1,20 +1,34 @@
-import { Controller, Get } from '@nestjs/common';
+import { Controller, Get, ServiceUnavailableException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
+import { InjectDataSource } from '@nestjs/typeorm';
+import { DataSource } from 'typeorm';
import { Public } from '../auth/decorators/auth.decorators';
import { SkipThrottle } from '@nestjs/throttler';
+import { ShutdownService } from '../../common/services/shutdown.service';
+
+interface DependencyStatus {
+ status: 'up' | 'down';
+}
interface HealthCheckResult {
status: 'ok' | 'error';
- info?: Record<string, unknown>;
- error?: Record<string, unknown>;
- details?: Record<string, unknown>;
+ details: Record<string, DependencyStatus>;
}
+/** Bound each dependency probe so a hung connection can't stall the readiness check. */
+const READINESS_PROBE_TIMEOUT_MS = 3000;
+
@ApiTags('health')
@Controller('health')
@Public()
@SkipThrottle()
export class HealthController {
+ constructor(
+ @InjectDataSource('main') private readonly mainDataSource: DataSource,
+ @InjectDataSource('data') private readonly dataDataSource: DataSource,
+ private readonly shutdownService: ShutdownService,
+ ) {}
+
@Get()
@ApiOperation({ summary: 'Basic health check' })
@ApiResponse({ status: 200, description: 'Application is healthy' })
@@ -29,22 +43,58 @@ export class HealthController {
@ApiOperation({ summary: 'Liveness probe for Kubernetes' })
@ApiResponse({ status: 200, description: 'Application is alive' })
liveness(): { status: string } {
+ // Liveness only reflects process liveness — deliberately static so a transient
+ // dependency outage doesn't trigger a pod KILL (that's readiness' job).
return { status: 'ok' };
}
@Get('ready')
- @ApiOperation({ summary: 'Readiness probe for Kubernetes' })
- @ApiResponse({
- status: 200,
- description: 'Application is ready to accept traffic',
- })
- readiness(): HealthCheckResult {
- // In the future, check database connection, Redis, etc.
- return {
- status: 'ok',
- details: {
- database: { status: 'up' },
- },
+ @ApiOperation({ summary: 'Readiness probe — verifies the auth/audit + data databases respond' })
+ @ApiResponse({ status: 200, description: 'Application is ready to accept traffic' })
+ @ApiResponse({ status: 503, description: 'A required dependency is down' })
+ async readiness(): Promise<HealthCheckResult> {
+ // While draining (shutdown started), report 503 so the LB/orchestrator stops
+ // routing new traffic before teardown — even if the DBs are still up.
+ if (this.shutdownService.isShuttingDown()) {
+ throw new ServiceUnavailableException({ status: 'error', details: { shutdown: { status: 'draining' } } });
+ }
+
+ const [main, data] = await Promise.all([
+ this.probeDatabase(this.mainDataSource),
+ this.probeDatabase(this.dataDataSource),
+ ]);
+
+ const details: Record<string, DependencyStatus> = {
+ mainDatabase: { status: main },
+ dataDatabase: { status: data },
};
+
+ if (main === 'down' || data === 'down') {
+ // 503 so orchestrators/LBs stop routing traffic to a node with a dead DB.
+ throw new ServiceUnavailableException({ status: 'error', details });
+ }
+
+ return { status: 'ok', details };
+ }
+
+ private async probeDatabase(dataSource: DataSource): Promise<'up' | 'down'> {
+ try {
+ await this.withTimeout(dataSource.query('SELECT 1'), READINESS_PROBE_TIMEOUT_MS);
+ return 'up';
+ } catch {
+ return 'down';
+ }
+ }
+
+ private async withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('readiness probe timed out')), ms);
+ });
+ try {
+ return await Promise.race([work, timeout]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
}
}
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index 7838a965c..179f8cfff 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -531,8 +531,9 @@ export class InfraController {
}
}
- // Schedule graceful shutdown after delay to allow response and container orchestration
- void this.shutdownService.shutdown(3000);
+ // Schedule graceful shutdown after the configurable bounded grace (SHUTDOWN_DELAY_MS,
+ // default 3s) — readiness reports 503 during the window so traffic drains first.
+ void this.shutdownService.shutdown();
// Calculate estimated time - base 15s + additional for each service (increased for reliability)
let estimatedTime = 15;
diff --git a/src/modules/label/dto/add-label.dto.ts b/src/modules/label/dto/add-label.dto.ts
new file mode 100644
index 000000000..20731b37d
--- /dev/null
+++ b/src/modules/label/dto/add-label.dto.ts
@@ -0,0 +1,10 @@
+import { ApiProperty } from '@nestjs/swagger';
+import { IsString, IsNotEmpty } from 'class-validator';
+
+/** Validated body for adding a label to a chat (was an inline @Body literal). */
+export class AddLabelDto {
+ @ApiProperty({ description: 'Label ID to add to the chat' })
+ @IsString()
+ @IsNotEmpty()
+ labelId: string;
+}
diff --git a/src/modules/label/label.controller.ts b/src/modules/label/label.controller.ts
index d109dff2a..d78a7e017 100644
--- a/src/modules/label/label.controller.ts
+++ b/src/modules/label/label.controller.ts
@@ -1,19 +1,12 @@
-import { Controller, Get, Post, Delete, Param, Body, BadRequestException, NotFoundException } from '@nestjs/common';
+import { Controller, Get, Post, Delete, Param, Body } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';
-import { SessionService } from '../session/session.service';
+import { LabelService } from './label.service';
+import { AddLabelDto } from './dto/add-label.dto';
@ApiTags('labels')
@Controller('sessions/:sessionId/labels')
export class LabelController {
- constructor(private readonly sessionService: SessionService) {}
-
- private getEngine(sessionId: string) {
- const engine = this.sessionService.getEngine(sessionId);
- if (!engine) {
- throw new BadRequestException('Session is not started');
- }
- return engine;
- }
+ constructor(private readonly labelService: LabelService) {}
@Get()
@ApiOperation({ summary: 'Get all labels (WhatsApp Business only)' })
@@ -25,8 +18,7 @@ export class LabelController {
@ApiResponse({ status: 400, description: 'Session not ready or not a business account' })
@ApiResponse({ status: 404, description: 'Session not found' })
async findAll(@Param('sessionId') sessionId: string) {
- const engine = this.getEngine(sessionId);
- return engine.getLabels();
+ return this.labelService.getLabels(sessionId);
}
@Get(':labelId')
@@ -39,12 +31,7 @@ export class LabelController {
})
@ApiResponse({ status: 404, description: 'Label not found' })
async findOne(@Param('sessionId') sessionId: string, @Param('labelId') labelId: string) {
- const engine = this.getEngine(sessionId);
- const label = await engine.getLabelById(labelId);
- if (!label) {
- throw new NotFoundException(`Label ${labelId} not found`);
- }
- return label;
+ return this.labelService.getLabelById(sessionId, labelId);
}
@Get('chat/:chatId')
@@ -56,8 +43,7 @@ export class LabelController {
description: 'List of labels for the chat',
})
async getChatLabels(@Param('sessionId') sessionId: string, @Param('chatId') chatId: string) {
- const engine = this.getEngine(sessionId);
- return engine.getChatLabels(chatId);
+ return this.labelService.getChatLabels(sessionId, chatId);
}
@Post('chat/:chatId')
@@ -80,10 +66,9 @@ export class LabelController {
async addLabelToChat(
@Param('sessionId') sessionId: string,
@Param('chatId') chatId: string,
- @Body() body: { labelId: string },
+ @Body() body: AddLabelDto,
) {
- const engine = this.getEngine(sessionId);
- await engine.addLabelToChat(chatId, body.labelId);
+ await this.labelService.addLabelToChat(sessionId, chatId, body.labelId);
return { success: true };
}
@@ -101,8 +86,7 @@ export class LabelController {
@Param('chatId') chatId: string,
@Param('labelId') labelId: string,
) {
- const engine = this.getEngine(sessionId);
- await engine.removeLabelFromChat(chatId, labelId);
+ await this.labelService.removeLabelFromChat(sessionId, chatId, labelId);
return { success: true };
}
}
diff --git a/src/modules/label/label.module.ts b/src/modules/label/label.module.ts
index d89320240..9b6a38dda 100644
--- a/src/modules/label/label.module.ts
+++ b/src/modules/label/label.module.ts
@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { LabelController } from './label.controller';
+import { LabelService } from './label.service';
import { SessionModule } from '../session/session.module';
@Module({
imports: [SessionModule],
controllers: [LabelController],
+ providers: [LabelService],
})
export class LabelModule {}
diff --git a/src/modules/label/label.service.spec.ts b/src/modules/label/label.service.spec.ts
new file mode 100644
index 000000000..4d5518c57
--- /dev/null
+++ b/src/modules/label/label.service.spec.ts
@@ -0,0 +1,26 @@
+import { BadRequestException, NotFoundException } from '@nestjs/common';
+import { LabelService } from './label.service';
+import { SessionService } from '../session/session.service';
+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+
+describe('LabelService', () => {
+ const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {
+ const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;
+ return new LabelService(sessionService);
+ };
+
+ it('throws 400 when the session is not started', () => {
+ expect(() => makeService(undefined).getLabels('s1')).toThrow(BadRequestException);
+ });
+
+ it('maps a missing label to 404', async () => {
+ const svc = makeService({ getLabelById: jest.fn().mockResolvedValue(null) });
+ await expect(svc.getLabelById('s1', 'l404')).rejects.toBeInstanceOf(NotFoundException);
+ });
+
+ it('delegates addLabelToChat to the engine', async () => {
+ const addLabelToChat = jest.fn().mockResolvedValue(undefined);
+ await makeService({ addLabelToChat }).addLabelToChat('s1', 'chat1', 'l1');
+ expect(addLabelToChat).toHaveBeenCalledWith('chat1', 'l1');
+ });
+});
diff --git a/src/modules/label/label.service.ts b/src/modules/label/label.service.ts
new file mode 100644
index 000000000..9a73bdf14
--- /dev/null
+++ b/src/modules/label/label.service.ts
@@ -0,0 +1,44 @@
+import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
+import { SessionService } from '../session/session.service';
+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+
+/**
+ * Owns engine access for label operations so the "session not started" guard and label
+ * business rules (not-found mapping) live behind the service boundary, not in the controller.
+ */
+@Injectable()
+export class LabelService {
+ constructor(private readonly sessionService: SessionService) {}
+
+ private getEngine(sessionId: string): IWhatsAppEngine {
+ const engine = this.sessionService.getEngine(sessionId);
+ if (!engine) {
+ throw new BadRequestException('Session is not started');
+ }
+ return engine;
+ }
+
+ getLabels(sessionId: string) {
+ return this.getEngine(sessionId).getLabels();
+ }
+
+ async getLabelById(sessionId: string, labelId: string) {
+ const label = await this.getEngine(sessionId).getLabelById(labelId);
+ if (!label) {
+ throw new NotFoundException(`Label ${labelId} not found`);
+ }
+ return label;
+ }
+
+ getChatLabels(sessionId: string, chatId: string) {
+ return this.getEngine(sessionId).getChatLabels(chatId);
+ }
+
+ addLabelToChat(sessionId: string, chatId: string, labelId: string) {
+ return this.getEngine(sessionId).addLabelToChat(chatId, labelId);
+ }
+
+ removeLabelFromChat(sessionId: string, chatId: string, labelId: string) {
+ return this.getEngine(sessionId).removeLabelFromChat(chatId, labelId);
+ }
+}
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
new file mode 100644
index 000000000..1633ba4e5
--- /dev/null
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -0,0 +1,43 @@
+import { Test, TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+import { BulkMessageService } from './bulk-message.service';
+import { MessageBatch, BatchStatus } from './entities/message-batch.entity';
+import { SessionService } from '../session/session.service';
+
+/** Regression lock: orphaned (restart-interrupted) PROCESSING batches are transitioned. */
+describe('BulkMessageService.onApplicationBootstrap', () => {
+ let service: BulkMessageService;
+ let repo: { find: jest.Mock; save: jest.Mock };
+
+ beforeEach(async () => {
+ repo = {
+ find: jest.fn().mockResolvedValue([]),
+ save: jest.fn().mockImplementation(b => Promise.resolve(b)),
+ };
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ BulkMessageService,
+ { provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },
+ { provide: SessionService, useValue: { getEngine: jest.fn() } },
+ ],
+ }).compile();
+ service = module.get<BulkMessageService>(BulkMessageService);
+ });
+
+ it('marks an orphaned PROCESSING batch FAILED on startup (no auto-resume)', async () => {
+ const batch = { id: 'b1', status: BatchStatus.PROCESSING } as unknown as MessageBatch;
+ repo.find.mockResolvedValue([batch]);
+
+ await service.onApplicationBootstrap();
+
+ expect(repo.find).toHaveBeenCalledWith({ where: { status: BatchStatus.PROCESSING } });
+ expect(batch.status).toBe(BatchStatus.FAILED);
+ expect(repo.save).toHaveBeenCalledWith(batch);
+ });
+
+ it('does nothing when there are no orphaned batches', async () => {
+ repo.find.mockResolvedValue([]);
+ await service.onApplicationBootstrap();
+ expect(repo.save).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index d088c2da1..29e80bd32 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, Logger, BadRequestException, NotFoundException } from '@nestjs/common';
+import { Injectable, Logger, BadRequestException, NotFoundException, OnApplicationBootstrap } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { randomUUID } from 'crypto';
@@ -24,7 +24,7 @@ interface BulkMessageContent {
}
@Injectable()
-export class BulkMessageService {
+export class BulkMessageService implements OnApplicationBootstrap {
private readonly logger = new Logger(BulkMessageService.name);
private readonly processingBatches = new Map<string, boolean>(); // Track active batches for cancellation
@@ -34,6 +34,25 @@ export class BulkMessageService {
private readonly sessionService: SessionService,
) {}
+ /**
+ * Transition orphaned batches on startup. A batch still in PROCESSING belongs to a
+ * previous (crashed/restarted) process — this fresh process is not driving it, so it would
+ * otherwise be stuck in PROCESSING forever. Mark it FAILED. Auto-resume is intentionally NOT
+ * done here: resuming risks re-sending messages already delivered before the crash.
+ */
+ async onApplicationBootstrap(): Promise<void> {
+ const orphaned = await this.batchRepository.find({ where: { status: BatchStatus.PROCESSING } });
+ for (const batch of orphaned) {
+ batch.status = BatchStatus.FAILED;
+ await this.batchRepository.save(batch);
+ }
+ if (orphaned.length > 0) {
+ this.logger.warn(
+ `Marked ${orphaned.length} orphaned PROCESSING batch(es) FAILED on startup (interrupted by a restart)`,
+ );
+ }
+ }
+
async createBatch(sessionId: string, dto: SendBulkMessageDto): Promise<MessageBatch> {
// Validate session exists
const engine = this.sessionService.getEngine(sessionId);
diff --git a/src/modules/message/dto/message-actions.dto.spec.ts b/src/modules/message/dto/message-actions.dto.spec.ts
new file mode 100644
index 000000000..a1b2e21c6
--- /dev/null
+++ b/src/modules/message/dto/message-actions.dto.spec.ts
@@ -0,0 +1,54 @@
+import { plainToInstance } from 'class-transformer';
+import { validate, ValidationError } from 'class-validator';
+import { SendLocationDto, ReactMessageDto, DeleteMessageDto, ForwardMessageDto } from './message-actions.dto';
+
+/**
+ * Regression locks: these endpoints previously took inline @Body literals (no
+ * runtime validation). e2e is deferred (broken harness), so we validate the
+ * decorators directly via class-validator.
+ */
+function errorsFor<T extends object>(cls: new () => T, obj: object): Promise<ValidationError[]> {
+ return validate(plainToInstance(cls, obj));
+}
+
+describe('message action DTOs', () => {
+ it('SendLocationDto: valid coordinates pass', async () => {
+ expect(await errorsFor(SendLocationDto, { chatId: '[email protected]', latitude: -6.2088, longitude: 106.8456 })).toHaveLength(
+ 0,
+ );
+ });
+
+ it('SendLocationDto: missing chatId is rejected', async () => {
+ const errs = await errorsFor(SendLocationDto, { latitude: -6.2, longitude: 106.8 });
+ expect(errs.some(e => e.property === 'chatId')).toBe(true);
+ });
+
+ it('SendLocationDto: non-numeric latitude is rejected', async () => {
+ const errs = await errorsFor(SendLocationDto, { chatId: '[email protected]', latitude: 'abc', longitude: 106.8 });
+ expect(errs.some(e => e.property === 'latitude')).toBe(true);
+ });
+
+ it('SendLocationDto: out-of-range latitude is rejected', async () => {
+ const errs = await errorsFor(SendLocationDto, { chatId: '[email protected]', latitude: 999, longitude: 106.8 });
+ expect(errs.some(e => e.property === 'latitude')).toBe(true);
+ });
+
+ it('ReactMessageDto: empty emoji is VALID (removes the reaction — foot-gun preserved)', async () => {
+ expect(await errorsFor(ReactMessageDto, { chatId: '[email protected]', messageId: 'm1', emoji: '' })).toHaveLength(0);
+ });
+
+ it('ReactMessageDto: missing messageId is rejected', async () => {
+ const errs = await errorsFor(ReactMessageDto, { chatId: '[email protected]', emoji: '👍' });
+ expect(errs.some(e => e.property === 'messageId')).toBe(true);
+ });
+
+ it('DeleteMessageDto: forEveryone is optional', async () => {
+ expect(await errorsFor(DeleteMessageDto, { chatId: '[email protected]', messageId: 'm1' })).toHaveLength(0);
+ });
+
+ it('ForwardMessageDto: requires all three ids', async () => {
+ const errs = await errorsFor(ForwardMessageDto, { fromChatId: '[email protected]' });
+ expect(errs.some(e => e.property === 'toChatId')).toBe(true);
+ expect(errs.some(e => e.property === 'messageId')).toBe(true);
+ });
+});
diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.ts
new file mode 100644
index 000000000..af14d30ec
--- /dev/null
+++ b/src/modules/message/dto/message-actions.dto.ts
@@ -0,0 +1,118 @@
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
+import { IsString, IsNotEmpty, IsOptional, IsLatitude, IsLongitude, IsBoolean } from 'class-validator';
+
+/**
+ * Validated DTOs for the message action endpoints. These replaced inline
+ * `@Body()` object-literal types, which erase at runtime so the global ValidationPipe had
+ * no metadata to validate or whitelist against.
+ */
+
+export class SendLocationDto {
+ @ApiProperty({ description: 'Chat ID (e.g. [email protected])' })
+ @IsString()
+ @IsNotEmpty()
+ chatId: string;
+
+ @ApiProperty({ example: -6.2088 })
+ @IsLatitude()
+ latitude: number;
+
+ @ApiProperty({ example: 106.8456 })
+ @IsLongitude()
+ longitude: number;
+
+ @ApiPropertyOptional()
+ @IsOptional()
+ @IsString()
+ description?: string;
+
+ @ApiPropertyOptional()
+ @IsOptional()
+ @IsString()
+ address?: string;
+}
+
+export class SendContactDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ chatId: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ contactName: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ contactNumber: string;
+}
+
+export class ReplyMessageDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ chatId: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ quotedMessageId: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ text: string;
+}
+
+export class ForwardMessageDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ fromChatId: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ toChatId: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ messageId: string;
+}
+
+export class ReactMessageDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ chatId: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ messageId: string;
+
+ // Empty string is VALID — it removes the reaction (endpoint contract). So @IsString, not @IsNotEmpty.
+ @ApiProperty({ description: 'Emoji to react with. Send an empty string to remove the reaction.' })
+ @IsString()
+ emoji: string;
+}
+
+export class DeleteMessageDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ chatId: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ messageId: string;
+
+ @ApiPropertyOptional({ description: 'Delete for everyone (default true)' })
+ @IsOptional()
+ @IsBoolean()
+ forEveryone?: boolean;
+}
diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.ts
index de95fee92..db36e1b4e 100644
--- a/src/modules/message/entities/message.entity.ts
+++ b/src/modules/message/entities/message.entity.ts
@@ -17,6 +17,9 @@ export enum MessageStatus {
@Entity('messages')
@Index(['sessionId', 'createdAt'])
@Index(['chatId'])
+// Composite index for the ack-driven status UPDATE (scoped by sessionId + waMessageId).
+// Without it every ack does a full table scan of a hot table.
+@Index(['sessionId', 'waMessageId'])
export class Message {
@PrimaryGeneratedColumn('uuid')
id: string;
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index 04bb9ee7c..4cf7fcb45 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -5,6 +5,14 @@ import { BulkMessageService } from './bulk-message.service';
import { SendTextMessageDto, SendMediaMessageDto, MessageResponseDto } from './dto';
import { SendTemplateMessageDto } from './dto/send-template.dto';
import { SendBulkMessageDto, BulkMessageResponseDto } from './dto/bulk-message.dto';
+import {
+ SendLocationDto,
+ SendContactDto,
+ ReplyMessageDto,
+ ForwardMessageDto,
+ ReactMessageDto,
+ DeleteMessageDto,
+} from './dto/message-actions.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
@@ -169,10 +177,7 @@ export class MessageController {
description: 'Location sent',
type: MessageResponseDto,
})
- async sendLocation(
- @Param('sessionId') sessionId: string,
- @Body() dto: { chatId: string; latitude: number; longitude: number; description?: string; address?: string },
- ): Promise<MessageResponseDto> {
+ async sendLocation(@Param('sessionId') sessionId: string, @Body() dto: SendLocationDto): Promise<MessageResponseDto> {
return this.messageService.sendLocation(sessionId, dto);
}
@@ -185,10 +190,7 @@ export class MessageController {
description: 'Contact sent',
type: MessageResponseDto,
})
- async sendContact(
- @Param('sessionId') sessionId: string,
- @Body() dto: { chatId: string; contactName: string; contactNumber: string },
- ): Promise<MessageResponseDto> {
+ async sendContact(@Param('sessionId') sessionId: string, @Body() dto: SendContactDto): Promise<MessageResponseDto> {
return this.messageService.sendContact(sessionId, dto);
}
@@ -217,10 +219,7 @@ export class MessageController {
description: 'Reply sent',
type: MessageResponseDto,
})
- async reply(
- @Param('sessionId') sessionId: string,
- @Body() dto: { chatId: string; quotedMessageId: string; text: string },
- ): Promise<MessageResponseDto> {
+ async reply(@Param('sessionId') sessionId: string, @Body() dto: ReplyMessageDto): Promise<MessageResponseDto> {
return this.messageService.reply(sessionId, dto);
}
@@ -233,16 +232,14 @@ export class MessageController {
description: 'Message forwarded',
type: MessageResponseDto,
})
- async forward(
- @Param('sessionId') sessionId: string,
- @Body() dto: { fromChatId: string; toChatId: string; messageId: string },
- ): Promise<MessageResponseDto> {
+ async forward(@Param('sessionId') sessionId: string, @Body() dto: ForwardMessageDto): Promise<MessageResponseDto> {
return this.messageService.forward(sessionId, dto);
}
// ========== Phase 3: Reactions ==========
@Post('react')
+ @HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Add or remove a reaction to a message' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -254,10 +251,7 @@ export class MessageController {
status: 400,
description: 'Session not active or message not found',
})
- async react(
- @Param('sessionId') sessionId: string,
- @Body() dto: { chatId: string; messageId: string; emoji: string },
- ): Promise<{ success: boolean }> {
+ async react(@Param('sessionId') sessionId: string, @Body() dto: ReactMessageDto): Promise<{ success: boolean }> {
await this.messageService.reactToMessage(sessionId, dto);
return { success: true };
}
@@ -316,6 +310,7 @@ export class MessageController {
// ========== Delete Message ==========
@Post('delete')
+ @HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Delete a message' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -329,7 +324,7 @@ export class MessageController {
})
async deleteMessage(
@Param('sessionId') sessionId: string,
- @Body() dto: { chatId: string; messageId: string; forEveryone?: boolean },
+ @Body() dto: DeleteMessageDto,
): Promise<{ success: boolean }> {
await this.messageService.deleteMessage(sessionId, dto);
return { success: true };
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index ec8271e5a..bc05e053e 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -8,6 +8,7 @@ import { SessionService } from '../session/session.service';
import { HookManager } from '../../core/hooks';
import { TemplateService } from '../template/template.service';
import { Template } from '../template/entities/template.entity';
+import { SsrfBlockedError } from '../../common/security/ssrf-guard';
const mockEngineResult = { id: 'wa-msg-1', timestamp: 1706868000 };
@@ -259,6 +260,59 @@ describe('MessageService', () => {
expect.objectContaining({ data: 'iVBORw0KGgoAAAAN...', mimetype: 'image/png' }),
);
});
+
+ it('maps a blocked-media-URL SSRF error to HTTP 400', async () => {
+ mockEngine.sendImageMessage.mockRejectedValueOnce(new SsrfBlockedError('Blocked internal address: 127.0.0.1'));
+
+ await expect(
+ service.sendImage('sess-1', { chatId: '[email protected]', url: 'http://127.0.0.1/x.png' }),
+ ).rejects.toBeInstanceOf(BadRequestException);
+ });
+ });
+
+ // ── getMessages pagination guard ──────────────────────────────────
+
+ describe('getMessages pagination guard', () => {
+ interface QbMock {
+ where: jest.Mock;
+ orderBy: jest.Mock;
+ skip: jest.Mock;
+ take: jest.Mock;
+ andWhere: jest.Mock;
+ getManyAndCount: jest.Mock;
+ }
+ const makeQb = (): QbMock => {
+ const qb: QbMock = {
+ where: jest.fn(),
+ orderBy: jest.fn(),
+ skip: jest.fn(),
+ take: jest.fn(),
+ andWhere: jest.fn(),
+ getManyAndCount: jest.fn().mockResolvedValue([[], 0]),
+ };
+ qb.where.mockReturnValue(qb);
+ qb.orderBy.mockReturnValue(qb);
+ qb.skip.mockReturnValue(qb);
+ qb.take.mockReturnValue(qb);
+ qb.andWhere.mockReturnValue(qb);
+ return qb;
+ };
+
+ it('falls back to defaults on NaN limit/offset (never take(NaN))', async () => {
+ const qb = makeQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+ await service.getMessages('sess-1', { limit: NaN, offset: NaN });
+ expect(qb.take).toHaveBeenCalledWith(50);
+ expect(qb.skip).toHaveBeenCalledWith(0);
+ });
+
+ it('clamps an oversized limit to 100 and a negative offset to 0', async () => {
+ const qb = makeQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+ await service.getMessages('sess-1', { limit: 999, offset: -5 });
+ expect(qb.take).toHaveBeenCalledWith(100);
+ expect(qb.skip).toHaveBeenCalledWith(0);
+ });
});
// ── sendVideo / sendAudio / sendDocument / sendSticker ────────────
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index ebfc89322..0fb17ffc2 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -10,6 +10,7 @@ import { HookManager } from '../../core/hooks';
import { TemplateService } from '../template/template.service';
import { renderTemplate } from '../../common/utils/template-render';
import { createLogger } from '../../common/services/logger.service';
+import { SsrfBlockedError } from '../../common/security/ssrf-guard';
export interface GetMessagesOptions {
chatId?: string;
@@ -137,7 +138,7 @@ export class MessageService {
} catch (error) {
message.status = MessageStatus.FAILED;
await this.messageRepository.save(message);
- throw error;
+ throw this.toClientFacingError(error);
}
}
@@ -171,7 +172,7 @@ export class MessageService {
} catch (error) {
message.status = MessageStatus.FAILED;
await this.messageRepository.save(message);
- throw error;
+ throw this.toClientFacingError(error);
}
}
@@ -204,7 +205,7 @@ export class MessageService {
} catch (error) {
message.status = MessageStatus.FAILED;
await this.messageRepository.save(message);
- throw error;
+ throw this.toClientFacingError(error);
}
}
@@ -238,7 +239,7 @@ export class MessageService {
} catch (error) {
message.status = MessageStatus.FAILED;
await this.messageRepository.save(message);
- throw error;
+ throw this.toClientFacingError(error);
}
}
@@ -249,7 +250,14 @@ export class MessageService {
sessionId: string,
options: GetMessagesOptions = {},
): Promise<{ messages: Message[]; total: number }> {
- const { chatId, limit = 50, offset = 0 } = options;
+ const { chatId } = options;
+ // Sanitize pagination: a non-finite limit/offset — e.g. `?limit=abc` -> NaN —
+ // must never reach TypeORM's take()/skip(). Clamp to sane bounds; fall back to defaults.
+ const rawLimit = options.limit;
+ const rawOffset = options.offset;
+ const limit =
+ typeof rawLimit === 'number' && Number.isFinite(rawLimit) ? Math.min(Math.max(Math.trunc(rawLimit), 1), 100) : 50;
+ const offset = typeof rawOffset === 'number' && Number.isFinite(rawOffset) ? Math.max(Math.trunc(rawOffset), 0) : 0;
const query = this.messageRepository
.createQueryBuilder('message')
@@ -302,7 +310,7 @@ export class MessageService {
} catch (error) {
message.status = MessageStatus.FAILED;
await this.messageRepository.save(message);
- throw error;
+ throw this.toClientFacingError(error);
}
}
@@ -338,7 +346,7 @@ export class MessageService {
} catch (error) {
message.status = MessageStatus.FAILED;
await this.messageRepository.save(message);
- throw error;
+ throw this.toClientFacingError(error);
}
}
@@ -371,7 +379,7 @@ export class MessageService {
} catch (error) {
message.status = MessageStatus.FAILED;
await this.messageRepository.save(message);
- throw error;
+ throw this.toClientFacingError(error);
}
}
@@ -418,7 +426,7 @@ export class MessageService {
} catch (error) {
message.status = MessageStatus.FAILED;
await this.messageRepository.save(message);
- throw error;
+ throw this.toClientFacingError(error);
}
}
@@ -451,7 +459,7 @@ export class MessageService {
} catch (error) {
message.status = MessageStatus.FAILED;
await this.messageRepository.save(message);
- throw error;
+ throw this.toClientFacingError(error);
}
}
@@ -557,6 +565,18 @@ export class MessageService {
return engine;
}
+ /**
+ * Map a blocked outbound media fetch (SSRF guard) to an HTTP 400 so a
+ * caller-supplied internal/unsafe URL returns a client error instead of a 500.
+ * All other errors pass through unchanged.
+ */
+ private toClientFacingError(error: unknown): unknown {
+ if (error instanceof SsrfBlockedError) {
+ return new BadRequestException(error.message);
+ }
+ return error;
+ }
+
private buildMediaInput(dto: SendMediaMessageDto): MediaInput {
if (!dto.url && !dto.base64) {
throw new BadRequestException('Either url or base64 must be provided');
diff --git a/src/modules/metrics/metrics.controller.ts b/src/modules/metrics/metrics.controller.ts
new file mode 100644
index 000000000..fb569e28f
--- /dev/null
+++ b/src/modules/metrics/metrics.controller.ts
@@ -0,0 +1,29 @@
+import { Controller, Get, Header, Headers } from '@nestjs/common';
+import { ApiTags, ApiOperation, ApiResponse, ApiExcludeEndpoint } from '@nestjs/swagger';
+import { SkipThrottle } from '@nestjs/throttler';
+import { Public } from '../auth/decorators/auth.decorators';
+import { MetricsService } from './metrics.service';
+
+/**
+ * Prometheus scrape endpoint. `@Public()` bypasses the API-key guard and
+ * `@SkipThrottle()` keeps a scrape interval from eating the rate-limit budget; access is
+ * instead gated by METRICS_TOKEN inside the service (disabled-by-default).
+ */
+@ApiTags('metrics')
+@Controller('metrics')
+@Public()
+@SkipThrottle()
+export class MetricsController {
+ constructor(private readonly metricsService: MetricsService) {}
+
+ @Get()
+ @ApiExcludeEndpoint()
+ @ApiOperation({ summary: 'Prometheus metrics (requires METRICS_TOKEN bearer)' })
+ @ApiResponse({ status: 200, description: 'Prometheus exposition text' })
+ @Header('Content-Type', 'text/plain; version=0.0.4; charset=utf-8')
+ @Header('Cache-Control', 'no-store')
+ async scrape(@Headers('authorization') authorization?: string): Promise<string> {
+ this.metricsService.assertScrapeAuthorized(authorization);
+ return this.metricsService.render();
+ }
+}
diff --git a/src/modules/metrics/metrics.module.ts b/src/modules/metrics/metrics.module.ts
new file mode 100644
index 000000000..8868fcd36
--- /dev/null
+++ b/src/modules/metrics/metrics.module.ts
@@ -0,0 +1,12 @@
+import { Module } from '@nestjs/common';
+import { ConfigModule } from '@nestjs/config';
+import { MetricsController } from './metrics.controller';
+import { MetricsService } from './metrics.service';
+import { StatsModule } from '../stats/stats.module';
+
+@Module({
+ imports: [ConfigModule, StatsModule],
+ controllers: [MetricsController],
+ providers: [MetricsService],
+})
+export class MetricsModule {}
diff --git a/src/modules/metrics/metrics.service.spec.ts b/src/modules/metrics/metrics.service.spec.ts
new file mode 100644
index 000000000..bc015b34f
--- /dev/null
+++ b/src/modules/metrics/metrics.service.spec.ts
@@ -0,0 +1,63 @@
+import { NotFoundException, UnauthorizedException } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import { MetricsService } from './metrics.service';
+import { StatsService, OverviewStats } from '../stats/stats.service';
+
+describe('MetricsService', () => {
+ const overview: OverviewStats = {
+ sessions: { active: 2, total: 3, byStatus: { ready: 2, failed: 1 } },
+ messages: { sent: 100, received: 50, failed: 3, today: { sent: 10, received: 5 } },
+ };
+
+ const makeService = (token?: string): MetricsService => {
+ const config = { get: (k: string) => (k === 'METRICS_TOKEN' ? token : undefined) } as unknown as ConfigService;
+ const stats = { getOverview: jest.fn().mockResolvedValue(overview) } as unknown as StatsService;
+ return new MetricsService(config, stats);
+ };
+
+ describe('assertScrapeAuthorized', () => {
+ it('returns 404 when no token is configured (endpoint disabled by default)', () => {
+ const svc = makeService(undefined);
+ expect(() => svc.assertScrapeAuthorized('Bearer anything')).toThrow(NotFoundException);
+ });
+
+ it('rejects a missing bearer with 401 when a token is configured', () => {
+ const svc = makeService('s3cret');
+ expect(() => svc.assertScrapeAuthorized(undefined)).toThrow(UnauthorizedException);
+ });
+
+ it('rejects a wrong token with 401', () => {
+ const svc = makeService('s3cret');
+ expect(() => svc.assertScrapeAuthorized('Bearer nope')).toThrow(UnauthorizedException);
+ });
+
+ it('accepts a correct bearer token', () => {
+ const svc = makeService('s3cret');
+ expect(() => svc.assertScrapeAuthorized('Bearer s3cret')).not.toThrow();
+ });
+
+ it('is tolerant of bearer casing/whitespace', () => {
+ const svc = makeService('s3cret');
+ expect(() => svc.assertScrapeAuthorized('bearer s3cret')).not.toThrow();
+ });
+ });
+
+ describe('render', () => {
+ it('emits Prometheus exposition with session + message gauges', async () => {
+ const svc = makeService('s3cret');
+ const out = await svc.render();
+
+ expect(out).toContain('openwa_up 1');
+ expect(out).toContain('openwa_sessions_active 2');
+ expect(out).toContain('openwa_sessions_total 3');
+ expect(out).toContain('openwa_sessions{status="ready"} 2');
+ expect(out).toContain('openwa_sessions{status="failed"} 1');
+ expect(out).toContain('openwa_messages_total{direction="outgoing"} 100');
+ expect(out).toContain('openwa_messages_total{direction="incoming"} 50');
+ expect(out).toContain('openwa_messages_failed_total 3');
+ // Every metric must declare HELP/TYPE before its sample.
+ expect(out).toContain('# TYPE openwa_messages_total counter');
+ expect(out.endsWith('\n')).toBe(true);
+ });
+ });
+});
diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.ts
new file mode 100644
index 000000000..e99640e76
--- /dev/null
+++ b/src/modules/metrics/metrics.service.ts
@@ -0,0 +1,92 @@
+import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import { timingSafeEqual } from 'crypto';
+import { StatsService } from '../stats/stats.service';
+
+/**
+ * Prometheus exposition for OpenWA. Kept dependency-free (no prom-client) — the
+ * surface is small and the text format (v0.0.4) is trivial to emit by hand.
+ *
+ * Scraping is gated by METRICS_TOKEN: when it is unset the endpoint is disabled entirely
+ * (404, so a scanner cannot even confirm it exists); when set, a matching `Bearer` token
+ * is required. This keeps operational internals (session counts, failure totals) from
+ * being exposed publicly by default on a self-hosted box.
+ */
+@Injectable()
+export class MetricsService {
+ constructor(
+ private readonly config: ConfigService,
+ private readonly statsService: StatsService,
+ ) {}
+
+ private get token(): string {
+ return (this.config.get<string>('METRICS_TOKEN') ?? '').trim();
+ }
+
+ /**
+ * Throws if the caller may not scrape: 404 when metrics are disabled (no token configured),
+ * 401 when a token is configured but the request's bearer is missing or wrong.
+ */
+ assertScrapeAuthorized(authorizationHeader: string | undefined): void {
+ const expected = this.token;
+ if (!expected) {
+ throw new NotFoundException('Metrics endpoint is disabled (set METRICS_TOKEN to enable)');
+ }
+ const provided = (authorizationHeader ?? '').replace(/^Bearer\s+/i, '').trim();
+ if (!provided || !this.safeEqual(provided, expected)) {
+ throw new UnauthorizedException('Invalid metrics token');
+ }
+ }
+
+ private safeEqual(a: string, b: string): boolean {
+ const ab = Buffer.from(a);
+ const bb = Buffer.from(b);
+ // timingSafeEqual requires equal lengths; compare to a fixed digest of `b` to avoid
+ // leaking the expected length through an early return.
+ if (ab.length !== bb.length) return false;
+ return timingSafeEqual(ab, bb);
+ }
+
+ /** Render the current metrics in Prometheus text exposition format. */
+ async render(): Promise<string> {
+ const overview = await this.statsService.getOverview();
+ const mem = process.memoryUsage();
+ const lines: string[] = [];
+
+ const gauge = (name: string, help: string, value: number, labels = ''): void => {
+ lines.push(`# HELP ${name} ${help}`);
+ lines.push(`# TYPE ${name} gauge`);
+ lines.push(`${name}${labels} ${value}`);
+ };
+
+ gauge('openwa_up', 'Whether the OpenWA process is up (always 1 when scraped).', 1);
+ gauge('openwa_process_uptime_seconds', 'Process uptime in seconds.', Math.round(process.uptime()));
+ gauge('openwa_process_resident_memory_bytes', 'Resident set size in bytes.', mem.rss);
+ gauge('openwa_process_heap_used_bytes', 'V8 heap used in bytes.', mem.heapUsed);
+
+ gauge('openwa_sessions_total', 'Total number of configured sessions.', overview.sessions.total);
+ gauge('openwa_sessions_active', 'Number of READY (active) sessions.', overview.sessions.active);
+
+ // Per-status session counts share one metric name with a `status` label.
+ lines.push('# HELP openwa_sessions Number of sessions by status.');
+ lines.push('# TYPE openwa_sessions gauge');
+ for (const [status, count] of Object.entries(overview.sessions.byStatus)) {
+ lines.push(`openwa_sessions{status="${this.escapeLabel(status)}"} ${count}`);
+ }
+
+ lines.push('# HELP openwa_messages_total Total messages by direction.');
+ lines.push('# TYPE openwa_messages_total counter');
+ lines.push(`openwa_messages_total{direction="outgoing"} ${overview.messages.sent}`);
+ lines.push(`openwa_messages_total{direction="incoming"} ${overview.messages.received}`);
+
+ lines.push('# HELP openwa_messages_failed_total Total messages in FAILED state.');
+ lines.push('# TYPE openwa_messages_failed_total counter');
+ lines.push(`openwa_messages_failed_total ${overview.messages.failed}`);
+
+ return lines.join('\n') + '\n';
+ }
+
+ private escapeLabel(value: string): string {
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
+ }
+}
diff --git a/src/modules/queue/processors/webhook.processor.spec.ts b/src/modules/queue/processors/webhook.processor.spec.ts
new file mode 100644
index 000000000..ee1558b35
--- /dev/null
+++ b/src/modules/queue/processors/webhook.processor.spec.ts
@@ -0,0 +1,104 @@
+import { Job } from 'bullmq';
+import { Repository } from 'typeorm';
+import { WebhookProcessor } from './webhook.processor';
+import { Webhook } from '../../webhook/entities/webhook.entity';
+import { HookManager } from '../../../core/hooks';
+import { WebhookJobData } from '../../webhook/webhook.service';
+
+/**
+ * Regression coverage for the production (QUEUE_ENABLED) webhook delivery path, which was
+ * previously untested. Covers the success path, the off-by-one final-attempt gate, the
+ * retry-count header, and the redirect refusal when SSRF protection is on.
+ */
+describe('WebhookProcessor', () => {
+ let processor: WebhookProcessor;
+ let repo: { update: jest.Mock };
+ let hookManager: { execute: jest.Mock };
+ let mockFetch: jest.Mock;
+ const origProtect = process.env.WEBHOOK_SSRF_PROTECT;
+
+ const makeJob = (overrides: Partial<WebhookJobData> = {}, attemptsMade = 0): Job<WebhookJobData> =>
+ ({
+ id: 'job-1',
+ attemptsMade,
+ data: {
+ webhookId: 'wh-1',
+ url: 'https://8.8.8.8/hook', // IP literal → SSRF guard needs no DNS lookup
+ event: 'message.received',
+ payload: {
+ event: 'message.received',
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ data: {},
+ },
+ signature: '',
+ headers: { 'Content-Type': 'application/json' },
+ attempt: 1,
+ maxRetries: 3,
+ ...overrides,
+ },
+ }) as unknown as Job<WebhookJobData>;
+
+ beforeEach(() => {
+ repo = { update: jest.fn().mockResolvedValue({ affected: 1 }) };
+ hookManager = { execute: jest.fn().mockResolvedValue({ continue: true, data: {} }) };
+ processor = new WebhookProcessor(repo as unknown as Repository<Webhook>, hookManager as unknown as HookManager);
+ mockFetch = jest.fn();
+ global.fetch = mockFetch as typeof global.fetch;
+ process.env.WEBHOOK_SSRF_PROTECT = 'false'; // delivery-logic tests; redirect test flips it on
+ });
+
+ afterEach(() => {
+ mockFetch.mockReset();
+ if (origProtect === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;
+ else process.env.WEBHOOK_SSRF_PROTECT = origProtect;
+ });
+
+ it('on success updates lastTriggeredAt and fires webhook:delivered', async () => {
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+
+ const result = await processor.process(makeJob());
+
+ expect(result.success).toBe(true);
+ expect(repo.update).toHaveBeenCalledTimes(1);
+ const updateArgs = repo.update.mock.calls[0] as unknown as [string, { lastTriggeredAt: Date }];
+ expect(updateArgs[0]).toBe('wh-1');
+ expect(updateArgs[1].lastTriggeredAt).toBeInstanceOf(Date);
+ expect(hookManager.execute).toHaveBeenCalledWith('webhook:delivered', expect.anything(), expect.anything());
+ });
+
+ it('sets X-OpenWA-Retry-Count to the attempt number', async () => {
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+
+ await processor.process(makeJob({}, 2));
+
+ const call = mockFetch.mock.calls[0] as unknown as [string, { headers: Record<string, string> }];
+ expect(call[1].headers['X-OpenWA-Retry-Count']).toBe('2');
+ });
+
+ it('throws on a non-ok response WITHOUT firing webhook:error before the final attempt', async () => {
+ mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Server Error' });
+
+ await expect(processor.process(makeJob({ maxRetries: 3 }, 0))).rejects.toThrow();
+ expect(hookManager.execute).not.toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());
+ });
+
+ it('fires webhook:error only on the final attempt', async () => {
+ mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Server Error' });
+
+ // attemptsMade=2, maxRetries=3 -> attemptsMade+1 >= maxRetries -> final
+ await expect(processor.process(makeJob({ maxRetries: 3 }, 2))).rejects.toThrow();
+ expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());
+ });
+
+ it('refuses to follow a redirect when SSRF protection is on', async () => {
+ process.env.WEBHOOK_SSRF_PROTECT = 'true';
+ mockFetch.mockResolvedValue({ ok: false, status: 0, type: 'opaqueredirect' });
+
+ await expect(processor.process(makeJob({ maxRetries: 1 }, 0))).rejects.toThrow();
+ expect(mockFetch).toHaveBeenCalledWith('https://8.8.8.8/hook', expect.objectContaining({ redirect: 'manual' }));
+ expect(repo.update).not.toHaveBeenCalled(); // never treated as delivered
+ });
+});
diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.ts
index 05edcea64..b0c70e755 100644
--- a/src/modules/queue/processors/webhook.processor.ts
+++ b/src/modules/queue/processors/webhook.processor.ts
@@ -7,7 +7,7 @@ import { QUEUE_NAMES } from '../queue-names';
import { WebhookJobData } from '../../webhook/webhook.service';
import { Webhook } from '../../webhook/entities/webhook.entity';
import { HookManager } from '../../../core/hooks';
-import { assertSafeWebhookUrl, isSsrfProtectionEnabled } from '../../../common/security/ssrf-guard';
+import { assertSafeFetchUrl, assertNoRedirect, isSsrfProtectionEnabled } from '../../../common/security/ssrf-guard';
export interface WebhookJobResult {
statusCode: number;
@@ -48,16 +48,21 @@ export class WebhookProcessor extends WorkerHost {
'X-OpenWA-Retry-Count': String(job.attemptsMade),
};
+ const ssrfProtected = isSsrfProtectionEnabled();
try {
- if (isSsrfProtectionEnabled()) {
- await assertSafeWebhookUrl(url);
+ if (ssrfProtected) {
+ await assertSafeFetchUrl(url);
}
const response = await fetch(url, {
method: 'POST',
headers: requestHeaders,
body: JSON.stringify(payload),
signal: AbortSignal.timeout(10000),
+ redirect: ssrfProtected ? 'manual' : 'follow',
});
+ if (ssrfProtected) {
+ assertNoRedirect(response, url);
+ }
const responseTime = Date.now() - startTime;
const success = response.ok;
diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.ts
index 7f589a663..169a962d7 100644
--- a/src/modules/session/session.module.ts
+++ b/src/modules/session/session.module.ts
@@ -1,4 +1,4 @@
-import { Module, forwardRef } from '@nestjs/common';
+import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Session } from './entities/session.entity';
import { Message } from '../message/entities/message.entity';
@@ -7,7 +7,9 @@ import { SessionController } from './session.controller';
import { WebhookModule } from '../webhook/webhook.module';
@Module({
- imports: [TypeOrmModule.forFeature([Session, Message], 'data'), forwardRef(() => WebhookModule)],
+ // WebhookModule does not import SessionModule back, so the dependency is one-directional —
+ // no forwardRef() needed.
+ imports: [TypeOrmModule.forFeature([Session, Message], 'data'), WebhookModule],
controllers: [SessionController],
providers: [SessionService],
exports: [SessionService],
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 52f6207fb..ceb20af3d 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -299,6 +299,40 @@ describe('SessionService', () => {
// ── engine onError / lastError surfacing (#219) ───────────────────
+ describe('reconnect/stop race', () => {
+ interface Internals {
+ executeReconnect: (id: string, session: Session, state: unknown) => Promise<void>;
+ stoppingSessions: Set<string>;
+ engines: Map<string, unknown>;
+ }
+ const internals = (): Internals => service as unknown as Internals;
+ const reconnectState = { attempts: 1, timer: null, maxAttempts: 5, baseDelay: 5000 };
+
+ it('does not create an engine when the session was already stopped (early guard)', async () => {
+ const i = internals();
+ i.stoppingSessions.add('sess-uuid-1');
+
+ await i.executeReconnect('sess-uuid-1', createMockSession(), reconnectState);
+
+ expect(i.engines.has('sess-uuid-1')).toBe(false);
+ expect(engineFactory.create).not.toHaveBeenCalled();
+ });
+
+ it('tears down an engine created when a stop lands during init (post-init guard)', async () => {
+ const i = internals();
+ // Simulate a concurrent stop() during engine init: initialize() flips the teardown flag.
+ mockEngine.initialize.mockImplementation(() => {
+ i.stoppingSessions.add('sess-uuid-1');
+ return Promise.resolve();
+ });
+
+ await i.executeReconnect('sess-uuid-1', createMockSession(), reconnectState);
+
+ expect(mockEngine.destroy).toHaveBeenCalled();
+ expect(i.engines.has('sess-uuid-1')).toBe(false);
+ });
+ });
+
describe('engine onError', () => {
type EngineCallbacks = { onError?: (reason: string) => void; onReady?: (phone: string, name: string) => void };
@@ -394,6 +428,19 @@ describe('SessionService', () => {
expect(sent[0][0]).toBe('sess-uuid-1');
});
+ it('scopes the ack status UPDATE by sessionId, not just waMessageId', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ expect(typeof callbacks.onMessageAck).toBe('function');
+
+ callbacks.onMessageAck!('wa-msg-1', 2); // ack=2 -> DELIVERED
+ await flush();
+
+ expect(messageRepository.update).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: 'sess-uuid-1', waMessageId: 'wa-msg-1' }),
+ expect.objectContaining({ status: MessageStatus.DELIVERED }),
+ );
+ });
+
it('does not dispatch message.sent for an incoming message_create event (fromMe=false)', async () => {
const callbacks = await startAndCaptureCallbacks();
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 0feafb41e..f13d2a90e 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -46,6 +46,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Reconnection state per session
private reconnectStates: Map<string, ReconnectState> = new Map();
+ // Sessions currently being stopped/deleted. An in-flight executeReconnect awaits
+ // engine init, so a stop/delete during that window could re-register an engine AFTER
+ // teardown (orphan). stop()/delete() add the id here; executeReconnect checks it after its
+ // awaits and destroys any engine it just created; start() clears it (intentional restart).
+ private stoppingSessions: Set<string> = new Set();
+
constructor(
@InjectRepository(Session, 'data')
private readonly sessionRepository: Repository<Session>,
@@ -211,6 +217,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async delete(id: string): Promise<void> {
const session = await this.findOne(id);
+ // Mark as tearing down BEFORE cleanup so an in-flight reconnect can't resurrect it.
+ this.stoppingSessions.add(id);
// Cancel any reconnection attempts
this.cancelReconnect(id);
@@ -252,6 +260,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
throw new BadRequestException('Session is already started');
}
+ // A fresh start intentionally (re-)creates the engine — clear any stale stop/delete mark.
+ this.stoppingSessions.delete(id);
+
// Execute hook before starting
await this.hookManager.execute(
'session:starting',
@@ -466,7 +477,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
const status = ackToMessageStatus(ack);
if (status) {
void this.messageRepository
- .update({ waMessageId: messageId, status: In(ackStatusTransitionFrom(status)) }, { status })
+ // Scope by sessionId: waMessageId is unique per account/chat, not global —
+ // an ack on one session must never advance a same-id row in another session.
+ .update({ sessionId: id, waMessageId: messageId, status: In(ackStatusTransitionFrom(status)) }, { status })
.then(result => {
// affected:0 — the row was not advanced: either the send's 2nd save (which sets
// waMessageId) hasn't committed yet, or the status is already at/above the target.
@@ -639,6 +652,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
private async executeReconnect(id: string, session: Session, state: ReconnectState): Promise<void> {
+ // The session may have been stopped/deleted before this fired — don't resurrect it.
+ if (this.stoppingSessions.has(id)) {
+ return;
+ }
try {
// Clean up old engine
const oldEngine = this.engines.get(id);
@@ -649,6 +666,17 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Re-initialize
await this.initializeEngine(id, session);
+
+ // A stop()/delete() may have run while we awaited init — if so, tear down the engine we
+ // just registered so it isn't orphaned (the session is meant to be down).
+ if (this.stoppingSessions.has(id)) {
+ const resurrected = this.engines.get(id);
+ if (resurrected) {
+ await resurrected.destroy();
+ this.engines.delete(id);
+ }
+ return;
+ }
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
this.logger.error(`Reconnect attempt ${state.attempts} failed`, errorMessage, {
@@ -672,6 +700,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async stop(id: string): Promise<Session> {
const session = await this.findOne(id);
+ // Mark as tearing down BEFORE cleanup so an in-flight reconnect can't resurrect it.
+ this.stoppingSessions.add(id);
// Cancel any reconnection attempts
this.cancelReconnect(id);
diff --git a/src/modules/webhook/dto/webhook.dto.spec.ts b/src/modules/webhook/dto/webhook.dto.spec.ts
new file mode 100644
index 000000000..6791c74e0
--- /dev/null
+++ b/src/modules/webhook/dto/webhook.dto.spec.ts
@@ -0,0 +1,35 @@
+import { plainToInstance } from 'class-transformer';
+import { validate, ValidationError } from 'class-validator';
+import { CreateWebhookDto, UpdateWebhookDto } from './webhook.dto';
+
+/** Regression locks: webhook `events[]` must be constrained to known types + '*'. */
+function errorsFor<T extends object>(cls: new () => T, obj: object): Promise<ValidationError[]> {
+ return validate(plainToInstance(cls, obj));
+}
+
+describe('webhook DTO event validation', () => {
+ it('CreateWebhookDto: rejects an unknown/typo event', async () => {
+ const errs = await errorsFor(CreateWebhookDto, { url: 'https://x.example/hook', events: ['mesage.received'] });
+ expect(errs.some(e => e.property === 'events')).toBe(true);
+ });
+
+ it("CreateWebhookDto: accepts the '*' wildcard (must stay valid)", async () => {
+ expect(await errorsFor(CreateWebhookDto, { url: 'https://x.example/hook', events: ['*'] })).toHaveLength(0);
+ });
+
+ it('CreateWebhookDto: accepts known events', async () => {
+ expect(
+ await errorsFor(CreateWebhookDto, { url: 'https://x.example/hook', events: ['message.received', 'group.join'] }),
+ ).toHaveLength(0);
+ });
+
+ it('UpdateWebhookDto: rejects an empty events array (ArrayMinSize parity)', async () => {
+ const errs = await errorsFor(UpdateWebhookDto, { events: [] });
+ expect(errs.some(e => e.property === 'events')).toBe(true);
+ });
+
+ it('UpdateWebhookDto: rejects an unknown event', async () => {
+ const errs = await errorsFor(UpdateWebhookDto, { events: ['nope'] });
+ expect(errs.some(e => e.property === 'events')).toBe(true);
+ });
+});
diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.ts
index 2523a4071..aab2e33e8 100644
--- a/src/modules/webhook/dto/webhook.dto.ts
+++ b/src/modules/webhook/dto/webhook.dto.ts
@@ -1,5 +1,20 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
-import { IsString, IsUrl, IsArray, IsOptional, IsBoolean, IsInt, Min, Max, ArrayMinSize } from 'class-validator';
+import {
+ IsString,
+ IsUrl,
+ IsArray,
+ IsOptional,
+ IsBoolean,
+ IsInt,
+ Min,
+ Max,
+ MaxLength,
+ ArrayMinSize,
+ IsIn,
+ IsObject,
+} from 'class-validator';
+import { Expose, plainToInstance } from 'class-transformer';
+import { Webhook } from '../entities/webhook.entity';
export const WEBHOOK_EVENTS = [
'message.received',
@@ -27,13 +42,15 @@ export class CreateWebhookDto {
url: string;
@ApiPropertyOptional({
- description: 'Event types to subscribe to',
+ description: "Event types to subscribe to. '*' subscribes to all events.",
example: ['message.received', 'session.status'],
enum: WEBHOOK_EVENTS,
})
@IsOptional()
@IsArray()
@ArrayMinSize(1)
+ // Must include '*' (wildcard subscribe-all) alongside the known events.
+ @IsIn([...WEBHOOK_EVENTS, '*'], { each: true })
events?: string[];
@ApiPropertyOptional({
@@ -42,6 +59,7 @@ export class CreateWebhookDto {
})
@IsOptional()
@IsString()
+ @MaxLength(255)
secret?: string;
@ApiPropertyOptional({
@@ -49,6 +67,7 @@ export class CreateWebhookDto {
example: { 'X-Custom-Header': 'value' },
})
@IsOptional()
+ @IsObject()
headers?: Record<string, string>;
@ApiPropertyOptional({
@@ -70,18 +89,22 @@ export class UpdateWebhookDto {
@IsUrl()
url?: string;
- @ApiPropertyOptional({ description: 'Event types to subscribe to' })
+ @ApiPropertyOptional({ description: "Event types to subscribe to. '*' subscribes to all events." })
@IsOptional()
@IsArray()
+ @ArrayMinSize(1)
+ @IsIn([...WEBHOOK_EVENTS, '*'], { each: true })
events?: string[];
@ApiPropertyOptional({ description: 'Secret key for HMAC signature' })
@IsOptional()
@IsString()
+ @MaxLength(255)
secret?: string;
@ApiPropertyOptional({ description: 'Custom headers' })
@IsOptional()
+ @IsObject()
headers?: Record<string, string>;
@ApiPropertyOptional({ description: 'Enable/disable webhook' })
@@ -97,31 +120,57 @@ export class UpdateWebhookDto {
retryCount?: number;
}
+/**
+ * Public response shape for a webhook. Deliberately omits `secret` (the HMAC
+ * signing key) and `headers` (which may carry receiver credentials) — these are
+ * write-only and must never appear in any API response.
+ *
+ * `@Expose()` is required on every field: `fromEntity` maps with
+ * `excludeExtraneousValues: true`, so only exposed fields are serialized and any
+ * undeclared entity field (secret, headers, the session relation) is dropped.
+ */
export class WebhookResponseDto {
+ @Expose()
@ApiProperty()
id: string;
+ @Expose()
@ApiProperty()
sessionId: string;
+ @Expose()
@ApiProperty()
url: string;
+ @Expose()
@ApiProperty()
events: string[];
+ @Expose()
@ApiProperty()
active: boolean;
+ @Expose()
@ApiProperty()
retryCount: number;
+ @Expose()
@ApiPropertyOptional()
lastTriggeredAt?: Date | null;
+ @Expose()
@ApiProperty()
createdAt: Date;
+ @Expose()
@ApiProperty()
updatedAt: Date;
+
+ static fromEntity(entity: Webhook): WebhookResponseDto {
+ return plainToInstance(WebhookResponseDto, entity, { excludeExtraneousValues: true });
+ }
+
+ static fromEntities(entities: Webhook[]): WebhookResponseDto[] {
+ return entities.map(entity => WebhookResponseDto.fromEntity(entity));
+ }
}
diff --git a/src/modules/webhook/utils/idempotency.util.spec.ts b/src/modules/webhook/utils/idempotency.util.spec.ts
index 4be9faed3..c88281912 100644
--- a/src/modules/webhook/utils/idempotency.util.spec.ts
+++ b/src/modules/webhook/utils/idempotency.util.spec.ts
@@ -2,35 +2,41 @@ import { generateIdempotencyKey, generateDeliveryId } from './idempotency.util';
describe('Idempotency Utils', () => {
describe('generateIdempotencyKey', () => {
- it('should generate key for message.received', () => {
- const key = generateIdempotencyKey('message.received', { messageId: 'ABC123' });
- expect(key).toBe('msg_ABC123');
+ it('should generate a session-scoped key for message.received', () => {
+ const key = generateIdempotencyKey('message.received', { messageId: 'ABC123', sessionId: 'A' });
+ expect(key).toBe('msg_A_ABC123');
});
- it('should generate key for message.ack', () => {
- const key = generateIdempotencyKey('message.ack', { messageId: 'ABC123', ack: 3 });
- expect(key).toBe('ack_ABC123_3');
+ it('should generate a session-scoped key for message.ack', () => {
+ const key = generateIdempotencyKey('message.ack', { messageId: 'ABC123', ack: 3, sessionId: 'A' });
+ expect(key).toBe('ack_A_ABC123_3');
});
it('should use the IncomingMessage `id` field for message.received (the real dispatch shape)', () => {
// session.service dispatches the IncomingMessage object, which carries `id`, not `messageId`.
- const key = generateIdempotencyKey('message.received', { id: 'ABC123' });
- expect(key).toBe('msg_ABC123');
+ const key = generateIdempotencyKey('message.received', { id: 'ABC123', sessionId: 'A' });
+ expect(key).toBe('msg_A_ABC123');
});
it('should prefer `id` over a legacy `messageId` when both are present for message.received', () => {
- const key = generateIdempotencyKey('message.received', { id: 'REAL', messageId: 'LEGACY' });
- expect(key).toBe('msg_REAL');
+ const key = generateIdempotencyKey('message.received', { id: 'REAL', messageId: 'LEGACY', sessionId: 'A' });
+ expect(key).toBe('msg_A_REAL');
});
it('should use the `id` field for message.ack (the real dispatch shape)', () => {
- const key = generateIdempotencyKey('message.ack', { id: 'ABC123', ack: 3 });
- expect(key).toBe('ack_ABC123_3');
+ const key = generateIdempotencyKey('message.ack', { id: 'ABC123', ack: 3, sessionId: 'A' });
+ expect(key).toBe('ack_A_ABC123_3');
});
it('should use the `id` field for message.revoked (the real dispatch shape)', () => {
- const key = generateIdempotencyKey('message.revoked', { id: 'ABC123' });
- expect(key).toBe('rev_ABC123');
+ const key = generateIdempotencyKey('message.revoked', { id: 'ABC123', sessionId: 'A' });
+ expect(key).toBe('rev_A_ABC123');
+ });
+
+ it('gives the same waMessageId in different sessions DISTINCT keys', () => {
+ const a = generateIdempotencyKey('message.ack', { id: 'X', ack: 2, sessionId: 'A' });
+ const b = generateIdempotencyKey('message.ack', { id: 'X', ack: 2, sessionId: 'B' });
+ expect(a).not.toBe(b);
});
it('should generate key for session.status', () => {
diff --git a/src/modules/webhook/utils/idempotency.util.ts b/src/modules/webhook/utils/idempotency.util.ts
index 8df9b36fd..aa370b870 100644
--- a/src/modules/webhook/utils/idempotency.util.ts
+++ b/src/modules/webhook/utils/idempotency.util.ts
@@ -35,17 +35,19 @@ export function generateIdempotencyKey(event: string, data: Record<string, unkno
// Dispatched payload is an IncomingMessage, which carries `id`; fall back to a legacy `messageId`.
// Resolve the value before toStr() — toStr() returns a truthy 'unknown' fallback, so chaining with
// `||` would short-circuit before reaching the second field.
- return `msg_${toStr(data.id ?? data.messageId)}`;
+ // Scope by sessionId: waMessageIds are unique per account, not globally, so two
+ // sessions could otherwise collide on the same key and wrongly dedupe each other's events.
+ return `msg_${toStr(data.sessionId)}_${toStr(data.id ?? data.messageId)}`;
case 'message.ack':
// Message ID + ack status together are unique
- return `ack_${toStr(data.id ?? data.messageId)}_${toStr(data.ack, '0')}`;
+ return `ack_${toStr(data.sessionId)}_${toStr(data.id ?? data.messageId)}_${toStr(data.ack, '0')}`;
case 'message.failed':
- return `failed_${toStr(data.id ?? data.messageId)}_${toStr(data.ack, '0')}`;
+ return `failed_${toStr(data.sessionId)}_${toStr(data.id ?? data.messageId)}_${toStr(data.ack, '0')}`;
case 'message.revoked':
- return `rev_${toStr(data.id ?? data.messageId)}`;
+ return `rev_${toStr(data.sessionId)}_${toStr(data.id ?? data.messageId)}`;
case 'session.status':
// Session + status combo (same status emitted once per transition)
diff --git a/src/modules/webhook/webhook.controller.spec.ts b/src/modules/webhook/webhook.controller.spec.ts
new file mode 100644
index 000000000..6e70c957a
--- /dev/null
+++ b/src/modules/webhook/webhook.controller.spec.ts
@@ -0,0 +1,141 @@
+import { Test, TestingModule } from '@nestjs/testing';
+import { Reflector } from '@nestjs/core';
+import { WebhookController } from './webhook.controller';
+import { WebhooksListController } from './webhooks-list.controller';
+import { WebhookService } from './webhook.service';
+import { Webhook } from './entities/webhook.entity';
+import { Session } from '../session/entities/session.entity';
+import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';
+import { ApiKeyRole } from '../auth/entities/api-key.entity';
+
+/**
+ * Regression locks for the secret/headers leak and read authorization.
+ * e2e coverage is deferred (the e2e harness is currently broken),
+ * so these controller-level unit tests are the regression gate.
+ */
+
+function createSecretWebhook(overrides: Partial<Webhook> = {}): Webhook {
+ return {
+ id: 'wh-uuid-1',
+ sessionId: 'sess-1',
+ url: 'https://example.com/webhook',
+ events: ['message.received'],
+ secret: 's3cr3t-hmac-key',
+ headers: { Authorization: 'Bearer receiver-token' },
+ active: true,
+ retryCount: 3,
+ lastTriggeredAt: null,
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),
+ session: undefined as unknown as Session,
+ ...overrides,
+ };
+}
+
+describe('Webhook controllers (secret leak + read authz)', () => {
+ let controller: WebhookController;
+ let listController: WebhooksListController;
+ let reflector: Reflector;
+ let service: jest.Mocked<Partial<WebhookService>>;
+
+ beforeEach(async () => {
+ service = {
+ create: jest.fn(),
+ findBySession: jest.fn(),
+ findOne: jest.fn(),
+ findAll: jest.fn(),
+ update: jest.fn(),
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ controllers: [WebhookController, WebhooksListController],
+ providers: [{ provide: WebhookService, useValue: service }],
+ }).compile();
+
+ controller = module.get<WebhookController>(WebhookController);
+ listController = module.get<WebhooksListController>(WebhooksListController);
+ reflector = new Reflector();
+ });
+
+ // ── secret/headers must never appear in any response body ──────
+
+ it('findOne does not return secret or headers, but keeps safe fields', async () => {
+ (service.findOne as jest.Mock).mockResolvedValue(createSecretWebhook());
+
+ const result = await controller.findOne('wh-uuid-1');
+
+ expect(result).not.toHaveProperty('secret');
+ expect(result).not.toHaveProperty('headers');
+ expect(JSON.stringify(result)).not.toContain('s3cr3t');
+ expect(result.id).toBe('wh-uuid-1');
+ expect(result.url).toBe('https://example.com/webhook');
+ expect(result.events).toEqual(['message.received']);
+ expect(result.active).toBe(true);
+ });
+
+ it('findBySession strips secret/headers from every item', async () => {
+ (service.findBySession as jest.Mock).mockResolvedValue([
+ createSecretWebhook(),
+ createSecretWebhook({ id: 'wh-2' }),
+ ]);
+
+ const result = await controller.findBySession('sess-1');
+
+ expect(result).toHaveLength(2);
+ for (const w of result) {
+ expect(w).not.toHaveProperty('secret');
+ expect(w).not.toHaveProperty('headers');
+ }
+ expect(JSON.stringify(result)).not.toContain('s3cr3t');
+ });
+
+ it('cross-session findAll strips secret/headers', async () => {
+ (service.findAll as jest.Mock).mockResolvedValue([createSecretWebhook()]);
+
+ const result = await listController.findAll();
+
+ expect(result[0]).not.toHaveProperty('secret');
+ expect(result[0]).not.toHaveProperty('headers');
+ expect(JSON.stringify(result)).not.toContain('Bearer receiver-token');
+ });
+
+ it('create response echoes no secret/headers', async () => {
+ (service.create as jest.Mock).mockResolvedValue(createSecretWebhook());
+
+ const result = await controller.create('sess-1', { url: 'https://example.com/webhook', secret: 's3cr3t-hmac-key' });
+
+ expect(result).not.toHaveProperty('secret');
+ expect(result).not.toHaveProperty('headers');
+ expect(result.id).toBe('wh-uuid-1');
+ });
+
+ it('update response returns no secret/headers', async () => {
+ (service.update as jest.Mock).mockResolvedValue(createSecretWebhook({ url: 'https://new.example.com/hook' }));
+
+ const result = await controller.update('wh-uuid-1', { url: 'https://new.example.com/hook' });
+
+ expect(result).not.toHaveProperty('secret');
+ expect(result).not.toHaveProperty('headers');
+ expect(result.url).toBe('https://new.example.com/hook');
+ });
+
+ // ── read routes require OPERATOR+ (VIEWER → 403 via guard) ─────
+
+ it('findBySession requires OPERATOR role', () => {
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- reading route metadata, not invoking
+ const role = reflector.get<ApiKeyRole>(REQUIRED_ROLE_KEY, controller.findBySession);
+ expect(role).toBe(ApiKeyRole.OPERATOR);
+ });
+
+ it('findOne requires OPERATOR role', () => {
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- reading route metadata, not invoking
+ const role = reflector.get<ApiKeyRole>(REQUIRED_ROLE_KEY, controller.findOne);
+ expect(role).toBe(ApiKeyRole.OPERATOR);
+ });
+
+ it('cross-session findAll requires OPERATOR role', () => {
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- reading route metadata, not invoking
+ const role = reflector.get<ApiKeyRole>(REQUIRED_ROLE_KEY, listController.findAll);
+ expect(role).toBe(ApiKeyRole.OPERATOR);
+ });
+});
diff --git a/src/modules/webhook/webhook.controller.ts b/src/modules/webhook/webhook.controller.ts
index 471d5db0e..e4b240e57 100644
--- a/src/modules/webhook/webhook.controller.ts
+++ b/src/modules/webhook/webhook.controller.ts
@@ -2,7 +2,6 @@ import { Controller, Get, Post, Put, Delete, Param, Body, HttpCode, HttpStatus }
import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';
import { WebhookService } from './webhook.service';
import { CreateWebhookDto, UpdateWebhookDto, WebhookResponseDto } from './dto';
-import { Webhook } from './entities/webhook.entity';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
@@ -20,11 +19,12 @@ export class WebhookController {
description: 'Webhook created',
type: WebhookResponseDto,
})
- async create(@Param('sessionId') sessionId: string, @Body() dto: CreateWebhookDto): Promise<Webhook> {
- return this.webhookService.create(sessionId, dto);
+ async create(@Param('sessionId') sessionId: string, @Body() dto: CreateWebhookDto): Promise<WebhookResponseDto> {
+ return WebhookResponseDto.fromEntity(await this.webhookService.create(sessionId, dto));
}
@Get()
+ @RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'List all webhooks for a session' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiResponse({
@@ -32,11 +32,12 @@ export class WebhookController {
description: 'List of webhooks',
type: [WebhookResponseDto],
})
- async findBySession(@Param('sessionId') sessionId: string): Promise<Webhook[]> {
- return this.webhookService.findBySession(sessionId);
+ async findBySession(@Param('sessionId') sessionId: string): Promise<WebhookResponseDto[]> {
+ return WebhookResponseDto.fromEntities(await this.webhookService.findBySession(sessionId));
}
@Get(':id')
+ @RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Get a webhook by ID' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiParam({ name: 'id', description: 'Webhook ID' })
@@ -46,8 +47,8 @@ export class WebhookController {
type: WebhookResponseDto,
})
@ApiResponse({ status: 404, description: 'Webhook not found' })
- async findOne(@Param('id') id: string): Promise<Webhook> {
- return this.webhookService.findOne(id);
+ async findOne(@Param('id') id: string): Promise<WebhookResponseDto> {
+ return WebhookResponseDto.fromEntity(await this.webhookService.findOne(id));
}
@Put(':id')
@@ -61,8 +62,8 @@ export class WebhookController {
type: WebhookResponseDto,
})
@ApiResponse({ status: 404, description: 'Webhook not found' })
- async update(@Param('id') id: string, @Body() dto: UpdateWebhookDto): Promise<Webhook> {
- return this.webhookService.update(id, dto);
+ async update(@Param('id') id: string, @Body() dto: UpdateWebhookDto): Promise<WebhookResponseDto> {
+ return WebhookResponseDto.fromEntity(await this.webhookService.update(id, dto));
}
@Post(':id/test')
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index 1cf8292af..8a73b7105 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -1,8 +1,14 @@
+// SSRF protection is now ON by default; resolve any host to a public IP so existing
+// dispatch/create tests stay offline. Literal-IP tests (8.8.8.8 / 127.0.0.1) bypass lookup.
+jest.mock('dns/promises', () => ({
+ lookup: jest.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),
+}));
+
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { getQueueToken } from '@nestjs/bullmq';
import { Repository } from 'typeorm';
-import { NotFoundException } from '@nestjs/common';
+import { NotFoundException, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as crypto from 'crypto';
import { WebhookService, WebhookPayload } from './webhook.service';
@@ -121,6 +127,37 @@ describe('WebhookService', () => {
}),
);
});
+
+ // ── validate URL at registration, default-on ──────────
+
+ it('rejects an internal webhook URL at registration with 400 (protection on by default)', async () => {
+ const origProtect = process.env.WEBHOOK_SSRF_PROTECT;
+ delete process.env.WEBHOOK_SSRF_PROTECT; // default → on
+ try {
+ await expect(service.create('sess-1', { url: 'http://127.0.0.1/hook' })).rejects.toBeInstanceOf(
+ BadRequestException,
+ );
+ expect(repository.create).not.toHaveBeenCalled();
+ } finally {
+ if (origProtect === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;
+ else process.env.WEBHOOK_SSRF_PROTECT = origProtect;
+ }
+ });
+
+ it('accepts an internal webhook URL when protection is explicitly disabled', async () => {
+ const origProtect = process.env.WEBHOOK_SSRF_PROTECT;
+ process.env.WEBHOOK_SSRF_PROTECT = 'false';
+ try {
+ const webhook = createMockWebhook({ url: 'http://127.0.0.1/hook' });
+ (repository.create as jest.Mock).mockReturnValue(webhook);
+ (repository.save as jest.Mock).mockResolvedValue(webhook);
+
+ await expect(service.create('sess-1', { url: 'http://127.0.0.1/hook' })).resolves.toBeDefined();
+ } finally {
+ if (origProtect === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;
+ else process.env.WEBHOOK_SSRF_PROTECT = origProtect;
+ }
+ });
});
// ── findBySession / findAll / findOne ──────────────────────────────
@@ -285,6 +322,99 @@ describe('WebhookService', () => {
});
});
+ // ── custom-header sanitization ───────────────────────────────
+
+ describe('custom header merge', () => {
+ it('drops reserved custom headers so the system headers always win', async () => {
+ const webhook = createMockWebhook({
+ events: ['message.received'],
+ headers: { 'X-OpenWA-Event': 'forged', 'Content-Type': 'text/plain', 'X-Custom': 'ok' },
+ });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ const captured: Record<string, string> = {};
+ const mockFetch = jest.fn().mockImplementation((_url: string, opts: RequestInit) => {
+ Object.assign(captured, opts.headers as Record<string, string>);
+ return Promise.resolve({ ok: true, status: 200 });
+ });
+ global.fetch = mockFetch as typeof global.fetch;
+
+ const payload: WebhookPayload = {
+ event: 'message.received',
+ data: {},
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', event: 'message.received', payload },
+ });
+
+ await service.dispatch('sess-1', 'message.received', {});
+
+ expect(captured['X-OpenWA-Event']).toBe('message.received'); // system value, not 'forged'
+ expect(captured['Content-Type']).toBe('application/json');
+ expect(captured['X-Custom']).toBe('ok'); // legitimate custom header preserved
+ mockFetch.mockReset();
+ });
+ });
+
+ // ── redirect refusal ─────────────────────────────────────────
+
+ describe('dispatch — redirect refusal', () => {
+ const mockFetch = jest.fn();
+ const origProtect = process.env.WEBHOOK_SSRF_PROTECT;
+
+ beforeEach(() => {
+ global.fetch = mockFetch as typeof global.fetch;
+ process.env.WEBHOOK_SSRF_PROTECT = 'true';
+ });
+
+ afterEach(() => {
+ mockFetch.mockReset();
+ if (origProtect === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;
+ else process.env.WEBHOOK_SSRF_PROTECT = origProtect;
+ });
+
+ it('does NOT follow a redirect and treats it as a delivery failure when protection is on', async () => {
+ // Public literal IP → assertSafeFetchUrl passes with no DNS lookup; retryCount:1 → no retry loop.
+ const webhook = createMockWebhook({
+ url: 'https://8.8.8.8/webhook',
+ events: ['message.received'],
+ retryCount: 1,
+ });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ // Simulate undici's redirect:'manual' result — an opaque redirect, never followed.
+ mockFetch.mockResolvedValue({ ok: false, status: 0, type: 'opaqueredirect' });
+
+ const payload: WebhookPayload = {
+ event: 'message.received',
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ data: {},
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', event: 'message.received', payload },
+ });
+
+ await service.dispatch('sess-1', 'message.received', {});
+
+ // fetch was issued with redirect:'manual' and the redirect was NOT followed (no success path)
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://8.8.8.8/webhook',
+ expect.objectContaining({ redirect: 'manual' }),
+ );
+ expect(repository.update).not.toHaveBeenCalled(); // lastTriggeredAt never set → delivery failed
+ expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());
+ });
+ });
+
// ── generateSignature (via dispatch) ──────────────────────────────
describe('generateSignature', () => {
diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.ts
index 34d5c4a6e..0ff33b14f 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, NotFoundException, Optional } from '@nestjs/common';
+import { Injectable, NotFoundException, Optional, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
@@ -10,7 +10,12 @@ import { CreateWebhookDto, UpdateWebhookDto } from './dto';
import { createLogger } from '../../common/services/logger.service';
import { QUEUE_NAMES } from '../queue/queue-names';
import { generateIdempotencyKey, generateDeliveryId } from './utils/idempotency.util';
-import { assertSafeWebhookUrl, isSsrfProtectionEnabled } from '../../common/security/ssrf-guard';
+import {
+ assertSafeFetchUrl,
+ assertNoRedirect,
+ isSsrfProtectionEnabled,
+ SsrfBlockedError,
+} from '../../common/security/ssrf-guard';
import { HookManager } from '../../core/hooks';
export interface WebhookPayload {
@@ -50,7 +55,25 @@ export class WebhookService {
this.queueEnabled = configService.get<boolean>('queue.enabled', false);
}
+ /**
+ * Reject an internal/unsafe webhook URL at registration, so a bad URL fails
+ * synchronously with a 400 instead of silently failing at delivery time. Honors the same
+ * SSRF flag + SSRF_ALLOWED_HOSTS escape-hatch as delivery. Maps the guard error to 400.
+ */
+ private async validateWebhookUrl(url: string): Promise<void> {
+ if (!isSsrfProtectionEnabled()) return;
+ try {
+ await assertSafeFetchUrl(url);
+ } catch (error) {
+ if (error instanceof SsrfBlockedError) {
+ throw new BadRequestException(error.message);
+ }
+ throw error;
+ }
+ }
+
async create(sessionId: string, dto: CreateWebhookDto): Promise<Webhook> {
+ await this.validateWebhookUrl(dto.url);
const webhook = this.webhookRepository.create({
sessionId,
url: dto.url,
@@ -87,9 +110,14 @@ export class WebhookService {
async update(id: string, dto: UpdateWebhookDto): Promise<Webhook> {
const webhook = await this.findOne(id);
- if (dto.url !== undefined) webhook.url = dto.url;
+ if (dto.url !== undefined) {
+ await this.validateWebhookUrl(dto.url);
+ webhook.url = dto.url;
+ }
if (dto.events !== undefined) webhook.events = dto.events;
- if (dto.secret !== undefined) webhook.secret = dto.secret;
+ // Normalize empty string to null (parity with create) — an empty secret means "no HMAC",
+ // not a stored blank that silently disables signing while looking configured.
+ if (dto.secret !== undefined) webhook.secret = dto.secret || null;
if (dto.headers !== undefined) webhook.headers = dto.headers;
if (dto.active !== undefined) webhook.active = dto.active;
if (dto.retryCount !== undefined) webhook.retryCount = dto.retryCount;
@@ -120,29 +148,35 @@ export class WebhookService {
const body = JSON.stringify(testPayload);
const headers: Record<string, string> = {
+ // Custom headers FIRST so the system headers below always win.
+ ...this.sanitizeCustomHeaders(webhook.headers),
'Content-Type': 'application/json',
'User-Agent': 'OpenWA-Webhook/1.0.0',
'X-OpenWA-Event': 'test',
'X-OpenWA-Idempotency-Key': testPayload.idempotencyKey,
'X-OpenWA-Delivery-Id': testPayload.deliveryId,
'X-OpenWA-Retry-Count': '0',
- ...webhook.headers,
};
if (webhook.secret) {
headers['X-OpenWA-Signature'] = this.generateSignature(body, webhook.secret);
}
+ const ssrfProtected = isSsrfProtectionEnabled();
try {
- if (isSsrfProtectionEnabled()) {
- await assertSafeWebhookUrl(webhook.url);
+ if (ssrfProtected) {
+ await assertSafeFetchUrl(webhook.url);
}
const response = await fetch(webhook.url, {
method: 'POST',
headers,
body,
signal: AbortSignal.timeout(10000),
+ redirect: ssrfProtected ? 'manual' : 'follow',
});
+ if (ssrfProtected) {
+ assertNoRedirect(response, webhook.url);
+ }
return {
success: response.ok,
@@ -198,15 +232,15 @@ export class WebhookService {
// Use potentially modified payload
const finalPayload = (hookResult as { payload: WebhookPayload }).payload;
- // Build headers
+ // Build headers — custom headers FIRST so the system headers below always win.
const headers: Record<string, string> = {
+ ...this.sanitizeCustomHeaders(webhook.headers),
'Content-Type': 'application/json',
'User-Agent': 'OpenWA-Webhook/1.0.0',
'X-OpenWA-Event': event,
'X-OpenWA-Idempotency-Key': idempotencyKey,
'X-OpenWA-Delivery-Id': deliveryId,
'X-OpenWA-Retry-Count': '0',
- ...webhook.headers,
};
// Use queue if available, otherwise fallback to direct delivery
@@ -318,16 +352,21 @@ export class WebhookService {
headers['X-OpenWA-Signature'] = this.generateSignature(body, webhook.secret);
}
+ const ssrfProtected = isSsrfProtectionEnabled();
try {
- if (isSsrfProtectionEnabled()) {
- await assertSafeWebhookUrl(webhook.url);
+ if (ssrfProtected) {
+ await assertSafeFetchUrl(webhook.url);
}
const response = await fetch(webhook.url, {
method: 'POST',
headers,
body,
signal: AbortSignal.timeout(this.configService.get<number>('webhook.timeout', 10000)),
+ redirect: ssrfProtected ? 'manual' : 'follow',
});
+ if (ssrfProtected) {
+ assertNoRedirect(response, webhook.url);
+ }
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
@@ -360,6 +399,21 @@ export class WebhookService {
}
}
+ /**
+ * Drop operator-supplied custom headers that target reserved names (Content-Type or any
+ * X-OpenWA-* header) so a webhook config cannot forge the signature/event/idempotency
+ * headers. Spread the result BEFORE the system headers so system always wins.
+ */
+ private sanitizeCustomHeaders(custom: Record<string, string> | null | undefined): Record<string, string> {
+ const safe: Record<string, string> = {};
+ for (const [key, value] of Object.entries(custom ?? {})) {
+ if (!/^(content-type|x-openwa-)/i.test(key)) {
+ safe[key] = value;
+ }
+ }
+ return safe;
+ }
+
private generateSignature(payload: string, secret: string): string {
const hmac = crypto.createHmac('sha256', secret);
hmac.update(payload);
diff --git a/src/modules/webhook/webhooks-list.controller.ts b/src/modules/webhook/webhooks-list.controller.ts
index a7252ad02..e86055b14 100644
--- a/src/modules/webhook/webhooks-list.controller.ts
+++ b/src/modules/webhook/webhooks-list.controller.ts
@@ -1,7 +1,9 @@
import { Controller, Get } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { WebhookService } from './webhook.service';
-import { Webhook } from './entities/webhook.entity';
+import { WebhookResponseDto } from './dto';
+import { RequireRole } from '../auth/decorators/auth.decorators';
+import { ApiKeyRole } from '../auth/entities/api-key.entity';
@ApiTags('webhooks')
@Controller('webhooks')
@@ -9,12 +11,14 @@ export class WebhooksListController {
constructor(private readonly webhookService: WebhookService) {}
@Get()
+ @RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'List all webhooks across all sessions' })
@ApiResponse({
status: 200,
description: 'List of all webhooks',
+ type: [WebhookResponseDto],
})
- async findAll(): Promise<Webhook[]> {
- return this.webhookService.findAll();
+ async findAll(): Promise<WebhookResponseDto[]> {
+ return WebhookResponseDto.fromEntities(await this.webhookService.findAll());
}
}
diff --git a/test/app.e2e-spec.ts b/test/app.e2e-spec.ts
index 5c64fac01..53e2d9520 100644
--- a/test/app.e2e-spec.ts
+++ b/test/app.e2e-spec.ts
@@ -1,22 +1,64 @@
+// archiver v8 is ESM-only and is pulled in transitively via the @Global StorageModule when
+// AppModule boots; stub it so ts-jest (CommonJS) can load the module graph.
+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));
+
import { Test, TestingModule } from '@nestjs/testing';
-import { INestApplication } from '@nestjs/common';
+import { INestApplication, ValidationPipe } from '@nestjs/common';
import request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
-describe('AppController (e2e)', () => {
+/**
+ * Smoke e2e: the previous test asserted a non-existent Hello-World route and failed to
+ * even compile (ESM archiver). This boots the real app (SQLite, no queue) and checks the
+ * public health route, the auth boundary, and unknown-route handling.
+ */
+describe('App smoke (e2e)', () => {
let app: INestApplication<App>;
- beforeEach(async () => {
+ beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
+ // Mirror the bits of main.ts that affect routing/validation.
+ app.setGlobalPrefix('api');
+ app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
await app.init();
});
- it('/ (GET)', () => {
- return request(app.getHttpServer()).get('/').expect(200).expect('Hello World!');
+ afterAll(async () => {
+ // app.close() can throw a "could not find DataSource" during TypeORM's shutdown hook because
+ // both connections are NAMED ('main'/'data') with no default DataSource — a teardown-only
+ // artifact, not an app bug (the smoke assertions above already validated a healthy boot).
+ try {
+ await app?.close();
+ } catch {
+ /* ignore teardown-only multi-datasource quirk */
+ }
+ });
+
+ it('GET /api/health is public and returns ok', () => {
+ return request(app.getHttpServer())
+ .get('/api/health')
+ .expect(200)
+ .expect(res => {
+ const body = res.body as { status?: string };
+ if (body.status !== 'ok') throw new Error(`unexpected health body: ${JSON.stringify(res.body)}`);
+ });
+ });
+
+ it('GET /api/sessions without an API key is rejected (401)', () => {
+ return request(app.getHttpServer()).get('/api/sessions').expect(401);
+ });
+
+ it('GET an unknown route returns 404', () => {
+ return request(app.getHttpServer()).get('/api/this-route-does-not-exist').expect(404);
+ });
+
+ it('GET /api/metrics is disabled (404) when METRICS_TOKEN is unset', () => {
+ // Secure default: no scrape token configured → the endpoint must not exist.
+ return request(app.getHttpServer()).get('/api/metrics').expect(404);
});
});
diff --git a/test/jest-e2e.json b/test/jest-e2e.json
index e9d912f3e..233bd6111 100644
--- a/test/jest-e2e.json
+++ b/test/jest-e2e.json
@@ -3,7 +3,9 @@
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
+ "setupFiles": ["<rootDir>/setup-e2e.ts"],
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
- }
+ },
+ "transformIgnorePatterns": ["node_modules/(?!(archiver|compress-commons|crc32-stream|zip-stream|archiver-utils)/)"]
}
diff --git a/test/setup-e2e.ts b/test/setup-e2e.ts
new file mode 100644
index 000000000..cfaec0fa2
--- /dev/null
+++ b/test/setup-e2e.ts
@@ -0,0 +1,9 @@
+// e2e boot environment. Set BEFORE AppModule is imported (setupFiles phase) so the
+// app boots against local SQLite with no Redis/queue and no production boot guard.
+process.env.NODE_ENV = 'test';
+process.env.DATABASE_TYPE = 'sqlite';
+process.env.QUEUE_ENABLED = 'false';
+process.env.AUTO_START_SESSIONS = 'false';
+// Keep the auth/audit + data schema zero-config for the test boot.
+process.env.MAIN_DATABASE_SYNCHRONIZE = 'true';
+process.env.DATABASE_SYNCHRONIZE = 'true';
diff --git a/traefik/traefik.yml b/traefik/traefik.yml
index 9ad1d71dc..43c837d36 100644
--- a/traefik/traefik.yml
+++ b/traefik/traefik.yml
@@ -1,11 +1,25 @@
# Traefik Static Configuration
api:
dashboard: true
- insecure: true
+ # M8: the dashboard is NOT served unauthenticated on :8080. Expose it, if needed, via a
+ # secured router (api@internal) behind auth + TLS — never with insecure mode in production.
+ insecure: false
entryPoints:
web:
address: ':80'
+ # In production, redirect plain HTTP to HTTPS (enable once TLS is configured below):
+ # http:
+ # redirections:
+ # entryPoint:
+ # to: websecure
+ # scheme: https
+ websecure:
+ address: ':443'
+
+# TLS is deployment-specific (M8): configure a certificatesResolver (e.g. Let's Encrypt) or
+# mount certificates via the file provider, OR terminate TLS at an external reverse proxy and
+# keep Traefik on an internal network. Do not expose the API over plain :80 in production.
providers:
file: