Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(engine): move Chromium profile hygiene out of the wwjs adapter

Yudhi Armyndharisea5141369279
diff --git a/src/engine/adapters/chromium-profile-hygiene.ts b/src/engine/adapters/chromium-profile-hygiene.ts
new file mode 100644
index 000000000..51c3ca047
--- /dev/null
+++ b/src/engine/adapters/chromium-profile-hygiene.ts
@@ -0,0 +1,103 @@
+import * as fs from 'fs';
+import * as path from 'path';
+import { execFile } from 'child_process';
+import type { LoggerService } from '../../common/services/logger.service';
+
+/**
+ * Chromium/profile hygiene run before a whatsapp-web.js browser launches.
+ *
+ * Neither of these is about WhatsApp. They clean up after the OPERATING SYSTEM and the container: a
+ * process killed with SIGKILL leaves an orphaned browser and stale profile locks behind, and both
+ * must be dealt with before the next launch. That is an independent audience — it changes when
+ * Docker, Puppeteer or the host platform changes, never when the WhatsApp protocol does — so it lives
+ * outside the adapter that implements the protocol.
+ *
+ * Both are best-effort by contract: they log at debug and never throw, so a hostile `ps` or an
+ * unreadable profile dir can never block an engine start.
+ */
+
+/** Just enough of the logger to report; the adapter passes its own so spies keep observing it. */
+type HygieneLogger = Pick<LoggerService, 'debug' | 'log'>;
+
+/**
+ * SIGKILL any Chromium orphaned by a previous lifetime of this process. When OpenWA dies hard
+ * (kill -9, crash, host reboot) Puppeteer's exit hook never runs, so the browser survives as an
+ * orphan — leaking memory and pinning the session profile dir. Orphans are identified by the
+ * `--openwa-session=<id>` marker arg appended to the puppeteer args at launch (Chromium ignores
+ * the unknown flag; it is purely a `ps` label). Best-effort: never throws — a `ps` failure only
+ * logs at debug, so the sweep can never block an engine start.
+ */
+export async function killOrphanedChromiumProcesses(sessionId: string, logger: HygieneLogger): Promise<void> {
+ if (process.platform !== 'darwin' && process.platform !== 'linux') {
+ logger.debug(`Skipping orphaned Chromium sweep: unsupported platform ${process.platform}`);
+ return;
+ }
+ try {
+ // No shell: the args array is handed to ps verbatim, so nothing here is injectable.
+ // maxBuffer is raised because `ps -eo args` prints full command lines, which on a busy host
+ // (many Chromium renderers carrying dozens of flags each) can exceed the 1MB default.
+ const psOutput = await new Promise<string>((resolve, reject) => {
+ execFile('ps', ['-eo', 'pid=,args='], { maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
+ // The @types/node ExecFileException is an Omit<> of ErrnoException, which the type
+ // checker no longer recognises as an Error — narrow it explicitly for the reject.
+ if (error) reject(error instanceof Error ? error : new Error(error.message));
+ else resolve(stdout);
+ });
+ });
+ // Token-exact marker match: the marker is a single argv token, so it must appear delimited by
+ // whitespace or string boundaries. A plain substring test would let restarting session
+ // `sales` SIGKILL the LIVE browser of sibling `sales2` (their markers share a prefix).
+ const marker = `--openwa-session=${sessionId}`;
+ const markerRe = new RegExp('(?:^|\\s)' + marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?=\\s|$)');
+ const killedPids: number[] = [];
+ for (const line of psOutput.split('\n')) {
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
+ if (!match) continue;
+ const pid = Number(match[1]);
+ const args = match[2];
+ if (pid === process.pid || !markerRe.test(args)) continue;
+ // Never kill a non-browser process that happens to carry the marker string
+ // (e.g. a `grep --openwa-session=…` probing the process table).
+ if (!/chrome|chromium|headless/i.test(args)) continue;
+ try {
+ process.kill(pid, 'SIGKILL');
+ killedPids.push(pid);
+ } catch (error) {
+ // ESRCH: the process exited between `ps` and the kill — nothing left to do.
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') {
+ logger.debug(`Could not SIGKILL orphaned Chromium pid ${pid}`, { error: String(error) });
+ }
+ }
+ }
+ if (killedPids.length > 0) {
+ logger.log(
+ `Killed ${killedPids.length} orphaned Chromium process(es) left over from a previous process lifetime`,
+ { sessionId, pids: killedPids },
+ );
+ }
+ } catch (error) {
+ logger.debug('Could not enumerate processes for the orphaned Chromium sweep', { error: String(error) });
+ }
+}
+
+/**
+ * Remove Chromium's SingletonLock/SingletonSocket/SingletonCookie from the LocalAuth profile dir
+ * (same dir clearLocalAuth removes) before the browser launches. A hard-killed Chromium
+ * (SIGKILL/crash) leaves them behind, and on some setups (e.g. Docker PID reuse) the stale files
+ * block the next launch unless they are cleared first. Best-effort: a removal
+ * failure only logs at debug and never fails the start.
+ */
+export async function removeStaleSingletonFiles(
+ sessionId: string,
+ sessionDataPath: string,
+ logger: HygieneLogger,
+): Promise<void> {
+ const profileDir = path.join(path.resolve(sessionDataPath), `session-${sessionId}`);
+ for (const name of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
+ try {
+ await fs.promises.rm(path.join(profileDir, name), { force: true });
+ } catch (error) {
+ logger.debug(`Could not remove stale ${name} from ${profileDir}`, { error: String(error) });
+ }
+ }
+}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index b23958060..12d265be8 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -13,7 +13,6 @@ import {
import * as qrcode from 'qrcode';
import * as path from 'path';
import * as fs from 'fs';
-import { execFile } from 'child_process';
import {
IWhatsAppEngine,
EngineStatus,
@@ -51,6 +50,7 @@ import {
} from '../interfaces/whatsapp-engine.interface';
import { resolveWebVersionPin } from '../wa-web-version';
import { resolveAuthTimeoutMs } from '../engine-init-timeout';
+import { killOrphanedChromiumProcesses, removeStaleSingletonFiles } from './chromium-profile-hygiene';
import { chatKind, isChannelJid, userPart } from '../identity/wa-id';
import { LidMappingStore } from '../identity/lid-mapping-store.service';
import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';
@@ -670,11 +670,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// Puppeteer exit hook never ran, leaving an orphaned browser holding the profile). Safe here
// for the same reason as the Singleton cleanup below: this runs only at engine (re)start,
// before this lifetime's browser exists, so it cannot kill a live browser.
- await this.killOrphanedChromiumProcesses();
+ await killOrphanedChromiumProcesses(this.config.sessionId, this.logger);
// Clear stale Chromium Singleton* files left by a hard kill before launching — see
// removeStaleSingletonFiles. This runs only at engine (re)start, never while
// the browser is alive, so it cannot pull the files out from under a running Chromium.
- await this.removeStaleSingletonFiles();
+ await removeStaleSingletonFiles(this.config.sessionId, this.config.sessionDataPath, this.logger);
await this.client.initialize();
// whatsapp-web.js 1.34.x never observes the Chromium process/page it drives, so a crashed
// browser leaves the client looking READY forever ("silent death"). Attach death listeners
@@ -1495,85 +1495,6 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
});
}
- /**
- * SIGKILL any Chromium orphaned by a previous lifetime of this process. When OpenWA dies hard
- * (kill -9, crash, host reboot) Puppeteer's exit hook never runs, so the browser survives as an
- * orphan — leaking memory and pinning the session profile dir. Orphans are identified by the
- * `--openwa-session=<id>` marker arg appended to the puppeteer args at launch (Chromium ignores
- * the unknown flag; it is purely a `ps` label). Best-effort: never throws — a `ps` failure only
- * logs at debug, so the sweep can never block an engine start.
- */
- private async killOrphanedChromiumProcesses(): Promise<void> {
- if (process.platform !== 'darwin' && process.platform !== 'linux') {
- this.logger.debug(`Skipping orphaned Chromium sweep: unsupported platform ${process.platform}`);
- return;
- }
- try {
- // No shell: the args array is handed to ps verbatim, so nothing here is injectable.
- // maxBuffer is raised because `ps -eo args` prints full command lines, which on a busy host
- // (many Chromium renderers carrying dozens of flags each) can exceed the 1MB default.
- const psOutput = await new Promise<string>((resolve, reject) => {
- execFile('ps', ['-eo', 'pid=,args='], { maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
- // The @types/node ExecFileException is an Omit<> of ErrnoException, which the type
- // checker no longer recognises as an Error — narrow it explicitly for the reject.
- if (error) reject(error instanceof Error ? error : new Error(error.message));
- else resolve(stdout);
- });
- });
- // Token-exact marker match: the marker is a single argv token, so it must appear delimited by
- // whitespace or string boundaries. A plain substring test would let restarting session
- // `sales` SIGKILL the LIVE browser of sibling `sales2` (their markers share a prefix).
- const marker = `--openwa-session=${this.config.sessionId}`;
- const markerRe = new RegExp('(?:^|\\s)' + marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?=\\s|$)');
- const killedPids: number[] = [];
- for (const line of psOutput.split('\n')) {
- const match = /^\s*(\d+)\s+(.*)$/.exec(line);
- if (!match) continue;
- const pid = Number(match[1]);
- const args = match[2];
- if (pid === process.pid || !markerRe.test(args)) continue;
- // Never kill a non-browser process that happens to carry the marker string
- // (e.g. a `grep --openwa-session=…` probing the process table).
- if (!/chrome|chromium|headless/i.test(args)) continue;
- try {
- process.kill(pid, 'SIGKILL');
- killedPids.push(pid);
- } catch (error) {
- // ESRCH: the process exited between `ps` and the kill — nothing left to do.
- if ((error as NodeJS.ErrnoException).code !== 'ESRCH') {
- this.logger.debug(`Could not SIGKILL orphaned Chromium pid ${pid}`, { error: String(error) });
- }
- }
- }
- if (killedPids.length > 0) {
- this.logger.log(
- `Killed ${killedPids.length} orphaned Chromium process(es) left over from a previous process lifetime`,
- { sessionId: this.config.sessionId, pids: killedPids },
- );
- }
- } catch (error) {
- this.logger.debug('Could not enumerate processes for the orphaned Chromium sweep', { error: String(error) });
- }
- }
-
- /**
- * Remove Chromium's SingletonLock/SingletonSocket/SingletonCookie from the LocalAuth profile dir
- * (same dir clearLocalAuth removes) before the browser launches. A hard-killed Chromium
- * (SIGKILL/crash) leaves them behind, and on some setups (e.g. Docker PID reuse) the stale files
- * block the next launch unless they are cleared first. Best-effort: a removal
- * failure only logs at debug and never fails the start.
- */
- private async removeStaleSingletonFiles(): Promise<void> {
- const profileDir = path.join(path.resolve(this.config.sessionDataPath), `session-${this.config.sessionId}`);
- for (const name of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
- try {
- await fs.promises.rm(path.join(profileDir, name), { force: true });
- } catch (error) {
- this.logger.debug(`Could not remove stale ${name} from ${profileDir}`, { error: String(error) });
- }
- }
- }
-
private async isClientRuntimeReady(): Promise<boolean> {
if (!this.client) return false;
if ((await this.client.getState()) !== WAState.CONNECTED) return false;