fix: stabilize CI path assumptions

This commit is contained in:
Peter Steinberger
2026-01-09 18:34:27 +01:00
parent 6aac3184c3
commit dac3b675cc
3 changed files with 166 additions and 153 deletions

View File

@@ -331,7 +331,11 @@ actor MacNodeBridgeSession {
let now = self.clock.now let now = self.clock.now
if now > last.advanced(by: timeout) { if now > last.advanced(by: timeout) {
let age = last.duration(to: now) let age = last.duration(to: now)
self.logger.warning("Node bridge heartbeat timed out; disconnecting (age: \(String(describing: age), privacy: .public)).") let ageDescription = String(describing: age)
let message =
"Node bridge heartbeat timed out; disconnecting " +
"(age: \(ageDescription, privacy: .public))."
self.logger.warning(message)
await self.disconnect() await self.disconnect()
return return
} }
@@ -341,7 +345,11 @@ actor MacNodeBridgeSession {
do { do {
try await self.send(BridgePing(type: "ping", id: id)) try await self.send(BridgePing(type: "ping", id: id))
} catch { } catch {
self.logger.warning("Node bridge ping send failed; disconnecting (error: \(String(describing: error), privacy: .public)).") let errorDescription = String(describing: error)
let message =
"Node bridge ping send failed; disconnecting " +
"(error: \(errorDescription, privacy: .public))."
self.logger.warning(message)
await self.disconnect() await self.disconnect()
return return
} }
@@ -356,7 +364,11 @@ actor MacNodeBridgeSession {
private func handleConnectionState(_ state: NWConnection.State) async { private func handleConnectionState(_ state: NWConnection.State) async {
switch state { switch state {
case let .failed(error): case let .failed(error):
self.logger.warning("Node bridge connection failed; disconnecting (error: \(String(describing: error), privacy: .public)).") let errorDescription = String(describing: error)
let message =
"Node bridge connection failed; disconnecting " +
"(error: \(errorDescription, privacy: .public))."
self.logger.warning(message)
await self.disconnect() await self.disconnect()
case .cancelled: case .cancelled:
self.logger.warning("Node bridge connection cancelled; disconnecting.") self.logger.warning("Node bridge connection cancelled; disconnecting.")

View File

@@ -2,122 +2,133 @@ import fs from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import JSZip from "jszip"; import JSZip from "jszip";
import sharp from "sharp"; import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
const realOs = await vi.importActual<typeof import("node:os")>("node:os"); import { withTempHome } from "../../test/helpers/temp-home.js";
const HOME = path.join(realOs.tmpdir(), "clawdbot-home-test");
vi.mock("node:os", () => ({
default: { homedir: () => HOME, tmpdir: () => realOs.tmpdir() },
homedir: () => HOME,
tmpdir: () => realOs.tmpdir(),
}));
const store = await import("./store.js");
describe("media store", () => { describe("media store", () => {
beforeAll(async () => {
await fs.rm(HOME, { recursive: true, force: true });
});
afterAll(async () => {
await fs.rm(HOME, { recursive: true, force: true });
});
it("creates and returns media directory", async () => { it("creates and returns media directory", async () => {
const dir = await store.ensureMediaDir(); await withTempHome(async () => {
const normalized = path.normalize(dir); vi.resetModules();
expect(normalized).toContain( const store = await import("./store.js");
`${path.sep}.clawdbot${path.sep}media`,
); const dir = await store.ensureMediaDir();
const stat = await fs.stat(dir); const normalized = path.normalize(dir);
expect(stat.isDirectory()).toBe(true); expect(normalized).toContain(`${path.sep}.clawdbot${path.sep}media`);
const stat = await fs.stat(dir);
expect(stat.isDirectory()).toBe(true);
});
}); });
it("saves buffers and enforces size limit", async () => { it("saves buffers and enforces size limit", async () => {
const buf = Buffer.from("hello"); await withTempHome(async () => {
const saved = await store.saveMediaBuffer(buf, "text/plain"); vi.resetModules();
const savedStat = await fs.stat(saved.path); const store = await import("./store.js");
expect(savedStat.size).toBe(buf.length);
expect(saved.contentType).toBe("text/plain");
expect(saved.path.endsWith(".txt")).toBe(true);
const jpeg = await sharp({ const buf = Buffer.from("hello");
create: { width: 2, height: 2, channels: 3, background: "#123456" }, const saved = await store.saveMediaBuffer(buf, "text/plain");
}) const savedStat = await fs.stat(saved.path);
.jpeg({ quality: 80 }) expect(savedStat.size).toBe(buf.length);
.toBuffer(); expect(saved.contentType).toBe("text/plain");
const savedJpeg = await store.saveMediaBuffer(jpeg, "image/jpeg"); expect(saved.path.endsWith(".txt")).toBe(true);
expect(savedJpeg.contentType).toBe("image/jpeg");
expect(savedJpeg.path.endsWith(".jpg")).toBe(true);
const huge = Buffer.alloc(5 * 1024 * 1024 + 1); const jpeg = await sharp({
await expect(store.saveMediaBuffer(huge)).rejects.toThrow( create: { width: 2, height: 2, channels: 3, background: "#123456" },
"Media exceeds 5MB limit", })
); .jpeg({ quality: 80 })
.toBuffer();
const savedJpeg = await store.saveMediaBuffer(jpeg, "image/jpeg");
expect(savedJpeg.contentType).toBe("image/jpeg");
expect(savedJpeg.path.endsWith(".jpg")).toBe(true);
const huge = Buffer.alloc(5 * 1024 * 1024 + 1);
await expect(store.saveMediaBuffer(huge)).rejects.toThrow(
"Media exceeds 5MB limit",
);
});
}); });
it("copies local files and cleans old media", async () => { it("copies local files and cleans old media", async () => {
const srcFile = path.join(HOME, "tmp-src.txt"); await withTempHome(async (home) => {
await fs.mkdir(HOME, { recursive: true }); vi.resetModules();
await fs.writeFile(srcFile, "local file"); const store = await import("./store.js");
const saved = await store.saveMediaSource(srcFile);
expect(saved.size).toBe(10);
const savedStat = await fs.stat(saved.path);
expect(savedStat.isFile()).toBe(true);
expect(path.extname(saved.path)).toBe(".txt");
// make the file look old and ensure cleanOldMedia removes it const srcFile = path.join(home, "tmp-src.txt");
const past = Date.now() - 10_000; await fs.mkdir(home, { recursive: true });
await fs.utimes(saved.path, past / 1000, past / 1000); await fs.writeFile(srcFile, "local file");
await store.cleanOldMedia(1); const saved = await store.saveMediaSource(srcFile);
await expect(fs.stat(saved.path)).rejects.toThrow(); expect(saved.size).toBe(10);
const savedStat = await fs.stat(saved.path);
expect(savedStat.isFile()).toBe(true);
expect(path.extname(saved.path)).toBe(".txt");
// make the file look old and ensure cleanOldMedia removes it
const past = Date.now() - 10_000;
await fs.utimes(saved.path, past / 1000, past / 1000);
await store.cleanOldMedia(1);
await expect(fs.stat(saved.path)).rejects.toThrow();
});
}); });
it("sets correct mime for xlsx by extension", async () => { it("sets correct mime for xlsx by extension", async () => {
const xlsxPath = path.join(HOME, "sheet.xlsx"); await withTempHome(async (home) => {
await fs.mkdir(HOME, { recursive: true }); vi.resetModules();
await fs.writeFile(xlsxPath, "not really an xlsx"); const store = await import("./store.js");
const saved = await store.saveMediaSource(xlsxPath); const xlsxPath = path.join(home, "sheet.xlsx");
expect(saved.contentType).toBe( await fs.mkdir(home, { recursive: true });
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", await fs.writeFile(xlsxPath, "not really an xlsx");
);
expect(path.extname(saved.path)).toBe(".xlsx"); const saved = await store.saveMediaSource(xlsxPath);
expect(saved.contentType).toBe(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
);
expect(path.extname(saved.path)).toBe(".xlsx");
});
}); });
it("renames media based on detected mime even when extension is wrong", async () => { it("renames media based on detected mime even when extension is wrong", async () => {
const pngBytes = await sharp({ await withTempHome(async (home) => {
create: { width: 2, height: 2, channels: 3, background: "#00ff00" }, vi.resetModules();
}) const store = await import("./store.js");
.png()
.toBuffer();
const bogusExt = path.join(HOME, "image-wrong.bin");
await fs.writeFile(bogusExt, pngBytes);
const saved = await store.saveMediaSource(bogusExt); const pngBytes = await sharp({
expect(saved.contentType).toBe("image/png"); create: { width: 2, height: 2, channels: 3, background: "#00ff00" },
expect(path.extname(saved.path)).toBe(".png"); })
.png()
.toBuffer();
const bogusExt = path.join(home, "image-wrong.bin");
await fs.writeFile(bogusExt, pngBytes);
const buf = await fs.readFile(saved.path); const saved = await store.saveMediaSource(bogusExt);
expect(buf.equals(pngBytes)).toBe(true); expect(saved.contentType).toBe("image/png");
expect(path.extname(saved.path)).toBe(".png");
const buf = await fs.readFile(saved.path);
expect(buf.equals(pngBytes)).toBe(true);
});
}); });
it("sniffs xlsx mime for zip buffers and renames extension", async () => { it("sniffs xlsx mime for zip buffers and renames extension", async () => {
const zip = new JSZip(); await withTempHome(async (home) => {
zip.file( vi.resetModules();
"[Content_Types].xml", const store = await import("./store.js");
'<Types><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>',
);
zip.file("xl/workbook.xml", "<workbook/>");
const fakeXlsx = await zip.generateAsync({ type: "nodebuffer" });
const bogusExt = path.join(HOME, "sheet.bin");
await fs.writeFile(bogusExt, fakeXlsx);
const saved = await store.saveMediaSource(bogusExt); const zip = new JSZip();
expect(saved.contentType).toBe( zip.file(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "[Content_Types].xml",
); '<Types><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>',
expect(path.extname(saved.path)).toBe(".xlsx"); );
zip.file("xl/workbook.xml", "<workbook/>");
const fakeXlsx = await zip.generateAsync({ type: "nodebuffer" });
const bogusExt = path.join(home, "sheet.bin");
await fs.writeFile(bogusExt, fakeXlsx);
const saved = await store.saveMediaSource(bogusExt);
expect(saved.contentType).toBe(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
);
expect(path.extname(saved.path)).toBe(".xlsx");
});
}); });
}); });

View File

@@ -1,10 +1,10 @@
import fs from "node:fs"; import fs from "node:fs";
import fsPromises from "node:fs/promises";
import os from "node:os";
import path from "node:path"; import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { withTempHome } from "../../test/helpers/temp-home.js";
const runtime = { const runtime = {
log: vi.fn(), log: vi.fn(),
error: vi.fn(), error: vi.fn(),
@@ -12,84 +12,74 @@ const runtime = {
}; };
describe("web logout", () => { describe("web logout", () => {
const origHomedir = os.homedir;
let tmpDir: string;
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-logout-"));
vi.spyOn(os, "homedir").mockReturnValue(tmpDir);
vi.resetModules();
vi.doMock("../utils.js", async () => {
const actual =
await vi.importActual<typeof import("../utils.js")>("../utils.js");
return {
...actual,
CONFIG_DIR: path.join(tmpDir, ".clawdbot"),
};
});
}); });
afterEach(async () => { afterEach(() => {
vi.restoreAllMocks(); vi.restoreAllMocks();
vi.doUnmock("../utils.js");
await fsPromises
.rm(tmpDir, { recursive: true, force: true })
.catch(() => {});
// restore for safety
// eslint-disable-next-line @typescript-eslint/unbound-method
(os.homedir as unknown as typeof origHomedir) = origHomedir;
}); });
it( it(
"deletes cached credentials when present", "deletes cached credentials when present",
{ timeout: 15_000 }, { timeout: 15_000 },
async () => { async () => {
const { logoutWeb, WA_WEB_AUTH_DIR } = await import("./session.js"); await withTempHome(async (home) => {
vi.resetModules();
const { logoutWeb, WA_WEB_AUTH_DIR } = await import("./session.js");
const normalizedAuthDir = path.resolve(WA_WEB_AUTH_DIR); const rel = path.relative(
const normalizedHome = path.resolve(tmpDir); path.resolve(home),
if (process.platform === "win32") { path.resolve(WA_WEB_AUTH_DIR),
expect( );
normalizedAuthDir expect(rel && !rel.startsWith("..") && !path.isAbsolute(rel)).toBe(
.toLowerCase() true,
.startsWith(normalizedHome.toLowerCase()), );
).toBe(true);
} else {
expect(normalizedAuthDir.startsWith(normalizedHome)).toBe(true);
}
fs.mkdirSync(WA_WEB_AUTH_DIR, { recursive: true });
fs.writeFileSync(path.join(WA_WEB_AUTH_DIR, "creds.json"), "{}");
const result = await logoutWeb({ runtime: runtime as never });
expect(result).toBe(true); fs.mkdirSync(WA_WEB_AUTH_DIR, { recursive: true });
expect(fs.existsSync(WA_WEB_AUTH_DIR)).toBe(false); fs.writeFileSync(path.join(WA_WEB_AUTH_DIR, "creds.json"), "{}");
const result = await logoutWeb({ runtime: runtime as never });
expect(result).toBe(true);
expect(fs.existsSync(WA_WEB_AUTH_DIR)).toBe(false);
});
}, },
); );
it("no-ops when nothing to delete", { timeout: 15_000 }, async () => { it("no-ops when nothing to delete", { timeout: 15_000 }, async () => {
const { logoutWeb } = await import("./session.js"); await withTempHome(async () => {
const result = await logoutWeb({ runtime: runtime as never }); vi.resetModules();
expect(result).toBe(false); const { logoutWeb } = await import("./session.js");
expect(runtime.log).toHaveBeenCalled(); const result = await logoutWeb({ runtime: runtime as never });
expect(result).toBe(false);
expect(runtime.log).toHaveBeenCalled();
});
}); });
it("keeps shared oauth.json when using legacy auth dir", async () => { it("keeps shared oauth.json when using legacy auth dir", async () => {
const { logoutWeb } = await import("./session.js"); await withTempHome(async () => {
const credsDir = path.join(tmpDir, ".clawdbot", "credentials"); vi.resetModules();
fs.mkdirSync(credsDir, { recursive: true }); const { logoutWeb } = await import("./session.js");
fs.writeFileSync(path.join(credsDir, "creds.json"), "{}");
fs.writeFileSync(path.join(credsDir, "oauth.json"), '{"token":true}');
fs.writeFileSync(path.join(credsDir, "session-abc.json"), "{}");
const result = await logoutWeb({ const { resolveOAuthDir } = await import("../config/paths.js");
authDir: credsDir, const credsDir = resolveOAuthDir();
isLegacyAuthDir: true,
runtime: runtime as never, fs.mkdirSync(credsDir, { recursive: true });
fs.writeFileSync(path.join(credsDir, "creds.json"), "{}");
fs.writeFileSync(path.join(credsDir, "oauth.json"), '{"token":true}');
fs.writeFileSync(path.join(credsDir, "session-abc.json"), "{}");
const result = await logoutWeb({
authDir: credsDir,
isLegacyAuthDir: true,
runtime: runtime as never,
});
expect(result).toBe(true);
expect(fs.existsSync(path.join(credsDir, "oauth.json"))).toBe(true);
expect(fs.existsSync(path.join(credsDir, "creds.json"))).toBe(false);
expect(fs.existsSync(path.join(credsDir, "session-abc.json"))).toBe(
false,
);
}); });
expect(result).toBe(true);
expect(fs.existsSync(path.join(credsDir, "oauth.json"))).toBe(true);
expect(fs.existsSync(path.join(credsDir, "creds.json"))).toBe(false);
expect(fs.existsSync(path.join(credsDir, "session-abc.json"))).toBe(false);
}); });
}); });