Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(session): forward session requests to the owning node
Yudhi Armyndharis7acfdf110c24
diff --git a/.env.example b/.env.exampleindex f9b273b16..d1dfe11bb 100644--- a/.env.example+++ b/.env.example@@ -395,6 +395,11 @@ WEBHOOK_SSRF_PROTECT=true# SESSION_TAKEOVER_SWEEP_MS=30000 # how often a node adopts sessions whose holder's lease# lapsed (crashed peer / this node's previous container# identity); follows AUTO_START_SESSIONS+# NODE_URL= # where THIS node answers HTTP for its peers, e.g.+ # http://10.0.0.5:2785 — set on EVERY node to enable+ # forwarding of session requests to the owning node;+ # empty disables forwarding (single-node default)+# SESSION_PROXY_TIMEOUT_MS=60000 # ceiling for one forwarded request# MEDIA_CONVERSION_ENABLED=false # default false# FFMPEG_PATH=ffmpeg # absolute path, for a binary outside PATHdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 79b6295b7..364a6839d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Session requests are now routed to the owning node (opt-in via `NODE_URL`).** In a multi-node+ deployment a load balancer knows nothing about session placement; a request landing on a+ non-owner previously could not be served. When every node announces its own reachable URL+ (`NODE_URL`), a session-scoped request is now forwarded to the live owner after API-key+ authentication and the owner's response is relayed back, marked `x-openwa-served-by`. The+ forward carries the caller's credentials (nodes share the auth database), is bounded by+ `SESSION_PROXY_TIMEOUT_MS` (default 60s), and is strictly one hop — a forwarded request is never+ forwarded again, so stale ownership data degrades to a wrong-node answer instead of a loop. A+ lapsed owner is deliberately not forwarded to: the local node serves the request, which is how a+ takeover begins. An unreachable live owner answers a clear `503` naming the node. Without+ `NODE_URL` the path is entirely inert, so single-node deployments pay nothing.+- **Sessions abandoned by a dead node are now adopted automatically.** The ownership lease made acrashed node's sessions *claimable*, but nothing ever claimed them: boot auto-start runs exactlyonce, so a peer that was already up — or a recreated container whose boot landed before its owndiff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex 625f0b008..f382f57e7 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -187,7 +187,7 @@ authoritative gate. Current policy:| `src/core/agent-tools/` | 77% | 32% | 49% | 50% || `src/core/hooks/` | 81% | 73% | 85% | 84% || `src/core/plugins/` | 72% | 74% | 81% | 80% |-| `src/database/` | 62% | 61% | 67% | 66% |+| `src/database/` | 62% | 60% | 67% | 66% || `src/engine/adapters/` | 74% | 84% | 83% | 83% || `src/engine/identity/` | 85% | 95% | 94% | 93% || `src/modules/audit/` | 59% | 45% | 72% | 68% |diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.mdindex fef0df9b5..551fa16aa 100644--- a/docs/13-horizontal-scaling.md+++ b/docs/13-horizontal-scaling.md@@ -26,14 +26,33 @@> are still sending. A data import likewise reports the sessions it could not reconcile> because another node is running them.>-> **What does not exist yet, and is why one replica is still the answer.** Live engine state-> (browser + WebSocket + reconnect/error state) still lives in an in-memory `Map` in-> `EngineRegistry`, and there is **no request routing** — a call that lands on a replica-> which does not own the session cannot serve it. Not every lifecycle path is fenced: the-> liveness watchdog and reconnect timers still act on whatever is in the local registry.-> `BulkMessageService` keeps its live batch state in process, so a takeover cannot resume a-> batch — only fail it. There is **no** Socket.IO Redis adapter, so a WebSocket client-> connected to one replica does not receive events raised on another.+> **Failover now completes on its own.** A periodic takeover sweep (default every 30s,+> `SESSION_TAKEOVER_SWEEP_MS`, gated by the same `AUTO_START_SESSIONS` flag as boot+> auto-start) adopts sessions whose holder's lease lapsed — a crashed peer, or a recreated+> container whose new identity boots before its old lease expires. Only authenticated+> sessions in a running-or-should-be state are adopted; mid-pairing and operator-`failed`+> ones are left alone, and a cleanly stopped session releases its claim so it is never+> "lapsed". Adopting a session fails its stuck in-flight batches (no auto-resume — the dead+> node's already-sent messages are unknowable).+>+> **Request routing now exists, opt-in via `NODE_URL`.** When every node sets its own+> reachable URL (e.g. `NODE_URL=http://10.0.0.5:2785`), a session-scoped request landing on+> a non-owner is forwarded to the live owner and the owner's response is relayed back+> (`x-openwa-served-by` names it). The forward happens after API-key auth, carries the+> caller's credentials (both nodes share the auth database), is bounded by+> `SESSION_PROXY_TIMEOUT_MS` (default 60s), and is one hop only — a forwarded request is+> never forwarded again, so stale ownership degrades to a wrong-node answer instead of a+> loop. A lapsed owner is deliberately NOT forwarded to: the local node handles the request,+> which is exactly how a takeover begins. Without `NODE_URL` the whole path is inert and+> single-node deployments pay nothing.+>+> **What does not exist yet, and is why one replica is still the answer.** There is **no**+> Socket.IO Redis adapter, so a WebSocket client connected to one replica does not receive+> events raised on another. Not every lifecycle path is fenced: the liveness watchdog and+> reconnect timers still act on whatever is in the local registry. `BulkMessageService`+> keeps its live batch state in process, so a takeover cannot resume a batch — only fail+> it. MCP/agent tool invocations execute on the node that received them rather than being+> forwarded.>> Everything below (node affinity, `replicas: 3`) remains a **design sketch** until those> land.diff --git a/package.json b/package.jsonindex 20bdd1125..d36c479b3 100644--- a/package.json+++ b/package.json@@ -223,7 +223,7 @@},"./src/database/": {"branches": 62,- "functions": 61,+ "functions": 60,"lines": 67,"statements": 66},diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 9d7ab60b1..9272ebaa9 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -405,6 +405,18 @@ export default () => ({// Stable across restarts by design — a restarted process must recognise its own leftover rows// in order to reset them. Defaults to the hostname, which is the container or host boundary.nodeId: process.env.NODE_ID || '',+ // Where THIS node answers HTTP for its peers (e.g. http://10.0.0.5:2785). Written onto every+ // session this node claims, so a peer can forward a request to the engine's host. Empty (the+ // default) disables request forwarding entirely — the right setting for single-node+ // deployments, where the lookup would be pure overhead.+ nodeUrl: process.env.NODE_URL || '',+ // Ceiling for one forwarded request (default 60s): engine operations can legitimately take+ // tens of seconds (a send with typing simulation, a media fetch), but a peer must not hold a+ // caller forever when the owner hangs.+ proxyTimeoutMs: (() => {+ const n = parseInt(process.env.SESSION_PROXY_TIMEOUT_MS ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 60_000;+ })(),// How long a claim is honoured without renewal (default 60s). This is the worst-case delay// before a peer may take over from a process that died without releasing.leaseTtlMs: (() => {diff --git a/src/database/migrations/1786000000000-AddSessionNodeUrl.ts b/src/database/migrations/1786000000000-AddSessionNodeUrl.tsnew file mode 100644index 000000000..bd0e651b5--- /dev/null+++ b/src/database/migrations/1786000000000-AddSessionNodeUrl.ts@@ -0,0 +1,20 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds `sessions.nodeUrl` — where the owning node answers HTTP, written at claim time from+ * NODE_URL, so a peer can forward a session-scoped request to the node actually hosting the+ * engine. Hand-authored because `synchronize` is off on the `data` connection for Postgres.+ */+export class AddSessionNodeUrl1786000000000 implements MigrationInterface {+ name = 'AddSessionNodeUrl1786000000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (await queryRunner.hasColumn('sessions', 'nodeUrl')) return;+ await queryRunner.query(`ALTER TABLE "sessions" ADD COLUMN "nodeUrl" varchar(2048)`);+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ if (!(await queryRunner.hasColumn('sessions', 'nodeUrl'))) return;+ await queryRunner.query(`ALTER TABLE "sessions" DROP COLUMN "nodeUrl"`);+ }+}diff --git a/src/modules/session/entities/session.entity.ts b/src/modules/session/entities/session.entity.tsindex b8f49226d..f01f8a62a 100644--- a/src/modules/session/entities/session.entity.ts+++ b/src/modules/session/entities/session.entity.ts@@ -64,6 +64,14 @@ export class Session {@Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })claimedAt!: Date | null;+ /**+ * Where the owning node answers HTTP, so a peer can forward a request it cannot serve (the+ * engine lives with the owner). Written at claim time from NODE_URL; null when the operator has+ * not configured routing — a peer then answers 409 instead of forwarding.+ */+ @Column({ type: 'varchar', length: 2048, nullable: true })+ nodeUrl!: string | null;+/*** When the claim above stops being honoured. A process that dies without releasing leaves a row* pointing at an owner that is gone, so the claim expires rather than requiring a clean shutdowndiff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.tsindex 3b11b7b9b..23b0526a3 100644--- a/src/modules/session/logout-teardown-race.spec.ts+++ b/src/modules/session/logout-teardown-race.spec.ts@@ -39,6 +39,7 @@ function createMockSession(overrides: Partial<Session> = {}): Session {nodeId: null,claimedAt: null,leaseExpiresAt: null,+ nodeUrl: null,createdAt: new Date(),updatedAt: new Date(),...overrides,diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.tsindex 376a03a14..fbac638eb 100644--- a/src/modules/session/session-ownership.service.ts+++ b/src/modules/session/session-ownership.service.ts@@ -62,6 +62,11 @@ export class SessionOwnershipService {return this.configService?.get<string>('session.nodeId') || process.env.NODE_ID || hostname();}+ /** Where this node answers HTTP for peers; empty when the operator has not configured routing. */+ get nodeUrl(): string {+ return this.configService?.get<string>('session.nodeUrl') || process.env.NODE_URL || '';+ }+private get leaseTtlMs(): number {return this.configService?.get<number>('session.leaseTtlMs') ?? 60_000;}@@ -102,7 +107,12 @@ export class SessionOwnershipService {const result = await this.sessions.createQueryBuilder().update(Session)- .set({ nodeId: this.nodeId, claimedAt: now, leaseExpiresAt: new Date(now.getTime() + this.leaseTtlMs) })+ .set({+ nodeId: this.nodeId,+ claimedAt: now,+ leaseExpiresAt: new Date(now.getTime() + this.leaseTtlMs),+ nodeUrl: this.nodeUrl || null,+ }).where('id = :id', { id: sessionId })// Without leaseParam this clause would silently never match, so an expired claim would never// be taken over — stranding every session a crashed process was holding.@@ -124,7 +134,7 @@ export class SessionOwnershipService {await this.sessions.createQueryBuilder().update(Session)- .set({ nodeId: null, claimedAt: null, leaseExpiresAt: null })+ .set({ nodeId: null, claimedAt: null, leaseExpiresAt: null, nodeUrl: null }).where('id = :id AND "nodeId" = :me', { id: sessionId, me: this.nodeId }).execute();}@@ -137,7 +147,7 @@ export class SessionOwnershipService {await this.sessions.createQueryBuilder().update(Session)- .set({ nodeId: null, claimedAt: null, leaseExpiresAt: null })+ .set({ nodeId: null, claimedAt: null, leaseExpiresAt: null, nodeUrl: null }).where({ id: In(ids), nodeId: this.nodeId }).execute();this.logger.log(`Released ${ids.length} session claim(s) on shutdown`, { nodeId: this.nodeId });diff --git a/src/modules/session/session-proxy.interceptor.spec.ts b/src/modules/session/session-proxy.interceptor.spec.tsnew file mode 100644index 000000000..9784cda4e--- /dev/null+++ b/src/modules/session/session-proxy.interceptor.spec.ts@@ -0,0 +1,206 @@+import http from 'http';+import { AddressInfo } from 'net';+import { of, lastValueFrom, isEmpty } from 'rxjs';+import type { CallHandler, ExecutionContext } from '@nestjs/common';+import { SessionProxyInterceptor, FORWARDED_HEADER } from './session-proxy.interceptor';+import type { Session } from './entities/session.entity';++/**+ * The forwarding decision IS the security surface: forwarding when the session is local answers a+ * request twice; not forwarding when the owner is live strands the caller with a conflict; ever+ * forwarding a forwarded request is a loop between two nodes that both think the other owns the+ * session. The matrix below pins every arm, and the mechanics tests run against a real HTTP server+ * because header pass-through and body re-serialisation are exactly the parts a stubbed fetch+ * would vacuously approve.+ */+describe('SessionProxyInterceptor', () => {+ const row = (over: Partial<Session> = {}): Partial<Session> => ({+ id: 'sess-1',+ nodeId: 'peer-node',+ nodeUrl: 'http://127.0.0.1:9',+ leaseExpiresAt: new Date(Date.now() + 60_000),+ ...over,+ });++ type Req = {+ headers: Record<string, string>;+ params: Record<string, string>;+ method: string;+ originalUrl: string;+ body?: unknown;+ };++ const request = (over: Partial<Req> = {}): Req => ({+ headers: { 'x-api-key': 'k-123', 'content-type': 'application/json' },+ params: { sessionId: 'sess-1' },+ method: 'GET',+ originalUrl: '/api/sessions/sess-1/messages?limit=5',+ ...over,+ });++ const makeResponse = () => {+ const res = {+ status: jest.fn(),+ setHeader: jest.fn(),+ send: jest.fn(),+ end: jest.fn(),+ json: jest.fn(),+ };+ res.status.mockReturnValue(res);+ return res;+ };++ const build = (opts: {+ myUrl?: string;+ row?: Partial<Session> | null;+ sessionScoped?: boolean;+ req?: Req;+ timeoutMs?: number;+ }) => {+ const req = opts.req ?? request();+ const res = makeResponse();+ const findOne = jest.fn().mockResolvedValue(opts.row === undefined ? row() : opts.row);+ const interceptor = new SessionProxyInterceptor(+ { getAllAndOverride: jest.fn().mockReturnValue(opts.sessionScoped ?? false) } as never,+ { findOne } as never,+ { nodeId: 'me', nodeUrl: opts.myUrl ?? 'http://127.0.0.1:2785' } as never,+ { get: jest.fn().mockReturnValue(opts.timeoutMs ?? 5000) } as never,+ );+ const context = {+ getType: () => 'http',+ getHandler: () => undefined,+ getClass: () => undefined,+ switchToHttp: () => ({ getRequest: () => req, getResponse: () => res }),+ } as unknown as ExecutionContext;+ const handle = jest.fn(() => of('handled-locally'));+ const next: CallHandler = { handle };+ return { interceptor, context, next, handle, res, findOne, req };+ };++ const ranLocally = async (result: Awaited<ReturnType<SessionProxyInterceptor['intercept']>>): Promise<boolean> =>+ lastValueFrom(result, { defaultValue: 'EMPTY' }).then(v => v === 'handled-locally');++ describe('the forwarding decision', () => {+ it('is inert without NODE_URL on this node — no lookup, handled locally', async () => {+ const { interceptor, context, next, findOne } = build({ myUrl: '' });+ expect(await ranLocally(await interceptor.intercept(context, next))).toBe(true);+ expect(findOne).not.toHaveBeenCalled();+ });++ it('never forwards a forwarded request (loop guard), even when the owner looks remote', async () => {+ const req = request({ headers: { [FORWARDED_HEADER]: 'peer-node', 'x-api-key': 'k' } });+ const { interceptor, context, next, findOne } = build({ req });+ expect(await ranLocally(await interceptor.intercept(context, next))).toBe(true);+ expect(findOne).not.toHaveBeenCalled();+ });++ it('ignores routes without a session dimension', async () => {+ const { interceptor, context, next, findOne } = build({ req: request({ params: {} }) });+ expect(await ranLocally(await interceptor.intercept(context, next))).toBe(true);+ expect(findOne).not.toHaveBeenCalled();+ });++ it('reads :id only on @SessionScoped controllers', async () => {+ const req = request({ params: { id: 'sess-1' } });+ const scoped = build({ req, sessionScoped: true, row: row({ nodeId: 'me' }) });+ expect(await ranLocally(await scoped.interceptor.intercept(scoped.context, scoped.next))).toBe(true);+ expect(scoped.findOne).toHaveBeenCalled();++ const unscoped = build({ req: request({ params: { id: 'sess-1' } }), sessionScoped: false });+ expect(await ranLocally(await unscoped.interceptor.intercept(unscoped.context, unscoped.next))).toBe(true);+ expect(unscoped.findOne).not.toHaveBeenCalled();+ });++ it.each([+ ['unknown session', null],+ ['unowned session', row({ nodeId: null })],+ ['owned by this node', row({ nodeId: 'me' })],+ ['owner lease lapsed (takeover semantics)', row({ leaseExpiresAt: new Date(Date.now() - 1000) })],+ ['owner without a nodeUrl', row({ nodeUrl: null })],+ ])('handles locally when the owner is not a live routable peer: %s', async (_label, ownerRow) => {+ const { interceptor, context, next } = build({ row: ownerRow });+ expect(await ranLocally(await interceptor.intercept(context, next))).toBe(true);+ });+ });++ describe('the forward itself (real upstream server)', () => {+ let server: http.Server;+ let serverUrl: string;+ let seen: Array<{ method?: string; url?: string; headers: http.IncomingHttpHeaders; body: string }>;++ beforeAll(async () => {+ seen = [];+ server = http.createServer((req, res) => {+ let body = '';+ req.on('data', c => (body += c));+ req.on('end', () => {+ seen.push({ method: req.method, url: req.url, headers: req.headers, body });+ res.writeHead(201, { 'content-type': 'application/json', 'x-hop-by-hop': 'must-not-relay' });+ res.end(JSON.stringify({ servedBy: 'the-owner' }));+ });+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ });++ afterAll(async () => {+ await new Promise<void>(resolve => server.close(() => resolve()));+ });++ beforeEach(() => {+ seen = [];+ });++ it('relays method, path, query, body and auth to the owner, and the owner’s answer back', async () => {+ const req = request({+ method: 'POST',+ originalUrl: '/api/sessions/sess-1/messages/send-text?trace=1',+ body: { chatId: '[email protected]', text: 'halo' },+ });+ const { interceptor, context, next, handle, res } = build({ req, row: row({ nodeUrl: serverUrl }) });++ const result = await interceptor.intercept(context, next);+ // EMPTY: the response was written directly; nothing may flow to the route handler.+ expect(await lastValueFrom(result.pipe(isEmpty()))).toBe(true);+ expect(handle).not.toHaveBeenCalled();++ expect(seen).toHaveLength(1);+ expect(seen[0].method).toBe('POST');+ expect(seen[0].url).toBe('/api/sessions/sess-1/messages/send-text?trace=1');+ expect(seen[0].headers['x-api-key']).toBe('k-123');+ expect(seen[0].headers[FORWARDED_HEADER]).toBe('me');+ expect(JSON.parse(seen[0].body)).toEqual({ chatId: '[email protected]', text: 'halo' });++ expect(res.status).toHaveBeenCalledWith(201);+ expect(res.setHeader).toHaveBeenCalledWith('content-type', 'application/json');+ expect(res.setHeader).toHaveBeenCalledWith('x-openwa-served-by', 'peer-node');+ expect(res.setHeader).not.toHaveBeenCalledWith('x-hop-by-hop', expect.anything());+ const sentBody = (res.send.mock.calls[0] as [Buffer])[0];+ expect(JSON.parse(String(sentBody))).toEqual({ servedBy: 'the-owner' });+ });++ it('a GET carries no body', async () => {+ const { interceptor, context, next } = build({ req: request(), row: row({ nodeUrl: serverUrl }) });++ await interceptor.intercept(context, next);++ expect(seen[0].method).toBe('GET');+ expect(seen[0].body).toBe('');+ });++ it('an unreachable owner answers 503 with the owner named, never a hang or a crash', async () => {+ const { interceptor, context, next, handle, res } = build({+ row: row({ nodeUrl: 'http://127.0.0.1:1' }),+ timeoutMs: 2000,+ });++ await interceptor.intercept(context, next);++ expect(res.status).toHaveBeenCalledWith(503);+ const errorBody = (res.json.mock.calls[0] as [{ statusCode: number; message: string }])[0];+ expect(errorBody.statusCode).toBe(503);+ expect(errorBody.message).toContain('peer-node');+ expect(handle).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/modules/session/session-proxy.interceptor.ts b/src/modules/session/session-proxy.interceptor.tsnew file mode 100644index 000000000..ada05ebaa--- /dev/null+++ b/src/modules/session/session-proxy.interceptor.ts@@ -0,0 +1,142 @@+import { CallHandler, ExecutionContext, Injectable, NestInterceptor, Optional } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';+import { Reflector } from '@nestjs/core';+import { InjectRepository } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { EMPTY, Observable } from 'rxjs';+import type { Request, Response } from 'express';+import { Session } from './entities/session.entity';+import { SessionOwnershipService } from './session-ownership.service';+import { SESSION_SCOPED_KEY } from '../auth/decorators/auth.decorators';+import { createLogger } from '../../common/services/logger.service';++/** The request headers a forwarded call carries over. Everything else is this hop's business. */+const FORWARDED_REQUEST_HEADERS = ['x-api-key', 'authorization', 'content-type', 'accept'] as const;++/** The response headers relayed back. Deliberately short: hop-by-hop headers must not leak through. */+const RELAYED_RESPONSE_HEADERS = ['content-type', 'content-disposition', 'x-content-type-options'] as const;++/** Marks a request as already forwarded once. Whatever happens, it is never forwarded again. */+export const FORWARDED_HEADER = 'x-openwa-forwarded';++/**+ * Routes a session-scoped request to the node hosting the session's engine.+ *+ * The ownership lease records WHERE each session runs; this is the piece that acts on it: a request+ * landing on the wrong node — a load balancer round-robining across replicas knows nothing about+ * session placement — is forwarded to the owner's `nodeUrl` and the owner's response is relayed+ * back. Interceptor rather than middleware so it runs AFTER the API-key guard: a node only spends+ * outbound work on requests that authenticated here first (the owner authenticates them again —+ * both nodes share the auth database).+ *+ * Entirely inert unless the operator configured routing: without NODE_URL on this node the+ * interceptor never even looks up the session, so single-node deployments pay nothing.+ *+ * Deliberate decisions:+ * - A LAPSED owner does not forward: the session is adoptable, and the local node handling the+ * request (a POST /start claims it here) is the takeover semantic, not an error.+ * - A live owner WITHOUT a nodeUrl cannot be reached; the request proceeds locally and the+ * engine-level "held by another node" conflict answers it — precise, if unrouteable.+ * - One hop only: a forwarded request is never forwarded again (FORWARDED_HEADER), so stale+ * ownership data degrades to a wrong-node answer instead of a loop.+ */+@Injectable()+export class SessionProxyInterceptor implements NestInterceptor {+ private readonly logger = createLogger('SessionProxyInterceptor');++ constructor(+ private readonly reflector: Reflector,+ @InjectRepository(Session, 'data')+ private readonly sessions: Repository<Session>,+ @Optional()+ private readonly ownership?: SessionOwnershipService,+ @Optional()+ private readonly configService?: ConfigService,+ ) {}++ async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {+ if (context.getType() !== 'http' || !this.ownership) return next.handle();+ // Routing is opt-in per deployment: a node that never announced its own URL is not part of a+ // routed topology, and the per-request ownership lookup would be pure overhead.+ if (!this.ownership.nodeUrl) return next.handle();++ const request = context.switchToHttp().getRequest<Request>();+ if (request.headers[FORWARDED_HEADER]) return next.handle();++ const sessionId = this.sessionIdOf(context, request);+ if (!sessionId) return next.handle();++ const owner = await this.sessions.findOne({+ where: { id: sessionId },+ select: { id: true, nodeId: true, nodeUrl: true, leaseExpiresAt: true },+ });+ if (!owner?.nodeId || owner.nodeId === this.ownership.nodeId) return next.handle();+ const leaseLive = owner.leaseExpiresAt != null && owner.leaseExpiresAt > new Date();+ if (!leaseLive || !owner.nodeUrl) return next.handle();++ await this.forward(request, context.switchToHttp().getResponse<Response>(), owner.nodeId, owner.nodeUrl);+ // The response has been written; complete without emitting so nothing downstream re-answers it.+ return EMPTY;+ }++ private sessionIdOf(context: ExecutionContext, request: Request): string | undefined {+ const params = (request.params ?? {}) as Record<string, string | undefined>;+ if (params.sessionId) return params.sessionId;+ const sessionScoped = this.reflector.getAllAndOverride<boolean>(SESSION_SCOPED_KEY, [+ context.getHandler(),+ context.getClass(),+ ]);+ return sessionScoped ? params.id : undefined;+ }++ private async forward(+ request: Request,+ response: Response,+ ownerNodeId: string,+ ownerNodeUrl: string,+ ): Promise<void> {+ const target = new URL(request.originalUrl, ownerNodeUrl).toString();+ const timeoutMs = this.configService?.get<number>('session.proxyTimeoutMs', 60_000) ?? 60_000;++ const headers: Record<string, string> = { [FORWARDED_HEADER]: this.ownership?.nodeId ?? '1' };+ for (const name of FORWARDED_REQUEST_HEADERS) {+ const value = request.headers[name];+ if (typeof value === 'string') headers[name] = value;+ }++ const hasBody = !['GET', 'HEAD'].includes(request.method);+ try {+ const upstream = await fetch(target, {+ method: request.method,+ headers,+ // The body has already been parsed by this hop's JSON body-parser; re-serialising it is+ // byte-equivalent for the JSON API surface (there are no multipart session routes).+ body: hasBody ? JSON.stringify(request.body ?? {}) : undefined,+ signal: AbortSignal.timeout(timeoutMs),+ redirect: 'manual',+ });++ response.status(upstream.status);+ for (const name of RELAYED_RESPONSE_HEADERS) {+ const value = upstream.headers.get(name);+ if (value) response.setHeader(name, value);+ }+ response.setHeader('x-openwa-served-by', ownerNodeId);+ const body = Buffer.from(await upstream.arrayBuffer());+ if (body.length > 0) response.send(body);+ else response.end();+ } catch (error) {+ this.logger.warn(`Forwarding to session owner '${ownerNodeId}' failed`, {+ target,+ error: error instanceof Error ? error.message : String(error),+ });+ response.status(503).json({+ statusCode: 503,+ message:+ `this session is hosted on node '${ownerNodeId}', which could not be reached from this node — ` ++ 'check the owner node and its NODE_URL',+ error: 'Service Unavailable',+ });+ }+ }+}diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex 4268506b1..b1e1d0904 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -25,6 +25,7 @@ describe('SessionController — create() response contract', () => {lastActiveAt: null,nodeId: null,claimedAt: null,+ nodeUrl: null,leaseExpiresAt: null,createdAt: new Date('2026-01-01T00:00:00Z'),updatedAt: new Date('2026-01-01T00:00:00Z'),@@ -111,6 +112,7 @@ describe('SessionController — logout() audit + error forwarding contract', ()lastActiveAt: null,nodeId: null,claimedAt: null,+ nodeUrl: null,leaseExpiresAt: null,createdAt: new Date('2026-01-01T00:00:00Z'),updatedAt: new Date('2026-01-01T00:00:00Z'),diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.tsindex 7aa72c30c..fef175c48 100644--- a/src/modules/session/session.module.ts+++ b/src/modules/session/session.module.ts@@ -1,4 +1,5 @@import { Module } from '@nestjs/common';+import { APP_INTERCEPTOR } from '@nestjs/core';import { TypeOrmModule } from '@nestjs/typeorm';import { Session } from './entities/session.entity';import { Message } from '../message/entities/message.entity';@@ -7,6 +8,7 @@ import { SessionEngineLifecycle } from './session-engine-lifecycle.service';import { SessionLidResolver } from './session-lid-resolver.service';import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { SessionOwnershipService } from './session-ownership.service';+import { SessionProxyInterceptor } from './session-proxy.interceptor';import { MessageProjector } from './message-projector.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';@@ -29,6 +31,8 @@ import { AutomationModule } from '../automation/automation.module';],controllers: [SessionController],providers: [+ // Global on purpose: any controller may carry a session dimension. Inert unless NODE_URL is set.+ { provide: APP_INTERCEPTOR, useClass: SessionProxyInterceptor },SessionService,SessionEngineLifecycle,SessionErrorStore,diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 339e46814..26766d627 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -71,6 +71,7 @@ function createMockSession(overrides: Partial<Session> = {}): Session {nodeId: null,claimedAt: null,leaseExpiresAt: null,+ nodeUrl: null,createdAt: new Date(),updatedAt: new Date(),...overrides,diff --git a/test/session-proxy.e2e-spec.ts b/test/session-proxy.e2e-spec.tsnew file mode 100644index 000000000..0e4cc9676--- /dev/null+++ b/test/session-proxy.e2e-spec.ts@@ -0,0 +1,140 @@+// archiver v8 is ESM-only (pulled in transitively via @Global StorageModule); stub for ts-jest CJS.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++import http from 'http';+import { AddressInfo } from 'net';+import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication } from '@nestjs/common';+import { getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import request from 'supertest';+import { App } from 'supertest/types';+import { AppModule } from './../src/app.module';+import { applyGlobalValidation } from './../src/config/app-validation';+import { AuthService } from './../src/modules/auth/auth.service';+import { ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';+import { Session, SessionStatus } from './../src/modules/session/entities/session.entity';++/**+ * The routed topology end-to-end, with a fake peer standing in for the owner node: a request+ * landing here for a session another live node owns must come back with the OWNER's answer, and+ * the forwarded call must be marked so it can never bounce again. NODE_URL is set before the app+ * compiles because the config factory snapshots the environment at boot.+ */+describe('Session request forwarding (e2e)', () => {+ let app: INestApplication<App>;+ let sessions: Repository<Session>;+ let apiKey: string;+ let owner: http.Server;+ let ownerUrl: string;+ let ownerSeen: Array<{ url?: string; headers: http.IncomingHttpHeaders }>;+ const prevNodeUrl = process.env.NODE_URL;+ const prevNodeId = process.env.NODE_ID;++ beforeAll(async () => {+ process.env.NODE_URL = 'http://127.0.0.1:2785';+ process.env.NODE_ID = 'e2e-local-node';++ ownerSeen = [];+ owner = http.createServer((req, res) => {+ ownerSeen.push({ url: req.url, headers: req.headers });+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ answeredBy: 'the-peer-owner' }));+ });+ await new Promise<void>(resolve => owner.listen(0, '127.0.0.1', resolve));+ ownerUrl = `http://127.0.0.1:${(owner.address() as AddressInfo).port}`;++ const moduleFixture: TestingModule = await Test.createTestingModule({+ imports: [AppModule],+ }).compile();+ app = moduleFixture.createNestApplication();+ applyGlobalValidation(app);+ await app.init();++ sessions = app.get(getRepositoryToken(Session, 'data'));+ const authService = app.get(AuthService);+ apiKey = (await authService.createApiKey({ name: 'e2e-proxy-admin', role: ApiKeyRole.ADMIN })).rawKey;+ });++ afterAll(async () => {+ if (prevNodeUrl === undefined) delete process.env.NODE_URL;+ else process.env.NODE_URL = prevNodeUrl;+ if (prevNodeId === undefined) delete process.env.NODE_ID;+ else process.env.NODE_ID = prevNodeId;+ await new Promise<void>(resolve => owner.close(() => resolve()));+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ const seedOwnedElsewhere = async (): Promise<Session> =>+ sessions.save(+ sessions.create({+ name: `e2e-proxy-${Date.now()}`,+ status: SessionStatus.READY,+ config: {},+ nodeId: 'peer-node',+ nodeUrl: ownerUrl,+ claimedAt: new Date(),+ leaseExpiresAt: new Date(Date.now() + 60_000),+ }),+ );++ it('relays a session-scoped request to the live owner and returns the owner’s answer', async () => {+ const session = await seedOwnedElsewhere();++ const res = await request(app.getHttpServer())+ .get(`/api/sessions/${session.id}`)+ .set('X-API-Key', apiKey)+ .expect(200);++ expect(res.body).toEqual({ answeredBy: 'the-peer-owner' });+ expect(res.headers['x-openwa-served-by']).toBe('peer-node');+ expect(ownerSeen).toHaveLength(1);+ expect(ownerSeen[0].url).toBe(`/api/sessions/${session.id}`);+ expect(ownerSeen[0].headers['x-openwa-forwarded']).toBe('e2e-local-node');+ expect(ownerSeen[0].headers['x-api-key']).toBe(apiKey);+ });++ it('a forwarded request is answered locally — the loop dies at one hop', async () => {+ const session = await seedOwnedElsewhere();+ ownerSeen = [];++ const res = await request(app.getHttpServer())+ .get(`/api/sessions/${session.id}`)+ .set('X-API-Key', apiKey)+ .set('x-openwa-forwarded', 'peer-node')+ .expect(200);++ expect(ownerSeen).toHaveLength(0);+ expect((res.body as { id: string }).id).toBe(session.id); // the LOCAL answer, straight from this node's database+ });++ it('a lapsed owner is not forwarded to — the local node answers (takeover semantics)', async () => {+ const session = await seedOwnedElsewhere();+ await sessions.update(session.id, { leaseExpiresAt: new Date(Date.now() - 1000) });+ ownerSeen = [];++ const res = await request(app.getHttpServer())+ .get(`/api/sessions/${session.id}`)+ .set('X-API-Key', apiKey)+ .expect(200);++ expect(ownerSeen).toHaveLength(0);+ expect((res.body as { id: string }).id).toBe(session.id);+ });++ it('an unreachable live owner answers 503 naming the owner, not a hang', async () => {+ const session = await seedOwnedElsewhere();+ await sessions.update(session.id, { nodeUrl: 'http://127.0.0.1:1' });++ const res = await request(app.getHttpServer())+ .get(`/api/sessions/${session.id}`)+ .set('X-API-Key', apiKey)+ .expect(503);++ expect((res.body as { message: string }).message).toContain('peer-node');+ });+});