Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): key engine auth directories by session id

Yudhi Armyndharis3d7e3f9afdb9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a7545c0ed..3ae3f3aad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Engine auth directories are named after the session id instead of the session name, so two sessions whose names differ only in letter case no longer share one WhatsApp login, or wipe each other's, on a case-insensitive filesystem such as macOS APFS, Windows, or a Docker Desktop bind mount of either ([#1597](https://github.com/rmyndharis/OpenWA/issues/1597)). Existing directories are renamed at the first boot after the upgrade.
- The Baileys live path drops a message made only of sender-key distributions or message-history notices instead of delivering it as a bodyless `unknown` `message.received`; other messages it cannot type still arrive as `unknown` ([#1568](https://github.com/rmyndharis/OpenWA/issues/1568)). Thanks @berodcdev for the report.
- A Baileys reconnect loop is observable through `lastError` on the session, a `session.reconnect_loop` webhook every fifth attempt and reconnect metrics; a QR left unscanned is not reported as one ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
- A Baileys connection attempt refused at the WebSocket upgrade is closed and retried instead of leaving the session at `initializing` ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
@@ -86,6 +87,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Upgrade notes (behavior changes)
- whatsapp-web.js: back up `sessions/` before upgrading. A rollback to an image with an older browser major deletes the stored WhatsApp logins unless `sessions/` is restored from that backup, and a session first paired after the upgrade must be paired again (see `docs/11-operational-runbooks.md`). Baileys sessions are unaffected.
+- Back up `sessions/` and `baileys/` before upgrading. The first boot renames each session's auth directory from the session name to its id; a rollback to 0.23.4 or earlier looks for the name-keyed directory, finds nothing, and starts every session on both engines at a QR code unless both directories are restored from that backup (see `docs/11-operational-runbooks.md`).
+- whatsapp-web.js on a non-container install: confirm no Chromium survived the stop before starting 0.23.5. The orphan sweep matches the session id from this release on, so a browser orphaned by a hard kill of the older version is no longer recognised and would hold the same profile as the one launched next to it.
- The amd64 image moves from Chrome for Testing 146 to 153, so every amd64 rollback to 0.23.4 or earlier crosses a browser major; the arm64 image runs the chromium Debian ships at build time, whose major can differ between releases.
- A `LOG_LEVEL` other than `error`, `warn`, `info`, `debug` or `verbose` now stops the boot instead of logging at info.
- Multi-node deployments run the lapsed-status correction even with `AUTO_START_SESSIONS` off, so every node needs a synced clock and, on PostgreSQL, one time zone without daylight saving (`TZ=UTC` recommended); otherwise live sessions can be marked disconnected (see `docs/13-horizontal-scaling.md`).
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.md
index 677ccde86..f45536cdf 100644
--- a/docs/03-system-architecture.md
+++ b/docs/03-system-architecture.md
@@ -955,9 +955,11 @@ The factory resolves the engine through the **plugin loader**, not a hard-coded
configured engine (`engine.type`, default `'whatsapp-web.js'`) is read once in the constructor; the
built-in `whatsapp-web.js` and `baileys` plugins are registered and the configured one is enabled in
`onModuleInit()`. `create()` takes an **options object** (engine-neutral per-call config —
-`sessionId` / `dbSessionId` / `proxyUrl` / `proxyType`), not a `type` argument. The two ids are
-distinct: `sessionId` is the session **name** (the on-disk auth-directory key), `dbSessionId` is the
-session **UUID** (`Session.id`), needed by FK-bound stores such as `baileys_stored_messages`. There is
+`sessionId` / `dbSessionId` / `proxyUrl` / `proxyType`), not a `type` argument. The two ids carry the
+same value: `sessionId` is the session **UUID** (`Session.id`), which is the on-disk auth-directory key
+since 0.23.5, and `dbSessionId` is that UUID under the name FK-bound stores such as
+`baileys_stored_messages` read. An out-of-tree engine plugin that keys its own storage by `sessionId`
+has to re-key it on upgrade: `SessionAuthDirMigration` renames the two built-in shapes only. There is
no `EngineType` union, no `switch`, and no `Unknown engine type` throw: if the plugin is unavailable it
logs a warning and falls back to the legacy direct adapter — but that fallback can only build
`whatsapp-web.js`. For any other configured engine (e.g. `ENGINE_TYPE=baileys` with its plugin
@@ -974,7 +976,7 @@ import { WhatsAppWebJsAdapter } from './adapters/whatsapp-web-js.adapter';
import { PluginLoaderService, PluginType, IEnginePlugin } from '../core/plugins';
export interface EngineCreateOptions {
- /** Session NAME — the on-disk auth-directory key. */
+ /** Session UUID (Session.id): the on-disk auth-directory key, same value as dbSessionId. */
sessionId: string;
/** Session UUID (Session.id) — the DB-row key for FK-bound stores (e.g. baileys_stored_messages). */
dbSessionId: string;
diff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.md
index 9061d0bfd..0ee84925b 100644
--- a/docs/11-operational-runbooks.md
+++ b/docs/11-operational-runbooks.md
@@ -522,6 +522,14 @@ curl -H "X-API-Key: $API_KEY" http://localhost:2785/api/health
> the restore and hits this. A session first paired on the newer image is not in that backup and must be
> paired again either way. Baileys sessions are unaffected.
+> Restoring `sessions/` **and** `baileys/` is likewise required when rolling back past 0.23.5, on either
+> engine and either architecture. 0.23.5 renames each session's auth directory from the session name to
+> its UUID id at first boot (`session-<id>` under `SESSION_DATA_PATH`, `<id>` under `BAILEYS_AUTH_DIR`);
+> an older image looks for the name-keyed directory, finds nothing, and starts every session at a QR
+> code. The rename keeps nothing behind to fall back to, so the backup must again predate the first
+> start on 0.23.5. Restoring both directories from that backup returns every session to its previous
+> pairing.
+
---
### Runbook: Database Backup
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 5c462dcfc..21e75fea6 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -213,11 +213,11 @@ curl -H "X-API-Key: $API_KEY" \
# Check WhatsApp engine logs
docker compose logs openwa-api 2>&1 | grep -i "whatsapp\|puppeteer\|browser"
-# Check auth folder. Both engines key it on the session NAME, but the location differs:
-# whatsapp-web.js → SESSION_DATA_PATH (default /app/data/sessions), dir `session-<name>`
-# baileys → BAILEYS_AUTH_DIR (default /app/data/baileys), dir `<name>` (no prefix)
-docker compose exec openwa-api ls -la /app/data/sessions/session-<name>/ # whatsapp-web.js
-docker compose exec openwa-api ls -la /app/data/baileys/<name>/ # baileys
+# Check auth folder. Both engines key it on the session UUID id, but the location differs:
+# whatsapp-web.js → SESSION_DATA_PATH (default /app/data/sessions), dir `session-<id>`
+# baileys → BAILEYS_AUTH_DIR (default /app/data/baileys), dir `<id>` (no prefix)
+docker compose exec openwa-api ls -la /app/data/sessions/session-<id>/ # whatsapp-web.js
+docker compose exec openwa-api ls -la /app/data/baileys/<id>/ # baileys
```
**Solutions:**
@@ -231,10 +231,10 @@ docker compose exec openwa-api ls -la /app/data/baileys/<name>/ # bai
| WhatsApp blocked | Set a per-session proxy (`proxyUrl`) |
```bash
-# Clear auth and restart (the profile dir carries the session NAME, not its UUID id).
+# Clear auth and restart (the profile dir carries the session's UUID id, not its name).
# Remove the one that matches the session's engine — deleting the other path is a silent no-op.
-docker compose exec openwa-api rm -rf /app/data/sessions/session-<name> # whatsapp-web.js
-docker compose exec openwa-api rm -rf /app/data/baileys/<name> # baileys
+docker compose exec openwa-api rm -rf /app/data/sessions/session-<id> # whatsapp-web.js
+docker compose exec openwa-api rm -rf /app/data/baileys/<id> # baileys
docker compose restart openwa-api
```
@@ -437,7 +437,7 @@ show:
Protocol error (Runtime.callFunctionOn): Execution context was destroyed.
```
-**Cause:** The session's persistent browser profile (`<SESSION_DATA_PATH>/session-<name>`, created by
+**Cause:** The session's persistent browser profile (`<SESSION_DATA_PATH>/session-<id>`, created by
whatsapp-web.js's `LocalAuth`) was built with a different Chromium/Chrome binary than the one the new
image runs. A browser profile carries binary-bound state (page caches, GPU shader caches, IndexedDB /
Local Storage version markers) that is not safely portable across Chromium major versions or binary
@@ -461,12 +461,12 @@ upgrade runbook's rollback in docs/11); without one, scan a new QR.
profile cannot be salvaged — clearing only the cache subdirs (`Cache`, `GPUCache`, `Code Cache`, …) is
**not** enough, the taint is deeper than the caches — so a one-time re-authentication is required.
-The profile dir is named after the session **name**, while the REST API addresses a session by its
-**id** (a UUID) — so the two placeholders below are different values:
+The profile dir is named after the session **id** (the UUID the REST API addresses it by), so
+`GET /api/sessions` gives you the value for both commands below:
```bash
-docker exec openwa-api rm -rf /app/data/sessions/session-<name>
-# then POST /sessions/<id>/force-kill and POST /sessions/<id>/start (the session's UUID id), and scan the new QR
+docker exec openwa-api rm -rf /app/data/sessions/session-<id>
+# then POST /sessions/<id>/force-kill and POST /sessions/<id>/start, and scan the new QR
```
Re-creating the session (`DELETE /sessions/<id>`) also purges its profile dir; create it again and
diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.md
index 0f0257e13..e1d9f0380 100644
--- a/docs/14-migration-guide.md
+++ b/docs/14-migration-guide.md
@@ -565,7 +565,7 @@ LIMIT 10;
```
whatsapp-web.js (LocalAuth) — SESSION_DATA_PATH, default ./data/sessions
./data/sessions/
-├── session-{sessionName}/
+├── session-{sessionId}/
│ ├── Default/
│ │ ├── IndexedDB/
│ │ ├── Local Storage/
@@ -574,33 +574,39 @@ whatsapp-web.js (LocalAuth) — SESSION_DATA_PATH, default ./data/sessions
Baileys — BAILEYS_AUTH_DIR, default ./data/baileys
./data/baileys/
-└── {sessionName}/ # multi-file auth state
+└── {sessionId}/ # multi-file auth state
```
> [!IMPORTANT]
-> **Directories are keyed by session NAME, not by the REST id.** The API addresses a session by its
-> UUID (`/api/sessions/{sessionId}`), but the engine receives `session.name` as its client id, so the on-disk
-> profile is `session-<name>` (whatsapp-web.js) or `<name>` (Baileys). Resolve the name via
-> `GET /api/sessions/{sessionId}` before copying anything.
+> **Directories are keyed by the session id**, the same UUID the API addresses a session by
+> (`/api/sessions/{sessionId}`): the on-disk profile is `session-<id>` (whatsapp-web.js) or `<id>`
+> (Baileys). Up to 0.23.4 they were keyed by the session NAME; 0.23.5 renames them onto the id at
+> first boot, so a directory copied off an older install still carries a name and has to be renamed
+> to the target's session id by hand.
### Transfer Methods
#### Method 1: Direct File Copy (Server to Server)
Moves the auth profile only. The session's database record is created separately — either by
-`POST /api/sessions` on the target with the same `name`, or with the infra export/import of
-Method 2. Copying rows between SQLite files by hand is not supported: the `sessions` table carries
-columns the copy would have to reproduce exactly, and a mismatch corrupts the row.
+`POST /api/sessions` on the target, or with the infra export/import of Method 2. Copying rows
+between SQLite files by hand is not supported: the `sessions` table carries columns the copy would
+have to reproduce exactly, and a mismatch corrupts the row.
+
+The profile directory is named after the session id, and a session created with `POST /api/sessions`
+on the target gets a **new** id, so the copy below renames the directory as it lands. Method 2
+carries the ids over unchanged and needs no rename.
Under the shipped compose the data directory lives in a named Docker volume
(`openwa-data:/app/data`), not a host bind mount, so the profile is copied through the container
with `docker compose cp` rather than straight off the host filesystem. `APP_DIR` is the directory
-holding `docker-compose.yml` on each server; `SESSION_NAME` is the session `name` (resolve it via
-`GET /api/sessions/{sessionId}` — the on-disk directory is keyed by name, not by the REST id).
+holding `docker-compose.yml` on each server; `OLD_ID` and `NEW_ID` are the session ids on the source
+and the target (`GET /api/sessions` on each).
```bash
APP_DIR=/srv/openwa # docker compose project directory on both hosts
-SESSION_NAME=my-session
+OLD_ID=3f1c... # id on the source host
+NEW_ID=9a2e... # id of the session created on the target host
# 1. Stop the app on both hosts. Use `stop`, not `down`: a running engine holds the profile open,
# but `down` removes the container that step 2 copies through.
@@ -608,20 +614,20 @@ ssh old-server "cd $APP_DIR && docker compose stop openwa-api"
ssh new-server "cd $APP_DIR && docker compose stop openwa-api"
# 2. Copy the auth profile out of the source container, to the target host, and back in.
-# whatsapp-web.js: /app/data/sessions/session-<name>.
-# Baileys: /app/data/baileys/<name> (no "session-" prefix).
+# whatsapp-web.js: /app/data/sessions/session-<id>.
+# Baileys: /app/data/baileys/<id> (no "session-" prefix).
ssh old-server "cd $APP_DIR && docker compose cp \
- openwa-api:/app/data/sessions/session-$SESSION_NAME ./session-$SESSION_NAME"
-rsync -avz --progress "old-server:$APP_DIR/session-$SESSION_NAME/" \
- "new-server:$APP_DIR/session-$SESSION_NAME/"
+ openwa-api:/app/data/sessions/session-$OLD_ID ./session-$OLD_ID"
+rsync -avz --progress "old-server:$APP_DIR/session-$OLD_ID/" \
+ "new-server:$APP_DIR/session-$NEW_ID/"
ssh new-server "cd $APP_DIR && docker compose cp \
- ./session-$SESSION_NAME openwa-api:/app/data/sessions/session-$SESSION_NAME"
+ ./session-$NEW_ID openwa-api:/app/data/sessions/session-$NEW_ID"
# 3. Start the target back up.
ssh new-server "cd $APP_DIR && docker compose start openwa-api"
```
-Delete the staging copies (`$APP_DIR/session-$SESSION_NAME` on both hosts) afterwards — they hold
+Delete the staging copies (`$APP_DIR/session-$OLD_ID` and `$APP_DIR/session-$NEW_ID`) afterwards — they hold
live WhatsApp credentials.
#### Method 2: Records via the Infra API + auth state by file copy
@@ -641,7 +647,8 @@ curl -X POST 'http://new-server:2785/api/infra/import-data' \
-H 'Content-Type: application/json' \
-d @data-backup.json
-# 2. Move the engine auth state with both instances stopped (Method 1), keyed by session NAME.
+# 2. Move the engine auth state with both instances stopped. The import preserves session ids, so
+# the directories transfer as they are, with no rename.
# OLD_DIR/NEW_DIR are each host's OpenWA working directory; SESSION_DATA_PATH defaults to
# ./data/sessions and BAILEYS_AUTH_DIR to ./data/baileys, relative to it. The production
# docker-compose.yml keeps /app/data in the named volume `openwa_openwa-data` rather than on the
@@ -1153,7 +1160,7 @@ docker compose up -d
# Check database integrity
sqlite3 ./data/openwa.sqlite "PRAGMA integrity_check;"
-# Verify auth session files (directories are named after the session NAME)
+# Verify auth session files (directories are named after the session id)
ls -la ./data/sessions/session-*/
ls -la ./data/baileys/ # Baileys engine
diff --git a/docs/21-glossary.md b/docs/21-glossary.md
index d804f3f4b..fdcfc129d 100644
--- a/docs/21-glossary.md
+++ b/docs/21-glossary.md
@@ -28,7 +28,7 @@ Authentication token to access the OpenWA API. Sent via the `X-API-Key` header.
### Auth State
-WhatsApp Web session authentication data. On the whatsapp-web.js engine it is a Chrome profile (cookies, local/session storage) under `SESSION_DATA_PATH` — default `./data/sessions`, one `session-<name>` directory per session. On Baileys it is a set of credential JSON files under `BAILEYS_AUTH_DIR`, default `./data/baileys`. Losing it unlinks the WhatsApp account and requires a fresh QR scan.
+WhatsApp Web session authentication data. On the whatsapp-web.js engine it is a Chrome profile (cookies, local/session storage) under `SESSION_DATA_PATH` — default `./data/sessions`, one `session-<id>` directory per session, named after the session's UUID. On Baileys it is a set of credential JSON files under `BAILEYS_AUTH_DIR`, default `./data/baileys`, one `<id>` directory per session. Losing it unlinks the WhatsApp account and requires a fresh QR scan.
## B
diff --git a/src/common/utils/path-safety.ts b/src/common/utils/path-safety.ts
index c73222515..236bc6e7a 100644
--- a/src/common/utils/path-safety.ts
+++ b/src/common/utils/path-safety.ts
@@ -33,12 +33,13 @@ export function isSafeStorageKey(key: string): boolean {
}
/**
- * Returns true if `name` is a safe engine session name — the same conservative charset the
- * CreateSessionDto enforces (letters, digits, hyphen). A session name becomes the engine auth-directory
- * key (`path.join(authDir, name)` / `session-${name}`), so a '.', '/', or '\\' could traverse outside it
+ * Returns true if `value` is a safe engine auth-directory key: the same conservative charset the
+ * CreateSessionDto enforces on a session name (letters, digits, hyphen). The key reaching the sink is
+ * a `Session.id`, and the boot migration also weighs a stored name against it; either becomes a path
+ * (`path.join(authDir, key)` / `session-${key}`), so a '.', '/', or '\\' could traverse outside it
* (arbitrary write, and `rm -rf` on teardown). This is the sink-side guard for every path that reaches
- * the auth dir — normal creation validates via the DTO, but data import / seed can carry a raw name.
+ * the auth dir: normal creation validates via the DTO, but data import / seed can carry a raw value.
*/
-export function isSafeSessionName(name: unknown): name is string {
- return typeof name === 'string' && /^[a-zA-Z0-9-]+$/.test(name);
+export function isSafeSessionName(value: unknown): value is string {
+ return typeof value === 'string' && /^[a-zA-Z0-9-]+$/.test(value);
}
diff --git a/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts b/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts
new file mode 100644
index 000000000..67cccc106
--- /dev/null
+++ b/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts
@@ -0,0 +1,42 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Re-key `chat_states` from `Session.name` to `Session.id`.
+ *
+ * The Baileys adapter stamps its per-session rows with the same key that names its auth directory.
+ * That key moved from the session name to the session id, so without this the persisted mute,
+ * archive and pin state of every existing session is orphaned: the chat list would report the
+ * defaults until WhatsApp's next app-state sync re-delivers them, and the old rows would never be
+ * read again.
+ *
+ * Idempotent: after a successful run no `sessionId` matches a session name, so a re-run updates
+ * nothing. Rows whose key matches no session are left alone (they belong to a deleted session and
+ * nothing reads them either way), and a row whose target key is already taken is skipped rather than
+ * violating the (sessionId, chatId) primary key.
+ */
+export class ReKeyChatStatesBySessionId1786500000000 implements MigrationInterface {
+ name = 'ReKeyChatStatesBySessionId1786500000000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ if (!(await queryRunner.hasTable('chat_states'))) return;
+ await queryRunner.query(this.rekey('name', 'id'));
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ if (!(await queryRunner.hasTable('chat_states'))) return;
+ await queryRunner.query(this.rekey('id', 'name'));
+ }
+
+ /**
+ * Correlated-subquery UPDATE rather than `UPDATE ... FROM`, which SQLite and PostgreSQL spell
+ * differently.
+ */
+ private rekey(from: 'name' | 'id', to: 'name' | 'id'): string {
+ const target = `(SELECT s."${to}" FROM sessions s WHERE s."${from}" = chat_states."sessionId")`;
+ return `UPDATE chat_states SET "sessionId" = ${target}
+ WHERE EXISTS (SELECT 1 FROM sessions s WHERE s."${from}" = chat_states."sessionId")
+ AND NOT EXISTS (
+ SELECT 1 FROM chat_states c WHERE c."chatId" = chat_states."chatId" AND c."sessionId" = ${target}
+ )`;
+ }
+}
diff --git a/src/database/rekey-chat-states-migration.spec.ts b/src/database/rekey-chat-states-migration.spec.ts
new file mode 100644
index 000000000..5c796eff0
--- /dev/null
+++ b/src/database/rekey-chat-states-migration.spec.ts
@@ -0,0 +1,97 @@
+// NOTE: kept OUT of src/database/migrations/ on purpose: the TypeORM migrations glob
+// (`migrations/*{.ts,.js}`) would otherwise load this spec as a migration under ts-node
+// (the CLI datasource / start:dev) and crash on `describe`.
+import { DataSource, QueryRunner } from 'typeorm';
+import { ReKeyChatStatesBySessionId1786500000000 } from './migrations/1786500000000-ReKeyChatStatesBySessionId';
+
+// A real SQLite database rather than a mocked query runner: this migration rewrites rows, so the
+// statement itself is the thing under test.
+describe('ReKeyChatStatesBySessionId migration', () => {
+ const ALICE_ID = '8f5b1d9e-0c4a-4e21-9d6b-2a7c3f0e1b44';
+ const BOB_ID = '1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f';
+ const migration = new ReKeyChatStatesBySessionId1786500000000();
+
+ let dataSource: DataSource;
+ let queryRunner: QueryRunner;
+
+ beforeEach(async () => {
+ dataSource = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [], migrations: [] });
+ await dataSource.initialize();
+ queryRunner = dataSource.createQueryRunner();
+ await queryRunner.query(`CREATE TABLE "sessions" ("id" varchar PRIMARY KEY, "name" varchar NOT NULL UNIQUE)`);
+ await queryRunner.query(
+ `CREATE TABLE "chat_states" ("sessionId" varchar NOT NULL, "chatId" varchar NOT NULL, "archived" boolean NOT NULL DEFAULT (0), PRIMARY KEY ("sessionId", "chatId"))`,
+ );
+ await queryRunner.query(
+ `INSERT INTO sessions ("id", "name") VALUES ('${ALICE_ID}', 'alice'), ('${BOB_ID}', 'bob')`,
+ );
+ });
+
+ afterEach(async () => {
+ await queryRunner.release();
+ await dataSource.destroy();
+ });
+
+ const states = (): Promise<Array<{ sessionId: string; chatId: string }>> =>
+ queryRunner.query('SELECT "sessionId", "chatId" FROM chat_states ORDER BY "chatId", "sessionId"') as Promise<
+ Array<{ sessionId: string; chatId: string }>
+ >;
+
+ it('moves every name-keyed row onto its session id', async () => {
+ await queryRunner.query(
+ `INSERT INTO chat_states ("sessionId", "chatId") VALUES ('alice', '[email protected]'), ('bob', '[email protected]')`,
+ );
+
+ await migration.up(queryRunner);
+
+ expect(await states()).toEqual([
+ { sessionId: ALICE_ID, chatId: '[email protected]' },
+ { sessionId: BOB_ID, chatId: '[email protected]' },
+ ]);
+ });
+
+ it('is idempotent: a second run leaves the already-migrated rows alone', async () => {
+ await queryRunner.query(`INSERT INTO chat_states ("sessionId", "chatId") VALUES ('alice', '[email protected]')`);
+
+ await migration.up(queryRunner);
+ await migration.up(queryRunner);
+
+ expect(await states()).toEqual([{ sessionId: ALICE_ID, chatId: '[email protected]' }]);
+ });
+
+ it('leaves rows of a deleted session untouched', async () => {
+ await queryRunner.query(`INSERT INTO chat_states ("sessionId", "chatId") VALUES ('gone', '[email protected]')`);
+
+ await migration.up(queryRunner);
+
+ expect(await states()).toEqual([{ sessionId: 'gone', chatId: '[email protected]' }]);
+ });
+
+ it('skips a row whose target key is already taken instead of breaking the primary key', async () => {
+ await queryRunner.query(
+ `INSERT INTO chat_states ("sessionId", "chatId") VALUES ('alice', '[email protected]'), ('${ALICE_ID}', '[email protected]')`,
+ );
+
+ await expect(migration.up(queryRunner)).resolves.toBeUndefined();
+
+ expect(await states()).toEqual([
+ { sessionId: ALICE_ID, chatId: '[email protected]' },
+ { sessionId: 'alice', chatId: '[email protected]' },
+ ]);
+ });
+
+ it('is a no-op when chat_states does not exist yet (fresh database mid-bootstrap)', async () => {
+ await queryRunner.query('DROP TABLE chat_states');
+
+ await expect(migration.up(queryRunner)).resolves.toBeUndefined();
+ });
+
+ it('down() puts the rows back on the session name', async () => {
+ await queryRunner.query(`INSERT INTO chat_states ("sessionId", "chatId") VALUES ('alice', '[email protected]')`);
+
+ await migration.up(queryRunner);
+ await migration.down(queryRunner);
+
+ expect(await states()).toEqual([{ sessionId: 'alice', chatId: '[email protected]' }]);
+ });
+});
diff --git a/src/engine/adapters/baileys-chat-state.entity.ts b/src/engine/adapters/baileys-chat-state.entity.ts
index 3055a0324..a0de455a6 100644
--- a/src/engine/adapters/baileys-chat-state.entity.ts
+++ b/src/engine/adapters/baileys-chat-state.entity.ts
@@ -8,14 +8,14 @@ import { Column, Entity, PrimaryColumn, UpdateDateColumn } from 'typeorm';
* chats carried `muteEndTime`. So the value is persisted here and rehydrated on boot; live `chats.update`
* events (including an unmute, which arrives as `muteEndTime = null`) keep it current.
*
- * One row per (session, chat). `sessionId` is the session NAME used elsewhere in the engine surface,
- * provenance rather than a foreign key, so the row can outlive a single run. `muteEndTime` is stored as
+ * One row per (session, chat). `sessionId` is `Session.id`, the key used elsewhere in the engine
+ * surface, provenance rather than a foreign key, so the row can outlive a single run. `muteEndTime` is stored as
* canonical epoch MILLISECONDS (or null when unmuted); the numeric transformer keeps it a JS number
* rather than the string a bigint column otherwise reads back as.
*/
@Entity('chat_states')
export class ChatState {
- /** Session name that owns this chat state. */
+ /** `Session.id` of the session that owns this chat state. */
@PrimaryColumn()
sessionId!: string;
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 914ece8dd..67f5173aa 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -1,4 +1,3 @@
-import * as path from 'path';
import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';
import { isChannelJid } from '../identity/wa-id';
import type * as BaileysLib from '@whiskeysockets/baileys';
@@ -51,6 +50,7 @@ import { EngineNotSupportedError } from '../../common/errors/engine-not-supporte
import { NotFoundException } from '@nestjs/common';
import { createLogger } from '../../common/services/logger.service';
import { BaileysAdapterConfig } from '../types/baileys.types';
+import { baileysAuthDir } from '../auth-dir-paths';
import { BaileysSessionStore } from './baileys-session-store';
import { inboundMediaConcurrency } from './inbound-media-cap';
import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
@@ -112,7 +112,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
constructor(private readonly config: BaileysAdapterConfig) {
// Isolate each session's auth state under its own subdirectory of the shared auth dir.
- this.authPath = path.join(config.authDir, config.sessionId);
+ this.authPath = baileysAuthDir(config.authDir, config.sessionId);
this.sessionStore = new BaileysSessionStore(config.lidMappingStore, config.sessionId, config.chatStateStore);
// Constructed before messaging: the messaging delegate's own-send echo maps through
// events.mapMessage (and the lifecycle delegate clears that same live-call cache on teardown).
diff --git a/src/engine/adapters/chromium-profile-hygiene.ts b/src/engine/adapters/chromium-profile-hygiene.ts
index 51c3ca047..dd59d0f2a 100644
--- a/src/engine/adapters/chromium-profile-hygiene.ts
+++ b/src/engine/adapters/chromium-profile-hygiene.ts
@@ -2,6 +2,7 @@ import * as fs from 'fs';
import * as path from 'path';
import { execFile } from 'child_process';
import type { LoggerService } from '../../common/services/logger.service';
+import { wwjsAuthDir } from '../auth-dir-paths';
/**
* Chromium/profile hygiene run before a whatsapp-web.js browser launches.
@@ -92,7 +93,7 @@ export async function removeStaleSingletonFiles(
sessionDataPath: string,
logger: HygieneLogger,
): Promise<void> {
- const profileDir = path.join(path.resolve(sessionDataPath), `session-${sessionId}`);
+ const profileDir = wwjsAuthDir(sessionDataPath, sessionId);
for (const name of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
try {
await fs.promises.rm(path.join(profileDir, name), { force: true });
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index 6421f4776..b6f83143a 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -18,6 +18,7 @@ import { BACKPORT_MISSING_MESSAGE, isBackportMissing } from './wwebjs-backport-c
import { unappliedPatches, unappliedPatchesMessage } from './engine-patch-status';
import { type WhatsAppWebJsConfig } from './whatsapp-web-js.adapter';
import { AUTH_FAILURE_REASON, STALE_PROFILE_ADVICE } from '../terminal-engine-failure';
+import { wwjsAuthDir } from '../auth-dir-paths';
/**
* Detect Puppeteer's "Execution context was destroyed" error. During `Client.inject()` this is most
@@ -316,7 +317,7 @@ export class WwebjsLifecycle {
`"${reason}" during initialize. If this followed an OpenWA upgrade that changed the ` +
`Chromium/Chrome binary (v0.8.12 amd64 switched Debian Chromium → Chrome for Testing), the ` +
`session's browser profile is likely stale — delete the profile dir ` +
- `"${path.join(path.resolve(this.host.config.sessionDataPath), `session-${this.host.config.sessionId}`)}" ` +
+ `"${wwjsAuthDir(this.host.config.sessionDataPath, this.host.config.sessionId)}" ` +
`and start again to re-scan. If no upgrade happened, Puppeteer also raises this on a page ` +
`navigation or renderer crash (check for memory pressure or a WhatsApp Web reload). ` +
`See docs/12-troubleshooting-faq.md.`,
diff --git a/src/engine/adapters/wwebjs-stuck-auth.ts b/src/engine/adapters/wwebjs-stuck-auth.ts
index c5aaccdce..9d1a22a75 100644
--- a/src/engine/adapters/wwebjs-stuck-auth.ts
+++ b/src/engine/adapters/wwebjs-stuck-auth.ts
@@ -1,9 +1,9 @@
-import * as path from 'path';
import * as fs from 'fs';
import { type Client } from 'whatsapp-web.js';
import { type EngineEventCallbacks, EngineStatus } from '../interfaces/whatsapp-engine.interface';
import { type createLogger } from '../../common/services/logger.service';
import { type WhatsAppWebJsConfig } from './whatsapp-web-js.adapter';
+import { wwjsAuthDir } from '../auth-dir-paths';
/**
* Stuck-auth detection and recovery extracted from WhatsAppWebJsAdapter: what to do when a session
@@ -81,7 +81,7 @@ export class WwebjsStuckAuth {
/** Remove this session's LocalAuth directory so the next start re-pairs from a clean slate. */
async clearLocalAuth(): Promise<void> {
- const dir = path.join(path.resolve(this.host.config.sessionDataPath), `session-${this.host.config.sessionId}`);
+ const dir = wwjsAuthDir(this.host.config.sessionDataPath, this.host.config.sessionId);
await fs.promises
// maxRetries mirrors LocalAuth's own default: on a WhatsApp-initiated unlink the library never
// closes the browser, so Chromium is still rotating IndexedDB files while this walks the tree and
diff --git a/src/engine/auth-dir-paths.spec.ts b/src/engine/auth-dir-paths.spec.ts
new file mode 100644
index 000000000..ee01db541
--- /dev/null
+++ b/src/engine/auth-dir-paths.spec.ts
@@ -0,0 +1,90 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { baileysAuthDir, readAuthDirEntries, wwjsAuthDir } from './auth-dir-paths';
+import { BaileysAdapter } from './adapters/baileys.adapter';
+import { WhatsAppWebJsAdapter } from './adapters/whatsapp-web-js.adapter';
+
+// #1597: the engine auth directories are keyed by Session.id. Every writer of those paths has to
+// agree, so each is asserted against the shared builders rather than a hand-written string.
+describe('engine auth directory paths', () => {
+ const SESSION_ID = '8f5b1d9e-0c4a-4e21-9d6b-2a7c3f0e1b44';
+ const OTHER_ID = '1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f';
+
+ it('gives two sessions whose NAMES differ only in case two distinct directories', () => {
+ // The reported bug: `my-bot` and `My-Bot` are two rows, and on a case-insensitive filesystem the
+ // name-keyed directories collapsed into one. Ids differ in more than case, so the paths do too,
+ // and neither carries the name that used to collide.
+ for (const dirs of [
+ [wwjsAuthDir('./data/sessions', SESSION_ID), wwjsAuthDir('./data/sessions', OTHER_ID)],
+ [baileysAuthDir('./data/baileys', SESSION_ID), baileysAuthDir('./data/baileys', OTHER_ID)],
+ ]) {
+ expect(dirs[0].toLowerCase()).not.toBe(dirs[1].toLowerCase());
+ expect(dirs.join(' ')).not.toMatch(/my-bot/i);
+ }
+ });
+
+ it('the baileys adapter stores credentials at the id-keyed path', () => {
+ const adapter = new BaileysAdapter({
+ sessionId: SESSION_ID,
+ dbSessionId: SESSION_ID,
+ authDir: './data/baileys',
+ });
+
+ expect((adapter as unknown as { authPath: string }).authPath).toBe(baileysAuthDir('./data/baileys', SESSION_ID));
+ });
+
+ it('the whatsapp-web.js adapter removes the id-keyed LocalAuth profile', async () => {
+ // force:true makes an unstubbed rm silent, so it is stubbed: the assertion is the path, not the
+ // removal (covered in whatsapp-web-js.adapter.spec).
+ const rm = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ try {
+ const adapter = new WhatsAppWebJsAdapter({
+ sessionId: SESSION_ID,
+ sessionDataPath: './data/sessions',
+ puppeteer: {},
+ });
+
+ await (adapter as unknown as { clearLocalAuth: () => Promise<void> }).clearLocalAuth.call(adapter);
+
+ expect(rm).toHaveBeenCalledWith(wwjsAuthDir('./data/sessions', SESSION_ID), expect.anything());
+ } finally {
+ rm.mockRestore();
+ }
+ });
+
+ it('resolves the whatsapp-web.js base but leaves the baileys one as configured, as the adapters do', () => {
+ expect(wwjsAuthDir('./data/sessions', SESSION_ID)).toBe(
+ path.join(path.resolve('./data/sessions'), `session-${SESSION_ID}`),
+ );
+ expect(baileysAuthDir('./data/baileys', SESSION_ID)).toBe(path.join('./data/baileys', SESSION_ID));
+ });
+
+ describe('readAuthDirEntries', () => {
+ let tmpRoot: string;
+
+ beforeEach(() => {
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'auth-dir-entries-'));
+ });
+ afterEach(() => {
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ it('lists directories and symlinked directories, not plain files', () => {
+ fs.mkdirSync(path.join(tmpRoot, 'base', 'session-alice'), { recursive: true });
+ fs.mkdirSync(path.join(tmpRoot, 'elsewhere', 'profile'), { recursive: true });
+ fs.writeFileSync(path.join(tmpRoot, 'base', 'notes.txt'), 'x');
+ // An operator who moved a large profile off the data volume: the link is what the adapter
+ // opens, so it has to count as an auth directory.
+ fs.symlinkSync(path.join(tmpRoot, 'elsewhere', 'profile'), path.join(tmpRoot, 'base', 'session-bob'));
+
+ expect(readAuthDirEntries(path.join(tmpRoot, 'base'))).toEqual(new Set(['session-alice', 'session-bob']));
+ });
+
+ it('throws ENOENT for a missing base directory, so a caller can tell it from a failure', () => {
+ expect(() => readAuthDirEntries(path.join(tmpRoot, 'absent'))).toThrow(
+ expect.objectContaining({ code: 'ENOENT' }),
+ );
+ });
+ });
+});
diff --git a/src/engine/auth-dir-paths.ts b/src/engine/auth-dir-paths.ts
new file mode 100644
index 000000000..ef088413f
--- /dev/null
+++ b/src/engine/auth-dir-paths.ts
@@ -0,0 +1,48 @@
+import * as fs from 'fs';
+import * as path from 'path';
+
+/**
+ * The on-disk engine auth directories, keyed by the session's UUID (`Session.id`).
+ *
+ * They used to be keyed by `Session.name`. Names are unique case-sensitively, so `my-bot` and
+ * `My-Bot` are two rows, but on a case-insensitive filesystem (macOS APFS, Windows, and Docker
+ * Desktop bind mounts of a host directory on either) they resolved to ONE directory: the second
+ * session loaded the first one's WhatsApp login, and deleting either wiped both (#1597). A UUID has
+ * no case variants, so the key is unambiguous on every filesystem.
+ *
+ * These two builders are the single source of truth for the paths: the adapters build them to write
+ * credentials, EngineFactory to pre-create and purge them, and the boot migration to rename the
+ * legacy name-keyed directories onto them.
+ */
+
+/** whatsapp-web.js LocalAuth profile dir: `sessionDataPath` resolved, then `session-<id>` appended. */
+export function wwjsAuthDir(sessionDataPath: string, sessionId: string): string {
+ return path.join(path.resolve(sessionDataPath), `session-${sessionId}`);
+}
+
+/** Baileys multi-file auth dir: `authDir/<id>`, with `authDir` left unresolved, as the adapter does. */
+export function baileysAuthDir(authDir: string, sessionId: string): string {
+ return path.join(authDir, sessionId);
+}
+
+/**
+ * The auth-directory entries directly under `base`, by exact name. Throws whatever `readdir` throws,
+ * so a caller can tell a missing base directory (ENOENT) from one it may not read.
+ *
+ * Every caller that acts on a legacy name-keyed directory matches it against this listing instead of
+ * asking `fs.existsSync`: on a case-insensitive filesystem `existsSync` answers yes for
+ * `session-My-Bot` when only `session-my-bot` is stored, so the rename or the rm would hit another
+ * session's credentials, which is the very bug the id key exists to fix (#1597).
+ *
+ * A symlink counts as an entry: relocating a large profile onto another volume with one worked while
+ * the paths were only ever opened, so renaming or removing the link is what keeps those installs
+ * behaving as they did.
+ */
+export function readAuthDirEntries(base: string): Set<string> {
+ return new Set(
+ fs
+ .readdirSync(base, { withFileTypes: true })
+ .filter(entry => entry.isDirectory() || entry.isSymbolicLink())
+ .map(entry => entry.name),
+ );
+}
diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.ts
index 16a369daa..3d9e5ef07 100644
--- a/src/engine/engine.factory.spec.ts
+++ b/src/engine/engine.factory.spec.ts
@@ -7,8 +7,12 @@ import { PluginLoaderService, PluginType } from '../core/plugins';
import { BaileysMessageStoreService } from './adapters/baileys-message-store.service';
import { LidMappingStoreService } from './identity/lid-mapping-store.service';
import { ChatStateStoreService } from './adapters/baileys-chat-state-store.service';
+import { baileysAuthDir, wwjsAuthDir } from './auth-dir-paths';
describe('EngineFactory', () => {
+ // The auth-dir key is Session.id (#1597), so the on-disk assertions below use a UUID and build the
+ // expected paths with the same helpers the adapters use.
+ const SESSION_ID = '8f5b1d9e-0c4a-4e21-9d6b-2a7c3f0e1b44';
const engineBlob = {
type: 'whatsapp-web.js',
sessionDataPath: '/var/data/sessions',
@@ -44,7 +48,7 @@ describe('EngineFactory', () => {
reload: jest.fn().mockResolvedValue(undefined),
}) as unknown as ChatStateStoreService;
- it('refuses to create an engine for an unsafe session name (path-traversal into the auth dir)', () => {
+ it('refuses to create an engine for an unsafe session key (path-traversal into the auth dir)', () => {
const createEngine = jest.fn().mockReturnValue({});
const pluginLoader = {
getPlugin: jest.fn().mockReturnValue({ instance: { type: PluginType.ENGINE, createEngine } }),
@@ -57,8 +61,8 @@ describe('EngineFactory', () => {
buildChatStateStore(),
);
- expect(() => factory.create({ sessionId: '../../etc', dbSessionId: 'db-1' })).toThrow(/unsafe session name/i);
- expect(() => factory.create({ sessionId: 'a/b', dbSessionId: 'db-1' })).toThrow(/unsafe session name/i);
+ expect(() => factory.create({ sessionId: '../../etc', dbSessionId: 'db-1' })).toThrow(/unsafe session key/i);
+ expect(() => factory.create({ sessionId: 'a/b', dbSessionId: 'db-1' })).toThrow(/unsafe session key/i);
expect(createEngine).not.toHaveBeenCalled();
});
@@ -182,8 +186,8 @@ describe('EngineFactory', () => {
// An upgrade reuses the dirs a previous install left world-readable (default umask); fresh
// installs have no dirs at all. Both must end at 0o700 after create().
if (preLoosen) {
- fs.mkdirSync(path.join(sessionDataPath, 'session-alice'), { recursive: true, mode: 0o755 });
- fs.mkdirSync(path.join(authDir, 'alice'), { recursive: true, mode: 0o755 });
+ fs.mkdirSync(wwjsAuthDir(sessionDataPath, SESSION_ID), { recursive: true, mode: 0o755 });
+ fs.mkdirSync(baileysAuthDir(authDir, SESSION_ID), { recursive: true, mode: 0o755 });
}
const createEngine = jest.fn().mockReturnValue({});
const pluginLoader = {
@@ -201,22 +205,22 @@ describe('EngineFactory', () => {
);
return {
factory,
- wwjsDir: path.join(sessionDataPath, 'session-alice'),
- baileysDir: path.join(authDir, 'alice'),
+ wwjsDir: wwjsAuthDir(sessionDataPath, SESSION_ID),
+ baileysDir: baileysAuthDir(authDir, SESSION_ID),
};
};
it.each([false, true])('hardens both engine shapes on a %s install', preLoosen => {
const { factory, wwjsDir, baileysDir } = buildTmpFactory(preLoosen);
- factory.create({ sessionId: 'alice', dbSessionId: 'db-1' });
+ factory.create({ sessionId: SESSION_ID, dbSessionId: SESSION_ID });
expect(fs.statSync(wwjsDir).mode & 0o777).toBe(0o700);
expect(fs.statSync(baileysDir).mode & 0o777).toBe(0o700);
});
});
- describe('purgeSessionData (delete fully removes on-disk auth, keyed by session name)', () => {
+ describe('purgeSessionData (delete fully removes on-disk auth, keyed by session id)', () => {
const noPluginLoader = () => ({ getPlugin: jest.fn() }) as unknown as PluginLoaderService;
let tmpRoot: string;
@@ -242,7 +246,11 @@ describe('EngineFactory', () => {
buildLidStore(),
buildChatStateStore(),
);
- return { factory, wwjsDir: path.join(sessionDataPath, 'session-alice'), baileysDir: path.join(authDir, 'alice') };
+ return {
+ factory,
+ wwjsDir: wwjsAuthDir(sessionDataPath, SESSION_ID),
+ baileysDir: baileysAuthDir(authDir, SESSION_ID),
+ };
};
it.each(['whatsapp-web.js', 'baileys'])(
@@ -254,7 +262,7 @@ describe('EngineFactory', () => {
fs.writeFileSync(path.join(wwjsDir, 'creds.json'), '{}');
fs.writeFileSync(path.join(baileysDir, 'creds.json'), '{}');
- await factory.purgeSessionData('alice');
+ await factory.purgeSessionData(SESSION_ID);
expect(fs.existsSync(wwjsDir)).toBe(false);
expect(fs.existsSync(baileysDir)).toBe(false);
@@ -274,7 +282,7 @@ describe('EngineFactory', () => {
return realRm(...args);
});
try {
- await expect(factory.purgeSessionData('alice')).resolves.toBeUndefined();
+ await expect(factory.purgeSessionData(SESSION_ID)).resolves.toBeUndefined();
} finally {
spy.mockRestore();
}
@@ -289,13 +297,46 @@ describe('EngineFactory', () => {
await expect(factory.purgeSessionData('never-linked')).resolves.toBeUndefined();
});
- it('refuses to purge an unsafe session name (no rm on a traversal path)', async () => {
+ // The boot migration keeps a legacy name-keyed directory it could not rename (an open profile, or
+ // a conflict with an id-keyed one). Delete has to take it too, or a complete WhatsApp login stays
+ // on the volume, and in every backup, after the session is gone.
+ it('removes the legacy name-keyed directories of the deleted session as well', async () => {
+ const { factory, wwjsDir, baileysDir } = buildBothDirFactory('baileys');
+ fs.mkdirSync(wwjsDir, { recursive: true });
+ fs.mkdirSync(baileysDir, { recursive: true });
+ const legacyWwjs = wwjsAuthDir(path.join(tmpRoot, 'sessions'), 'alice');
+ const legacyBaileys = baileysAuthDir(path.join(tmpRoot, 'baileys'), 'alice');
+ fs.mkdirSync(legacyWwjs, { recursive: true });
+ fs.mkdirSync(legacyBaileys, { recursive: true });
+
+ await factory.purgeSessionData(SESSION_ID, 'alice');
+
+ expect(fs.existsSync(legacyWwjs)).toBe(false);
+ expect(fs.existsSync(legacyBaileys)).toBe(false);
+ });
+
+ // Why the legacy purge matches a directory listing instead of asking existsSync: there, deleting
+ // `Alice` would remove the directory holding `alice`'s login, which is #1597 through the delete
+ // path. The two only diverge on a case-insensitive filesystem, which is where the bug lives.
+ it('leaves a legacy directory whose stored name differs only in case alone', async () => {
+ const { factory } = buildBothDirFactory('baileys');
+ const otherSession = wwjsAuthDir(path.join(tmpRoot, 'sessions'), 'alice');
+ fs.mkdirSync(otherSession, { recursive: true });
+
+ await factory.purgeSessionData(SESSION_ID, 'Alice');
+
+ expect(fs.existsSync(otherSession)).toBe(true);
+ });
+
+ it('refuses to purge an unsafe session key (no rm on a traversal path)', async () => {
// A sibling that a '../' name would resolve to — it must survive the refused purge.
const sibling = path.join(tmpRoot, 'baileys-evil');
fs.mkdirSync(sibling, { recursive: true });
const { factory } = buildBothDirFactory('baileys');
await factory.purgeSessionData('../baileys-evil');
+ // Same guard on the legacy name, which an imported row can carry raw.
+ await factory.purgeSessionData(SESSION_ID, '../baileys-evil');
expect(fs.existsSync(sibling)).toBe(true);
});
diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.ts
index 8eb60afe6..adfec8a8c 100644
--- a/src/engine/engine.factory.ts
+++ b/src/engine/engine.factory.ts
@@ -13,9 +13,15 @@ import { LidMappingStoreService } from './identity/lid-mapping-store.service';
import { ChatStateStoreService } from './adapters/baileys-chat-state-store.service';
import { isSafeSessionName } from '../common/utils/path-safety';
import { ensurePrivateDir } from '../common/utils/private-dir.util';
+import { baileysAuthDir, readAuthDirEntries, wwjsAuthDir } from './auth-dir-paths';
export interface EngineCreateOptions {
- /** Session NAME — the on-disk auth-directory key (matches the dirs purgeSessionData removes). */
+ /**
+ * Session UUID (Session.id): the on-disk auth-directory key (matches the dirs purgeSessionData
+ * removes), and what the adapters stamp on their per-session rows and logs. Carries the same value
+ * as `dbSessionId`; both stay in the per-call config because an out-of-tree engine plugin reads
+ * them by name.
+ */
sessionId: string;
/** Session UUID (Session.id) — the DB-row key for FK-bound stores (e.g. baileys_stored_messages). */
dbSessionId: string;
@@ -99,11 +105,11 @@ export class EngineFactory implements OnModuleInit {
create(options: EngineCreateOptions): IWhatsAppEngine {
// The sessionId becomes the engine's on-disk auth-directory key (path.join(authDir, sessionId) /
- // session-${sessionId}), so a name containing '.', '/' or '\\' could traverse outside it. Normal
- // creation validates via CreateSessionDto, but alternate paths (data import, seed) can reach this
- // sink with a raw name — assert here so the traversal can never materialize regardless of source.
+ // session-${sessionId}), so a value containing '.', '/' or '\\' could traverse outside it. It is a
+ // Session.id (a UUID) on every in-tree path, but a restored/imported row carries whatever its
+ // archive held — assert here so the traversal can never materialize regardless of source.
if (!isSafeSessionName(options.sessionId)) {
- throw new Error(`Refusing to create an engine for an unsafe session name: ${JSON.stringify(options.sessionId)}`);
+ throw new Error(`Refusing to create an engine for an unsafe session key: ${JSON.stringify(options.sessionId)}`);
}
// Both engine shapes' credential dirs are made owner-only up front, whichever engine this
@@ -139,46 +145,58 @@ export class EngineFactory implements OnModuleInit {
/**
* Remove a session's persistent on-disk auth/store directories so deleting a session fully purges
- * its footprint. The dir is keyed by session NAME — the same key {@link create} uses
- * (`path.join(authDir, name)` for baileys, `session-${name}` under sessionDataPath for
+ * its footprint. The dir is keyed by session ID — the same key {@link create} uses
+ * (`path.join(authDir, id)` for baileys, `session-${id}` under sessionDataPath for
* whatsapp-web.js) — and survives independently of any engine instance. On delete the engine is
* frequently not even loaded (a stopped session has none), so the paths are derived from config
- * here rather than from a live adapter; otherwise recreating a session under the same name would
- * reload a stale store.
+ * here rather than from a live adapter; otherwise the residue would sit on the volume forever.
*
* BOTH engine shapes are purged, not just the active engine's: ENGINE_TYPE is a deploy-level
* switch, so a session that ever ran under both engines leaves a live auth dir for each, and
* removing only the active engine's would strand the other's WhatsApp credentials on disk after
* "delete" — able to silently re-link if the engine is ever switched back (and carried into
- * backups). Each rm is isolated best-effort: an unsafe name is refused up front, and one engine's
+ * backups). Each rm is isolated best-effort: an unsafe key is refused up front, and one engine's
* rm failure is logged per-engine — it neither fails the delete nor skips the other engine's purge.
*
* Note: session START deliberately does NOT purge the inactive engine's residue. An operator
* trialling the other engine keeps the previous engine's link so switching back doesn't force a
* re-pair; the residue is removed only when the session itself is deleted.
+ *
+ * `legacyName` is the row's name, passed by delete. SessionAuthDirMigration leaves the legacy
+ * name-keyed directory in place whenever it could not rename it (an open profile on Windows, or an
+ * id-keyed directory already there), so purging only the id-keyed dirs would strand a complete
+ * WhatsApp login on the volume and in every backup taken after the delete. It is removed only when
+ * the base directory really holds an entry with that exact name; see readAuthDirEntries.
*/
- async purgeSessionData(sessionName: string): Promise<void> {
- if (!isSafeSessionName(sessionName)) {
- // Same guard as create(): never let a name with '.', '/' or '\\' reach an rm -rf sink.
- this.logger.warn('Refusing to purge session data for an unsafe session name', {
+ async purgeSessionData(sessionId: string, legacyName?: string): Promise<void> {
+ if (!isSafeSessionName(sessionId)) {
+ // Same guard as create(): never let a key with '.', '/' or '\\' reach an rm -rf sink.
+ this.logger.warn('Refusing to purge session data for an unsafe session key', {
action: 'engine_purge_unsafe',
- sessionName: JSON.stringify(sessionName),
+ key: JSON.stringify(sessionId),
});
return;
}
const dirs: Array<{ engine: string; dir: string }> = [
- { engine: 'whatsapp-web.js', dir: this.wwjsAuthDir(sessionName) },
- { engine: 'baileys', dir: this.baileysAuthDir(sessionName) },
+ { engine: 'whatsapp-web.js', dir: this.wwjsAuthDir(sessionId) },
+ { engine: 'baileys', dir: this.baileysAuthDir(sessionId) },
];
+ if (legacyName !== undefined && isSafeSessionName(legacyName)) {
+ const legacyDirs = [
+ { engine: 'whatsapp-web.js', dir: this.wwjsAuthDir(legacyName) },
+ { engine: 'baileys', dir: this.baileysAuthDir(legacyName) },
+ ];
+ dirs.push(...legacyDirs.filter(({ dir }) => this.authDirExists(dir)));
+ }
for (const { engine, dir } of dirs) {
try {
await fs.promises.rm(dir, { recursive: true, force: true });
- this.logger.log('Purged session auth directory', { action: 'engine_purge', engine, sessionName, dir });
+ this.logger.log('Purged session auth directory', { action: 'engine_purge', engine, sessionId, dir });
} catch (error) {
this.logger.warn('Failed to purge session auth directory', {
action: 'engine_purge_failed',
engine,
- sessionName,
+ sessionId,
dir,
error: error instanceof Error ? error.message : String(error),
});
@@ -186,23 +204,23 @@ export class EngineFactory implements OnModuleInit {
}
}
- /**
- * The on-disk auth directory whatsapp-web.js keeps for `sessionName`, matching exactly what the
- * adapter constructs: sessionDataPath resolved, then `session-${name}` appended (mirrors
- * WhatsAppWebJsAdapter.clearLocalAuth).
- */
- private wwjsAuthDir(sessionName: string): string {
- const sessionDataPath = this.configService.get<string>('engine.sessionDataPath') ?? './data/sessions';
- return path.join(path.resolve(sessionDataPath), `session-${sessionName}`);
+ /** The whatsapp-web.js LocalAuth profile dir for `sessionId`, with sessionDataPath from config. */
+ private wwjsAuthDir(sessionId: string): string {
+ return wwjsAuthDir(this.configService.get<string>('engine.sessionDataPath') ?? './data/sessions', sessionId);
}
- /**
- * The on-disk auth directory baileys keeps for `sessionName`: `path.join(authDir, name)`, with
- * authDir left unresolved, as the adapter does.
- */
- private baileysAuthDir(sessionName: string): string {
- const authDir = this.configService.get<string>('engine.baileys.authDir') ?? './data/baileys';
- return path.join(authDir, sessionName);
+ /** The baileys multi-file auth dir for `sessionId`, with authDir from config. */
+ private baileysAuthDir(sessionId: string): string {
+ return baileysAuthDir(this.configService.get<string>('engine.baileys.authDir') ?? './data/baileys', sessionId);
+ }
+
+ /** True when `dir`'s base directory holds an entry with exactly that name (see readAuthDirEntries). */
+ private authDirExists(dir: string): boolean {
+ try {
+ return readAuthDirEntries(path.dirname(dir)).has(path.basename(dir));
+ } catch {
+ return false; // base directory missing or unreadable: nothing of this shape to purge
+ }
}
private isEnginePlugin(instance: unknown): instance is IEnginePlugin {
diff --git a/src/engine/types/baileys.types.ts b/src/engine/types/baileys.types.ts
index 47a21d49b..c8770e512 100644
--- a/src/engine/types/baileys.types.ts
+++ b/src/engine/types/baileys.types.ts
@@ -26,7 +26,7 @@ export interface BaileysMessageStore {
* (the adapter appends the session id to isolate each session).
*/
export interface BaileysAdapterConfig {
- /** Session NAME — keys the on-disk auth directory and LID-mapping provenance. */
+ /** Session UUID (Session.id) — keys the on-disk auth directory, chat state and LID provenance. */
sessionId: string;
/** Session UUID (Session.id) — keys the FK-bound baileys_stored_messages rows via messageStore. */
dbSessionId: string;
diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.ts
index e5d20de95..cbbea189c 100644
--- a/src/modules/infra/table-importers.ts
+++ b/src/modules/infra/table-importers.ts
@@ -65,9 +65,10 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [
sql: `INSERT INTO sessions (id, name, status, phone, "pushName", config, "proxyUrl", "proxyType", "connectedAt", "lastActiveAt", "createdAt", "updatedAt")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
id: (session: SessionRow) => session.id,
- // A session name becomes the engine auth-directory key, so an unvalidated imported name (this
- // path bypasses CreateSessionDto) could traverse the filesystem. Skip + warn instead of
- // throwing, so one bad row doesn't 500 the whole restore.
+ // A session name is still weighed against the on-disk auth directories (the boot migration and
+ // the legacy purge on delete), so an unvalidated imported name (this path bypasses
+ // CreateSessionDto) could traverse the filesystem. Skip + warn instead of throwing, so one bad
+ // row doesn't 500 the whole restore.
skip: (session: SessionRow) => {
if (isSafeSessionName(session.name)) return null;
return `Skipped session ${session.id}: unsafe name ${JSON.stringify(session.name)}`;
diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.ts
index da48432e7..065c1f08d 100644
--- a/src/modules/session/logout-teardown-race.spec.ts
+++ b/src/modules/session/logout-teardown-race.spec.ts
@@ -229,7 +229,7 @@ describe('SessionService logout() name-scoped teardown fence', () => {
releaseLogout();
await deleteCall;
- expect(engineFactory.purgeSessionData).toHaveBeenCalledWith(SESSION_NAME);
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith(SESSION_UUID, SESSION_NAME);
expect(pendingOf().has(SESSION_NAME)).toBe(false);
} finally {
jest.useRealTimers();
diff --git a/src/modules/session/session-auth-dir-migration.service.spec.ts b/src/modules/session/session-auth-dir-migration.service.spec.ts
new file mode 100644
index 000000000..ea3846737
--- /dev/null
+++ b/src/modules/session/session-auth-dir-migration.service.spec.ts
@@ -0,0 +1,206 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { ConfigService } from '@nestjs/config';
+import { Repository } from 'typeorm';
+import { SessionAuthDirMigration } from './session-auth-dir-migration.service';
+import { Session } from './entities/session.entity';
+
+// Real temporary directories throughout: the whole point of the migration is what it does to the
+// filesystem, and the case-insensitivity trap it avoids is invisible to a mocked fs.
+describe('SessionAuthDirMigration', () => {
+ const ALICE_ID = '8f5b1d9e-0c4a-4e21-9d6b-2a7c3f0e1b44';
+ const BOB_ID = '1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f';
+
+ let tmpRoot: string;
+ let sessionsDir: string;
+ let baileysDir: string;
+
+ beforeEach(() => {
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'auth-dir-migration-'));
+ sessionsDir = path.join(tmpRoot, 'sessions');
+ baileysDir = path.join(tmpRoot, 'baileys');
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ const buildMigration = (rows: Array<Pick<Session, 'id' | 'name'>>): SessionAuthDirMigration => {
+ const repository = { find: jest.fn().mockResolvedValue(rows) } as unknown as Repository<Session>;
+ const values: Record<string, unknown> = {
+ 'engine.sessionDataPath': sessionsDir,
+ 'engine.baileys.authDir': baileysDir,
+ };
+ const configService = { get: jest.fn((key: string) => values[key]) } as unknown as ConfigService;
+ return new SessionAuthDirMigration(repository, configService);
+ };
+
+ const seed = (dir: string, marker: string): void => {
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'creds.json'), marker);
+ };
+
+ const markerAt = (dir: string): string => fs.readFileSync(path.join(dir, 'creds.json'), 'utf8');
+
+ it('renames the legacy name-keyed directories of both engines onto the session id', async () => {
+ seed(path.join(sessionsDir, 'session-alice'), 'wwjs-alice');
+ seed(path.join(baileysDir, 'alice'), 'baileys-alice');
+
+ await buildMigration([{ id: ALICE_ID, name: 'alice' }]).onModuleInit();
+
+ expect(markerAt(path.join(sessionsDir, `session-${ALICE_ID}`))).toBe('wwjs-alice');
+ expect(markerAt(path.join(baileysDir, ALICE_ID))).toBe('baileys-alice');
+ expect(fs.existsSync(path.join(sessionsDir, 'session-alice'))).toBe(false);
+ expect(fs.existsSync(path.join(baileysDir, 'alice'))).toBe(false);
+ });
+
+ it('is a no-op when the id-keyed directory is already the only one (a second boot)', async () => {
+ seed(path.join(sessionsDir, `session-${ALICE_ID}`), 'wwjs-alice');
+ seed(path.join(baileysDir, ALICE_ID), 'baileys-alice');
+
+ const migration = buildMigration([{ id: ALICE_ID, name: 'alice' }]);
+ await migration.onModuleInit();
+ await migration.onModuleInit();
+
+ expect(markerAt(path.join(sessionsDir, `session-${ALICE_ID}`))).toBe('wwjs-alice');
+ expect(fs.readdirSync(sessionsDir)).toEqual([`session-${ALICE_ID}`]);
+ expect(fs.readdirSync(baileysDir)).toEqual([ALICE_ID]);
+ });
+
+ it('leaves both directories in place and warns when a legacy and an id-keyed one coexist', async () => {
+ seed(path.join(sessionsDir, 'session-alice'), 'legacy');
+ seed(path.join(sessionsDir, `session-${ALICE_ID}`), 'current');
+ const migration = buildMigration([{ id: ALICE_ID, name: 'alice' }]);
+ const warn = jest
+ .spyOn((migration as unknown as { logger: { warn: jest.Mock } }).logger, 'warn')
+ .mockImplementation(() => undefined);
+
+ await migration.onModuleInit();
+
+ expect(markerAt(path.join(sessionsDir, 'session-alice'))).toBe('legacy');
+ expect(markerAt(path.join(sessionsDir, `session-${ALICE_ID}`))).toBe('current');
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('alice'),
+ expect.objectContaining({ action: 'auth_dir_migration_conflict' }),
+ );
+ });
+
+ it('does nothing on a fresh install, where neither base directory exists', async () => {
+ await expect(buildMigration([{ id: ALICE_ID, name: 'alice' }]).onModuleInit()).resolves.toBeUndefined();
+
+ expect(fs.existsSync(sessionsDir)).toBe(false);
+ expect(fs.existsSync(baileysDir)).toBe(false);
+ });
+
+ // The #1597 scenario: on a case-insensitive filesystem `alice` and `Alice` are two rows sharing
+ // ONE directory. Matching the on-disk entry name exactly (rather than asking existsSync) is what
+ // stops the migration handing `alice`'s WhatsApp login to `Alice`.
+ it('moves only the directory whose stored name matches exactly, never a case variant', async () => {
+ seed(path.join(sessionsDir, 'session-alice'), 'wwjs-alice');
+
+ // `Alice` is listed FIRST, so an existsSync-based check would rename the directory onto its id
+ // before `alice` is reached. The two assertions only diverge on a case-insensitive filesystem,
+ // which is where the bug lives and which CI is not; on a case-sensitive one they hold trivially.
+ await buildMigration([
+ { id: BOB_ID, name: 'Alice' },
+ { id: ALICE_ID, name: 'alice' },
+ ]).onModuleInit();
+
+ expect(markerAt(path.join(sessionsDir, `session-${ALICE_ID}`))).toBe('wwjs-alice');
+ expect(fs.existsSync(path.join(sessionsDir, `session-${BOB_ID}`))).toBe(false);
+ });
+
+ it('warns that only one of two case-colliding sessions keeps its stored login', async () => {
+ seed(path.join(sessionsDir, 'session-alice'), 'wwjs-alice');
+ const migration = buildMigration([
+ { id: ALICE_ID, name: 'alice' },
+ { id: BOB_ID, name: 'Alice' },
+ ]);
+ const warn = jest
+ .spyOn((migration as unknown as { logger: { warn: jest.Mock } }).logger, 'warn')
+ .mockImplementation(() => undefined);
+
+ await migration.onModuleInit();
+
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('differ only in letter case'),
+ expect.objectContaining({ action: 'auth_dir_case_collision' }),
+ );
+ });
+
+ // Names cannot be renamed, so a warning that ignores the disk would repeat at every boot forever,
+ // and on a case-sensitive filesystem (or for names created after the upgrade) it is simply untrue:
+ // each row has always had a directory of its own.
+ it('stays silent about case-colliding names when no legacy directory was found for them', async () => {
+ seed(path.join(sessionsDir, `session-${ALICE_ID}`), 'wwjs-alice');
+ seed(path.join(baileysDir, BOB_ID), 'baileys-bob');
+ const migration = buildMigration([
+ { id: ALICE_ID, name: 'alice' },
+ { id: BOB_ID, name: 'Alice' },
+ ]);
+ const warn = jest
+ .spyOn((migration as unknown as { logger: { warn: jest.Mock } }).logger, 'warn')
+ .mockImplementation(() => undefined);
+
+ await migration.onModuleInit();
+
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ // Dirent.isDirectory() is false for a symlink, and an operator who moved a large profile onto
+ // another volume has one here. Renaming the link is what keeps that install working.
+ it('renames a symlinked legacy directory, leaving its target where it is', async () => {
+ const relocated = path.join(tmpRoot, 'elsewhere', 'alice-profile');
+ seed(relocated, 'wwjs-alice');
+ fs.mkdirSync(sessionsDir, { recursive: true });
+ fs.symlinkSync(relocated, path.join(sessionsDir, 'session-alice'));
+
+ await buildMigration([{ id: ALICE_ID, name: 'alice' }]).onModuleInit();
+
+ expect(fs.readlinkSync(path.join(sessionsDir, `session-${ALICE_ID}`))).toBe(relocated);
+ expect(markerAt(path.join(sessionsDir, `session-${ALICE_ID}`))).toBe('wwjs-alice');
+ expect(markerAt(relocated)).toBe('wwjs-alice');
+ });
+
+ // A base directory that exists but cannot be listed (EACCES after the container user changed,
+ // ENOTDIR when the path is a file) skips EVERY session under it, so it must not look like a fresh
+ // install: without a line here the sessions come back at a QR with nothing to explain it.
+ it('warns when the base directory exists but cannot be listed', async () => {
+ fs.writeFileSync(sessionsDir, 'not a directory');
+ const migration = buildMigration([{ id: ALICE_ID, name: 'alice' }]);
+ const warn = jest
+ .spyOn((migration as unknown as { logger: { warn: jest.Mock } }).logger, 'warn')
+ .mockImplementation(() => undefined);
+
+ await migration.onModuleInit();
+
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('whatsapp-web.js'),
+ expect.objectContaining({ action: 'auth_dir_migration_unreadable' }),
+ );
+ });
+
+ // Not reachable through the API (CreateSessionDto restricts names), but a row written outside the
+ // app can carry one: path.join + basename would resolve `../alice` onto alice's own directory and
+ // rename her login onto the crafted row's id.
+ it('never lets a traversal name reach the rename, leaving the session it points at alone', async () => {
+ seed(path.join(baileysDir, 'alice'), 'baileys-alice');
+
+ await buildMigration([
+ { id: BOB_ID, name: '../alice' },
+ { id: ALICE_ID, name: 'alice' },
+ ]).onModuleInit();
+
+ expect(markerAt(path.join(baileysDir, ALICE_ID))).toBe('baileys-alice');
+ expect(fs.existsSync(path.join(baileysDir, BOB_ID))).toBe(false);
+ });
+
+ it('skips the query and the filesystem entirely when there are no sessions', async () => {
+ seed(path.join(sessionsDir, 'session-orphan'), 'orphan');
+
+ await buildMigration([]).onModuleInit();
+
+ expect(fs.readdirSync(sessionsDir)).toEqual(['session-orphan']);
+ });
+});
diff --git a/src/modules/session/session-auth-dir-migration.service.ts b/src/modules/session/session-auth-dir-migration.service.ts
new file mode 100644
index 000000000..e8cac0d13
--- /dev/null
+++ b/src/modules/session/session-auth-dir-migration.service.ts
@@ -0,0 +1,171 @@
+import * as fs from 'fs';
+import * as path from 'path';
+import { Injectable, OnModuleInit } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import { InjectRepository } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
+import { Session } from './entities/session.entity';
+import { baileysAuthDir, readAuthDirEntries, wwjsAuthDir } from '../../engine/auth-dir-paths';
+import { isSafeSessionName } from '../../common/utils/path-safety';
+import { createLogger } from '../../common/services/logger.service';
+
+/**
+ * One-time rename of the engine auth directories from the legacy `Session.name` key to `Session.id`.
+ *
+ * Runs in `onModuleInit`, which Nest completes for EVERY module before the first
+ * `onApplicationBootstrap` hook: auto-start launches engines from that later hook and the HTTP
+ * listener binds later still, so no engine can have opened a directory while this runs.
+ *
+ * Safety properties, in the order they matter:
+ *
+ * - It only ever RENAMES. A legacy directory is never deleted, so a run that fails halfway (or a
+ * second node racing this one) can lose nothing: `rename` is atomic within a filesystem, so each
+ * directory is either at its old path or its whole self at the new one, and the loser of a race
+ * gets ENOENT and logs.
+ * - It is idempotent. After a successful run the legacy entry is gone, so the next boot matches
+ * nothing. A directory already at the id key is left alone.
+ * - It matches the on-disk entry name EXACTLY, from a directory listing, rather than asking
+ * `fs.existsSync` whether the legacy path exists. That is what makes it safe on the
+ * case-insensitive filesystems the bug (#1597) comes from: there, `existsSync` answers yes for
+ * `session-My-Bot` when only `session-my-bot` is stored, and the rename would hand one session's
+ * WhatsApp login to another. An exact match moves each directory to the id of the row that really
+ * owns it.
+ * - A missing base directory (fresh install, or an engine never used here) is a no-op.
+ *
+ * Keep it beyond one release: an operator can upgrade from any older version, and the directories
+ * they bring are name-keyed.
+ */
+@Injectable()
+export class SessionAuthDirMigration implements OnModuleInit {
+ private readonly logger = createLogger('SessionAuthDirMigration');
+
+ constructor(
+ @InjectRepository(Session, 'data')
+ private readonly sessionRepository: Repository<Session>,
+ private readonly configService: ConfigService,
+ ) {}
+
+ async onModuleInit(): Promise<void> {
+ const rows = await this.sessionRepository.find({ select: { id: true, name: true } });
+ if (rows.length === 0) return;
+
+ // Sink guard, the same one EngineFactory keeps for the same reason: `legacy` below is derived
+ // from a stored name, and a row written outside the app (a crafted archive) could carry
+ // `../alice`, whose path.join + basename resolves onto another session's directory and would
+ // rename that login onto this row's id. Names the API accepts can never fail this.
+ const sessions = rows.filter(row => isSafeSessionName(row.name) && isSafeSessionName(row.id));
+ if (sessions.length < rows.length) {
+ this.logger.warn(
+ `Skipped ${rows.length - sessions.length} session(s) whose name or id is not a safe auth-directory key; ` +
+ 'their auth directories stay where they are and those sessions start at a QR code.',
+ { action: 'auth_dir_migration_unsafe_key' },
+ );
+ }
+
+ const sessionDataPath = this.configService.get<string>('engine.sessionDataPath') ?? './data/sessions';
+ const authDir = this.configService.get<string>('engine.baileys.authDir') ?? './data/baileys';
+ // Both engine shapes, whatever ENGINE_TYPE says: a session that ever ran under the other engine
+ // still has a live auth directory there, and leaving it name-keyed would strand it (the same
+ // reason EngineFactory.purgeSessionData removes both).
+ const found = [
+ ...this.migrateBase('whatsapp-web.js', sessions, path.resolve(sessionDataPath), key =>
+ wwjsAuthDir(sessionDataPath, key),
+ ),
+ ...this.migrateBase('baileys', sessions, authDir, key => baileysAuthDir(authDir, key)),
+ ];
+ this.warnOnCaseCollisions(sessions, new Set(found));
+ }
+
+ /**
+ * Rename every legacy directory under one engine's base directory, and return the names a legacy
+ * directory was actually found for. The entry names come from `dirFor`, the same builder the
+ * adapters use, so the per-engine shape (`session-<key>` for whatsapp-web.js, a bare `<key>` for
+ * baileys) is not spelled out a second time here.
+ */
+ private migrateBase(engine: string, sessions: Session[], base: string, dirFor: (key: string) => string): string[] {
+ let entries: Set<string>;
+ try {
+ entries = readAuthDirEntries(base);
+ } catch (error) {
+ // ENOENT is the ordinary case: a fresh install, or an engine that never stored credentials
+ // here. Anything else (EACCES after the container user changed, ENOTDIR) skips EVERY session
+ // on this engine, which looks exactly like an unexplained mass unlink unless it is said here.
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ this.logger.warn(`Could not list the ${engine} auth directory, so no session was migrated under it`, {
+ action: 'auth_dir_migration_unreadable',
+ engine,
+ base,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ return [];
+ }
+
+ const found: string[] = [];
+ for (const session of sessions) {
+ const legacy = path.basename(dirFor(session.name));
+ const target = path.basename(dirFor(session.id));
+ if (legacy === target || !entries.has(legacy)) continue;
+ found.push(session.name);
+ if (entries.has(target)) {
+ this.logger.warn(
+ `Session "${session.name}" has both a legacy and an id-keyed ${engine} auth directory; ` +
+ `keeping both and using the id-keyed one. Remove "${path.join(base, legacy)}" once you have ` +
+ 'confirmed the session links correctly.',
+ { sessionId: session.id, action: 'auth_dir_migration_conflict', engine, legacy, target },
+ );
+ continue;
+ }
+ try {
+ fs.renameSync(path.join(base, legacy), path.join(base, target));
+ entries.delete(legacy);
+ entries.add(target);
+ this.logger.log(`Moved the ${engine} auth directory of session "${session.name}" onto its session id`, {
+ sessionId: session.id,
+ action: 'auth_dir_migrated',
+ engine,
+ legacy,
+ target,
+ });
+ } catch (error) {
+ this.logger.warn(`Could not move the ${engine} auth directory of session "${session.name}"`, {
+ sessionId: session.id,
+ action: 'auth_dir_migration_failed',
+ engine,
+ legacy,
+ target,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ return found;
+ }
+
+ /**
+ * Names that differ only in case are distinct rows but were ONE directory on a case-insensitive
+ * filesystem, so at most one of them can carry the stored login forward: the rename above matches
+ * the on-disk entry exactly, so the row whose name is the stored one keeps it and the others come
+ * back at a QR. Say so at boot, or that re-pairing looks like an unexplained unlink.
+ *
+ * Only for a group the walk really found a legacy directory for (`legacyNames`): names cannot be
+ * renamed, so warning on the names alone would repeat at every boot forever, and it would be
+ * untrue on a case-sensitive filesystem and on names created after the upgrade, where each row has
+ * always had a directory of its own.
+ */
+ private warnOnCaseCollisions(sessions: Session[], legacyNames: Set<string>): void {
+ const byFoldedName = new Map<string, string[]>();
+ for (const session of sessions) {
+ const folded = session.name.toLowerCase();
+ byFoldedName.set(folded, [...(byFoldedName.get(folded) ?? []), session.name]);
+ }
+ for (const names of byFoldedName.values()) {
+ if (names.length < 2 || !names.some(name => legacyNames.has(name))) continue;
+ this.logger.warn(
+ `Sessions ${names.map(name => `"${name}"`).join(', ')} have names that differ only in letter case. ` +
+ 'On a case-insensitive filesystem they shared one engine auth directory, so only one keeps its ' +
+ 'stored WhatsApp login; the others come back with a QR to scan.',
+ { action: 'auth_dir_case_collision', names },
+ );
+ }
+ }
+}
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index a152e61f0..982d30389 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -57,7 +57,7 @@ export interface SessionEngineControlsHost {
cancelReconnect(id: string): void;
initializeEngine(id: string, session: Session): Promise<void>;
isSessionRetired(id: string): Promise<boolean>;
- purgeAuthDirsIfDeleted(id: string, name: string): Promise<void>;
+ purgeAuthDirsIfDeleted(id: string): Promise<void>;
updateStatus(id: string, status: SessionStatus): Promise<void>;
/** Ownership gate, same contract as SessionEngineWiringHost.ownsSession. */
ownsSession(id: string): boolean;
@@ -175,9 +175,9 @@ export class SessionEngineControls {
// checks and BEFORE any lifecycle mutation (stop-mark clear, hook, reconnect-state, engine
// creation, recovery-budget reset) or auth-dir access. A logout teardown that lost its deadline
// race is still running and ends in an fs.rm of this session's on-disk profile — the same path
- // initializeEngine is about to populate. The fence is keyed by session NAME (the auth-dir key)
- // and FAIL CLOSED: a still-wedged teardown could still rm a fresh profile under this name, so
- // refuse with a retryable 409 instead of proceeding. On a 409, no lifecycle state is touched
+ // initializeEngine is about to populate. The fence is keyed by session NAME (see
+ // awaitPendingTeardown) and FAIL CLOSED: a still-wedged teardown could still rm the fresh
+ // profile, so refuse with a retryable 409 instead of proceeding. On a 409, no lifecycle state is touched
// (the stop mark, reconnect timer, engine, last status/error, and recovery budget are left as
// they were) — start() simply did not happen. The one transient exception is the
// initializingSessions reservation added synchronously at start() entry: its finally removes it
@@ -262,7 +262,7 @@ export class SessionEngineControls {
}
// A delete() that raced this start purged the on-disk auth dirs BEFORE this init re-created
// them — purge again so the window leaves no credential residue behind (no-op for a stop()).
- await this.host.purgeAuthDirsIfDeleted(id, session.name);
+ await this.host.purgeAuthDirsIfDeleted(id);
}
return this.requireSession(id);
} finally {
@@ -375,9 +375,9 @@ export class SessionEngineControls {
// Await THIS engine's in-flight INITIALIZING write before teardown / the final DISCONNECTED
// write so a delayed pre-initialize status update can never settle after the retirement.
await this.fences.awaitInitialStatus(id, engine);
- // The credential fence is keyed by session NAME (the auth-dir key). Captured immutably here so a
- // raw logout that outlives its deadline race is tracked under the right name even if the row is
- // later deleted/recreated.
+ // The credential fence is keyed by session NAME (see awaitPendingTeardown). Captured immutably
+ // here so a raw logout that outlives its deadline race is tracked under the right name even if
+ // the row is later deleted/recreated.
const unlinked = await this.fences.teardownEngineSafely(id, engine, e => e.logout(), 'logout', session.name);
this.engines.deleteIfLive(id, engine);
await this.host.updateStatus(id, SessionStatus.DISCONNECTED);
@@ -458,9 +458,9 @@ export class SessionEngineControls {
// FENCE #1 — fail-fast on an ALREADY-PENDING credential teardown for this session NAME, BEFORE
// any lifecycle mutation. A logout teardown that lost its deadline race is still running and ends
- // in an fs.rm of this session's on-disk auth dir (keyed by name). Releasing the name via the DB
- // delete below while that rm is live would let a recreated session under the same name race the
- // stale rm. The fence is keyed by session NAME and fails CLOSED (409). On a 409 NOTHING else runs:
+ // in an fs.rm of this session's on-disk auth dir. Running the purge below while that rm is live
+ // would leave the two removals racing over the same tree, and a stale rm must not outlive the
+ // row. The fence is keyed by session NAME and fails CLOSED (409). On a 409 NOTHING else runs:
// no stop mark, no reconnect cancel, no engine teardown, no state cleanup — delete() simply did
// not happen, and the entry stays reserved.
await this.fences.awaitPendingTeardown(session.name);
@@ -552,12 +552,13 @@ export class SessionEngineControls {
// Purge the persistent on-disk auth/store dirs — BOTH engine shapes (see EngineFactory), since
// an engine switch may have left a live link for the other engine behind. They're keyed by
- // session NAME and live independently of the (now torn-down, and on delete often never-loaded)
- // engine instance, so the teardown above doesn't touch them. Without this, recreating a session
- // under the same name reloads a stale store. Best-effort inside the factory — never fails an
- // otherwise-successful delete. By this point both fences passed, so no old remover is live
- // against this name (the transaction freed the name; the dirs are safe to purge).
- await this.engineFactory.purgeSessionData(session.name);
+ // session ID and live independently of the (now torn-down, and on delete often never-loaded)
+ // engine instance, so the teardown above doesn't touch them. Without this, the deleted
+ // session's WhatsApp credentials stay on the volume. Best-effort inside the factory — never
+ // fails an otherwise-successful delete. By this point both fences passed, so no old remover is
+ // live against this session's directories. The name goes too: it is the key the directories
+ // carried before 0.23.5, and the boot migration keeps a legacy one it could not rename.
+ await this.engineFactory.purgeSessionData(session.id, session.name);
} finally {
// Always clear the teardown mark so a later recreate/start with this id isn't suppressed. This
// stop mark was set after fence #1, so clearing it on a rejected 409 only undoes what THIS
diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.ts
index b9b3e3111..0c2c37e8f 100644
--- a/src/modules/session/session-engine-event-wiring.ts
+++ b/src/modules/session/session-engine-event-wiring.ts
@@ -484,12 +484,12 @@ export class SessionEngineEventWiring {
},
onCredentialTeardownStarted: (operation: Promise<void>): void => {
// The adapter fired the moment it began the call that ends in an fs.rm of this session's
- // on-disk auth dir. Track it under the captured session NAME (the auth-dir key) — NOT the
- // UUID, and NOT guarded on this engine still being live: a logout that captured this engine
- // must register its destructive promise even as a concurrent stop()/delete() evicts it,
- // because the rm targets the session name's dir and would otherwise race a (re)created
- // session under that same name. `session.name` is the immutable snapshot captured at
- // initializeEngine entry, so a row delete/recreate under the same name cannot poison the key.
+ // on-disk auth dir. Track it under the captured session NAME (the fence key — see
+ // awaitPendingTeardown), and NOT guarded on this engine still being live: a logout that
+ // captured this engine must register its destructive promise even as a concurrent
+ // stop()/delete() evicts it, or the rm would race a start this fence should have held back.
+ // `session.name` is the immutable snapshot captured at initializeEngine entry, so a row
+ // delete/recreate under the same name cannot poison the key.
host.trackPendingCredentialTeardown(sessionName, operation);
},
claimStuckAuthRecovery: (): boolean => host.claimStuckAuthRecovery(id, engine),
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 9f33cc99f..8e73c6950 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -218,15 +218,16 @@ export class SessionEngineLifecycle {
}
// Destructive credential-teardown promises (logout rms of the session's on-disk WhatsApp auth
- // dir), keyed by session NAME — the on-disk auth-dir key (EngineFactory.wwjsAuthDir/baileysAuthDir
- // and adapter clearLocalAuth all build the path from Session.name), NOT the UUID. A losing
- // logout() promise keeps running past its deadline race and ends in an fs.rm of that dir — the
- // same path a later start() under the SAME name re-creates — so start()/delete()/executeReconnect
- // consult this map and wait (bounded, fail-closed) for settlement before touching that path. After
- // an old UUID's session is deleted and the name is recreated, a late logout from the old UUID
- // still targets the new session's dir (same name → same path), so keying by name keeps the fence
- // attached to the credential path that is actually at risk. Entries self-remove on settlement
- // (identity-checked); nothing else evicts them (delete()'s finally no longer drops them).
+ // dir), keyed by session NAME. A losing logout() promise keeps running past its deadline race and
+ // ends in an fs.rm of that dir — the same path a later start() re-creates — so
+ // start()/delete()/executeReconnect consult this map and wait (bounded, fail-closed) for
+ // settlement before touching that path. The dirs themselves are keyed by Session.id (#1597), and
+ // the name is unique, so for a live row the two keys are 1:1 and the name fence covers exactly the
+ // id's path; across a delete and a recreate under the same name it merely holds the new session
+ // back a little longer than strictly needed, which is the safe direction. The name is also what
+ // the public refusal code (SESSION_NAME_TEARDOWN_PENDING) is documented against. Entries
+ // self-remove on settlement (identity-checked); nothing else evicts them (delete()'s finally no
+ // longer drops them).
private readonly pendingTeardowns = new Map<string, Promise<void>>();
// The in-flight `updateStatus(INITIALIZING)` write keyed by id, carrying the EXACT engine it
@@ -376,7 +377,7 @@ export class SessionEngineLifecycle {
cancelReconnect: id => this.cancelReconnect(id),
initializeEngine: (id, session) => this.initializeEngine(id, session),
isSessionRetired: id => this.isSessionRetired(id),
- purgeAuthDirsIfDeleted: (id, name) => this.purgeAuthDirsIfDeleted(id, name),
+ purgeAuthDirsIfDeleted: id => this.purgeAuthDirsIfDeleted(id),
updateStatus: (id, status) => this.updateStatus(id, status),
stoppingSessions: this.stoppingSessions,
reconnectStates: this.reconnectStates,
@@ -567,8 +568,11 @@ export class SessionEngineLifecycle {
proxyEnabled: !!session.proxyUrl,
});
+ // The engine is keyed by the session UUID, not its name: names are unique case-sensitively, so
+ // two rows differing only in case shared one auth directory on a case-insensitive filesystem
+ // (#1597). SessionAuthDirMigration renames the legacy name-keyed directories at boot.
const engine = this.engineFactory.create({
- sessionId: session.name,
+ sessionId: id,
dbSessionId: id,
proxyUrl: session.proxyUrl || undefined,
proxyType: session.proxyType || undefined,
@@ -1082,17 +1086,16 @@ export class SessionEngineLifecycle {
* engine eviction and its row removal initializes a fresh engine that RE-CREATES the auth dir
* purgeSessionData just emptied (both engines mkdir at init); the post-init guard tears the engine
* down, but engine teardown never touches the on-disk dirs, so without this second purge the race
- * leaves live WhatsApp credentials behind — and a later same-name recreate would silently re-link
- * them. Gated two ways so ONLY the delete race purges: a stop() retirement still has its row (its
- * credentials must survive), and a row re-created under the SAME name now owns those dirs, so
- * purging would wipe the fresh session's link. Best-effort: a failure is logged, never thrown —
- * the retirement path must still surface the deleted session as NotFound.
+ * leaves live WhatsApp credentials behind on the volume. Gated on the row so ONLY the delete race
+ * purges: a stop() retirement still has its row and its credentials must survive. The dirs are
+ * keyed by the session id, which no recreate can reuse, so a surviving row under the same NAME is
+ * no longer consulted: it owns a different directory. Best-effort: a failure is logged, never
+ * thrown — the retirement path must still surface the deleted session as NotFound.
*/
- private async purgeAuthDirsIfDeleted(id: string, name: string): Promise<void> {
+ private async purgeAuthDirsIfDeleted(id: string): Promise<void> {
try {
if ((await this.sessionRepository.findOne({ where: { id } })) != null) return;
- if ((await this.sessionRepository.findOne({ where: { name } })) != null) return;
- await this.engineFactory.purgeSessionData(name);
+ await this.engineFactory.purgeSessionData(id);
} catch (error) {
this.logger.warn('Failed to re-purge session auth dirs after a start/delete race', {
sessionId: id,
@@ -1130,7 +1133,7 @@ export class SessionEngineLifecycle {
// Credential-teardown fence — BEFORE engineFactory.create (inside initializeEngine). A logout
// teardown that lost its deadline race is still running and ends in an fs.rm of this session's
// on-disk profile — the same path initializeEngine is about to populate. Keyed by session NAME
- // (the auth-dir key) and FAIL CLOSED: a timeout becomes a failed reconnect attempt that is
+ // (see awaitPendingTeardown) and FAIL CLOSED: a timeout becomes a failed reconnect attempt that is
// rescheduled WITHOUT touching the auth dir (the catch below schedules the next attempt; no
// engine was created, so there is nothing to evict and no dir to purge).
await this.awaitPendingTeardown(session.name);
@@ -1170,7 +1173,7 @@ export class SessionEngineLifecycle {
}
// Same start/delete window as start()'s post-init guard: this re-init re-created auth dirs
// delete() had already purged — purge again so no credentials outlive the row.
- await this.purgeAuthDirsIfDeleted(id, session.name);
+ await this.purgeAuthDirsIfDeleted(id);
return;
}
} catch (error: unknown) {
diff --git a/src/modules/session/session-lifecycle-fences.ts b/src/modules/session/session-lifecycle-fences.ts
index 200ea8eb6..24494fd21 100644
--- a/src/modules/session/session-lifecycle-fences.ts
+++ b/src/modules/session/session-lifecycle-fences.ts
@@ -54,8 +54,8 @@ export class SessionLifecycleFences {
* A teardown that loses the deadline race keeps running past the caller's return. For 'logout'
* that leftover promise ends in an fs.rm of the session's on-disk profile — the same path a
* later start() re-creates — so the raw promise is registered in pendingTeardowns (keyed by the
- * session NAME, which is the auth-dir key) and start()/delete() wait (bounded, fail-closed) for
- * it to settle before touching that path.
+ * session NAME, 1:1 with the live row whose id keys that dir) and start()/delete() wait (bounded,
+ * fail-closed) for it to settle before touching that path.
*/
async teardownEngineSafely(
sessionId: string,
@@ -89,10 +89,10 @@ export class SessionLifecycleFences {
}
/**
- * Track a destructive credential-teardown promise under the session NAME (the on-disk auth-dir
- * key — NOT the UUID). A logout's `engine.logout()` ends in an `fs.rm` of the same directory a
- * later start() under the same name re-creates, so start()/delete()/executeReconnect consult this
- * map and wait (bounded, fail-closed) before touching that path.
+ * Track a destructive credential-teardown promise under the session NAME. A logout's
+ * `engine.logout()` ends in an `fs.rm` of the same directory a later start() re-creates, so
+ * start()/delete()/executeReconnect consult this map and wait (bounded, fail-closed) before
+ * touching that path. See awaitPendingTeardown for why the name, not the id, is the key.
*
* Settlement marker only — never rejects, so it can't drive a caller's deadline race to a false
* "completed". A concurrent teardown for the same name CHAINS onto the previous entry instead of
@@ -117,14 +117,16 @@ export class SessionLifecycleFences {
* Wait (bounded) for a teardown that lost its deadline race to settle. A losing logout() promise
* ends in an fs.rm of the on-disk profile — the same deterministic path start() re-creates and
* delete() purges — so those paths call this before touching disk. The fence is FAIL CLOSED: a
- * teardown still wedged past the bound could still land its rm on credentials a (re)created session
- * under the same name would write, so the operation refuses with a retryable 409
- * (SESSION_NAME_TEARDOWN_PENDING) instead of proceeding. The entry is NOT dropped on timeout — a
- * retry after the rm eventually settles will see it gone and proceed.
+ * teardown still wedged past the bound could still land its rm on credentials a (re)started session
+ * would write, so the operation refuses with a retryable 409 (SESSION_NAME_TEARDOWN_PENDING)
+ * instead of proceeding. The entry is NOT dropped on timeout — a retry after the rm eventually
+ * settles will see it gone and proceed.
*
- * Keyed by the session NAME: the auth directories are built from `Session.name`, so two sessions
- * sharing a name (a deleted UUID recreated under the same name) share the credential path and must
- * share the fence.
+ * Keyed by the session NAME even though the auth directories are keyed by `Session.id` (#1597):
+ * the name is unique, so for a live row the two keys are 1:1 and this fence covers exactly the
+ * directory at risk. Across a delete and a recreate under the same name it holds the new session
+ * back a little longer than strictly needed, which is the safe direction, and it keeps the public
+ * refusal code meaning what it says.
*/
async awaitPendingTeardown(sessionName: string): Promise<void> {
const pending = this.pendingTeardowns.get(sessionName);
diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.ts
index 7555f8f1e..37885a121 100644
--- a/src/modules/session/session.module.ts
+++ b/src/modules/session/session.module.ts
@@ -4,6 +4,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { Session } from './entities/session.entity';
import { Message } from '../message/entities/message.entity';
import { SessionService } from './session.service';
+import { SessionAuthDirMigration } from './session-auth-dir-migration.service';
import { SessionEngineLifecycle } from './session-engine-lifecycle.service';
import { SessionLidResolver } from './session-lid-resolver.service';
import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
@@ -35,6 +36,10 @@ import { PLUGIN_SESSION_PORT } from '../../core/plugins/plugin-host-ports';
// Global on purpose: any controller may carry a session dimension. Inert unless NODE_URL is set.
{ provide: APP_INTERCEPTOR, useClass: SessionProxyInterceptor },
SessionService,
+ // onModuleInit only, and every module's runs before the first onApplicationBootstrap, so the
+ // legacy name-keyed auth directories are moved onto their session ids before auto-start or the
+ // HTTP listener can open one.
+ SessionAuthDirMigration,
SessionEngineLifecycle,
SessionErrorStore,
SessionRestrictionStore,
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 95fa3c7a8..96f93a691 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -303,7 +303,7 @@ describe('SessionService', () => {
expect(dataSource.transaction).toHaveBeenCalled(); // DB removal still ran
});
- it('delete() purges the on-disk auth dirs (keyed by session NAME) so a same-name recreate starts clean', async () => {
+ it('delete() purges the on-disk auth dirs, keyed by the session id, so no credentials outlive the row', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(
createMockSession({ id: 'sess-uuid-1', name: 'test-session' }),
);
@@ -311,7 +311,9 @@ describe('SessionService', () => {
await service.delete('sess-uuid-1');
- expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');
+ // The name goes with it: a legacy name-keyed directory the boot migration could not rename is
+ // still a complete WhatsApp login, and delete is the only path that can take it.
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('sess-uuid-1', 'test-session');
});
it('delete() delegates the both-engines purge exactly once, after the DB rows are removed', async () => {
@@ -322,10 +324,10 @@ describe('SessionService', () => {
await expect(service.delete('sess-uuid-1')).resolves.toBeUndefined();
// The factory owns the per-engine best-effort isolation (covered in engine.factory.spec);
- // the service hands it the session NAME once, only after the DB removal has committed.
+ // the service hands it the session ID once, only after the DB removal has committed.
expect(dataSource.transaction).toHaveBeenCalled();
expect(engineFactory.purgeSessionData).toHaveBeenCalledTimes(1);
- expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('sess-uuid-1', 'test-session');
const txOrder = (dataSource.transaction as jest.Mock).mock.invocationCallOrder[0];
const purgeOrder = (engineFactory.purgeSessionData as jest.Mock).mock.invocationCallOrder[0];
expect(txOrder).toBeLessThan(purgeOrder);
@@ -339,7 +341,7 @@ describe('SessionService', () => {
await service.delete('sess-uuid-1');
- expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('sess-uuid-1', 'test-session');
});
it('stop() escalates to forceDestroy when engine.disconnect() rejects — stop completes with a warning', async () => {
@@ -538,7 +540,7 @@ describe('SessionService', () => {
releaseLogout();
await deleteCall;
- expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('sess-uuid-1', 'test-session');
expect(pendingTeardownsOf().has('test-session')).toBe(false);
} finally {
jest.useRealTimers();
@@ -1143,7 +1145,7 @@ describe('SessionService', () => {
await service.start('sess-uuid-1');
expect(engineFactory.create).toHaveBeenCalledWith(
- expect.objectContaining({ sessionId: 'test-session', dbSessionId: 'sess-uuid-1' }),
+ expect.objectContaining({ sessionId: 'sess-uuid-1', dbSessionId: 'sess-uuid-1' }),
);
expect(mockEngine.initialize).toHaveBeenCalled();
expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', {
@@ -2259,7 +2261,7 @@ describe('SessionService', () => {
expect(mockEngine.destroy).toHaveBeenCalled();
expect(i.engines.has('sess-uuid-1')).toBe(false);
// delete() purged BEFORE this re-init re-created the auth dir — the guard purges a second time.
- expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('sess-uuid-1');
});
it('still re-initializes when the old engine destroy() hangs (time-bounded teardown)', async () => {
@@ -6286,7 +6288,7 @@ describe('SessionService', () => {
// delete() runs its purge BEFORE this start's init resolves; the init re-creates the auth dir
// (both engines mkdir at init), so the retirement guard must purge a second time — keyed by
- // session NAME, same as delete()'s purge — or the race leaves credentials behind.
+ // the session id, same as delete()'s purge — or the race leaves credentials behind.
mockEngine.initialize.mockImplementationOnce(() => {
(repository.findOne as jest.Mock).mockResolvedValue(null);
return Promise.resolve();
@@ -6295,7 +6297,7 @@ describe('SessionService', () => {
await expect(service.start('sess-uuid-1')).rejects.toThrow(NotFoundException);
expect(mockEngine.destroy).toHaveBeenCalled();
- expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('sess-uuid-1');
});
it('emits no QR/status event for the retired engine once the post-init guard has run', async () => {
@@ -6317,13 +6319,14 @@ describe('SessionService', () => {
expect(webhookService.dispatch).not.toHaveBeenCalledWith('sess-uuid-1', 'session.qr', expect.anything());
});
- it('does not re-purge when the same name was re-created under a new id mid-race (the new row owns the dirs)', async () => {
+ it('re-purges the deleted id even when the same NAME was re-created mid-race (different dirs)', async () => {
const session = createMockSession();
(repository.findOne as jest.Mock).mockResolvedValue(session);
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- // delete(old id) + create(same name) land during init: the old row is gone but a NEW row now
- // owns the name — purging would wipe the fresh session's auth dir, so the guard must skip it.
+ // delete(old id) + create(same name) land during init. The dirs are keyed by id, so the new row
+ // owns its OWN directories: skipping the purge here (as the name-keyed guard used to) would
+ // strand the deleted session's credentials on the volume for good.
mockEngine.initialize.mockImplementationOnce(() => {
(repository.findOne as jest.Mock).mockImplementation(({ where }: { where: { id?: string; name?: string } }) => {
if (where.name === 'test-session') return Promise.resolve(createMockSession({ id: 'sess-uuid-2' }));
@@ -6335,7 +6338,8 @@ describe('SessionService', () => {
await expect(service.start('sess-uuid-1')).rejects.toThrow(NotFoundException);
expect(mockEngine.destroy).toHaveBeenCalled();
- expect(engineFactory.purgeSessionData).not.toHaveBeenCalled();
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('sess-uuid-1');
+ expect(engineFactory.purgeSessionData).not.toHaveBeenCalledWith('sess-uuid-2');
});
it('does not purge anything on a normal start (session row present throughout)', async () => {