Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): harden logout teardown tracking and guarded downloads (#1007)

Yudhi Armyndharisd771251e128e
diff --git a/.env.example b/.env.example
index 5a1bd52f0..5d0e00af9 100644
--- a/.env.example
+++ b/.env.example
@@ -457,6 +457,12 @@ PLUGINS_DIR=./data/plugins # Plugin directory
# Per-plugin bound on ctx.storage writes; writes beyond it are rejected. A non-positive or non-numeric
# value falls back to the default.
# PLUGIN_STORAGE_MAX_BYTES=52428800 # default 50 MiB
+# Allow an https plugin-download URL to redirect to a plain-http hop (default: refused — the package
+# is executable code and an http hop exposes it to on-path substitution). Enable only if your vendor
+# or release host genuinely downgrades (e.g. behind TLS-terminating infrastructure). Only a hop that
+# downgrades AFTER an https hop is refused; a chain that starts on plain http is not itself a
+# downgrade (though an http→https→http chain is still refused).
+# PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS=false
# =============================================================================
# SECURITY
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 241ea3dda..5699426c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -84,7 +84,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
-- **`send-document` really sends a document on the whatsapp-web.js engine** (#989, #1003). Without an
+- **`send-document` really sends a document on the whatsapp-web.js engine** (#989, #996, #1000, #1003). Without an
explicit document flag, WhatsApp Web classifies an attachment from its declared mimetype, so an
`image/*`, `video/*` or `audio/*` payload posted to the document endpoint arrived as a photo, video
or audio bubble — re-encoded, and with its filename dropped. Baileys has always forced the document
@@ -202,7 +202,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
per-session config (`PUT /api/plugins/:id/config/:sessionId`) continue to accept restricted keys
and remain scoped to the sessions the key allows.
-- The queue dashboard (`/admin/queues`, available when `QUEUE_ENABLED=true`) now refuses API keys
+- The queue dashboard (`/api/admin/queues`, available when `QUEUE_ENABLED=true`) now refuses API keys
restricted to specific sessions. The dashboard exposes and mutates every queue in the deployment
and has no session dimension to scope against.
@@ -214,6 +214,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Redriving a dead-lettered integration delivery now fails closed for session-restricted keys when
the integration instance no longer exists. Previously the scope check was skipped for a missing
instance, so retained dead-letter rows could be re-dispatched for sessions outside the key's scope.
+ **Breaking (behavior):** the session-restricted-key denials in this section change behavior for
+ existing API consumers — a key carrying an `allowedSessions` list that previously reached these
+ deployment-global routes is now refused. Unrestricted keys are unaffected.
- Outbound downloads that follow redirects (plugin packages and the plugin catalog) now validate
every redirect hop before connecting. Previously a redirect whose target was a bare IP address
diff --git a/SECURITY.md b/SECURITY.md
index b88b884fc..1abbb49d2 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -78,3 +78,25 @@ use the built-in datastore orchestration (Dashboard → Infrastructure built-in
toggles), disable the proxy entirely — see the `docker-proxy` comments in
`docker-compose.yml`; `DockerService` then reports Docker unavailable and
orchestration degrades gracefully.
+
+### Session-restricted API keys
+
+An API key can be restricted to a subset of sessions (`allowedSessions`). A key
+with a non-empty restriction is denied on every route that acts on the whole
+deployment rather than on a single session:
+
+- Infrastructure routes (`/api/infra/*`)
+- API-key lifecycle routes (`/api/auth/api-keys/*`)
+- Plugin installation and lifecycle (`/api/plugins/*` — per-session activation
+ and per-session config remain available, scoped to the sessions the key
+ allows)
+- Cross-session statistics (`GET /api/stats/overview`, `GET /api/stats/messages`)
+- Application settings (`GET` / `PUT /api/settings`)
+- Session creation (`POST /api/sessions`)
+- The queue dashboard (`/api/admin/queues`)
+
+Redriving a dead-lettered integration delivery also fails closed (`404`) when
+the instance sits outside the key's scope, so retained dead-letter rows cannot
+be re-dispatched across the boundary. Per-session routes for the sessions the
+key allows remain available, and keys without an `allowedSessions` restriction
+are unaffected.
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsx
index 23360cd50..b48c80ad9 100644
--- a/dashboard/src/pages/Sessions.tsx
+++ b/dashboard/src/pages/Sessions.tsx
@@ -56,6 +56,7 @@ export function Sessions() {
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
const [killConfirmId, setKillConfirmId] = useState<string | null>(null);
const [unlinkConfirmId, setUnlinkConfirmId] = useState<string | null>(null);
+ const [unlinkingId, setUnlinkingId] = useState<string | null>(null);
const fetchSessions = useCallback(async (): Promise<Session[]> => {
try {
@@ -365,6 +366,10 @@ export function Sessions() {
};
const handleUnlink = async (id: string) => {
+ // Guard against a second concurrent request: the button is disabled while in flight, but a
+ // rapid double-click would otherwise fire overlapping logouts and race the teardown tracking.
+ if (unlinkingId) return;
+ setUnlinkingId(id);
try {
await sessionApi.logout(id);
setSessions(sessions.map(s => (s.id === id ? { ...s, status: 'disconnected' } : s)));
@@ -382,6 +387,7 @@ export function Sessions() {
fetchSessions();
} finally {
setUnlinkConfirmId(null);
+ setUnlinkingId(null);
}
};
@@ -800,7 +806,11 @@ export function Sessions() {
<button className="btn-secondary" onClick={() => setUnlinkConfirmId(null)}>
{t('common.cancel')}
</button>
- <button className="btn-danger" onClick={() => handleUnlink(unlinkConfirmId)}>
+ <button
+ className="btn-danger"
+ onClick={() => handleUnlink(unlinkConfirmId)}
+ disabled={unlinkingId !== null}
+ >
{t('sessions.unlink.confirm')}
</button>
</>
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index e5a91b393..044c9d895 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -129,6 +129,8 @@ All media send routes (`send-image`, `send-video`, `send-audio`, `send-document`
Provide **exactly one** of `url` or `base64`. Omitting both, or supplying `base64` without `mimetype`, returns `400`.
+A document sent without a `filename` is delivered under the default name `file` — on the whatsapp-web.js engine, a URL-based send first derives the URL basename before that fallback applies.
+
```json
{
"chatId": "[email protected]",
@@ -1137,6 +1139,8 @@ Send a document/file (by URL or base64). Uses `SendMediaMessageDto`; `filename`
{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
```
+**Engine differences:** Baileys always sends a document as a document, while whatsapp-web.js deliberately keeps normal mimetype classification for `status@broadcast` and broadcast lists — the library returns `null` for document-mode sends to those recipients, so forcing the flag there would turn a working send into a failure. For URL-based sends without an explicit `filename`, whatsapp-web.js derives the URL basename; Baileys falls back to the literal `file`.
+
**Errors:** `400` media validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
#### POST /api/sessions/:sessionId/messages/send-location
@@ -4567,7 +4571,7 @@ Install a plugin from an uploaded `.zip` package.
#### POST /api/plugins/install-url
-Install a plugin by downloading its `.zip` from an HTTPS URL (SSRF-guarded fetch: host validated, redirects refused, size-capped at `plugins.downloadMaxBytes`, default 5 MB). Plain `http://` is rejected — the package is executable code and must be integrity-protected in transit; private-network targets remain subject to the SSRF guard.
+Install a plugin by downloading its `.zip` from an HTTPS URL (SSRF-guarded fetch: host validated, redirects followed with every hop re-validated through the guard and the chain capped at 5 hops, size-capped at `plugins.downloadMaxBytes`, default 5 MB). Plain `http://` is rejected — the package is executable code and must be integrity-protected in transit; private-network targets remain subject to the SSRF guard. A redirect hop that downgrades back to plain `http://` mid-chain is likewise refused (set `PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS=true` only if your vendor genuinely redirects that way); a chain over the cap fails with an explicit "too many redirects" error.
Optional content pinning: append `#sha256=<64 hex>` (URL fragment — never sent to the server) to require the downloaded bytes to match that digest; the fragment is the only honored marker — query params are deliberately ignored. A mismatch or a malformed marker fails the install closed; no marker means no verification (HTTPS + the SSRF guard are the baseline).
diff --git a/openapi.json b/openapi.json
index 9a4ad3810..ffb217cf7 100644
--- a/openapi.json
+++ b/openapi.json
@@ -6790,7 +6790,7 @@
},
"filename": {
"type": "string",
- "description": "Filename for the media",
+ "description": "Filename for the media. Only rendered on document sends — defaults to 'file' when omitted (a URL-based document send on whatsapp-web.js first derives the URL basename)",
"example": "image.jpg"
},
"caption": {
@@ -6838,7 +6838,7 @@
},
"filename": {
"type": "string",
- "description": "Filename for the media",
+ "description": "Filename for the media. Only rendered on document sends — defaults to 'file' when omitted (a URL-based document send on whatsapp-web.js first derives the URL basename)",
"example": "image.jpg"
},
"caption": {
diff --git a/scripts/patch-wwebjs-201832.js b/scripts/patch-wwebjs-201832.js
index 2f594b8ce..28d5eae80 100644
--- a/scripts/patch-wwebjs-201832.js
+++ b/scripts/patch-wwebjs-201832.js
@@ -201,6 +201,16 @@ function applyBackport(wwjsDir = DEFAULT_WWJS, patchFile = DEFAULT_PATCH) {
// as "already fixed" and ship it. Matched loosely (`Base._normalizeId(` OR an inline `$1` fallback)
// so a future upstream release that fixes this differently still stands the patcher down.
const msgJs = path.join(wwjsDir, 'src', 'structures', 'Message.js');
+ if (!fs.existsSync(msgJs)) {
+ // A dep tree with Base.js but no Message.js is version skew vs the backport base — say so,
+ // instead of dying on a raw ENOENT from the read below. A plain Error, NOT partialTree:
+ // nothing has been written yet, so `--best-effort` may still degrade on a pristine tree.
+ throw new Error(
+ `whatsapp-web.js at ${wwjsDir} has src/structures/Base.js but no src/structures/Message.js — ` +
+ 'version skew vs the backport base. Reinstall the dependency, or drop this backport if the ' +
+ 'installed version restructured these files.',
+ );
+ }
const msgSrc = fs.readFileSync(msgJs, 'utf8');
if (/_normalizeId\(|\.\$1/.test(msgSrc)) {
// Message.js normalizing is necessary but NOT sufficient to stand down. `patch` writes as it goes and
diff --git a/sdk/python/openwa/resources/sessions.py b/sdk/python/openwa/resources/sessions.py
index 09e7d61eb..ebcf64ebf 100644
--- a/sdk/python/openwa/resources/sessions.py
+++ b/sdk/python/openwa/resources/sessions.py
@@ -26,34 +26,53 @@ class SessionsResource:
self._http = http
def list(self) -> list[SessionResponse]:
+ """List sessions."""
return self._http.request("GET", "/api/sessions")
def get(self, session_id: str) -> SessionResponse:
+ """Return a single session."""
return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}")
def create(self, body: CreateSessionRequest) -> SessionResponse:
+ """Provision a new session."""
return self._http.request("POST", "/api/sessions", body=body)
def delete(self, session_id: str) -> None:
+ """Remove a session."""
self._http.request("DELETE", f"/api/sessions/{quote_segment(session_id)}")
def start(self, session_id: str) -> SessionResponse:
+ """Connect a session (triggers QR / pairing)."""
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/start")
def stop(self, session_id: str) -> SessionResponse:
+ """Disconnect a session gracefully."""
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/stop")
def logout(self, session_id: str) -> SessionResponse:
+ """Request WhatsApp to unlink this device, then tear the session down.
+
+ Unlike stop() and delete(), this asks WhatsApp to remove the device
+ from the account holder's Linked Devices list, so a later start()
+ requires a fresh QR scan or pairing code. Requires a running session.
+ Raises on HTTP 502 when the session was stopped locally but WhatsApp
+ did not confirm the unlink (the device may still be listed) — start
+ the session and retry to confirm.
+ """
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/logout")
def force_kill(self, session_id: str) -> SessionResponse:
+ """Terminate a stuck session immediately."""
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/force-kill")
def get_qr_code(self, session_id: str) -> QrCodeResponse:
+ """Return the current QR code for a session awaiting scan."""
return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/qr")
def request_pairing_code(self, session_id: str, body: RequestPairingCodeRequest) -> PairingCodeResponse:
+ """Request a phone-pairing code."""
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/pairing-code", body=body)
def stats(self) -> SessionStatsOverview:
+ """Return the aggregate session stats overview."""
return self._http.request("GET", "/api/sessions/stats/overview")
diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.ts
index 68ead6227..fb37c43c9 100644
--- a/src/common/security/ssrf-guard.spec.ts
+++ b/src/common/security/ssrf-guard.spec.ts
@@ -4,13 +4,13 @@ import {
assertNoRedirect,
SsrfBlockedError,
isSsrfProtectionEnabled,
+ redactSsrfError,
resolveSafeFetchTarget,
pinnedLookup,
- validatingLookup,
withSafeFetch,
} from './ssrf-guard';
import * as dnsPromises from 'dns/promises';
-import { fetch as undiciFetch, Agent } from 'undici';
+import { fetch as undiciFetch, Agent, Headers } from 'undici';
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
@@ -328,6 +328,159 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {
expect(use).not.toHaveBeenCalled();
});
+ it('refuses a redirect hop that downgrades from https to http', async () => {
+ // The payload on this path is executable code, so the caller forces https on the initial URL;
+ // a 302 to a plain-http hop would expose the bytes to on-path substitution. The refusal must
+ // happen BEFORE that hop's socket opens.
+ const savedHatch = process.env.PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS;
+ delete process.env.PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS; // pin the secure default
+ try {
+ (dnsPromises.lookup as jest.Mock)
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }])
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
+ (undiciFetch as jest.Mock).mockResolvedValueOnce({
+ status: 302,
+ type: 'basic',
+ headers: new Map([['location', 'http://cdn.example.com/p.zip']]),
+ });
+ const use = jest.fn();
+
+ await expect(
+ withSafeFetch('https://github.com/x/releases/p.zip', {}, use, { followRedirects: true }),
+ ).rejects.toThrow(/downgrades from https to http/);
+ expect(use).not.toHaveBeenCalled();
+ expect(undiciFetch as jest.Mock).toHaveBeenCalledTimes(1);
+ } finally {
+ if (savedHatch === undefined) delete process.env.PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS;
+ else process.env.PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS = savedHatch;
+ }
+ });
+
+ it('allows a chain that started on plain http (no downgrade — it never was secure)', async () => {
+ (dnsPromises.lookup as jest.Mock)
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }])
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
+ (undiciFetch as jest.Mock)
+ .mockResolvedValueOnce({
+ status: 302,
+ type: 'basic',
+ headers: new Map([['location', 'http://mirror.example.com/catalog.json']]),
+ })
+ .mockResolvedValueOnce({ status: 200, type: 'basic' });
+ const use = jest.fn(() => 'catalog');
+
+ const result = await withSafeFetch('http://plugins.internal.example/catalog.json', {}, use, {
+ followRedirects: true,
+ });
+
+ expect(result).toBe('catalog');
+ expect(undiciFetch as jest.Mock).toHaveBeenCalledTimes(2);
+ });
+
+ it('follows an https→http hop only when the insecure-redirect escape hatch is enabled', async () => {
+ const savedHatch = process.env.PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS;
+ process.env.PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS = 'true';
+ try {
+ (dnsPromises.lookup as jest.Mock)
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }])
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
+ (undiciFetch as jest.Mock)
+ .mockResolvedValueOnce({
+ status: 302,
+ type: 'basic',
+ headers: new Map([['location', 'http://cdn.example.com/p.zip']]),
+ })
+ .mockResolvedValueOnce({ status: 200, type: 'basic' });
+ const use = jest.fn(() => 'downloaded');
+
+ const result = await withSafeFetch('https://github.com/x/releases/p.zip', {}, use, {
+ followRedirects: true,
+ });
+
+ expect(result).toBe('downloaded');
+ expect(undiciFetch as jest.Mock).toHaveBeenCalledTimes(2);
+ } finally {
+ if (savedHatch === undefined) delete process.env.PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS;
+ else process.env.PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS = savedHatch;
+ }
+ });
+
+ it('strips credentials on a cross-origin hop and rewrites 303 to a bodiless GET', async () => {
+ (dnsPromises.lookup as jest.Mock)
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }])
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
+ (undiciFetch as jest.Mock)
+ .mockResolvedValueOnce({
+ status: 303,
+ type: 'basic',
+ headers: new Map([['location', 'https://cdn.example.com/p']]),
+ })
+ .mockResolvedValueOnce({ status: 200, type: 'basic' });
+ const use = jest.fn(() => 'ok');
+ const init = {
+ method: 'POST',
+ body: 'payload',
+ headers: { authorization: 'Bearer secret', 'x-custom': 'keep' },
+ };
+
+ await withSafeFetch('https://api.example.com/upload', init, use, { followRedirects: true });
+
+ const calls = (undiciFetch as jest.Mock).mock.calls as Array<
+ [string, { method?: string; body?: unknown; headers?: Headers }]
+ >;
+ const hop2 = calls[1][1];
+ expect(hop2.method).toBe('GET');
+ expect(hop2.body).toBeUndefined();
+ expect(hop2.headers?.get('authorization')).toBeNull();
+ expect(hop2.headers?.get('x-custom')).toBe('keep');
+ });
+
+ it('keeps credentials on a same-origin hop', async () => {
+ (dnsPromises.lookup as jest.Mock)
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }])
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
+ (undiciFetch as jest.Mock)
+ .mockResolvedValueOnce({
+ status: 302,
+ type: 'basic',
+ headers: new Map([['location', 'https://api.example.com/other']]),
+ })
+ .mockResolvedValueOnce({ status: 200, type: 'basic' });
+ const use = jest.fn(() => 'ok');
+ const init = { headers: { authorization: 'Bearer secret' } };
+
+ await withSafeFetch('https://api.example.com/first', init, use, { followRedirects: true });
+
+ const calls = (undiciFetch as jest.Mock).mock.calls as Array<
+ [string, { headers?: Headers | Record<string, string> }]
+ >;
+ const hop2Headers = calls[1][1].headers;
+ const auth = hop2Headers instanceof Headers ? hop2Headers.get('authorization') : hop2Headers?.authorization;
+ expect(auth).toBe('Bearer secret');
+ });
+
+ it('surfaces the hop-cap error verbatim (not redacted to the generic SSRF message)', async () => {
+ // A legit >5-hop chain must be distinguishable from an SSRF block: the operator needs the real
+ // cause, and the message carries only the caller-supplied URL — nothing internal to redact.
+ for (let i = 0; i < 6; i++) {
+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
+ }
+ (undiciFetch as jest.Mock).mockResolvedValue({
+ status: 302,
+ type: 'basic',
+ headers: new Map([['location', 'https://cdn.example.com/next']]),
+ });
+ const use = jest.fn(() => 'ok');
+
+ const error: unknown = await withSafeFetch('https://github.com/x/releases/p.zip', {}, use, {
+ followRedirects: true,
+ }).catch((err: unknown) => err);
+
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain('Too many redirects');
+ expect(redactSsrfError(error)).toContain('Too many redirects');
+ });
+
it('cancels an unread response body before tearing down the dispatcher (#887)', async () => {
// Status-only callers leave the body unread; if we destroy the Agent while the stream is still
// open, undici can emit TypeError: terminated / ECONNRESET as an uncaughtException. Cancelling
@@ -486,69 +639,6 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {
});
});
-describe('validatingLookup (standalone validating resolver)', () => {
- const run = (hostname: string): Promise<{ err: unknown; rest: unknown[] }> =>
- new Promise(resolve => {
- const lookup = validatingLookup() as unknown as (
- h: string,
- o: { all: boolean },
- cb: (err: unknown, ...rest: unknown[]) => void,
- ) => void;
- lookup(hostname, { all: true }, (err, ...rest) => resolve({ err, rest }));
- });
-
- it('passes a public IP literal through', async () => {
- const { err, rest } = await run('93.184.216.34');
- expect(err).toBeNull();
- expect(rest[0]).toEqual([{ address: '93.184.216.34', family: 4 }]);
- });
-
- it('refuses an internal IPv4 literal (a redirect target cannot be loopback/private)', async () => {
- expect((await run('127.0.0.1')).err).toBeInstanceOf(SsrfBlockedError);
- expect((await run('169.254.169.254')).err).toBeInstanceOf(SsrfBlockedError); // cloud metadata
- expect((await run('10.0.0.5')).err).toBeInstanceOf(SsrfBlockedError);
- });
-
- it('refuses an internal IPv6 literal', async () => {
- expect((await run('::1')).err).toBeInstanceOf(SsrfBlockedError);
- });
-
- it('refuses a hostname that resolves to an internal address', async () => {
- (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '10.0.0.9', family: 4 }]);
- expect((await run('rebind.evil.example')).err).toBeInstanceOf(SsrfBlockedError);
- });
-
- it('passes a hostname that resolves to a public address', async () => {
- (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
- const { err, rest } = await run('cdn.example.com');
- expect(err).toBeNull();
- expect(rest[0]).toEqual([{ address: '93.184.216.34', family: 4 }]);
- });
-
- it('returns a single (address, family) pair in non-all form', async () => {
- const single = await new Promise<{ err: unknown; rest: unknown[] }>(resolve => {
- const lookup = validatingLookup() as unknown as (
- h: string,
- o: { all: boolean },
- cb: (err: unknown, ...rest: unknown[]) => void,
- ) => void;
- lookup('93.184.216.34', { all: false }, (err, ...rest) => resolve({ err, rest }));
- });
- expect(single.err).toBeNull();
- expect(single.rest).toEqual(['93.184.216.34', 4]);
- });
-
- it('surfaces a DNS resolution failure to the callback (does not hang the connect)', async () => {
- (dnsPromises.lookup as jest.Mock).mockRejectedValueOnce(new Error('ENOTFOUND'));
- expect((await run('nope.example')).err).toBeInstanceOf(Error);
- });
-
- it('refuses a host that resolves to no addresses', async () => {
- (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([]);
- expect((await run('empty.example')).err).toBeInstanceOf(SsrfBlockedError);
- });
-});
-
describe('isSsrfProtectionEnabled', () => {
const orig = process.env.WEBHOOK_SSRF_PROTECT;
afterEach(() => {
@@ -655,11 +745,12 @@ describe('withSafeFetch followRedirects validates every hop over real sockets',
const port = (server.address() as AddressInfo).port;
try {
+ // An actionable operator error (not a blocked address), so it is not an SsrfBlockedError.
await expect(
withSafeFetch(`http://localhost:${port}/`, {}, async response => await response.text(), {
followRedirects: true,
}),
- ).rejects.toBeInstanceOf(SsrfBlockedError);
+ ).rejects.toThrow(/Too many redirects/);
} finally {
await new Promise<void>(resolve => server.close(() => resolve()));
}
diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.ts
index d888dd01d..d0eeb33ab 100644
--- a/src/common/security/ssrf-guard.ts
+++ b/src/common/security/ssrf-guard.ts
@@ -1,7 +1,7 @@
import { isIPv4, isIPv6, type LookupFunction } from 'net';
import { lookup } from 'dns/promises';
import { type LookupAddress, type LookupOptions } from 'dns';
-import { Agent, fetch as undiciFetch, type RequestInit, type Response } from 'undici';
+import { Agent, fetch as undiciFetch, Headers, type RequestInit, type Response } from 'undici';
/** Thrown when an outbound URL is blocked by the SSRF guard. */
export class SsrfBlockedError extends Error {
@@ -337,52 +337,6 @@ export function pinnedLookup(addresses: LookupAddress[]): LookupFunction {
return fn as unknown as LookupFunction;
}
-/**
- * A `connect.lookup` that resolves EVERY host it is asked to connect to and refuses any that resolve
- * to an internal/reserved address. Used by the redirect-following download path so that each hop —
- * the original URL AND every redirect target — is validated at connect time, not just the first one.
- * This closes the redirect-bypass hole a single-host pin can't: a 3xx to an internal host is rejected
- * at the socket. Allowlisted hosts (SSRF_ALLOWED_HOSTS) are resolved without the block check, matching
- * {@link resolveSafeFetchTarget}.
- */
-export function validatingLookup(): LookupFunction {
- const fn = (hostname: string, options: LookupOptions, callback: (...args: unknown[]) => void): void => {
- const host = hostname.replace(/^\[|\]$/g, ''); // strip IPv6 brackets
- const allowlisted = getAllowedHosts().has(host.toLowerCase());
- const finish = (addrs: LookupAddress[]): void => {
- if (options.all) callback(null, addrs);
- else callback(null, addrs[0].address, addrs[0].family);
- };
-
- if (isIPv4(host) || isIPv6(host)) {
- if (!allowlisted && isBlockedAddress(host)) {
- callback(new SsrfBlockedError(`Blocked internal address: ${host}`));
- return;
- }
- finish([{ address: host, family: isIPv6(host) ? 6 : 4 }]);
- return;
- }
-
- lookupWithDeadline(host)
- .then(resolved => {
- if (resolved.length === 0) {
- callback(new SsrfBlockedError(`Could not resolve host: ${host}`));
- return;
- }
- if (!allowlisted) {
- const bad = resolved.find(a => isBlockedAddress(a.address));
- if (bad) {
- callback(new SsrfBlockedError(`Host ${host} resolves to a blocked internal address: ${bad.address}`));
- return;
- }
- }
- finish(resolved);
- })
- .catch((err: unknown) => callback(err instanceof Error ? err : new Error(String(err))));
- };
- return fn as unknown as LookupFunction;
-}
-
/**
* Cancel an unread response body before the per-request dispatcher is destroyed.
*
@@ -414,6 +368,42 @@ async function useAndSettleBody<T>(response: Response, use: (response: Response)
}
}
+/**
+ * Escape hatch for deployments whose plugin vendor / release host legitimately redirects an https
+ * URL to a plain-http hop (e.g. behind TLS-terminating infrastructure). Default OFF: an https→http
+ * downgrade hop is refused because the payload on this path is executable code and an http hop
+ * exposes it to on-path substitution. Set PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS=true to allow.
+ */
+function isInsecureRedirectHopAllowed(): boolean {
+ return process.env.PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS === 'true';
+}
+
+/**
+ * undici's native redirector strips credentials on cross-origin hops and rewrites 301/302/303 to a
+ * bodiless GET — the manual loop must do the same, or a redirect target would receive the original
+ * request's Authorization/Cookie headers and body.
+ */
+function nextRedirectHopInit(init: RequestInit, status: number, nextUrl: string, initialOrigin: string): RequestInit {
+ let next = init;
+ if (
+ status !== 307 &&
+ status !== 308 &&
+ next.method !== undefined &&
+ next.method !== 'GET' &&
+ next.method !== 'HEAD'
+ ) {
+ next = { ...next, method: 'GET' };
+ delete next.body;
+ }
+ if (new URL(nextUrl).origin !== initialOrigin && next.headers !== undefined) {
+ const headers = new Headers(next.headers);
+ headers.delete('authorization');
+ headers.delete('cookie');
+ next = { ...next, headers };
+ }
+ return next;
+}
+
/**
* Perform an SSRF-safe fetch and hand the response to `use`, then tear down the per-request
* connection. The host is validated and resolved ONCE; the connection is pinned to the vetted IP(s)
@@ -450,11 +440,23 @@ export async function withSafeFetch<T>(
// IP-literal host, so a custom lookup is never invoked for `Location: http://127.0.0.1/` and the
// hop goes unchecked. Each hop below is validated BEFORE its socket is opened.
let currentUrl = rawUrl;
+ let initialOrigin: string | undefined;
+ let hopInit = init;
+ let sawSecureHop = false;
for (let hop = 0; ; hop++) {
const target = await resolveSafeFetchTarget(currentUrl);
+ // Parsed already by resolveSafeFetchTarget above, so this cannot throw.
+ const current = new URL(currentUrl);
+ initialOrigin ??= current.origin;
+ // A hop that downgrades https→http exposes the (executable) download to on-path substitution.
+ // Chains that STARTED on plain http are unaffected — they were never secure to begin with.
+ if (current.protocol === 'http:' && sawSecureHop && !isInsecureRedirectHopAllowed()) {
+ throw new Error(`Refusing redirect that downgrades from https to http: ${currentUrl}`);
+ }
+ if (current.protocol === 'https:') sawSecureHop = true;
const dispatcher = target ? new Agent({ connect: { lookup: pinnedLookup(target) } }) : undefined;
try {
- const response = await undiciFetch(currentUrl, { ...init, redirect: 'manual', dispatcher });
+ const response = await undiciFetch(currentUrl, { ...hopInit, redirect: 'manual', dispatcher });
if (!REDIRECT_STATUSES.has(response.status)) {
return await useAndSettleBody(response, use);
}
@@ -464,9 +466,13 @@ export async function withSafeFetch<T>(
throw new SsrfBlockedError(`Redirect from ${currentUrl} carried no Location header`);
}
if (hop >= MAX_REDIRECT_HOPS) {
- throw new SsrfBlockedError(`Too many redirects while fetching ${rawUrl}`);
+ // Deliberately NOT an SsrfBlockedError: this is an actionable operator error, not a
+ // blocked-address rejection, so it must survive redactSsrfError verbatim.
+ throw new Error(`Too many redirects while fetching ${rawUrl}`);
}
- currentUrl = new URL(location, currentUrl).toString();
+ const nextUrl = new URL(location, currentUrl).toString();
+ hopInit = nextRedirectHopInit(hopInit, response.status, nextUrl, initialOrigin);
+ currentUrl = nextUrl;
} finally {
if (dispatcher) await dispatcher.destroy().catch(() => undefined);
}
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index 620e49fee..a3ba82765 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -240,6 +240,9 @@ export function validateEnv(config: EnvConfig): EnvConfig {
// Read at boot by the throttler factory (app.module.ts) and CacheService with `=== 'true'`: a
// typo like `ture` silently downgrades rate-limit storage + cache to per-process in-memory.
'REDIS_ENABLED',
+ // Read by the SSRF guard's redirect loop with `=== 'true'`: a typo silently keeps the secure
+ // default, but an accidental 'true'-ish string is not the flag the operator meant to audit.
+ 'PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS',
]) {
checkBool(key);
}
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index bd610b5fd..0b04a6235 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -562,6 +562,9 @@ export class BaileysAdapter implements IWhatsAppEngine {
}
try {
+ // Baileys' sock.logout() resolves once the WebSocket write has flushed — WhatsApp sends no
+ // iq ack for the unlink — and it transmits nothing at all when authState.creds.me is unset.
+ // A resolved promise therefore means "sent (or nothing to send)", not "unlink acknowledged".
await this.sock.logout();
} catch (err) {
// End the socket so the session still dies locally, but keep the on-disk creds: wiping
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index c5115c2c7..96f2a014e 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -4579,21 +4579,24 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
describe('probeOnboardingModal (in-page onboarding modal detection)', () => {
type FakeEl = {
tagName: string;
+ role: string | null;
textContent: string;
parentElement: FakeEl | null;
offsetParent: unknown;
getBoundingClientRect: () => { width: number; height: number };
- matchesButton: boolean;
click: jest.Mock;
};
- const el = (textContent: string, opts: { button?: boolean; hidden?: boolean } = {}): FakeEl => ({
+ const el = (
+ textContent: string,
+ opts: { button?: boolean; roleButton?: boolean; hidden?: boolean } = {},
+ ): FakeEl => ({
tagName: opts.button ? 'BUTTON' : 'DIV',
+ role: opts.roleButton ? 'button' : null,
textContent,
parentElement: null,
offsetParent: opts.hidden ? null : {},
getBoundingClientRect: () => (opts.hidden ? { width: 0, height: 0 } : { width: 200, height: 40 }),
- matchesButton: !!opts.button,
click: jest.fn(),
});
@@ -4605,8 +4608,16 @@ describe('probeOnboardingModal (in-page onboarding modal detection)', () => {
const install = (all: FakeEl[]): void => {
(globalThis as unknown as { document: unknown }).document = {
- // The probe only ever queries for buttons, so honour that selector and ignore the rest.
- querySelectorAll: (selector: string) => (selector.includes('button') ? all.filter(e => e.matchesButton) : []),
+ // The probe's selector is 'button, [role="button"]'. Mirror the DOM per branch: the tag branch
+ // matches BUTTON elements, the attribute branch matches anything carrying role="button".
+ querySelectorAll: (selector: string) => {
+ const branches = selector.split(',').map(branch => branch.trim());
+ return all.filter(
+ e =>
+ (branches.includes('button') && e.tagName === 'BUTTON') ||
+ (branches.includes('[role="button"]') && e.role === 'button'),
+ );
+ },
};
};
@@ -4634,6 +4645,18 @@ describe('probeOnboardingModal (in-page onboarding modal detection)', () => {
expect(button.click).toHaveBeenCalledTimes(1);
});
+ // The probe's selector covers ARIA buttons too ('button, [role="button"]'): WhatsApp Web has
+ // rendered the control as a div[role="button"] in some builds. A role-button carrying the exact
+ // label inside the modal is the same presence signal as a real <button>.
+ it('detects a div[role="button"] carrying the exact Continue label', () => {
+ const button = el('Continue', { roleButton: true });
+ nest(el("What's new on WhatsApp Web"), button);
+ install([button]);
+
+ expect(probeOnboardingModal()).toEqual({ modalPresent: true, dismissed: true });
+ expect(button.click).toHaveBeenCalledTimes(1);
+ });
+
// The regression that matters: an element's text includes all of its descendants, so a chat row
// previewing an ordinary message matches a heading-only test. Reporting a modal here took a healthy
// session out of READY, which refuses every send.
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 4c8713834..b69e26723 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1304,7 +1304,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.reportActionRequired(
`WhatsApp is still showing its onboarding modal after ${this.onboardingDismissClicks} ` +
"attempts to dismiss it. Open WhatsApp Web on the account holder's own browser and click " +
- 'through the "What\'s new" screen, or the companion device will be unlinked.',
+ 'through the "What\'s new" screen, or the companion device will be unlinked. Then restart ' +
+ 'the session (stop, then start) — acknowledging the modal does not return it to ready on its own.',
);
}
} catch {
diff --git a/src/engine/adapters/wwebjs-backport-201832.spec.ts b/src/engine/adapters/wwebjs-backport-201832.spec.ts
index ebe7505c6..a61698e54 100644
--- a/src/engine/adapters/wwebjs-backport-201832.spec.ts
+++ b/src/engine/adapters/wwebjs-backport-201832.spec.ts
@@ -150,6 +150,15 @@ describe('patch-wwebjs-201832 (build-time backport of upstream #201832)', () =>
expect(() => applyBackport(dir)).toThrow(/PARTIALLY patched/);
});
+ it('fails with a curated version-skew error when Message.js is missing', () => {
+ const dir = copyWwjs();
+ // A future whatsapp-web.js could keep Base.js but drop or rename Message.js — the patcher must
+ // diagnose that as version skew, not die on a raw ENOENT.
+ fs.rmSync(path.join(dir, 'src', 'structures', 'Message.js'));
+
+ expect(() => applyBackport(dir)).toThrow(/version skew/);
+ });
+
it('applies the backport across every id-normalization site', () => {
const dir = copyWwjs();
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 327180c43..a37d350c4 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -34,6 +34,7 @@ export interface MessageResult {
export interface MediaInput {
mimetype: string;
data: Buffer | string; // Buffer or base64 or URL
+ /** Caller-supplied filename wins. Document sends fall back to 'file' when omitted (wwebjs first derives the URL basename); image/video/audio sends carry no filename. */
filename?: string;
caption?: string;
/** Neutral WIDs (`<phone>@c.us`) to @mention in the caption. The adapter de-normalizes per engine. */
@@ -535,7 +536,9 @@ export interface EngineEventCallbacks {
* linking that must be acknowledged, and the adapter dismisses it automatically; this fires only if
* that dismissal fails, so a headless deployment is told (rather than left to be logged out ~5m
* later). The engine has already moved to ACTION_REQUIRED; `reason` carries a human-readable cause.
- * Distinct from `onError` (terminal) and `onDisconnected` (recoverable): intervention clears it.
+ * Distinct from `onError` (terminal) and `onDisconnected` (recoverable): it does NOT clear on its
+ * own — once the operator has acted, the session must be restarted (stop, then start) to return
+ * to READY.
*/
onActionRequired?: (reason: string) => void;
/**
diff --git a/src/modules/auth/global-route-fence-coverage.spec.ts b/src/modules/auth/global-route-fence-coverage.spec.ts
index 4594f6e55..5c201e2f5 100644
--- a/src/modules/auth/global-route-fence-coverage.spec.ts
+++ b/src/modules/auth/global-route-fence-coverage.spec.ts
@@ -57,19 +57,21 @@ export function handlersMissingGlobalFence(source: string): string[] {
const offenders: string[] = [];
// Capture each handler's decorator block plus its method name. Decorators are the contiguous run of
- // `@...` lines immediately preceding a 2-space-indented method declaration.
- const handlerRe = /((?:^ {2}@[\s\S]*?)?)^ {2}(?:async\s+)?([a-zA-Z0-9_]+)\s*\(/gm;
+ // `@...` lines immediately preceding an indented method declaration. Any indentation depth matches —
+ // a handler indented by something other than two spaces is still a route the fence decision covers.
+ const handlerRe = /((?:^ +@[\s\S]*?)?)^ +(?:async\s+)?([a-zA-Z0-9_]+)\s*\(/gm;
for (let m = handlerRe.exec(source); m !== null; m = handlerRe.exec(source)) {
const [, decorators, name] = m;
if (name === 'constructor') continue;
- // Only HTTP handlers matter; a private helper has no route decorator.
- if (!/@(Get|Post|Put|Patch|Delete)\(/.test(decorators)) continue;
+ // Only HTTP handlers matter; a private helper has no route decorator. @All, @Sse and @Head bind
+ // routes too, so a handler using one is still an endpoint the fence decision applies to.
+ if (!/@(Get|Post|Put|Patch|Delete|All|Sse|Head)\(/.test(decorators)) continue;
if (/@Public\(\)/.test(decorators)) continue;
if (/@RequireUnscopedKey\(\)/.test(decorators)) continue;
// A :sessionId route param gives the guard something to scope against.
- if (/@(Get|Post|Put|Patch|Delete)\([^)]*:sessionId/.test(decorators)) continue;
+ if (/@(Get|Post|Put|Patch|Delete|All|Sse|Head)\([^)]*:sessionId/.test(decorators)) continue;
// On a @SessionScoped controller the bare `:id` param is a session id, so it is scoped too.
- if (classIsSessionScoped && /@(Get|Post|Put|Patch|Delete)\([^)]*:id/.test(decorators)) continue;
+ if (classIsSessionScoped && /@(Get|Post|Put|Patch|Delete|All|Sse|Head)\([^)]*:id/.test(decorators)) continue;
offenders.push(name);
}
return offenders;
@@ -100,6 +102,32 @@ export class ThingController {
expect(handlersMissingGlobalFence(vulnerable)).toEqual(['findAll']);
});
+ it('flags an @All handler with no fence', () => {
+ const vulnerable = `
+export class ThingController {
+ @All('everything')
+ @RequireRole(ApiKeyRole.ADMIN)
+ handleAll(): string[] {
+ return [];
+ }
+}
+`;
+ expect(handlersMissingGlobalFence(vulnerable)).toEqual(['handleAll']);
+ });
+
+ it('flags a handler indented deeper than two spaces', () => {
+ const vulnerable = `
+export class ThingController {
+ @Get('everything')
+ @RequireRole(ApiKeyRole.ADMIN)
+ findAll(): string[] {
+ return [];
+ }
+}
+`;
+ expect(handlersMissingGlobalFence(vulnerable)).toEqual(['findAll']);
+ });
+
it('clears a handler carrying the fence', () => {
const fixed = `
export class ThingController {
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
index 687cdd47f..a4a6320c6 100644
--- a/src/modules/infra/infra.controller.spec.ts
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -2130,6 +2130,24 @@ describe('InfraController.requestRestart constrains teardown to managed profiles
expect(orchestrateProfiles).toHaveBeenCalledTimes(1);
expect(orchestrateProfiles).toHaveBeenCalledWith(['postgres']);
});
+
+ it('writes only allowlisted profiles to the no-Docker signal file (symmetry with the Docker path)', async () => {
+ const writeFileSync = fs.writeFileSync as jest.Mock;
+ writeFileSync.mockClear();
+ const controller = buildController({ isDockerAvailable: () => false });
+
+ // The signal file is consumed by an external host script — it must never be handed a name the
+ // in-process Docker path would have refused.
+ await controller.requestRestart({ profiles: ['postgres', 'not-managed'], profilesToRemove: ['evil', 'redis'] });
+
+ const written = (writeFileSync.mock.calls as Array<[unknown, unknown]>).find(call =>
+ String(call[0]).endsWith('.orchestration-request.json'),
+ );
+ expect(written).toBeDefined();
+ const payload = JSON.parse(String(written![1])) as { profiles: string[]; profilesToRemove: string[] };
+ expect(payload.profiles).toEqual(['postgres']);
+ expect(payload.profilesToRemove).toEqual(['redis']);
+ });
});
// C002: the infra module exposed sensitive ADMIN operations (credential config write, restart/Docker
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index ce6a602cf..b22156181 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -1076,13 +1076,21 @@ export class InfraController implements OnApplicationBootstrap {
}
} else {
this.logger.warn('Docker not available, writing signal file instead');
- // Fallback: write signal file for host script
+ // Fallback: write signal file for host script — but apply the SAME managed-profile
+ // constraint as the Docker path above: the external consumer of this file must never be
+ // handed a profile name the in-process path would have refused.
try {
const signalFile = path.resolve(process.cwd(), 'data', '.orchestration-request.json');
+ const toStart = profiles.filter(p => MANAGED_DOCKER_PROFILES.includes(p));
+ const toRemove = profilesToRemove.filter(p => !profiles.includes(p) && MANAGED_DOCKER_PROFILES.includes(p));
+ const ignored = [...profiles, ...profilesToRemove].filter(p => !MANAGED_DOCKER_PROFILES.includes(p));
+ if (ignored.length > 0) {
+ this.logger.warn('Ignoring non-managed profiles in the signal-file request', { ignored });
+ }
const orchestrationRequest = {
timestamp: new Date().toISOString(),
- profiles,
- profilesToRemove,
+ profiles: toStart,
+ profilesToRemove: toRemove,
action: 'restart-with-profiles',
};
fs.writeFileSync(signalFile, JSON.stringify(orchestrationRequest, null, 2), 'utf8');
diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.ts
index bd89b8ff7..644de7ad5 100644
--- a/src/modules/message/dto/send-message.dto.ts
+++ b/src/modules/message/dto/send-message.dto.ts
@@ -82,7 +82,8 @@ export class SendMediaMessageDto {
mimetype?: string;
@ApiPropertyOptional({
- description: 'Filename for the media',
+ description:
+ "Filename for the media. Only rendered on document sends — defaults to 'file' when omitted (a URL-based document send on whatsapp-web.js first derives the URL basename)",
example: 'image.jpg',
})
@IsOptional()
diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.ts
index abe0128dc..9ab3cf5c2 100644
--- a/src/modules/plugins/plugins.service.ts
+++ b/src/modules/plugins/plugins.service.ts
@@ -342,7 +342,8 @@ export class PluginsService {
/**
* Install a plugin from an HTTPS URL: download the .zip through the SSRF guard (host validated,
- * connection pinned, redirects refused, size-capped), then run the exact same validate-write-load
+ * connection pinned, redirects followed with every hop re-validated through the guard and the
+ * chain capped at 5 hops, size-capped), then run the exact same validate-write-load
* pipeline as an uploaded package. The downloaded buffer is treated as untrusted, identical to an
* upload. When the URL pins a digest (`#sha256=<hex>` fragment — the only honored marker; query
* params are deliberately ignored, see plugin-download.ts), the bytes MUST match it: a mismatch
diff --git a/src/modules/queue/bull-board-mount-coverage.spec.ts b/src/modules/queue/bull-board-mount-coverage.spec.ts
new file mode 100644
index 000000000..13158afa1
--- /dev/null
+++ b/src/modules/queue/bull-board-mount-coverage.spec.ts
@@ -0,0 +1,45 @@
+import * as fs from 'fs';
+import * as path from 'path';
+
+/**
+ * The queue dashboard is a middleware mount, not a Nest controller — so neither
+ * global-route-fence-coverage.spec.ts nor the APP_GUARD pipeline can see it. Its auth fence
+ * (BullBoardAuthMiddleware) only holds while the mount path in main.ts covers the exact path
+ * BullBoardModule serves. A drift in any of the three literals (global prefix, module route,
+ * middleware mount) silently re-opens the deployment-global mount to session-restricted keys —
+ * or 404s the board — and no other test or CI step would catch it. This spec is that tripwire.
+ */
+
+function extractGlobalPrefix(appValidationSrc: string): string {
+ const match = /setGlobalPrefix\(\s*'([^']+)'/.exec(appValidationSrc);
+ if (!match) throw new Error('setGlobalPrefix literal not found in app-validation.ts');
+ return match[1];
+}
+
+function extractBullBoardRoute(queueModuleSrc: string): string {
+ const match = /BullBoardModule\.forRoot\(\{\s*route:\s*'([^']+)'/.exec(queueModuleSrc);
+ if (!match) throw new Error('BullBoardModule route literal not found in queue.module.ts');
+ return match[1];
+}
+
+function mountCoversRoute(mainSrc: string, prefix: string, route: string): boolean {
+ return mainSrc.includes(`app.use('/${prefix}${route}'`);
+}
+
+describe('bull-board mount path tripwire', () => {
+ const mainSrc = fs.readFileSync(path.join(__dirname, '..', '..', 'main.ts'), 'utf8');
+ const queueModuleSrc = fs.readFileSync(path.join(__dirname, 'queue.module.ts'), 'utf8');
+ const appValidationSrc = fs.readFileSync(path.join(__dirname, '..', '..', 'config', 'app-validation.ts'), 'utf8');
+
+ it('main.ts mounts the auth middleware on the exact path BullBoardModule serves', () => {
+ const prefix = extractGlobalPrefix(appValidationSrc);
+ const route = extractBullBoardRoute(queueModuleSrc);
+ expect(mountCoversRoute(mainSrc, prefix, route)).toBe(true);
+ });
+
+ it('the check fails when any of the three literals drifts', () => {
+ expect(mountCoversRoute(mainSrc, 'api', '/other/path')).toBe(false);
+ expect(mountCoversRoute(mainSrc, 'wrongprefix', '/admin/queues')).toBe(false);
+ expect(mountCoversRoute("app.use('/api/admin/queues', handler);", 'api', '/admin/queues')).toBe(true);
+ });
+});
diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.ts
new file mode 100644
index 000000000..fee705fb4
--- /dev/null
+++ b/src/modules/session/logout-teardown-race.spec.ts
@@ -0,0 +1,164 @@
+import { Test, TestingModule } from '@nestjs/testing';
+import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';
+import { Repository, DataSource } from 'typeorm';
+import { BadGatewayException } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import { SessionService } from './session.service';
+import { Session, SessionStatus } from './entities/session.entity';
+import { Message } from '../message/entities/message.entity';
+import { EngineFactory } from '../../engine/engine.factory';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { EventsGateway } from '../events/events.gateway';
+import { WebhookService } from '../webhook/webhook.service';
+import { HookManager } from '../../core/hooks';
+import { StatusStoreService } from '../status-store/status-store.service';
+
+function createMockSession(overrides: Partial<Session> = {}): Session {
+ return {
+ id: 'sess-uuid-1',
+ name: 'test-session',
+ status: SessionStatus.CREATED,
+ phone: null,
+ pushName: null,
+ config: {},
+ proxyUrl: null,
+ proxyType: null,
+ connectedAt: null,
+ lastActiveAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides,
+ };
+}
+
+describe('SessionService logout() concurrent teardown tracking', () => {
+ let service: SessionService;
+ let repository: jest.Mocked<Partial<Repository<Session>>>;
+ let engineFactory: jest.Mocked<Partial<EngineFactory>>;
+
+ beforeEach(async () => {
+ repository = {
+ findOne: jest.fn().mockResolvedValue(createMockSession()),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ };
+ const messageRepository = { find: jest.fn().mockResolvedValue([]) };
+ const manager = { delete: jest.fn().mockResolvedValue({ affected: 1 }), remove: jest.fn() };
+ const dataSource: Partial<DataSource> = {
+ transaction: jest.fn(async (cb: (m: unknown) => Promise<void>) =>
+ cb(manager),
+ ) as unknown as DataSource['transaction'],
+ };
+ const mockEngine = {
+ initialize: jest.fn().mockResolvedValue(undefined),
+ destroy: jest.fn().mockResolvedValue(undefined),
+ forceDestroy: jest.fn().mockResolvedValue(undefined),
+ disconnect: jest.fn().mockResolvedValue(undefined),
+ getQRCode: jest.fn().mockReturnValue(null),
+ };
+ engineFactory = {
+ create: jest.fn().mockReturnValue(mockEngine),
+ purgeSessionData: jest.fn().mockResolvedValue(undefined),
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ SessionService,
+ { provide: getRepositoryToken(Session, 'data'), useValue: repository },
+ { provide: getRepositoryToken(Message, 'data'), useValue: messageRepository },
+ { provide: getDataSourceToken('data'), useValue: dataSource },
+ { provide: EngineFactory, useValue: engineFactory },
+ {
+ provide: EventsGateway,
+ useValue: { emitSessionStatus: jest.fn(), emitSessionDisconnected: jest.fn(), emitQRCode: jest.fn() },
+ },
+ { provide: WebhookService, useValue: { dispatch: jest.fn().mockResolvedValue(undefined) } },
+ { provide: HookManager, useValue: { execute: jest.fn().mockResolvedValue({ continue: true, data: {} }) } },
+ {
+ provide: ConfigService,
+ useValue: { get: jest.fn().mockImplementation(<T>(_k: string, d?: T): T => d as T) },
+ },
+ { provide: LidMappingStoreService, useValue: { remember: jest.fn() } },
+ { provide: StatusStoreService, useValue: { ingest: jest.fn() } },
+ ],
+ }).compile();
+
+ service = module.get<SessionService>(SessionService);
+ });
+
+ const enginesOf = () => (service as unknown as { engines: Map<string, unknown> }).engines;
+ const pendingOf = () => (service as unknown as { pendingTeardowns: Map<string, Promise<void>> }).pendingTeardowns;
+
+ it('keeps the first teardown tracked when a second logout arrives mid-flight, so start() waits for it', async () => {
+ // The first logout's teardown wedges (its profile fs.rm outlives the request); the second
+ // logout's adapter call refuses immediately (the client is already being torn down).
+ let settleFirst: () => void = () => undefined;
+ const wedgedLogout = new Promise<void>(resolve => {
+ settleFirst = resolve;
+ });
+
+ const logout = jest
+ .fn()
+ .mockReturnValueOnce(wedgedLogout)
+ .mockReturnValueOnce(Promise.reject(new Error('No live WhatsApp Web client — the unlink was not sent')));
+
+ enginesOf().set('sess-uuid-1', { logout });
+
+ jest.useFakeTimers();
+ try {
+ const first = service.logout('sess-uuid-1');
+ // let logout1 get past findOne and register its pendingTeardowns entry
+ await jest.advanceTimersByTimeAsync(0);
+ expect(pendingOf().has('sess-uuid-1')).toBe(true);
+
+ // ---- a separate HTTP request, a macrotask later ----
+ const second = service.logout('sess-uuid-1');
+ await expect(second).rejects.toBeInstanceOf(BadGatewayException);
+ expect(logout).toHaveBeenCalledTimes(2); // engine still in the map => 2nd logout passed the guard
+
+ // The first (still-running) teardown must stay tracked: its late profile rm must gate start().
+ expect(pendingOf().has('sess-uuid-1')).toBe(true);
+
+ // start() must NOT re-create the profile while the first teardown's rm is pending.
+ const startCall = service.start('sess-uuid-1');
+ await jest.advanceTimersByTimeAsync(0);
+ expect(engineFactory.create).not.toHaveBeenCalled();
+
+ // Once the first teardown settles, start() proceeds.
+ settleFirst();
+ await jest.advanceTimersByTimeAsync(0);
+ await expect(first).resolves.toMatchObject({ id: 'sess-uuid-1' });
+ await jest.advanceTimersByTimeAsync(0);
+ expect(engineFactory.create).toHaveBeenCalledTimes(1);
+ await startCall;
+
+ // Entry cleaned up after everything settled.
+ expect(pendingOf().has('sess-uuid-1')).toBe(false);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('drops a wedged logout teardown entry when the session is deleted', async () => {
+ // A logout teardown that never settles keeps its pendingTeardowns entry past the bounded waits;
+ // deleting the session must drop it — the UUID can never be read again, so leaving it would
+ // grow the map without bound across logout-fail/delete churn.
+ const wedgedLogout = new Promise<void>(() => undefined);
+ const logout = jest.fn().mockReturnValue(wedgedLogout);
+ enginesOf().set('sess-uuid-1', { logout });
+
+ jest.useFakeTimers();
+ try {
+ const logoutCall = service.logout('sess-uuid-1');
+ await jest.advanceTimersByTimeAsync(10_000); // teardown loses its deadline race
+ await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);
+ expect(pendingOf().has('sess-uuid-1')).toBe(true); // the wedged raw keeps its entry
+
+ const deleteCall = service.delete('sess-uuid-1');
+ await jest.advanceTimersByTimeAsync(10_000); // delete's bounded wait elapses
+ await deleteCall;
+ expect(pendingOf().has('sess-uuid-1')).toBe(false);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+});
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 69280b580..d4cae47e5 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1848,6 +1848,51 @@ describe('SessionService', () => {
});
});
+ // ── engine ACTION_REQUIRED wiring (#982) ──────────────────────────
+
+ describe('engine ACTION_REQUIRED', () => {
+ const startAndCapture = async (): Promise<EngineEventCallbacks> => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ await service.start('sess-uuid-1');
+ const calls = mockEngine.initialize.mock.calls as [EngineEventCallbacks][];
+ return calls[0][0];
+ };
+
+ it('maps EngineStatus.ACTION_REQUIRED to SessionStatus.ACTION_REQUIRED via onStateChanged', async () => {
+ const callbacks = await startAndCapture();
+ (repository.update as jest.Mock).mockClear();
+
+ callbacks.onStateChanged?.(EngineStatus.ACTION_REQUIRED);
+
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.ACTION_REQUIRED });
+ });
+
+ it('records the onActionRequired reason and runs the session:error hook', async () => {
+ const callbacks = await startAndCapture();
+
+ callbacks.onActionRequired?.('onboarding modal needs a manual dismissal');
+
+ const sessionErrors = (service as unknown as { sessionErrors: Map<string, string> }).sessionErrors;
+ expect(sessionErrors.get('sess-uuid-1')).toBe('onboarding modal needs a manual dismissal');
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'session:error',
+ expect.objectContaining({ reason: 'onboarding modal needs a manual dismissal' }),
+ expect.objectContaining({ sessionId: 'sess-uuid-1' }),
+ );
+ });
+
+ it('surfaces the reason via lastError while the session is ACTION_REQUIRED', async () => {
+ const callbacks = await startAndCapture();
+ callbacks.onActionRequired?.('onboarding modal needs a manual dismissal');
+
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ status: SessionStatus.ACTION_REQUIRED }));
+ const result = await service.findOne('sess-uuid-1');
+
+ expect(result.lastError).toBe('onboarding modal needs a manual dismissal');
+ });
+ });
+
// ── engine-identity guard: stale-callback isolation ───────────────
// A callback can fire after its engine was torn down (post-stop) or after a newer engine
// replaced it for the same id (post-restart / reconnect). Such a stale callback must not
@@ -4461,6 +4506,19 @@ describe('SessionService', () => {
status: SessionStatus.DISCONNECTED,
});
});
+
+ it('treats ACTION_REQUIRED as an active status that gets reset on startup', async () => {
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.onModuleInit();
+
+ // The reset targets the active-status set via In(...) — ACTION_REQUIRED must be a member, or a
+ // session waiting on operator action would survive a restart looking resumable while the engine
+ // that could observe the action is gone.
+ const calls = (repository.update as jest.Mock).mock.calls as Array<[{ status: { value: unknown } }]>;
+ const where = calls[0][0];
+ expect(where.status.value).toEqual(expect.arrayContaining([SessionStatus.ACTION_REQUIRED]));
+ });
});
// ── onModuleDestroy ───────────────────────────────────────────────
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index d9aaa87fc..214f1da78 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -385,12 +385,17 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
const raw = teardown(engine);
if (label === 'logout') {
// Settlement marker only — never rejects, so it can't drive the race below to a false
- // "completed"; the race still observes the raw promise. Identity-checked on removal so a
- // newer teardown's entry isn't evicted by an older one settling.
+ // "completed"; the race still observes the raw promise. A concurrent logout chains onto the
+ // previous entry instead of overwriting it, so start()/delete() keep waiting until EVERY
+ // in-flight teardown for this session has settled — otherwise the second logout's fast
+ // settlement would drop the entry while the first teardown's profile rm is still pending.
+ // Identity-checked on removal so a newer teardown's entry isn't evicted by an older one settling.
const tracked = raw.catch(() => undefined);
- this.pendingTeardowns.set(sessionId, tracked);
- void tracked.finally(() => {
- if (this.pendingTeardowns.get(sessionId) === tracked) {
+ const previous = this.pendingTeardowns.get(sessionId);
+ const entry: Promise<void> = previous ? Promise.allSettled([previous, tracked]).then(() => undefined) : tracked;
+ this.pendingTeardowns.set(sessionId, entry);
+ void entry.finally(() => {
+ if (this.pendingTeardowns.get(sessionId) === entry) {
this.pendingTeardowns.delete(sessionId);
}
});
@@ -615,6 +620,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Drop the FAILED-reason entry too: it's keyed by a now-deleted UUID that can never be read
// again, so leaving it would grow the map without bound across create/fail/delete churn.
this.sessionErrors.delete(id);
+ // Same for a wedged logout-teardown entry: the wait above is only bounded, so a teardown
+ // that never settles would otherwise pin its entry (and its promise chain) forever.
+ this.pendingTeardowns.delete(id);
}
}
@@ -1555,7 +1563,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
});
// Record the reason so attachLastError surfaces it while the session is ACTION_REQUIRED,
// then updateStatus (via onStateChanged above) has already written the status. Set here too
- // to be defensive: the callback order is onActionRequired then onStateChanged, but persisting
+ // to be defensive: the callback order is onStateChanged then onActionRequired, but persisting
// the reason here means it is available regardless.
this.sessionErrors.set(id, reason);
void this.hookManager.execute('session:error', { reason }, { sessionId: id, source: 'Engine' });
diff --git a/test/global-routes-session-scope.e2e-spec.ts b/test/global-routes-session-scope.e2e-spec.ts
index 1848280b2..64ce2d408 100644
--- a/test/global-routes-session-scope.e2e-spec.ts
+++ b/test/global-routes-session-scope.e2e-spec.ts
@@ -24,6 +24,7 @@ describe('Global read and create routes reject session-scoped keys (e2e)', () =>
let scopedAdminKey: string; // ADMIN, allowedSessions: [sessA]
let scopedOperatorKey: string; // OPERATOR, allowedSessions: [sessA]
let adminKey: string; // ADMIN, unrestricted
+ let scopedSessionId: string; // the session the scoped keys are confined to
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule] }).compile();
@@ -33,6 +34,7 @@ describe('Global read and create routes reject session-scoped keys (e2e)', () =>
const sessionRepo: Repository<Session> = app.get(getRepositoryToken(Session, 'data'));
const a = await sessionRepo.save(sessionRepo.create({ name: `e2e-global-scope-${Date.now()}` }));
+ scopedSessionId = a.id;
const authService = app.get(AuthService);
scopedAdminKey = (
@@ -80,12 +82,32 @@ describe('Global read and create routes reject session-scoped keys (e2e)', () =>
.expect(403);
});
- it('leaves per-session stats reachable for an in-scope session', async () => {
- // Sanity: the fence must not spill onto the session-scoped route next door.
+ it('lets an unrestricted key reach the global stats overview', async () => {
+ // Control: the fence rejects scoped keys on this route but must not hinder an unrestricted one.
const res = await request(app.getHttpServer()).get('/api/stats/overview').set('X-API-Key', adminKey);
expect(res.status).toBe(200);
});
+ it('lets a session-scoped key reach per-session stats for its own session', async () => {
+ // The per-session route carries no fence — its :sessionId route param is the scope. Pin that the
+ // global-route fencing above does not over-reach onto it.
+ const res = await request(app.getHttpServer())
+ .get(`/api/stats/sessions/${scopedSessionId}`)
+ .set('X-API-Key', scopedAdminKey);
+ expect(res.status).toBe(200);
+ });
+
+ it('denies a session-scoped key per-session stats for a session outside its scope', async () => {
+ // The param-scope check surfaces as 401 (the key is not authorized for that session) — a
+ // different code path than the fence's 403 above, pinned here so the two are not conflated.
+ const sessionRepo: Repository<Session> = app.get(getRepositoryToken(Session, 'data'));
+ const other = await sessionRepo.save(sessionRepo.create({ name: `e2e-global-scope-other-${Date.now()}` }));
+ await request(app.getHttpServer())
+ .get(`/api/stats/sessions/${other.id}`)
+ .set('X-API-Key', scopedAdminKey)
+ .expect(401);
+ });
+
it('leaves an unrestricted ADMIN able to create a session', async () => {
await request(app.getHttpServer())
.post('/api/sessions')