Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): rebuild the forward target from the owner origin, and fence stop/delete against a live peer

Yudhi Armyndharisaca44ecde205
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2463b4890..ad4e0e332 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).
- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.
- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.
+- **Security (multi-node routing only): the session forwarder could be aimed at any origin.** HTTP/1.1's absolute-form request target (`GET http://elsewhere/api/sessions/x`) is matched by the router and left verbatim in the request URL, where resolving it against the owner's address discards that address — an authenticated caller could make a node forward their request, API key attached, to an origin of their choosing and read the response. The forward target is now rebuilt from the owner's origin plus the request's path and query, so the destination cannot be influenced at all. Deployments without `NODE_URL` (the default) were never affected: the forwarder is inert there.
+- **`stop` and `delete` are fenced against a session a live peer is running.** Only `start` was claim-checked, and neither of those two needs a local engine, so a request landing on the wrong node — routine when session ownership is configured but request routing is not — wrote `disconnected` over a peer's live session or deleted its row and credentials while the peer's engine kept running. Both now answer 409; a lapsed claim still proceeds, since taking over is what the claim rule allows.
- **Multi-node ownership races closed:** a `stop` landing while a `start` is mid-launch no longer hands back the claim under a live engine (which left the engine unclaimed and startable a second time elsewhere), a failed start no longer pins its session to that node forever, and a deliberate teardown of a session whose crashed owner's lease had lapsed now really leaves it down instead of being re-adopted by the takeover sweep. Successful forwarded requests also stop logging a spurious error.
- **The send breaker only counts failures that reached WhatsApp.** Client-fault and engine-state errors raised inside the send call — a blocked media URL, a capability the engine lacks, a disconnected socket, a malformed status post — no longer accumulate toward it, so a client sending bad requests can no longer 429 every send on a healthy session for the cooldown. Applied to single sends, bulk batches and status posts alike.
- **Backup/restore covers `automation_rules`.** The table was in neither the export nor the import while the restore's session wipe cascade-deletes it, so a documented backup→restore silently destroyed every autoreply rule.
diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.ts
index b0311993d..233a2ffd3 100644
--- a/src/modules/session/session-ownership.service.spec.ts
+++ b/src/modules/session/session-ownership.service.spec.ts
@@ -350,6 +350,22 @@ describe('SessionOwnershipService', () => {
* Drives an operator-facing warning during a data import: this process can only stop its own
* engines, so a session running elsewhere has to be named rather than quietly counted as handled.
*/
+ describe('is one session held elsewhere', () => {
+ it('is true only for a LIVE foreign claim', async () => {
+ const live = await seed({ nodeId: 'peer', leaseExpiresAt: new Date(Date.now() + 60_000) });
+ const lapsed = await seed({ nodeId: 'peer', leaseExpiresAt: new Date(Date.now() - 1000) });
+ const mine = await seed({ nodeId: 'node-a', leaseExpiresAt: new Date(Date.now() + 60_000) });
+ const free = await seed();
+ const nodeA = service('node-a');
+
+ await expect(nodeA.isHeldByOtherNode(live.id)).resolves.toBe(true);
+ // A lapsed holder may be gone — taking over is exactly what the claim rule allows.
+ await expect(nodeA.isHeldByOtherNode(lapsed.id)).resolves.toBe(false);
+ await expect(nodeA.isHeldByOtherNode(mine.id)).resolves.toBe(false);
+ await expect(nodeA.isHeldByOtherNode(free.id)).resolves.toBe(false);
+ });
+ });
+
describe('sessions held elsewhere', () => {
it('names sessions another node holds on a live lease', async () => {
const mine = await seed();
diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.ts
index bd563bef6..95ebf93e9 100644
--- a/src/modules/session/session-ownership.service.ts
+++ b/src/modules/session/session-ownership.service.ts
@@ -291,6 +291,24 @@ export class SessionOwnershipService {
* For operations that can only act on this process's own engines and would otherwise report
* success over work they never touched.
*/
+ /**
+ * Whether ONE session is held by another node on a live lease.
+ *
+ * The scoped counterpart of {@link heldByOtherNodes}, for the lifecycle verbs that act on a single
+ * id: they only need this answer, and scanning every claim to get it would grow with the whole
+ * deployment. A LAPSED foreign claim reads false — the holder may be gone, and taking over is
+ * exactly what the claim rule allows.
+ */
+ async isHeldByOtherNode(sessionId: string, now = new Date()): Promise<boolean> {
+ const count = await this.sessions
+ .createQueryBuilder('session')
+ .where('id = :id', { id: sessionId })
+ .andWhere('"nodeId" IS NOT NULL AND "nodeId" <> :me', { me: this.nodeId })
+ .andWhere('"leaseExpiresAt" > :now', { now: leaseParam(now) })
+ .getCount();
+ return count > 0;
+ }
+
async heldByOtherNodes(now = new Date()): Promise<string[]> {
const rows = await this.sessions
.createQueryBuilder('session')
diff --git a/src/modules/session/session-proxy.interceptor.spec.ts b/src/modules/session/session-proxy.interceptor.spec.ts
index d9a340417..8f892e33a 100644
--- a/src/modules/session/session-proxy.interceptor.spec.ts
+++ b/src/modules/session/session-proxy.interceptor.spec.ts
@@ -2,7 +2,7 @@ import http from 'http';
import { AddressInfo } from 'net';
import { of, lastValueFrom } from 'rxjs';
import type { CallHandler, ExecutionContext } from '@nestjs/common';
-import { SessionProxyInterceptor, FORWARDED_HEADER } from './session-proxy.interceptor';
+import { SessionProxyInterceptor, FORWARDED_HEADER, forwardTarget } from './session-proxy.interceptor';
import type { Session } from './entities/session.entity';
/**
@@ -221,6 +221,33 @@ describe('SessionProxyInterceptor', () => {
// Without the chain the owner sees every forwarded call as coming from THIS node — an
// allowedIps-restricted key 401s on every forwarded request, and the per-IP throttler pools
// all forwarded traffic into one bucket.
+ // End-to-end proof of the absolute-form vector: a raw HTTP request whose target names another
+ // origin must still be forwarded to the OWNER, never to the origin the caller chose — otherwise
+ // the caller receives the attacker origin's response with their own API key already spent on it.
+ it('forwards to the owner even when the caller supplies an absolute-form request target', async () => {
+ const attacker = http.createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ stolenBy: 'attacker' }));
+ });
+ await new Promise<void>(resolve => attacker.listen(0, '127.0.0.1', resolve));
+ const attackerPort = (attacker.address() as AddressInfo).port;
+
+ try {
+ const req = request({ originalUrl: `http://127.0.0.1:${attackerPort}/api/sessions/${SID}` });
+ const { interceptor, context, next, res } = build({ req, row: row({ nodeUrl: serverUrl }) });
+
+ await interceptor.intercept(context, next);
+
+ // The owner answered, not the attacker's origin.
+ expect(seen).toHaveLength(1);
+ expect(seen[0].url).toBe(`/api/sessions/${SID}`);
+ const sentBody = (res.send.mock.calls[0] as [Buffer])[0];
+ expect(JSON.parse(String(sentBody))).toEqual({ servedBy: 'the-owner' });
+ } finally {
+ await new Promise<void>(resolve => attacker.close(() => resolve()));
+ }
+ });
+
it('appends the observed peer to x-forwarded-for so the owner can resolve the real client', async () => {
const direct = build({
req: request({ socket: { remoteAddress: '::ffff:203.0.113.7' } }),
@@ -256,3 +283,31 @@ describe('SessionProxyInterceptor', () => {
});
});
});
+
+// The request target is caller-controlled: HTTP/1.1's absolute form is matched by Express and left
+// verbatim in `req.originalUrl`, and resolving that against a base DISCARDS the base. Forwarding it
+// would aim this node at an attacker's origin and hand over the caller's API key with the request.
+describe('forwardTarget', () => {
+ const OWNER = 'http://10.0.0.5:2785';
+
+ it('keeps path and query, on the owner origin', () => {
+ expect(forwardTarget('/api/sessions/s1/messages?limit=5', OWNER)).toBe(
+ 'http://10.0.0.5:2785/api/sessions/s1/messages?limit=5',
+ );
+ });
+
+ it.each([
+ ['absolute form', 'http://attacker.tld/api/sessions/s1'],
+ ['absolute form, https', 'https://attacker.tld/api/sessions/s1'],
+ ['protocol-relative', '//attacker.tld/api/sessions/s1'],
+ ['absolute form with credentials and port', 'http://user:[email protected]:9999/api/sessions/s1'],
+ ])('never leaves the owner origin for a %s target', (_label, originalUrl) => {
+ const target = new URL(forwardTarget(originalUrl, OWNER));
+ expect(target.origin).toBe('http://10.0.0.5:2785');
+ expect(target.pathname).toBe('/api/sessions/s1');
+ });
+
+ it('carries the owner base path when one is configured', () => {
+ expect(forwardTarget('/api/sessions/s1', 'http://10.0.0.5:2785/')).toBe('http://10.0.0.5:2785/api/sessions/s1');
+ });
+});
diff --git a/src/modules/session/session-proxy.interceptor.ts b/src/modules/session/session-proxy.interceptor.ts
index a899fbf8f..5703074e2 100644
--- a/src/modules/session/session-proxy.interceptor.ts
+++ b/src/modules/session/session-proxy.interceptor.ts
@@ -28,6 +28,23 @@ const RELAYED_RESPONSE_HEADERS = ['content-type', 'content-disposition', 'x-cont
/** Marks a request as already forwarded once. Whatever happens, it is never forwarded again. */
export const FORWARDED_HEADER = 'x-openwa-forwarded';
+/**
+ * The URL to forward to: ALWAYS the owner's origin, carrying only the request's path and query.
+ *
+ * The request target is caller-controlled. HTTP/1.1 allows the absolute form
+ * (`GET http://elsewhere/api/sessions/x HTTP/1.1`), Express matches the route for it, and
+ * `req.originalUrl` then holds that absolute URI — where `new URL(originalUrl, base)` DISCARDS the
+ * base entirely. Resolving that way would let an authenticated caller aim this node's forwarder at
+ * any origin they choose and receive the response, with the credentials of the call attached: a
+ * server-side request forgery that also exfiltrates the API key. Rebuilding from the owner's base
+ * makes the origin structurally un-influenceable rather than merely validated.
+ */
+export function forwardTarget(originalUrl: string, ownerNodeUrl: string): string {
+ const base = new URL(ownerNodeUrl);
+ const requested = new URL(originalUrl, base);
+ return new URL(`${requested.pathname}${requested.search}`, base).toString();
+}
+
/**
* Routes a session-scoped request to the node hosting the session's engine.
*
@@ -123,7 +140,7 @@ export class SessionProxyInterceptor implements NestInterceptor {
ownerNodeId: string,
ownerNodeUrl: string,
): Promise<void> {
- const target = new URL(request.originalUrl, ownerNodeUrl).toString();
+ const target = forwardTarget(request.originalUrl, ownerNodeUrl);
const timeoutMs = this.configService?.get<number>('session.proxyTimeoutMs', 60_000) ?? 60_000;
const headers: Record<string, string> = { [FORWARDED_HEADER]: this.ownership?.nodeId ?? '1' };
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 1a2a6f5e9..c3e756939 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1034,7 +1034,7 @@ describe('SessionService', () => {
// ── ownership claim lifecycle (multi-node) ────────────────────────
describe('ownership release', () => {
- type OwnershipStub = { claim: jest.Mock; release: jest.Mock };
+ type OwnershipStub = { claim: jest.Mock; release: jest.Mock; isHeldByOtherNode: jest.Mock };
// The trailing @Optional constructor dep the DI module deliberately omits; poked onto the
// instance like the other white-box seams in this file.
@@ -1042,6 +1042,8 @@ describe('SessionService', () => {
const ownership: OwnershipStub = {
claim: jest.fn().mockResolvedValue(claimResult),
release: jest.fn().mockResolvedValue(undefined),
+ // No live peer holds it unless a test says so — the single-node answer.
+ isHeldByOtherNode: jest.fn().mockResolvedValue(false),
};
Object.assign(service as unknown as Record<string, unknown>, { ownership });
return ownership;
@@ -1069,6 +1071,41 @@ describe('SessionService', () => {
expect(ownership.release).not.toHaveBeenCalled();
});
+ // start() is fenced by the claim, and logout/force-kill need a local engine — but stop() and
+ // delete() need neither, so a request landing on a non-owner (routine when ownership is
+ // configured and request routing is not) wrote DISCONNECTED over a peer's live session, or
+ // deleted its row and credentials, while the peer's engine kept running.
+ it.each([
+ ['stop', (s: SessionService) => s.stop('sess-uuid-1'), 'stop' as const],
+ ['delete', (s: SessionService) => s.delete('sess-uuid-1'), 'delete' as const],
+ ])('%s() refuses a session a LIVE peer holds, without touching the lifecycle', async (_verb, call, method) => {
+ const ownership = withOwnership();
+ Object.assign(ownership, { isHeldByOtherNode: jest.fn().mockResolvedValue(true) });
+ const lifecycleSpy = jest.spyOn(lifecycle, method).mockResolvedValue(createMockSession());
+
+ await expect(call(service)).rejects.toBeInstanceOf(ConflictException);
+
+ expect(lifecycleSpy).not.toHaveBeenCalled();
+ expect(ownership.release).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['stop', (s: SessionService) => s.stop('sess-uuid-1'), 'stop' as const],
+ ['delete', (s: SessionService) => s.delete('sess-uuid-1'), 'delete' as const],
+ ])(
+ '%s() proceeds when the foreign claim has LAPSED — taking over is what the rule allows',
+ async (_v, call, method) => {
+ const ownership = withOwnership();
+ Object.assign(ownership, { isHeldByOtherNode: jest.fn().mockResolvedValue(false) });
+ const lifecycleSpy = jest.spyOn(lifecycle, method).mockResolvedValue(createMockSession());
+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(false);
+
+ await call(service);
+
+ expect(lifecycleSpy).toHaveBeenCalledWith('sess-uuid-1');
+ },
+ );
+
it('start() answers 404, not 409, when the claim matched nothing because the session does not exist', async () => {
withOwnership(false);
(repository.findOne as jest.Mock).mockResolvedValue(null);
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 7fa518c22..e8d31a4cc 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -276,10 +276,31 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
/** Record removal + engine retirement + credential purge: owned by the lifecycle service. */
async delete(id: string): Promise<void> {
+ // Guarded at the call site rather than inside an always-awaited helper: without ownership there
+ // is nothing to check, and awaiting anything at all here would push the lifecycle call a
+ // microtask later — enough for an in-flight start to reach engine.initialize() before the
+ // retirement lands, which the pre-initialize retirement race deliberately prevents.
+ if (this.ownership) await this.assertNotHeldElsewhere(id);
await this.engineLifecycle.delete(id);
await this.ownership?.release(id);
}
+ /**
+ * Refuse a lifecycle write for a session a LIVE peer is running.
+ *
+ * start() is fenced by the claim itself, and logout/force-kill require a local engine, so they
+ * cannot act on a peer's session. stop() and delete() can: neither needs an engine here, so
+ * without this a request landing on the wrong node — routine when ownership is configured but
+ * request routing is not — writes DISCONNECTED over a peer's live session, or deletes its row and
+ * credentials outright, while the peer's engine keeps running. A LAPSED claim is not fenced: the
+ * holder may be gone, and taking over is exactly what the claim rule allows.
+ */
+ private async assertNotHeldElsewhere(id: string): Promise<void> {
+ if (await this.ownership?.isHeldByOtherNode(id)) {
+ throw new ConflictException(`Session ${id} is running on another node`);
+ }
+ }
+
async start(id: string): Promise<Session> {
// Claimed before the engine is launched, never after: launching first and discovering the
// session belongs elsewhere would already have opened a second connection to the account.
@@ -302,6 +323,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
async stop(id: string): Promise<Session> {
+ // Call-site guarded — see delete().
+ if (this.ownership) await this.assertNotHeldElsewhere(id);
const session = await this.engineLifecycle.stop(id);
// Handed back on the way out so a peer can pick it up immediately rather than waiting for the
// lease to lapse. Stop is the deliberate end of this process's ownership — but a start() that