Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): reclaim the teardown mark when the session id has no row

Yudhi Armyndharisddb880384871
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eeaa3f780..358dee6fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,6 +44,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `POST /sessions/:id/pairing-code` answers `409` while a whatsapp-web.js session is still starting up, instead of a `500` carrying a raw `TypeError`. The engine stored its client before launching Chromium, so for the whole launch — seconds on a modest host — the route passed its only guard and reached into a browser page that did not exist yet. Requesting a code straight after `POST /start`, which is what the dashboard's linking modal invites, landed in exactly that window. The request is now accepted only once the session reaches `qr_ready`, the state the pairing flow needs anyway.
- A burst of inbound media messages no longer loses the media of everything past the eighth. The Baileys adapter capped the download queue at its active slots, and an upsert is submitted in one synchronous pass, so admission was a constant 8 whatever the batch size — a 40-message upsert arrived with 32 of its files replaced by an omitted-media marker. The queue is now unbounded and a burst parks instead of shedding; the concurrent-download bound is unchanged.
+- Stopping or deleting a session id that does not exist no longer leaves an entry behind in the teardown-mark set. The mark is set synchronously at entry, before the existence check, so a `404` set one too — and nothing could remove it, because the two paths that clear a mark both run after their own lookup and a session id is never re-supplied. The set grew by one for every such request until the process restarted. A refusal against a session that does exist still keeps its mark, which is what the mark is for.
+
### Security
- An advisory usage-statistics write no longer persists the whole API-key row. A key deleted while a request that had already loaded it was in flight was re-inserted with its original hash and authenticated again; a revocation or a narrowing of role, allowlist, IP allowlist or expiry was likewise reverted to the values that request loaded. The write is now scoped to the two usage columns and affects nothing if the row is gone.
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 361574062..d9b868b63 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -450,6 +450,18 @@ export class SessionEngineLifecycle {
this.stoppingSessions.add(id);
}
+ /**
+ * Drop a mark set by markStopping().
+ *
+ * The "harmless, cleared by the next start()" reasoning above holds only while a session row
+ * exists. start() and delete() clear the mark after their own requireSession, so for an id that
+ * has no row neither reclamation path is reachable and the entry would outlive the process. Used
+ * by SessionService for exactly that case; a refusal against a real session still leaves its mark.
+ */
+ clearStopping(id: string): void {
+ this.stoppingSessions.delete(id);
+ }
+
/**
* True while this process still has anything alive for the session: a registered engine, an
* in-flight start(), or reconnect state whose armed/executing attempt will re-register one.
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 14a3cfc62..5971f43fa 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1171,6 +1171,41 @@ describe('SessionService', () => {
// Synchronously, on the same tick, the mark must already be set.
expect(stopping.has('sess-uuid-1')).toBe(true);
});
+
+ // The mark is deliberately set before the existence check, so a request for an id that has no
+ // row sets one too. Nothing can reclaim it: start() and delete() clear the mark only after
+ // their own requireSession, both of which 404 first, and a session id is DB-generated so the
+ // id is never re-supplied. Left alone the Set grows one entry per 404 for the life of the
+ // process.
+ it.each([
+ ['stop', (s: SessionService) => s.stop('sess-uuid-1')],
+ ['delete', (s: SessionService) => s.delete('sess-uuid-1')],
+ ])('%s() against an id with no session row leaves no stop mark behind', async (_verb, call) => {
+ (repository.findOne as jest.Mock).mockResolvedValue(null);
+ const stopping = (lifecycle as unknown as { stoppingSessions: Set<string> }).stoppingSessions;
+
+ await expect(call(service)).rejects.toThrow(NotFoundException);
+
+ expect(stopping.has('sess-uuid-1')).toBe(false);
+ });
+
+ // The counterpart, and the reason the reclamation is narrowed to 404 rather than every failure:
+ // a refusal against a session that DOES exist must still leave its mark, which is the
+ // documented "harmless, cleared by the next start()" behaviour the mark relies on.
+ it.each([
+ ['stop', (s: SessionService) => s.stop('sess-uuid-1')],
+ ['delete', (s: SessionService) => s.delete('sess-uuid-1')],
+ ])('%s() refused by the ownership fence keeps its stop mark', async (_verb, call) => {
+ const ownership = withOwnership();
+ ownership.isHeldByOtherNode.mockResolvedValue(true);
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ const stopping = (lifecycle as unknown as { stoppingSessions: Set<string> }).stoppingSessions;
+
+ await expect(call(service)).rejects.toThrow(ConflictException);
+
+ expect(stopping.has('sess-uuid-1')).toBe(true);
+ stopping.delete('sess-uuid-1');
+ });
});
describe('isEngineActive', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 28580f1a0..0548c20c1 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -326,9 +326,28 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// COUNT, or delete()'s own requireSession — would let the mark land after that window. A mark
// left behind when the fence refuses (409) is harmless and is cleared by the next start().
this.engineLifecycle.markStopping(id);
- if (this.ownership) await this.assertNotHeldElsewhere(id);
- await this.engineLifecycle.delete(id);
- await this.ownership?.release(id);
+ try {
+ if (this.ownership) await this.assertNotHeldElsewhere(id);
+ await this.engineLifecycle.delete(id);
+ await this.ownership?.release(id);
+ } catch (error) {
+ this.discardStopMarkForMissingSession(id, error);
+ throw error;
+ }
+ }
+
+ /**
+ * Reclaim the entry-time stop mark when the id turns out to have no session row.
+ *
+ * The mark is set synchronously, before the awaited existence check — deliberately, and the
+ * comments above say why. A mark left behind by a refusal is harmless because the next start()
+ * clears it, but that presupposes a row: start() and delete() both clear the mark only after
+ * their own requireSession, so for an id that never had one the entry is unreachable by every
+ * reclamation path and survives for the life of the process. A 404 also means there is no engine
+ * and no in-flight start() for the mark to guard, so dropping it is safe as well as necessary.
+ */
+ private discardStopMarkForMissingSession(id: string, error: unknown): void {
+ if (error instanceof NotFoundException) this.engineLifecycle.clearStopping(id);
}
/**
@@ -371,8 +390,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async stop(id: string): Promise<Session> {
// Synchronous stop-mark before the awaited fence — see delete() for why.
this.engineLifecycle.markStopping(id);
- if (this.ownership) await this.assertNotHeldElsewhere(id);
- const session = await this.engineLifecycle.stop(id);
+ let session: Session;
+ try {
+ if (this.ownership) await this.assertNotHeldElsewhere(id);
+ session = await this.engineLifecycle.stop(id);
+ } catch (error) {
+ this.discardStopMarkForMissingSession(id, error);
+ throw error;
+ }
// Handed back on the way out so a peer can pick it up immediately rather than waiting for the
// lease to lapse. Stop is the deliberate end of this process's ownership — but a start() that
// began before this stop and is still mid-launch owns the claim now, so the same