95 lines
2.6 KiB
TypeScript
95 lines
2.6 KiB
TypeScript
import { afterEach, describe, expect, test } from "bun:test";
|
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import {
|
|
clearCorpTokenCache,
|
|
clearSealSession,
|
|
getCorpTokenCache,
|
|
getHoseAuthCache,
|
|
getSealSession,
|
|
setHoseAuthCache,
|
|
setSealSession
|
|
} from "./token-store.js";
|
|
import { SealSession } from "./types.js";
|
|
|
|
const ORIGINAL_ENV = process.env.SEAL_HOME_TOKEN_STORE;
|
|
const tempDirs: string[] = [];
|
|
|
|
function makeTempStore(): string {
|
|
const dir = mkdtempSync(join(tmpdir(), "seal-token-store-test-"));
|
|
tempDirs.push(dir);
|
|
const filePath = join(dir, "tokens.json");
|
|
process.env.SEAL_HOME_TOKEN_STORE = filePath;
|
|
return filePath;
|
|
}
|
|
|
|
afterEach(() => {
|
|
if (ORIGINAL_ENV === undefined) {
|
|
delete process.env.SEAL_HOME_TOKEN_STORE;
|
|
} else {
|
|
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_ENV;
|
|
}
|
|
|
|
for (const dir of tempDirs.splice(0)) {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
describe("token-store", () => {
|
|
test("returns empty cache when store file does not exist", () => {
|
|
makeTempStore();
|
|
expect(getSealSession("corp-test")).toBeUndefined();
|
|
expect(getCorpTokenCache("corp-test")).toEqual({});
|
|
expect(getHoseAuthCache("corp-test")).toEqual({});
|
|
});
|
|
|
|
test("handles corrupted JSON gracefully", () => {
|
|
const storePath = makeTempStore();
|
|
writeFileSync(storePath, "{ invalid json", "utf-8");
|
|
expect(getSealSession("corp-test")).toBeUndefined();
|
|
});
|
|
|
|
test("sets, retrieves, and clears seal session", () => {
|
|
makeTempStore();
|
|
const session: SealSession = {
|
|
token: "test-token-123",
|
|
expiresAt: Date.now() + 3600_000,
|
|
enterprise: {
|
|
provider: "direct",
|
|
corpId: "corp-1",
|
|
staffId: "staff-1",
|
|
sealUrl: "https://seal.example.com"
|
|
}
|
|
};
|
|
|
|
setSealSession("corp-1", session);
|
|
expect(getSealSession("corp-1")).toEqual(session);
|
|
|
|
clearSealSession("corp-1");
|
|
expect(getSealSession("corp-1")).toBeUndefined();
|
|
});
|
|
|
|
test("sets, retrieves, and clears hose auth cache", () => {
|
|
makeTempStore();
|
|
const hoseCache = {
|
|
openapi: {
|
|
token: "openapi-token",
|
|
expiresAt: Date.now() + 3600_000
|
|
},
|
|
closeapi: {
|
|
token: "closeapi-token",
|
|
url: "https://app.ekuaibao.com/web/home.html",
|
|
expiresAt: Date.now() + 7200_000
|
|
}
|
|
};
|
|
|
|
setHoseAuthCache("corp-hose", hoseCache);
|
|
expect(getHoseAuthCache("corp-hose")).toEqual(hoseCache);
|
|
|
|
clearCorpTokenCache("corp-hose");
|
|
expect(getHoseAuthCache("corp-hose")).toEqual({});
|
|
expect(getCorpTokenCache("corp-hose")).toEqual({});
|
|
});
|
|
});
|