Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(session): record which process owns each session
Yudhi Armyndharisfb7cdd4a937f
diff --git a/.env.example b/.env.exampleindex 1c94333ea..674d95efc 100644--- a/.env.example+++ b/.env.example@@ -379,6 +379,20 @@ WEBHOOK_SSRF_PROTECT=true## The official Docker image already ships ffmpeg, so there enabling the flag is all that is needed.# On a source install the binary must be present, otherwise the endpoints answer 503 and say so.+# ---------------------------------------------------------------------------+# Session ownership (multi-process deployments)+# ---------------------------------------------------------------------------+# A session's WhatsApp engine runs in exactly one process. These record which, so a second process+# booting beside a live one leaves its sessions alone instead of reporting them disconnected, and so+# two processes never race to start the same session — which would open the same account twice.+#+# A single-process deployment needs none of this: unclaimed rows read as free, which is what every+# existing row is.+# NODE_ID= # defaults to the hostname; must be STABLE across restarts+# SESSION_LEASE_TTL_MS=60000 # how long a claim survives unrenewed (default 60s) —+# # also the worst-case failover delay after an unclean exit+# SESSION_LEASE_HEARTBEAT_MS=20000 # renewal cadence (default 20s)+# MEDIA_CONVERSION_ENABLED=false # default false# FFMPEG_PATH=ffmpeg # absolute path, for a binary outside PATH# MEDIA_CONVERSION_TIMEOUT_MS=60000 # kill one conversion after this long (default 60s)diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e7162f88f..85c259cbf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Sessions record which process owns them.** A session's WhatsApp engine runs in exactly one+ process, but nothing recorded which, so a booting process reset every active-looking session on+ the assumption they were all its own leftovers. With one process that is correct. With two it is+ not: a booting replica reported a live peer's sessions as disconnected, and both replicas raced to+ auto-start the same sessions — two browsers writing one LocalAuth directory, which is how a+ session gets corrupted into a forced logout.++ `sessions` gains `nodeId`, `claimedAt` and `leaseExpiresAt`. A process claims a session before+ starting its engine and refuses with `409` when another node holds a live claim; a boot resets+ only what it may claim. The claim is a lease rather than a lock, so a process that dies without+ releasing does not strand its sessions — the claim stops being honoured once unrenewed, and a+ running owner keeps extending it. `NODE_ID` names the process and defaults to the hostname;+ `SESSION_LEASE_TTL_MS` and `SESSION_LEASE_HEARTBEAT_MS` tune the rest.++ Existing rows read as unclaimed, so a single-process deployment behaves exactly as before.++ This is ownership only. Request routing, fencing on every lifecycle path, cross-process bulk-batch+ state and WebSocket fan-out are not done, so **one API instance per session-data volume remains+ the supported topology** — `docs/13-horizontal-scaling.md` states precisely what is and is not in+ place.++- **Voice status.** `POST /api/sessions/:sessionId/status/send-voice` posts an audio status as avoice note on both engines. It carries no caption, because WhatsApp has nowhere to render one on astatus voice note.diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.mdindex 49b494f68..fbf9ac715 100644--- a/docs/13-horizontal-scaling.md+++ b/docs/13-horizontal-scaling.md@@ -1,20 +1,29 @@# 13 - Horizontal Scaling Guide-> ## ⚠️ DESIGN REFERENCE ONLY — NOT IMPLEMENTED+> ## ⚠️ PARTIALLY IMPLEMENTED — STILL DEPLOY `replicas: 1`>-> **OpenWA is currently a single-process, single-instance application.** Live WhatsApp-> engine state (browser + WebSocket + reconnect/error state) lives in an in-memory `Map`-> in `EngineRegistry`; there is **no** DB-backed session registry, **no** node-claim/lease,-> and **no** Socket.IO Redis adapter.+> **Supported topology remains exactly one API instance per session-data volume.** Do not+> run the multi-replica examples below yet.>-> **Supported topology:** exactly **one** API instance per session-data volume. Running-> multiple replicas against a shared session volume — as the multi-node examples below-> describe — will cause **two browsers to write the same WhatsApp LocalAuth directory and-> corrupt the session** (forced logout / ban), especially with `AUTO_START_SESSIONS=true`.+> **What now exists.** Sessions carry an owner (`nodeId`) and a renewed lease+> (`leaseExpiresAt`). A process claims a session before starting its engine and refuses+> when another node holds a live claim, so two replicas can no longer both launch the same+> session — which is what corrupted the shared LocalAuth directory. A booting process also+> resets only the sessions it may claim, instead of reporting a live peer's sessions as+> disconnected. Claims are released on a clean shutdown and expire otherwise, so failover+> does not depend on one. `NODE_ID` names the process; it defaults to the hostname and must+> be stable across restarts.>-> Everything in this guide (session-claim, node affinity, `replicas: 3`) is a **future-> design sketch**, retained for planning. Until it is implemented, deploy with-> **`replicas: 1`** for the OpenWA API service.+> **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.+> `BulkMessageService` keeps batch state in process and its boot reaper does not distinguish+> a peer's in-flight batches from its own. There is **no** Socket.IO Redis adapter, so a+> WebSocket client connected to one replica does not receive events raised on another.+>+> Everything below (node affinity, `replicas: 3`) remains a **design sketch** until those+> land.This guide explains a *proposed* design for deploying OpenWA in a horizontally scaled environment for high availability and increased capacity.diff --git a/openapi.json b/openapi.jsonindex b9ef67f48..a95328a41 100644--- a/openapi.json+++ b/openapi.json@@ -497,7 +497,7 @@"description": "Session not found"},"409": {- "description": "A credential teardown for the same session name is still in flight (e.g. a prior logout that owns destructive cleanup). Retryable — the body carries `code: SESSION_NAME_TEARDOWN_PENDING`; wait for it to settle and retry. No destructive side effect runs before this refusal."+ "description": "A credential teardown for the same session name is still in flight (e.g. a prior logout that owns destructive cleanup). Retryable — the body carries `code: SESSION_NAME_TEARDOWN_PENDING`; wait for it to settle and retry. No destructive side effect runs before this refusal. Also returned when another node currently holds this session's engine: only the owner may start it, and the claim is refused before any engine is launched, so no second connection to the account is opened."}},"summary": "Start a session and initialize WhatsApp connection",diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex c04917646..3aca09fd5 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -399,6 +399,26 @@ export default () => ({})(),},+ // Session ownership across processes. A session's engine runs in exactly one process; these+ // record which, so a second process booting beside a live one does not disturb its sessions.+ session: {+ // 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 || '',+ // 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: (() => {+ const n = parseInt(process.env.SESSION_LEASE_TTL_MS ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 60_000;+ })(),+ // Renewal cadence (default 20s). Comfortably under the TTL so a single missed tick — a slow+ // query, a brief database blip — never costs a live process its sessions.+ leaseHeartbeatMs: (() => {+ const n = parseInt(process.env.SESSION_LEASE_HEARTBEAT_MS ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 20_000;+ })(),+ },+// Server-side media conversion (opt-in): transcodes caller-supplied audio and video into the// shapes WhatsApp clients actually play, by running the ffmpeg binary. Nothing is converted// implicitly — only the explicit conversion endpoints use this.diff --git a/src/database/migrations/1785800000000-AddSessionOwnership.ts b/src/database/migrations/1785800000000-AddSessionOwnership.tsnew file mode 100644index 000000000..50294689c--- /dev/null+++ b/src/database/migrations/1785800000000-AddSessionOwnership.ts@@ -0,0 +1,58 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds `nodeId`, `claimedAt` and `leaseExpiresAt` to `sessions`, recording which process currently+ * hosts a session's engine.+ *+ * A session's engine lives in one process, but nothing said which. On startup the service reset+ * every session in an active status to `disconnected`, on the reasonable assumption that no engine+ * survives a restart — true of the only process, and false the moment a second one exists, where a+ * booting replica would flip the status of sessions another replica is actively running.+ *+ * The lease is what makes the claim safe to hold. A process that dies without releasing leaves rows+ * pointing at a node that is gone; rather than requiring a clean shutdown for recovery, a claim+ * simply stops being honoured once `leaseExpiresAt` passes, so any process may take it over. A+ * running owner keeps extending it.+ *+ * All three are NULL for every existing row, which reads as unclaimed — so a single-process+ * deployment behaves exactly as before: it claims what it finds and resets it as it always did.+ *+ * Hand-authored because `synchronize` is off for the `data` connection on PostgreSQL. Idempotent:+ * each column is probed independently, so a run interrupted between ALTERs still completes.+ */+export class AddSessionOwnership1785800000000 implements MigrationInterface {+ name = 'AddSessionOwnership1785800000000';++ private async hasColumn(queryRunner: QueryRunner, name: string): Promise<boolean> {+ if (queryRunner.connection.options.type === 'postgres') {+ const rows = (await queryRunner.query(+ `SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'sessions' AND column_name = '${name}'`,+ )) as unknown[];+ return rows.length > 0;+ }+ const rows = (await queryRunner.query(`PRAGMA table_info("sessions")`)) as Array<{ name: string }>;+ return rows.some(r => r.name === name);+ }++ public async up(queryRunner: QueryRunner): Promise<void> {+ const timestamp = queryRunner.connection.options.type === 'postgres' ? 'TIMESTAMP' : 'datetime';+ if (!(await this.hasColumn(queryRunner, 'nodeId'))) {+ await queryRunner.query(`ALTER TABLE "sessions" ADD COLUMN "nodeId" varchar(190) NULL`);+ }+ if (!(await this.hasColumn(queryRunner, 'claimedAt'))) {+ await queryRunner.query(`ALTER TABLE "sessions" ADD COLUMN "claimedAt" ${timestamp} NULL`);+ }+ if (!(await this.hasColumn(queryRunner, 'leaseExpiresAt'))) {+ await queryRunner.query(`ALTER TABLE "sessions" ADD COLUMN "leaseExpiresAt" ${timestamp} NULL`);+ }+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ for (const column of ['leaseExpiresAt', 'claimedAt', 'nodeId']) {+ if (await this.hasColumn(queryRunner, column)) {+ await queryRunner.query(`ALTER TABLE "sessions" DROP COLUMN "${column}"`);+ }+ }+ }+}diff --git a/src/modules/session/entities/session.entity.ts b/src/modules/session/entities/session.entity.tsindex df21ab905..b8f49226d 100644--- a/src/modules/session/entities/session.entity.ts+++ b/src/modules/session/entities/session.entity.ts@@ -51,6 +51,27 @@ export class Session {@Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })lastActiveAt!: Date | null;+ /**+ * Which process currently hosts this session's engine, or NULL when nobody does.+ *+ * A session's engine lives in exactly one process. Recording the owner is what lets a booting+ * process tell "my own leftovers, which really are dead" from "another process's live session",+ * which it previously could not and so reset both.+ */+ @Column({ type: 'varchar', length: 190, nullable: true })+ nodeId!: string | null;++ @Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })+ claimedAt!: Date | 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 shutdown+ * to recover; a running owner keeps extending it.+ */+ @Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })+ leaseExpiresAt!: Date | null;+@CreateDateColumn()createdAt!: Date;diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.tsindex e4a0c55e2..3b11b7b9b 100644--- a/src/modules/session/logout-teardown-race.spec.ts+++ b/src/modules/session/logout-teardown-race.spec.ts@@ -36,6 +36,9 @@ function createMockSession(overrides: Partial<Session> = {}): Session {proxyType: null,connectedAt: null,lastActiveAt: null,+ nodeId: null,+ claimedAt: null,+ leaseExpiresAt: null,createdAt: new Date(),updatedAt: new Date(),...overrides,diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.tsnew file mode 100644index 000000000..1f1d9b83f--- /dev/null+++ b/src/modules/session/session-ownership.service.spec.ts@@ -0,0 +1,219 @@+import { DataSource, Repository } from 'typeorm';+import { SessionOwnershipService } from './session-ownership.service';+import { Session } from './entities/session.entity';+import { SessionStatus } from './entities/session.entity';++/**+ * Run against a real in-memory database rather than a mocked repository, because the part that has+ * to be right is the SQL: the claim is a conditional UPDATE, and whether two processes can both+ * win a race depends on the WHERE clause actually filtering. A mock would agree with whatever the+ * query builder was asked to do and prove nothing about the outcome.+ */+describe('SessionOwnershipService', () => {+ let dataSource: DataSource;+ let sessions: Repository<Session>;++ const nodeConfig = (nodeId: string, leaseTtlMs = 60_000) =>+ ({+ get: (key: string) => ({ 'session.nodeId': nodeId, 'session.leaseTtlMs': leaseTtlMs })[key as string],+ }) as never;++ const service = (nodeId: string, leaseTtlMs?: number): SessionOwnershipService =>+ new SessionOwnershipService(sessions, nodeConfig(nodeId, leaseTtlMs));++ const seed = async (overrides: Partial<Session> = {}): Promise<Session> =>+ sessions.save(+ sessions.create({+ name: `s-${Math.floor(performance.now() * 1000)}-${overrides.nodeId ?? 'free'}`,+ status: SessionStatus.READY,+ config: {},+ ...overrides,+ }),+ );++ beforeAll(async () => {+ dataSource = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [Session],+ synchronize: true,+ });+ await dataSource.initialize();+ sessions = dataSource.getRepository(Session);+ });++ afterAll(async () => {+ await dataSource.destroy();+ });++ afterEach(async () => {+ await sessions.clear();+ });++ describe('claiming', () => {+ it('claims a session nobody holds, recording this node and a future expiry', async () => {+ const session = await seed();++ await expect(service('node-a').claim(session.id)).resolves.toBe(true);++ const stored = await sessions.findOneByOrFail({ id: session.id });+ expect(stored.nodeId).toBe('node-a');+ expect(stored.claimedAt).toBeInstanceOf(Date);+ expect(stored.leaseExpiresAt!.getTime()).toBeGreaterThan(Date.now());+ });++ // The whole point: the second process must lose, and must lose in the database rather than by+ // having read a stale row a moment earlier.+ it('refuses a session another node holds on a live lease', async () => {+ const session = await seed();+ await service('node-a').claim(session.id);++ await expect(service('node-b').claim(session.id)).resolves.toBe(false);+ expect((await sessions.findOneByOrFail({ id: session.id })).nodeId).toBe('node-a');+ });++ it('lets a node re-claim what it already holds, so a restart is not blocked by itself', async () => {+ const session = await seed();+ const node = service('node-a');+ await node.claim(session.id);++ await expect(node.claim(session.id)).resolves.toBe(true);+ });++ // A process that dies without releasing must not strand its sessions forever.+ it('takes over once the holder’s lease has lapsed', async () => {+ const session = await seed({+ nodeId: 'node-a',+ claimedAt: new Date(Date.now() - 120_000),+ leaseExpiresAt: new Date(Date.now() - 60_000),+ });++ await expect(service('node-b').claim(session.id)).resolves.toBe(true);+ expect((await sessions.findOneByOrFail({ id: session.id })).nodeId).toBe('node-b');+ });++ it('only one of two nodes racing for the same free session wins', async () => {+ const session = await seed();++ const results = await Promise.all([service('node-a').claim(session.id), service('node-b').claim(session.id)]);++ expect(results.filter(Boolean)).toHaveLength(1);+ });+ });++ describe('releasing', () => {+ it('frees the session so a peer can take it without waiting for the lease', async () => {+ const session = await seed();+ const nodeA = service('node-a');+ await nodeA.claim(session.id);++ await nodeA.release(session.id);++ const stored = await sessions.findOneByOrFail({ id: session.id });+ expect(stored.nodeId).toBeNull();+ expect(stored.leaseExpiresAt).toBeNull();+ await expect(service('node-b').claim(session.id)).resolves.toBe(true);+ });++ // Releasing must be scoped to what this node holds, or a shutting-down process would hand away+ // a peer's live session.+ it('does not release a session another node holds', async () => {+ const session = await seed();+ await service('node-a').claim(session.id);++ await service('node-b').release(session.id);++ expect((await sessions.findOneByOrFail({ id: session.id })).nodeId).toBe('node-a');+ });++ it('releases everything held, on the way down', async () => {+ const [one, two] = [await seed(), await seed()];+ const nodeA = service('node-a');+ await nodeA.claim(one.id);+ await nodeA.claim(two.id);++ await nodeA.releaseAll();++ expect(nodeA.ownedIds()).toEqual([]);+ expect((await sessions.findOneByOrFail({ id: one.id })).nodeId).toBeNull();+ expect((await sessions.findOneByOrFail({ id: two.id })).nodeId).toBeNull();+ });+ });++ describe('renewing', () => {+ it('pushes the expiry out, so a busy node does not lose what it is running', async () => {+ const session = await seed();+ const nodeA = service('node-a', 5_000);+ await nodeA.claim(session.id);+ const first = (await sessions.findOneByOrFail({ id: session.id })).leaseExpiresAt!;++ await new Promise(resolve => setTimeout(resolve, 25));+ await nodeA.renew();++ const renewed = (await sessions.findOneByOrFail({ id: session.id })).leaseExpiresAt!;+ expect(renewed.getTime()).toBeGreaterThan(first.getTime());+ });++ /**+ * A node that lost a session must stop extending it. Renewal only writes `leaseExpiresAt`, so+ * the evidence is that value staying put — a stale node refreshing a peer's lease would keep+ * the peer's claim alive on the strength of a process that no longer owns anything.+ */+ it('never renews a session it no longer holds', async () => {+ const session = await seed();+ const nodeA = service('node-a');+ await nodeA.claim(session.id);+ // A peer took over after the lease lapsed; this node still has it in its own set.+ // Deliberately far from the TTL a renewal would write, so an unscoped renew is visible.+ // Matching the TTL would let both land on the same millisecond and read as "unchanged".+ const peerExpiry = new Date(Date.now() + 600_000);+ await sessions.update({ id: session.id }, { nodeId: 'node-b', leaseExpiresAt: peerExpiry });++ await nodeA.renew();++ const stored = await sessions.findOneByOrFail({ id: session.id });+ expect(stored.nodeId).toBe('node-b');+ expect(stored.leaseExpiresAt!.getTime()).toBe(peerExpiry.getTime());+ });+ });++ describe('what a booting process may reset', () => {+ const now = new Date();++ it('leaves alone a session another node holds on a live lease', () => {+ expect(+ service('node-b').ownedByOtherLiveNode(+ { nodeId: 'node-a', leaseExpiresAt: new Date(now.getTime() + 60_000) },+ now,+ ),+ ).toBe(true);+ });++ it('reclaims its own rows, which really are dead after a restart', () => {+ expect(+ service('node-a').ownedByOtherLiveNode(+ { nodeId: 'node-a', leaseExpiresAt: new Date(now.getTime() + 60_000) },+ now,+ ),+ ).toBe(false);+ });++ it('reclaims an unowned row and one whose lease has lapsed', () => {+ const node = service('node-b');+ expect(node.ownedByOtherLiveNode({ nodeId: null, leaseExpiresAt: null }, now)).toBe(false);+ expect(node.ownedByOtherLiveNode({ nodeId: 'node-a', leaseExpiresAt: new Date(now.getTime() - 1) }, now)).toBe(+ false,+ );+ });+ });++ describe('node identity', () => {+ it('falls back to the hostname when nothing is configured, and never to the pid', () => {+ const bare = new SessionOwnershipService(sessions);+ expect(bare.nodeId).toBeTruthy();+ // A pid-derived id would never match after a restart, so a process could not recognise — and+ // therefore could not reset — its own leftover rows.+ expect(bare.nodeId).not.toContain(String(process.pid));+ });+ });+});diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.tsnew file mode 100644index 000000000..55666f367--- /dev/null+++ b/src/modules/session/session-ownership.service.ts@@ -0,0 +1,181 @@+import { Injectable, Optional } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { ConfigService } from '@nestjs/config';+import { hostname } from 'node:os';+import { In, IsNull, LessThan, Repository } from 'typeorm';+import { Session } from './entities/session.entity';+import { createLogger } from '../../common/services/logger.service';+import { DateTransformer } from '../../common/transformers/date.transformer';++/**+ * Who currently hosts each session's engine.+ *+ * A session's engine runs in exactly one process. Nothing recorded which, so a booting process had+ * to assume every active-looking session was its own leftover and reset it — correct while there is+ * only one process, and destructive the moment a second one boots beside a live peer.+ *+ * The claim is a lease rather than a lock. A process that dies without releasing would otherwise+ * strand its sessions forever, so a claim simply stops being honoured once it goes unrenewed; a+ * running owner keeps extending it. That makes recovery automatic and bounded by the TTL instead of+ * conditional on a clean shutdown.+ *+ * NOTE: this establishes ownership. It does not yet route a request to the owning node, nor fence+ * every lifecycle path — see the horizontal-scaling documentation for what remains.+ */+@Injectable()+export class SessionOwnershipService {+ private readonly logger = createLogger('SessionOwnershipService');+ private heartbeat?: ReturnType<typeof setInterval>;+ /** Sessions this process believes it owns, so the heartbeat knows what to renew. */+ private readonly owned = new Set<string>();++ constructor(+ @InjectRepository(Session, 'data')+ private readonly sessions: Repository<Session>,+ @Optional()+ private readonly configService?: ConfigService,+ ) {}++ /**+ * This process's identity, stable across restarts.+ *+ * Deliberately not tied to the pid: a restarted process must recognise its own previous rows in+ * order to reset them, and a pid never matches after a restart. The hostname is stable for the+ * lifetime of a container or a host; where that is not the right boundary, `NODE_ID` overrides it.+ */+ get nodeId(): string {+ return this.configService?.get<string>('session.nodeId') || process.env.NODE_ID || hostname();+ }++ private get leaseTtlMs(): number {+ return this.configService?.get<number>('session.leaseTtlMs') ?? 60_000;+ }++ private get heartbeatMs(): number {+ return this.configService?.get<number>('session.leaseHeartbeatMs') ?? 20_000;+ }++ /**+ * A session is takeable when nobody holds it, when this process already holds it, or when the+ * holder's lease has lapsed. Expressed as a `where` fragment so the same rule drives the boot+ * reset, the auto-start scan and the claim itself — three places that must not disagree.+ */+ claimableWhere(now = new Date()): Array<Record<string, unknown>> {+ return [{ nodeId: IsNull() }, { nodeId: this.nodeId }, { leaseExpiresAt: LessThan(now) }];+ }++ /** Session ids this process may take over, out of the ones given. */+ async claimable(ids: string[]): Promise<string[]> {+ if (ids.length === 0) return [];+ const rows = await this.sessions.find({+ where: this.claimableWhere().map(clause => ({ ...clause, id: In(ids) })),+ select: { id: true },+ });+ return rows.map(row => row.id);+ }++ /**+ * Take ownership, returning false when another live process holds it.+ *+ * The update is conditional on the same predicate the read used, so two processes racing on the+ * same free session cannot both succeed: the second one's UPDATE matches no row, because the+ * first has already written its own `nodeId` and a future expiry. Deciding on the read alone+ * would let both pass.+ */+ async claim(sessionId: string): Promise<boolean> {+ const now = new Date();+ const result = await this.sessions+ .createQueryBuilder()+ .update(Session)+ .set({ nodeId: this.nodeId, claimedAt: now, leaseExpiresAt: new Date(now.getTime() + this.leaseTtlMs) })+ .where('id = :id', { id: sessionId })+ // `now` goes through the column's own transformer. Raw SQL bypasses it, and the stored form+ // is not a Date on every dialect — SQLite keeps an ISO string — so an untransformed parameter+ // compares against the wrong representation and the clause silently never matches. That would+ // not fail loudly: expired claims would simply never be taken over, stranding every session a+ // crashed process was holding.+ .andWhere('("nodeId" IS NULL OR "nodeId" = :me OR "leaseExpiresAt" < :now)', {+ me: this.nodeId,+ now: DateTransformer.to(now),+ })+ .execute();++ const claimed = (result.affected ?? 0) > 0;+ if (claimed) this.owned.add(sessionId);+ else this.logger.warn('Session is held by another node', { sessionId, nodeId: this.nodeId });+ return claimed;+ }++ /** Give a session up, so a peer can take it without waiting for the lease to lapse. */+ async release(sessionId: string): Promise<void> {+ this.owned.delete(sessionId);+ await this.sessions+ .createQueryBuilder()+ .update(Session)+ .set({ nodeId: null, claimedAt: null, leaseExpiresAt: null })+ .where('id = :id AND "nodeId" = :me', { id: sessionId, me: this.nodeId })+ .execute();+ }++ /** Release everything this process holds, on the way down. */+ async releaseAll(): Promise<void> {+ const ids = [...this.owned];+ this.owned.clear();+ if (ids.length === 0) return;+ await this.sessions+ .createQueryBuilder()+ .update(Session)+ .set({ nodeId: null, claimedAt: null, leaseExpiresAt: null })+ .where({ id: In(ids), nodeId: this.nodeId })+ .execute();+ this.logger.log(`Released ${ids.length} session claim(s) on shutdown`, { nodeId: this.nodeId });+ }++ /** Begin renewing this process's leases. Idempotent. */+ startHeartbeat(): void {+ if (this.heartbeat) return;+ this.heartbeat = setInterval(() => {+ void this.renew();+ }, this.heartbeatMs);+ // Never hold the process open: a lease that stops being renewed is exactly what shutdown means.+ this.heartbeat.unref?.();+ }++ stopHeartbeat(): void {+ if (!this.heartbeat) return;+ clearInterval(this.heartbeat);+ this.heartbeat = undefined;+ }++ /** Push every held lease out by another TTL. */+ async renew(): Promise<void> {+ const ids = [...this.owned];+ if (ids.length === 0) return;+ try {+ await this.sessions+ .createQueryBuilder()+ .update(Session)+ .set({ leaseExpiresAt: new Date(Date.now() + this.leaseTtlMs) })+ .where({ id: In(ids), nodeId: this.nodeId })+ .execute();+ } catch (error) {+ // A failed renewal is survivable — the next tick tries again, and the TTL is long enough to+ // absorb a transient database blip. Throwing here would take down the interval instead.+ this.logger.warn('Failed to renew session leases', {+ nodeId: this.nodeId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }++ /** For the boot reset, which must run before anything is claimed. */+ ownedByOtherLiveNode(session: Pick<Session, 'nodeId' | 'leaseExpiresAt'>, now = new Date()): boolean {+ if (!session.nodeId || session.nodeId === this.nodeId) return false;+ return session.leaseExpiresAt != null && session.leaseExpiresAt > now;+ }++ /** Test seam: what this process currently believes it holds. */+ ownedIds(): string[] {+ return [...this.owned];+ }+}diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex 5aa4fad37..4268506b1 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -23,6 +23,9 @@ describe('SessionController — create() response contract', () => {proxyType: 'http',connectedAt: null,lastActiveAt: null,+ nodeId: null,+ claimedAt: null,+ leaseExpiresAt: null,createdAt: new Date('2026-01-01T00:00:00Z'),updatedAt: new Date('2026-01-01T00:00:00Z'),};@@ -106,6 +109,9 @@ describe('SessionController — logout() audit + error forwarding contract', ()proxyType: null,connectedAt: null,lastActiveAt: null,+ nodeId: null,+ claimedAt: 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.controller.ts b/src/modules/session/session.controller.tsindex 8de810a6c..53dbcf3ce 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -141,7 +141,9 @@ export class SessionController {'A credential teardown for the same session name is still in flight (e.g. a prior logout ' +'that owns destructive cleanup). Retryable — the body carries `code: ' +'SESSION_NAME_TEARDOWN_PENDING`; wait for it to settle and retry. No destructive side ' +- 'effect runs before this refusal.',+ 'effect runs before this refusal. Also returned when another node currently holds this ' ++ "session's engine: only the owner may start it, and the claim is refused before any engine " ++ 'is launched, so no second connection to the account is opened.',})async start(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {const session = await this.sessionService.start(id);diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.tsindex f0314c31f..0e0b94970 100644--- a/src/modules/session/session.module.ts+++ b/src/modules/session/session.module.ts@@ -6,6 +6,7 @@ import { SessionService } from './session.service';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 { MessageProjector } from './message-projector.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';@@ -28,6 +29,7 @@ import { ChatMediaModule } from '../chat-media/chat-media.module';PresenceStore,SessionLidResolver,SessionLivenessWatchdog,+ SessionOwnershipService,MessageProjector,],exports: [SessionService, MessageProjector],diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 59fd63755..339e46814 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -68,6 +68,9 @@ function createMockSession(overrides: Partial<Session> = {}): Session {proxyType: null,connectedAt: null,lastActiveAt: null,+ nodeId: null,+ claimedAt: null,+ leaseExpiresAt: null,createdAt: new Date(),updatedAt: new Date(),...overrides,@@ -5221,9 +5224,12 @@ describe('SessionService', () => {await service.onModuleInit();- expect(repository.update).toHaveBeenCalledWith(expect.objectContaining({ status: expect.anything() as string }), {- status: SessionStatus.DISCONNECTED,- });+ // The `where` is now a list of OR clauses (one per way a session can be claimable), which for+ // a process with no ownership service is the single unrestricted clause it always was.+ expect(repository.update).toHaveBeenCalledWith(+ [expect.objectContaining({ status: expect.anything() as string })],+ { status: SessionStatus.DISCONNECTED },+ );});it('treats ACTION_REQUIRED as an active status that gets reset on startup', async () => {@@ -5234,8 +5240,8 @@ describe('SessionService', () => {// 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];+ const calls = (repository.update as jest.Mock).mock.calls as Array<[Array<{ status: { value: unknown } }>]>;+ const where = calls[0][0][0];expect(where.status.value).toEqual(expect.arrayContaining([SessionStatus.ACTION_REQUIRED]));});});diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex b1b45a2f0..cd88c106f 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -21,6 +21,7 @@ import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';import { PresenceStore, type ChatPresence } from './presence-store.service';import { SessionEngineLifecycle } from './session-engine-lifecycle.service';+import { SessionOwnershipService } from './session-ownership.service';import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';import { resolveFeatureFlags } from '../../config/feature-flags';@@ -78,11 +79,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatprivate readonly engineLifecycle: SessionEngineLifecycle,@Optional()private readonly configService?: ConfigService,+ // Trailing @Optional, like configService: the running app always provides it, while the+ // direct-construction unit tests omit it — every use below is `?.`-guarded, so a session simply+ // behaves as unowned there, which is what a single-process deployment is anyway.+ @Optional()+ private readonly ownership?: SessionOwnershipService,) {}/**- * On backend startup, reset all active session statuses to disconnected- * because the engines are not running yet after restart+ * On startup, mark as disconnected the sessions whose engines this process was running, since no+ * engine survives a restart.+ *+ * Scoped to what this process may claim. An active status means "an engine is running somewhere",+ * and resetting all of them assumed that somewhere was always here — true of a single process,+ * and wrong beside a live peer, whose sessions would be reported disconnected while they are+ * serving traffic. A row held by another node with an unexpired lease is therefore left alone.*/async onModuleInit(): Promise<void> {const activeStatuses = [@@ -93,8 +104,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatSessionStatus.ACTION_REQUIRED,];+ const claimable = this.ownership?.claimableWhere() ?? [{}];const result = await this.sessionRepository.update(- { status: In(activeStatuses) },+ claimable.map(clause => ({ ...clause, status: In(activeStatuses) })),{ status: SessionStatus.DISCONNECTED },);@@ -102,6 +114,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatthis.logger.log(`Reset ${result.affected} session(s) to disconnected on startup`, {action: 'startup_reset',affected: result.affected,+ nodeId: this.ownership?.nodeId,});}}@@ -112,11 +125,18 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// The watchdog owns the probe cadence and failure counting; a session it proves dead comes// back through the same disconnect path an engine-reported drop uses.this.watchdog.start((id, engine, reason) => this.engineLifecycle.handleEngineDisconnected(id, engine, reason));+ // Renewal runs regardless of auto-start: a session started through the API later is claimed the+ // same way and must keep its lease alive.+ this.ownership?.startHeartbeat();if (!resolveFeatureFlags(this.configService).autoStartSessions) return;+ // Restricted to sessions this node may claim. Without it every replica scans the same rows and+ // races to launch the same engines, which is a WhatsApp account being opened twice, not merely+ // duplicated work.+ const claimable = this.ownership?.claimableWhere() ?? [{}];const sessions = await this.sessionRepository.find({- where: { phone: Not(IsNull()), status: SessionStatus.DISCONNECTED },+ where: claimable.map(clause => ({ ...clause, phone: Not(IsNull()), status: SessionStatus.DISCONNECTED })),});if (sessions.length === 0) return;@@ -152,8 +172,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// Stop the watchdog FIRST (before any teardown below can hang): no new probe/disconnect handling// may start mid-shutdown. stop() is idempotent, so a second onModuleDestroy call stays safe.this.watchdog.stop();+ this.ownership?.stopHeartbeat();// Reconnect timers + engine teardown belong to the lifecycle owner.await this.engineLifecycle.shutdown();+ // Released only after the engines are actually down, so a peer never claims a session this+ // process is still holding open.+ await this.ownership?.releaseAll();}async create(dto: CreateSessionDto): Promise<Session> {@@ -242,15 +266,25 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat/** Record removal + engine retirement + credential purge: owned by the lifecycle service. */async delete(id: string): Promise<void> {- return this.engineLifecycle.delete(id);+ await this.engineLifecycle.delete(id);+ await this.ownership?.release(id);}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.+ if (this.ownership && !(await this.ownership.claim(id))) {+ throw new ConflictException(`Session ${id} is running on another node`);+ }return this.engineLifecycle.start(id);}async stop(id: string): Promise<Session> {- return this.engineLifecycle.stop(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.+ await this.ownership?.release(id);+ return session;}/** See SessionEngineLifecycle.logout() for the full unlink/502 contract. */