fix(whatsapp): avoid duplicate creds save warnings

This commit is contained in:
OwenYWT
2026-04-15 10:02:04 +08:00
committed by Marcus Castro
parent cac05362a9
commit 61ae553cb2
2 changed files with 3 additions and 14 deletions

View File

@@ -382,16 +382,17 @@ describe("web session", () => {
const writeFileSpy = vi.spyOn(fsSync.promises, "writeFile").mockResolvedValue(undefined);
const renameSpy = vi.spyOn(fsSync.promises, "rename").mockResolvedValue(undefined);
const rmSpy = vi.spyOn(fsSync.promises, "rm").mockResolvedValue(undefined);
const chmodSpy = vi.spyOn(fsSync, "chmodSync").mockImplementation(() => {});
await writeCredsJsonAtomically(
"/tmp/openclaw-oauth/whatsapp/default",
{ me: { id: "123@s.whatsapp.net" } },
{ warn: vi.fn() } as never,
);
expect(writeFileSpy).toHaveBeenCalledTimes(1);
expect(renameSpy).toHaveBeenCalledTimes(1);
expect(rmSpy).not.toHaveBeenCalled();
expect(chmodSpy).not.toHaveBeenCalled();
const writePath = String(writeFileSpy.mock.calls[0]?.[0] ?? "");
const renameArgs = renameSpy.mock.calls[0] ?? [];
expect(writePath).toContain(".creds.");

View File

@@ -47,25 +47,18 @@ async function loadQrTerminal() {
export async function writeCredsJsonAtomically(
authDir: string,
creds: unknown,
logger: ReturnType<typeof getChildLogger>,
): Promise<void> {
const credsPath = resolveWebCredsPath(authDir);
const tempPath = path.join(authDir, `.creds.${process.pid}.${Date.now()}.tmp`);
try {
await fs.writeFile(tempPath, JSON.stringify(creds, BufferJSON.replacer), { mode: 0o600 });
await fs.rename(tempPath, credsPath);
try {
fsSync.chmodSync(credsPath, 0o600);
} catch {
// best-effort on platforms that support it
}
} catch (err) {
try {
await fs.rm(tempPath, { force: true });
} catch {
// best-effort cleanup
}
logger.warn({ error: String(err) }, "failed atomic WhatsApp creds write");
throw err;
}
}
@@ -121,11 +114,6 @@ async function safeSaveCreds(
}
try {
await Promise.resolve(saveCreds());
try {
fsSync.chmodSync(resolveWebCredsPath(authDir), 0o600);
} catch {
// best-effort on platforms that support it
}
} catch (err) {
logger.warn({ error: String(err) }, "failed saving WhatsApp creds");
}
@@ -153,7 +141,7 @@ export async function createWaSocket(
maybeRestoreCredsFromBackup(authDir);
const { state } = await useMultiFileAuthState(authDir);
const saveCreds = async () => {
await writeCredsJsonAtomically(authDir, state.creds, sessionLogger);
await writeCredsJsonAtomically(authDir, state.creds);
};
const { version } = await fetchLatestBaileysVersion();
const agent = await resolveEnvProxyAgent(sessionLogger);