/** * @file server-s3-quota.test.js * @description S3 plan, P4: plan quota per member home. `quotas({home})` * reads Claude, Codex, Cursor, Grok, Kimi Code and OpenCode Go from that * Linux account's home only — never the host's logins, never agy — and only * files the member owns (review fix F3: a FIFO or another account's file is * not read). `GET /api/pricing/quota` gives a developer or an analyst their * OWN account's quota, an admin the host's. A fake passwd (mia, bob = this * test's uid) and server.conf make them provisioned members. * @author Nguyễn Ngọc Trí Vĩ */ const { describe, it, before, after } = require("node:test"); const assert = require("node:assert/strict"); const path = require("node:path"); const fs = require("node:fs"); const os = require("node:os"); const TMP = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "server-s3-quota-"))); const USERS = path.join(TMP, "users"); const MIA = path.join(USERS, "mia"); const BOB = path.join(USERS, "bob"); const HOST = path.join(TMP, "host"); process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db"); process.env.DASHBOARD_LIVENESS_PROBE = "0"; process.env.LANES_ROOT = path.join(TMP, "lanes"); process.env.AGENTHUB_SERVER_CONF = path.join(TMP, "server.conf"); process.env.AGENTHUB_PASSWD = path.join(TMP, "passwd"); process.env.AGENTHUB_AGY_USAGE = "0"; // The host's own logins, every one a different token than a member's. process.env.CLAUDE_HOME = path.join(HOST, ".claude"); process.env.CODEX_HOME = path.join(HOST, ".codex"); process.env.XDG_CONFIG_HOME = path.join(HOST, ".config"); process.env.AGENTHUB_CURSOR_DIR = path.join(HOST, ".cursor"); process.env.GROK_HOME = path.join(HOST, ".grok"); process.env.KIMI_CODE_HOME = path.join(HOST, ".kimi-code"); process.env.XDG_DATA_HOME = path.join(HOST, ".local", "share"); const { createApp, startServer } = require("../index"); const auth = require("../lib/auth"); const linux = require("../lib/linux-accounts"); const runAs = require("../lib/run-as"); const { quotas, __resetCache } = require("../lib/quota"); const { Database } = require("../db"); const LATER = Date.now() + 3600_000; const write = (file, body) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, typeof body === "string" ? body : JSON.stringify(body)); }; const jwt = (claims) => `h.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.s`; /** Every login a tool keeps under `home`, each token named `-`. */ function seedHome(home, who, { codexPercent }) { write(path.join(home, ".claude", ".credentials.json"), { claudeAiOauth: { accessToken: `${who}-claude`, expiresAt: LATER, subscriptionType: "pro" }, }); write(path.join(home, ".claude.json"), { oauthAccount: { emailAddress: `${who}@x.y` } }); write(path.join(home, ".codex", "auth.json"), { tokens: { id_token: jwt({ email: `${who}@codex` }), access_token: jwt({ exp: Math.floor(LATER / 1000) }), }, }); write( path.join(home, ".codex", "sessions", "2026", "10", "09", `rollout-${who}.jsonl`), `${JSON.stringify({ payload: { rate_limits: { primary: { used_percent: codexPercent, window_minutes: 300, resets_at: 4102444800 }, }, }, })}\n` ); write(path.join(home, ".config", "cursor", "auth.json"), { accessToken: `${who}-cursor` }); write(path.join(home, ".cursor", "cli-config.json"), { authInfo: { email: `${who}@cursor`, userId: "u1" }, }); write(path.join(home, ".grok", "auth.json"), { "https://auth.x.ai": { key: `${who}-grok`, expires_at: new Date(LATER).toISOString() }, }); write(path.join(home, ".kimi-code", "credentials", "kimi-code.json"), { access_token: `${who}-kimi`, expires_at: Math.floor(LATER / 1000), }); } /** OpenCode 2 keeps its key in `opencode.db` (WAL), not `auth.json`. */ function seedOpenCodeDb(home, key) { const dir = path.join(home, ".local", "share", "opencode"); fs.mkdirSync(dir, { recursive: true }); const db = new Database(path.join(dir, "opencode.db")); db.pragma?.("journal_mode = WAL"); db.exec( "CREATE TABLE credential (integration_id TEXT, value TEXT, active INT, time_created INT)" ); db.prepare("INSERT INTO credential VALUES ('opencode-go', ?, 1, 1)").run(JSON.stringify({ key })); db.close(); } let asked = []; const realFetch = global.fetch; global.fetch = async (url, opts = {}) => { if (String(url).startsWith("http://127.0.0.1")) return realFetch(url, opts); const h = opts.headers || {}; asked.push(h.Authorization || h.Cookie || ""); const u = String(url); const body = u.includes("anthropic.com") ? u.endsWith("/profile") ? { account: { email: "owner@x.y" } } : { five_hour: { utilization: 10, resets_at: null } } : {}; return { ok: true, status: 200, json: async () => body }; }; let server; let BASE; const setUid = (uid) => { fs.writeFileSync( process.env.AGENTHUB_PASSWD, `ah-mia:x:${uid}:${uid}::/:/bin/sh\nah-bob:x:${uid}:${uid}::/:/bin/sh\n` ); runAs.__resetCache(); }; before(async () => { seedHome(HOST, "host", { codexPercent: 77 }); write(path.join(HOST, ".local", "share", "opencode", "auth.json"), { "opencode-go": { type: "api", key: "host-opencode" }, }); seedHome(MIA, "mia", { codexPercent: 21 }); seedOpenCodeDb(MIA, "mia-opencode"); setUid(process.getuid()); fs.writeFileSync( process.env.AGENTHUB_SERVER_CONF, `HOST_USER=h\nHOST_UID=1\nUSERS_ROOT=${USERS}\nPORT=4820\n` ); fs.mkdirSync(BOB, { recursive: true }); linux.__resetConfCache(); linux.__setRunImpl(() => "ok"); server = await startServer(createApp(), 0); BASE = `http://127.0.0.1:${server.address().port}`; process.env.AGENTHUB_MODE = "server"; await auth.createUser("boss", "admin-pass-1", "admin"); await auth.createUser("mia", "member-pass-1", "developer"); await auth.createUser("bob", "analyst-pass-1", "analyst"); await auth.createUser("carl", "member-pass-2", "developer"); // never provisioned }); after(() => { delete process.env.AGENTHUB_MODE; global.fetch = realFetch; server?.close(); fs.rmSync(TMP, { recursive: true, force: true }); }); describe("quotas({home}) reads a member's own logins", () => { it("reads every tool from that home, never the host's, never agy", async () => { __resetCache(); asked = []; const { tools } = await quotas({ home: MIA }); assert.deepEqual(tools.map((t) => t.id).sort(), [ "claude", "codex", "cursor", "grok", "kimi", "opencode", ]); const codex = tools.find((t) => t.id === "codex"); assert.equal(codex.account, "mia@codex"); assert.equal(codex.windows[0].usedPercent, 21); assert.equal(tools.find((t) => t.id === "cursor").account, "mia@cursor"); assert.ok(asked.length >= 6, asked.join(",")); assert.ok( asked.every((a) => a.includes("mia-")), `only mia's tokens leave: ${asked.join(",")}` ); assert.ok( asked.some((a) => a.includes("mia-opencode")), "OpenCode 2's db is read" ); assert.ok(tools.every((t) => t.label === undefined || t.label === null)); }); it("leaves the host's own reading unchanged", async () => { __resetCache(); asked = []; const { tools } = await quotas(); assert.equal(tools.find((t) => t.id === "codex").windows[0].usedPercent, 77); assert.ok( asked.every((a) => a.includes("host-")), asked.join(",") ); }); it("reads no file the member does not own, and never blocks on a FIFO", async () => { fs.mkdirSync(path.join(BOB, ".grok"), { recursive: true }); require("node:child_process").execFileSync("mkfifo", [path.join(BOB, ".grok", "auth.json")]); __resetCache(); assert.deepEqual((await quotas({ home: BOB })).tools, []); // mia's files now belong to another uid: none is read. setUid(5001); try { __resetCache(); asked = []; assert.deepEqual((await quotas({ home: MIA })).tools, []); assert.deepEqual(asked, []); } finally { setUid(process.getuid()); } }); }); describe("GET /api/pricing/quota is the caller's own", () => { const as = async (username, password) => { const login = await fetch(`${BASE}/api/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }), }); const cookie = login.headers.get("set-cookie").split(";")[0]; __resetCache(); const res = await fetch(`${BASE}/api/pricing/quota`, { headers: { cookie } }); assert.equal(res.status, 200); return (await res.json()).tools; }; const codexPct = (tools) => tools.find((t) => t.id === "codex")?.windows[0].usedPercent; it("a developer gets their own home's, with their own account shown", async () => { const tools = await as("mia", "member-pass-1"); assert.equal(codexPct(tools), 21); assert.equal(tools.find((t) => t.id === "codex").account, "mia@codex"); }); it("an analyst gets their own, never the host's", async () => { assert.deepEqual(await as("bob", "analyst-pass-1"), []); }); it("a member with no provisioned account gets nothing", async () => { assert.deepEqual(await as("carl", "member-pass-2"), []); }); it("an admin gets the host's", async () => { assert.equal(codexPct(await as("boss", "admin-pass-1")), 77); }); });