diff --git a/extensions/whatsapp/src/auth-store.test.ts b/extensions/whatsapp/src/auth-store.test.ts index d3079d8ae931..26c62bed44df 100644 --- a/extensions/whatsapp/src/auth-store.test.ts +++ b/extensions/whatsapp/src/auth-store.test.ts @@ -76,10 +76,10 @@ describe("auth-store", () => { expect(fsSync.existsSync(credsPath)).toBe(false); }); - it("restores creds from a regular backup file", async () => { + it("restores malformed creds from a valid backup", async () => { const authDir = createTempAuthDir("openclaw-wa-auth-restore"); const credsPath = path.join(authDir, "creds.json"); - fsSync.writeFileSync(credsPath, "{", "utf-8"); + fsSync.writeFileSync(credsPath, "{x", "utf-8"); fsSync.writeFileSync( path.join(authDir, "creds.json.bak"), JSON.stringify({ me: { id: "123@s.whatsapp.net" } }), @@ -92,6 +92,16 @@ describe("auth-store", () => { }); }); + it("leaves malformed creds unchanged when the backup is malformed", async () => { + const authDir = createTempAuthDir("openclaw-wa-auth-malformed-backup"); + const credsPath = path.join(authDir, "creds.json"); + fsSync.writeFileSync(credsPath, "{x", "utf-8"); + fsSync.writeFileSync(path.join(authDir, "creds.json.bak"), "{y", "utf-8"); + + await expect(restoreCredsFromBackupIfNeeded(authDir)).resolves.toBe(false); + expect(fsSync.readFileSync(credsPath, "utf-8")).toBe("{x"); + }); + it("preserves valid large creds instead of treating them as corrupt", async () => { const authDir = createTempAuthDir("openclaw-wa-auth-large-creds"); const credsPath = path.join(authDir, "creds.json"); diff --git a/extensions/whatsapp/src/auth-store.ts b/extensions/whatsapp/src/auth-store.ts index 19781bcdfea0..a0f95b1133ae 100644 --- a/extensions/whatsapp/src/auth-store.ts +++ b/extensions/whatsapp/src/auth-store.ts @@ -67,6 +67,15 @@ async function waitForWebAuthBarrier( return result; } +function isValidJson(raw: string): boolean { + try { + JSON.parse(raw); + return true; + } catch { + return false; + } +} + export async function restoreCredsFromBackupIfNeeded(authDir: string): Promise { const logger = getChildLogger({ module: "web-session" }); try { @@ -78,19 +87,14 @@ export async function restoreCredsFromBackupIfNeeded(authDir: string): Promise