import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; // Mock the auth path to use a temp directory const tmp = mkdtempSync(join(tmpdir(), "vault-pt-test-")); const fakeAgentDir = join(tmp, ".pi", "agent"); const fakeAuthPath = join(fakeAgentDir, "auth.json"); vi.mock("node:os", async (importOriginal) => { const original = await importOriginal(); return { ...original, homedir: () => tmp }; }); // Import after mock const { PassthroughBackend } = await import("../backends/passthrough-backend.js"); afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); describe("PassthroughBackend", () => { let backend: InstanceType; beforeEach(() => { mkdirSync(fakeAgentDir, { recursive: true }); backend = new PassthroughBackend(); }); it("returns empty list when auth.json does not exist", async () => { const list = await backend.list(); expect(list).toEqual([]); }); it("reads existing auth.json entries", async () => { writeFileSync( fakeAuthPath, JSON.stringify({ anthropic: { type: "api_key", key: "sk-test" }, }), ); const entry = await backend.get("anthropic"); expect(entry).toEqual({ type: "api_key", key: "sk-test" }); }); it("writes and reads back", async () => { writeFileSync(fakeAuthPath, "{}"); await backend.set("test", { type: "api_key", key: "val" }); const entry = await backend.get("test"); expect(entry).toEqual({ type: "api_key", key: "val" }); // Verify it was written to the file const raw = JSON.parse(readFileSync(fakeAuthPath, "utf-8")); expect(raw.test).toEqual({ type: "api_key", key: "val" }); }); it("removes entries", async () => { writeFileSync( fakeAuthPath, JSON.stringify({ a: { type: "api_key", key: "1" } }), ); await backend.remove("a"); expect(await backend.get("a")).toBeUndefined(); }); it("lists provider IDs", async () => { writeFileSync( fakeAuthPath, JSON.stringify({ a: { type: "api_key", key: "1" }, b: { type: "oauth", access: "x", refresh: "y", expires: 0 }, }), ); const list = await backend.list(); expect(list).toEqual(["a", "b"]); }); it("parses oauth entries correctly", async () => { writeFileSync( fakeAuthPath, JSON.stringify({ provider: { type: "oauth", access: "acc", refresh: "ref", expires: 999, accountId: "id-1", }, }), ); const entry = await backend.get("provider"); expect(entry).toEqual({ type: "oauth", access: "acc", refresh: "ref", expires: 999, accountId: "id-1", }); }); it("returns undefined for malformed entries", async () => { writeFileSync( fakeAuthPath, JSON.stringify({ bad: { type: "unknown", foo: "bar" } }), ); expect(await backend.get("bad")).toBeUndefined(); }); it("check reports available", async () => { writeFileSync(fakeAuthPath, "{}"); const status = await backend.check(); expect(status.available).toBe(true); }); });