Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): auto-pin a settled WhatsApp Web build, not the latest (#693)
Yudhi Armyndharis7450da006568
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bfbfb3e9a..f736e94e3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **PostgreSQL upgrade crash-loop for deployments formerly run with `DATABASE_SYNCHRONIZE=true`.** On the PostgreSQL data connection, migrations always run at boot (`migrationsRun: true`), so a schema previously bootstrapped with `DATABASE_SYNCHRONIZE=true` — whose `@PrimaryGeneratedColumn('uuid')` columns TypeORM created as native `uuid` — collides with a migration chain that assumes `varchar` ids and crash-loops the container on boot. A new guard migration (`NormalizeSynchronizeUuidColumns`), ordered before the first colliding migration, now converts those `uuid` id and foreign-key columns to `varchar` (dropping and recreating the dependent cascade foreign keys, and re-applying the `gen_random_uuid()::varchar` defaults), so affected deployments self-heal on the next restart. It is a single-probe no-op on SQLite and on already-`varchar` (healthy) PostgreSQL. For very large `messages` tables the conversion holds an exclusive lock, so run `npm run migration:run` against the stopped app during a maintenance window if needed; `DATABASE_SYNCHRONIZE=true` on PostgreSQL remains unsupported for production. Fixes #690.+- **WhatsApp Web auto-version resolver now prefers a settled build.** The whatsapp-web.js engine auto-pins its WhatsApp Web build from the wppconnect wa-version registry; the resolver previously took the registry's `currentVersion` verbatim — the absolute latest build, which can be minutes old and unvalidated and, on some setups, never reaches QR readiness (the #684 whatsapp-web.js "stuck at Starting, no QR" report class). It now picks the newest non-beta, unexpired build published at least 12 hours ago, falling back to `currentVersion` only when no build qualifies, so auto-pinning no longer latches onto a brand-new build. Operators who set `WWEBJS_WEB_VERSION` explicitly are unaffected. Fixes the whatsapp-web.js "stuck at Starting, no QR" report from #684 (Bug 2); #692 fixes the dashboard-button part (Bug 1) of the same issue.+- **Baileys engine: messages no longer get stuck on "Waiting for this message. This may take a while." on iOS recipients.** Reported specifically on iOS WhatsApp: the recipient's chat shows the message as permanently pending, with no error and a stable connection. The Baileys `makeWASocket` config had no `getMessage` implementation, so WhatsApp's own retry-on-decrypt-failure protocol had nothing to resend, leaving the recipient stuck instead of recovering within seconds; it's now backed by the message store.- **Baileys message-store lookups no longer fail their FK check.** The engine factory keyed `messageStore.put`/`getMessage`/`clearSession` by the session's on-disk auth-directory name, but `BaileysStoredMessage.sessionId` is a foreign key to `sessions.id` — every write violated the FK and was silently dropped by the orphan guard, leaving the store empty and defeating the `getMessage` fix above. The engine config now carries the auth-directory key (`sessionId`, the session name) and the DB-row key (`dbSessionId`, the session's UUID) as two separate fields, so the message store is keyed correctly without disturbing the existing on-disk auth-directory layout (and `purgeSessionData`, still keyed by name, keeps working on delete).diff --git a/src/engine/wa-web-version.spec.ts b/src/engine/wa-web-version.spec.tsnew file mode 100644index 000000000..764dd75ce--- /dev/null+++ b/src/engine/wa-web-version.spec.ts@@ -0,0 +1,122 @@+import {+ __resetWebVersionCache,+ pickSettledWebVersion,+ resolveCurrentWebVersion,+ WEB_VERSION_SETTLE_MS,+} from './wa-web-version';++// Fixed reference instant (the #684 report timestamp) so the suite never depends on wall-clock time.+const FIXED_NOW = Date.parse('2026-07-11T07:05:00Z');++// Build a registry entry with released/expire relative to FIXED_NOW.+const entry = (version: string, ageMs: number, ttlMs: number, beta = false) => {+ const released = new Date(FIXED_NOW - ageMs).toISOString();+ const expire = new Date(FIXED_NOW + ttlMs).toISOString();+ return { version, beta, released, expire };+};++describe('pickSettledWebVersion', () => {+ const now = FIXED_NOW;+ const settled = (extra = 0) => WEB_VERSION_SETTLE_MS + extra;++ it('falls back to currentVersion when versions is missing or not an array', () => {+ expect(pickSettledWebVersion(undefined, now, '2.3000.1-alpha')).toBe('2.3000.1-alpha');+ expect(pickSettledWebVersion(null, now, '2.3000.1-alpha')).toBe('2.3000.1-alpha');+ expect(pickSettledWebVersion('nope', now, '2.3000.1-alpha')).toBe('2.3000.1-alpha');+ });++ it('falls back to currentVersion (or null) when no build qualifies', () => {+ expect(pickSettledWebVersion([], now, '2.3000.1-alpha')).toBe('2.3000.1-alpha');+ expect(pickSettledWebVersion([], now, null)).toBeNull();+ });++ it('prefers a settled build over a too-fresh currentVersion', () => {+ // currentVersion is 40 minutes old (the #684 scenario); one build is 2 days old.+ const versions = [+ entry('2.3000.1043012667-alpha', 40 * 60 * 1000, 60 * 86_400_000), // fresh — skip+ entry('2.3000.OLD-BUILD-alpha', 2 * 86_400_000, 50 * 86_400_000), // settled — pick+ ];+ expect(pickSettledWebVersion(versions, now, '2.3000.1043012667-alpha')).toBe('2.3000.OLD-BUILD-alpha');+ });++ it('skips builds newer than the settle window even if currentVersion is fresh', () => {+ const versions = [entry('2.3000.FRESH-alpha', 60 * 60 * 1000, 60 * 86_400_000)]; // 1h old+ expect(pickSettledWebVersion(versions, now, '2.3000.FRESH-alpha')).toBe('2.3000.FRESH-alpha'); // none settled → fallback+ });++ it('picks the NEWEST qualifying (settled) build', () => {+ const versions = [+ entry('2.3000.OLD-alpha', 10 * 86_400_000, 50 * 86_400_000),+ entry('2.3000.NEW-alpha', settled() + 60_000, 50 * 86_400_000), // just past settle, newest qualifying+ entry('2.3000.MID-alpha', 5 * 86_400_000, 50 * 86_400_000),+ ];+ expect(pickSettledWebVersion(versions, now, '2.3000.NEW-alpha')).toBe('2.3000.NEW-alpha');+ });++ it('skips beta builds', () => {+ const versions = [+ entry('2.3000.BETA-alpha', settled(), 50 * 86_400_000, true), // beta=true → skip+ entry('2.3000.STABLE-alpha', settled() + 1000, 50 * 86_400_000, false),+ ];+ expect(pickSettledWebVersion(versions, now, '2.3000.BETA-alpha')).toBe('2.3000.STABLE-alpha');+ });++ it('skips already-expired builds', () => {+ const versions = [+ entry('2.3000.EXPIRED-alpha', settled(), -1000, false), // expire in the past+ entry('2.3000.LIVE-alpha', settled() + 1000, 50 * 86_400_000, false),+ ];+ expect(pickSettledWebVersion(versions, now, '2.3000.EXPIRED-alpha')).toBe('2.3000.LIVE-alpha');+ });++ it('skips malformed entries (non-string version / unparseable released)', () => {+ const versions = [+ { version: 123, beta: false, released: new Date(now - settled()).toISOString() }, // non-string version+ { version: '2.3000.OK-alpha', beta: false, released: 'not-a-date' }, // bad released+ entry('2.3000.GOOD-alpha', settled() + 1000, 50 * 86_400_000, false),+ ];+ expect(pickSettledWebVersion(versions, now, null)).toBe('2.3000.GOOD-alpha');+ });+});++describe('resolveCurrentWebVersion', () => {+ beforeEach(() => __resetWebVersionCache());+ afterEach(() => __resetWebVersionCache());++ const json = (body: unknown) => ({+ ok: true,+ status: 200,+ json: () => Promise.resolve(body),+ });++ it('pins a settled build from versions[] over the raw currentVersion', async () => {+ const fetcher = jest.fn(() =>+ Promise.resolve(+ json({+ currentBeta: null,+ currentVersion: '2.3000.FRESH-alpha',+ versions: [+ {+ version: '2.3000.FRESH-alpha',+ beta: false,+ released: new Date(Date.now() - 10 * 60 * 1000).toISOString(),+ expire: '2099-01-01T00:00:00Z',+ },+ {+ version: '2.3000.SETTLED-alpha',+ beta: false,+ released: new Date(Date.now() - 2 * 86_400_000).toISOString(),+ expire: '2099-01-01T00:00:00Z',+ },+ ],+ }),+ ),+ );+ await expect(resolveCurrentWebVersion(fetcher as never)).resolves.toBe('2.3000.SETTLED-alpha');+ });++ it('falls back to currentVersion when the registry carries no versions[]', async () => {+ const fetcher = jest.fn(() => Promise.resolve(json({ currentBeta: null, currentVersion: '2.3000.SOLO-alpha' })));+ await expect(resolveCurrentWebVersion(fetcher as never)).resolves.toBe('2.3000.SOLO-alpha');+ });+});diff --git a/src/engine/wa-web-version.ts b/src/engine/wa-web-version.tsindex 9a656e667..cfd1ec77f 100644--- a/src/engine/wa-web-version.ts+++ b/src/engine/wa-web-version.ts@@ -21,6 +21,11 @@ const DEFAULT_REMOTE_TEMPLATE = 'https://raw.githubusercontent.com/wppconnect-te// `lastFailureAt`: subsequent calls return null instantly for FAILURE_BACKOFF_MS, then retry. `inFlight`// dedupes concurrent resolves into a single fetch.const FAILURE_BACKOFF_MS = 60_000;+// Minimum age a WhatsApp Web build must reach before we'll auto-pin it. The registry's+// `currentVersion` tracks the latest build, which can be minutes old and unvalidated; a build+// published at least this long ago is far less likely to hang before reaching QR readiness on a+// fresh start (the #488 / #684 failure class). Exposed for tests.+export const WEB_VERSION_SETTLE_MS = 12 * 60 * 60 * 1000; // 12hlet cachedCurrentVersion: string | undefined;let inFlight: Promise<string | null> | null = null;let lastFailureAt = 0;@@ -40,11 +45,39 @@ function buildRemotePin(version: string): WebVersionPin {};}+type WaVersionEntry = { version?: unknown; beta?: unknown; released?: unknown; expire?: unknown };++/**+ * Pick the WhatsApp Web build to auto-pin from the registry's `versions[]`: the newest non-beta,+ * unexpired build published at least `WEB_VERSION_SETTLE_MS` ago — i.e. one the ecosystem has had+ * time to validate — rather than the registry's `currentVersion`, which can be minutes old. Falls+ * back to `currentVersion` when no build qualifies (a freshly-reset registry, or every build still+ * too new), so this hardens pinning without ever defeating it. Pure: pass `now` explicitly.+ */+export function pickSettledWebVersion(versions: unknown, now: number, currentVersion: string | null): string | null {+ if (!Array.isArray(versions)) return currentVersion;+ const settledCutoff = now - WEB_VERSION_SETTLE_MS;+ let best: { version: string; released: number } | null = null;+ for (const raw of versions) {+ if (!raw || typeof raw !== 'object') continue;+ const e = raw as WaVersionEntry;+ if (typeof e.version !== 'string' || !/^\d/.test(e.version)) continue;+ if (e.beta === true) continue;+ const released = typeof e.released === 'string' ? Date.parse(e.released) : NaN;+ if (!Number.isFinite(released) || released > settledCutoff) continue; // too fresh+ const expire = typeof e.expire === 'string' ? Date.parse(e.expire) : NaN;+ if (Number.isFinite(expire) && expire <= now) continue; // already expired+ if (!best || best.released < released) best = { version: e.version, released };+ }+ return best?.version ?? currentVersion;+}+/*** Fetch the current known-good WhatsApp Web build from the wa-version registry. A SUCCESSFUL resolve* is cached for the process lifetime; a failure resolves to null WITHOUT caching, so a later call* retries (a single transient outage must not permanently defeat the #488 fix). Concurrent callers- * share one in-flight fetch.+ * share one in-flight fetch. Prefers a build that has settled (see `pickSettledWebVersion`) over the+ * registry's possibly-minute-old `currentVersion`.*/export async function resolveCurrentWebVersion(fetcher: typeof fetch = fetch): Promise<string | null> {if (typeof cachedCurrentVersion === 'string') return cachedCurrentVersion;@@ -59,13 +92,15 @@ export async function resolveCurrentWebVersion(fetcher: typeof fetch = fetch): Ptry {const res = await fetcher(WA_VERSION_REGISTRY_URL, { signal: controller.signal });if (!res.ok) throw new Error(`HTTP ${res.status}`);- const json = (await res.json()) as { currentVersion?: unknown };- const v = json.currentVersion;- if (typeof v === 'string' && /^\d/.test(v)) {- cachedCurrentVersion = v; // cache only on success- return v;+ const json = (await res.json()) as { currentVersion?: unknown; versions?: unknown };+ const rawCurrent =+ typeof json.currentVersion === 'string' && /^\d/.test(json.currentVersion) ? json.currentVersion : null;+ const picked = pickSettledWebVersion(json.versions, Date.now(), rawCurrent);+ if (picked) {+ cachedCurrentVersion = picked; // cache only on success+ return picked;}- lastFailureAt = Date.now(); // malformed payload — back off, then retry+ lastFailureAt = Date.now(); // nothing usable — back off, then retryreturn null;} finally {clearTimeout(timer);