import { expect, test } from "bun:test" import fs from "node:fs/promises" import os from "node:os" import path from "node:path" import { dataDir, isFresh, readStoredCredential, withRefreshLock } from "../src/refresh-lock.ts" import { PROVIDER_ID, REFRESH_SAFETY_WINDOW_MS } from "../src/constants.ts" async function tmpDir() { return fs.mkdtemp(path.join(os.tmpdir(), "kimi-v2-lock-")) } test("dataDir honors XDG_DATA_HOME and falls back to ~/.local/share/opencode", () => { expect(dataDir({ XDG_DATA_HOME: "/xdg" }, "/home/u")).toBe(path.join("/xdg", "opencode")) expect(dataDir({}, "/home/u")).toBe(path.join("/home/u", ".local", "share", "opencode")) }) test("isFresh applies the safety window", () => { const now = 1_000_000 expect(isFresh({ expires: now + REFRESH_SAFETY_WINDOW_MS + 1 }, now)).toBe(true) expect(isFresh({ expires: now + REFRESH_SAFETY_WINDOW_MS }, now)).toBe(false) expect(isFresh({ expires: now - 1 }, now)).toBe(false) }) test("withRefreshLock serializes concurrent work and removes the lock afterwards", async () => { const dir = await tmpDir() const lockDir = path.join(dir, `${PROVIDER_ID}.refresh.lock`) const order: string[] = [] const first = withRefreshLock(async () => { order.push("a:start") expect(await fs.stat(lockDir).then((s) => s.isDirectory())).toBe(true) await new Promise((r) => setTimeout(r, 150)) order.push("a:end") return "a" }, dir) await new Promise((r) => setTimeout(r, 20)) const second = withRefreshLock(async () => { order.push("b:start") order.push("b:end") return "b" }, dir) expect(await Promise.all([first, second])).toEqual(["a", "b"]) expect(order).toEqual(["a:start", "a:end", "b:start", "b:end"]) await expect(fs.stat(lockDir)).rejects.toThrow() }) test("withRefreshLock releases the lock when work throws and reclaims stale locks", async () => { const dir = await tmpDir() const lockDir = path.join(dir, `${PROVIDER_ID}.refresh.lock`) await expect( withRefreshLock(async () => { throw new Error("boom") }, dir), ).rejects.toThrow("boom") await expect(fs.stat(lockDir)).rejects.toThrow() // A lock left behind by a crashed process (old mtime, no owner heartbeat) // must not block refreshes forever. await fs.mkdir(lockDir, { recursive: true }) const ownerFile = path.join(lockDir, "owner.json") await fs.writeFile(ownerFile, JSON.stringify({ token: "dead", pid: 1, updatedAt: 0 })) const old = new Date(Date.now() - 10 * 60_000) await fs.utimes(ownerFile, old, old) await fs.utimes(lockDir, old, old) expect(await withRefreshLock(async () => "reclaimed", dir)).toBe("reclaimed") }) test("readStoredCredential reads the persisted OAuth row and ignores other shapes", async () => { const dir = await tmpDir() const file = path.join(dir, "opencode.db") const { Database } = await import("bun:sqlite") const db = new Database(file) db.run("create table credential (id text primary key, integration_id text, value text)") const oauth = { type: "oauth", methodID: "oauth", access: "a2", refresh: "r2", expires: Date.now() + 600_000 } db.run("insert into credential values (?1, ?2, ?3)", ["cred_oauth", PROVIDER_ID, JSON.stringify(oauth)]) db.run("insert into credential values (?1, ?2, ?3)", ["cred_key", PROVIDER_ID, JSON.stringify({ type: "key", key: "k" })]) db.close() expect(await readStoredCredential("cred_oauth", file)).toEqual(oauth) expect(await readStoredCredential("cred_key", file)).toBeUndefined() expect(await readStoredCredential("missing", file)).toBeUndefined() expect(await readStoredCredential("cred_oauth", path.join(dir, "nope.db"))).toBeUndefined() })