import { afterEach, describe, expect, test } from "bun:test"; import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { clearAgentAccountDrain, isAgentAccountClaimDrained, readAgentAccountDrain, writeAgentAccountDrain, type AgentAccountDrainState, } from "../src/security_telemetry/agent_account_gate"; import type { AgentAccountAdapter, AgentAccountIdentity, AgentAccountSnapshot, AgentAuthChallenge, AgentAuthState, AgentQuotaBucket, } from "../src/security_telemetry/agent_account_adapter"; import { handleSecurityAccountDwindling, monitorSecurityAccountAfterSuccess, startAgentAccountRecoveryMonitor, } from "../src/security_telemetry/security_account_manager"; import { createCursorAccountAdapter, cursorSnapshotFromUsage } from "../src/security_telemetry/cursor_account_adapter"; const dirs: string[] = []; function tempState(): string { const dir = mkdtempSync(path.join(tmpdir(), "streamline-agent-dwindling-")); dirs.push(dir); return dir; } afterEach(() => { createCursorAccountAdapter().finishReauth(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); const identity: AgentAccountIdentity = { account_id: "auth0|user_abc", email: "old@example.com", display_name: "Old", organization_id: null, organization_name: null, auth_method: "browser_login", plan: "pro", }; function makeAdapter(overrides: Partial = {}): AgentAccountAdapter & { logoutCalls: number; loginCalls: Array<{ resetCredentials: boolean }>; statusCalls: number; } { const logoutCalls = { n: 0 }; const loginCalls: Array<{ resetCredentials: boolean }> = []; const statusCalls = { n: 0 }; const adapter: AgentAccountAdapter = { id: "cursor-login", provider: "cursor", readIdentity: () => identity, async probeAccount(): Promise { throw new Error("probeAccount not used in this test"); }, async beginReauth({ resetCredentials }): Promise { loginCalls.push({ resetCredentials }); if (resetCredentials) logoutCalls.n++; return { kind: "browser_url", verification_uri: "https://cursor.example/authorize?id=dwindling", user_code: null, issued_at: new Date().toISOString(), }; }, async checkAuth(): Promise { statusCalls.n++; return { state: "AUTHENTICATED", account: "old@example.com" }; }, finishReauth: () => {}, ...overrides, }; return Object.assign(adapter, { get logoutCalls() { return logoutCalls.n; }, get loginCalls() { return loginCalls; }, get statusCalls() { return statusCalls.n; }, }); } const lowQuota: AgentQuotaBucket = { scope: "individual", label: "Individual", primary: true, used: 96_000, limit: 100_000, remaining: 4_000, used_percent: 96, remaining_percent: 4, resets_at: "2026-09-01T00:00:00.000Z", source: "https://cursor.com/api/usage-summary", }; function recoveryAdapter(email: string, remaining = 50): AgentAccountAdapter { return { ...createCursorAccountAdapter(), async probeAccount() { return cursorSnapshotFromUsage({ individualUsage: { overall: { enabled: true, used: 100 - remaining, limit: 100, remaining } }, }, { ...identity, email }); }, }; } describe("low-quota rotation", () => { test("dwindling drains, logs out, captures a login URL and posts a warning card", async () => { const stateDir = tempState(); const previous = process.env.SECURITY_TELEMETRY_DIR; process.env.SECURITY_TELEMETRY_DIR = stateDir; const cards: Array> = []; const originalFetch = globalThis.fetch; globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { cards.push({ url: String(input), body: JSON.parse(String(init?.body || "{}")) }); return new Response("", { status: 204 }); }) as typeof fetch; // Point the shared cursorAdapter's captureHeadlessLoginUrl at our fake // adapter by intercepting handleSecurityAccountDwindling directly. This // exercises the driveAccountRotation path end-to-end using a fake adapter. const fakeCursor = path.join(stateDir, "cursor-agent"); writeFileSync(fakeCursor, `#!/bin/sh case "$1" in logout) exit 0 ;; login) test "$NO_OPEN_BROWSER" = "1" || exit 9; printf 'Open https://cursor.example/authorize?id=dwindling\\n'; sleep 30 ;; status|whoami) printf '✓ Logged in as old@example.com\\n'; exit 0 ;; esac `, "utf8"); chmodSync(fakeCursor, 0o755); const previousBin = process.env.CURSOR_BIN; process.env.CURSOR_BIN = fakeCursor; const logs: Array<{ level: string; message: string }> = []; try { await handleSecurityAccountDwindling( { security: { id: "sec-dw", attempts: 0, clusters: ["security-android-a"] }, phase: "run", provider: "cursor", nodeId: "sat-1", }, identity, lowQuota, (level, message) => logs.push({ level, message }), ); const state = readAgentAccountDrain(); expect(state).toMatchObject({ reason: "TOKEN_DWINDLING", task_id: "sec-dw", provider: "cursor", login_url: "https://cursor.example/authorize?id=dwindling", }); expect(isAgentAccountClaimDrained()).toBe(true); expect(logs.some((entry) => entry.message.includes("global task claiming is now drained"))).toBe(true); expect(cards.length).toBe(1); const message = String((cards[0]!.body as any).card_info.message); expect(message).toContain("event_type=TOKEN_DWINDLING"); expect((cards[0]!.body as any).alert_level).toBe("warning"); expect(message).toContain("login_url=https://cursor.example/authorize?id=dwindling"); expect(message).toContain("quota_scope=individual"); // Clean up before the next test — otherwise the persisted drain would // still be active when the recovery-poll test runs. clearAgentAccountDrain(); } finally { globalThis.fetch = originalFetch; if (previous === undefined) delete process.env.SECURITY_TELEMETRY_DIR; else process.env.SECURITY_TELEMETRY_DIR = previous; if (previousBin === undefined) delete process.env.CURSOR_BIN; else process.env.CURSOR_BIN = previousBin; } }); test("dwindling is skipped when a recovery is already active but still refreshes the alert", async () => { const stateDir = tempState(); const previous = process.env.SECURITY_TELEMETRY_DIR; process.env.SECURITY_TELEMETRY_DIR = stateDir; const existing: AgentAccountDrainState = { schema_version: 1, provider: "cursor", reason: "TOKEN_EXHAUSTED", task_id: "sec-earlier", execution_id: "sec-earlier:run:1", phase: "run", cluster_name: "security-android-a", node_id: "sat-1", account: "old@example.com", card_id: "sec-earlier:run:1", recovery_id: "recovery-first", login_url: "https://cursor.example/authorize?id=first", drained_at: new Date().toISOString(), updated_at: new Date().toISOString(), }; writeAgentAccountDrain(existing); const cards: Array> = []; const originalFetch = globalThis.fetch; globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { cards.push({ url: String(input), body: JSON.parse(String(init?.body || "{}")) }); return new Response("", { status: 204 }); }) as typeof fetch; const logs: string[] = []; try { await handleSecurityAccountDwindling( { security: { id: "sec-dw-2", attempts: 0, clusters: ["security-android-a"] }, phase: "run", provider: "cursor", nodeId: "sat-1", }, identity, lowQuota, (_level, message) => logs.push(message), ); // The prior recovery record must remain intact. const state = readAgentAccountDrain(); expect(state?.recovery_id).toBe("recovery-first"); expect(state?.reason).toBe("TOKEN_EXHAUSTED"); expect(state?.task_id).toBe("sec-earlier"); // The alert still fires so operators know another task hit the threshold. expect(cards.length).toBe(1); expect(logs.some((message) => message.includes("recovery-first is already active"))).toBe(true); clearAgentAccountDrain(); } finally { globalThis.fetch = originalFetch; if (previous === undefined) delete process.env.SECURITY_TELEMETRY_DIR; else process.env.SECURITY_TELEMETRY_DIR = previous; } }); }); describe("recovery poller: must swap accounts", () => { test("leaves a pending login alive until it completes naturally, even when credentials are already visible", async () => { const stateDir = tempState(); const fake = path.join(stateDir, "cursor-agent"); writeFileSync(fake, `#!/bin/sh printf '%s\\n' "$1" >> "$CURSOR_TEST_LOGIN_DIR/calls" case "$1" in logout) exit 0 ;; login) printf '%s' "$$" > "$CURSOR_TEST_LOGIN_DIR/pid" printf 'Open https://cursor.example/authorize?id=original\\n' trap 'printf killed > "$CURSOR_TEST_LOGIN_DIR/killed"; exit 143' TERM while test ! -f "$CURSOR_TEST_LOGIN_DIR/complete"; do sleep 0.02; done exit 0 ;; status|whoami) printf '%s\\n' '{"status":"authenticated","isAuthenticated":true,"userInfo":{"email":"fresh@example.com"}}' ;; esac `, "utf8"); chmodSync(fake, 0o755); const previousBin = process.env.CURSOR_BIN; const previousState = process.env.SECURITY_TELEMETRY_DIR; const previousDir = process.env.CURSOR_TEST_LOGIN_DIR; process.env.CURSOR_BIN = fake; process.env.SECURITY_TELEMETRY_DIR = stateDir; process.env.CURSOR_TEST_LOGIN_DIR = stateDir; const originalFetch = globalThis.fetch; const cards: string[] = []; globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { cards.push(String(init?.body)); return new Response("", { status: 204 }); }) as typeof fetch; const logs: string[] = []; let stop = () => {}; try { const context = { security: { id: "sec-wait", attempts: 0, clusters: ["security"] }, phase: "run" as const, provider: "cursor" as const, nodeId: "sat-1" }; await handleSecurityAccountDwindling(context, identity, lowQuota, (_level, message) => logs.push(message)); stop = startAgentAccountRecoveryMonitor((_level, message) => logs.push(message), 20, { adapter: recoveryAdapter("fresh@example.com") }); await handleSecurityAccountDwindling(context, identity, lowQuota, (_level, message) => logs.push(message)); for (let i = 0; i < 80 && logs.filter((message) => message.includes("finish naturally")).length < 3; i++) await Bun.sleep(50); expect(logs.filter((message) => message.includes("finish naturally")).length).toBeGreaterThanOrEqual(3); expect(isAgentAccountClaimDrained()).toBe(true); expect(readAgentAccountDrain()?.login_url).toBe("https://cursor.example/authorize?id=original"); const calls = readFileSync(path.join(stateDir, "calls"), "utf8").trim().split("\n"); expect(calls.filter((call) => call === "login")).toHaveLength(1); expect(calls.filter((call) => call === "logout")).toHaveLength(1); expect(cards.every((card) => card.includes("login_url=https://cursor.example/authorize?id=original"))).toBe(true); expect(() => process.kill(Number(readFileSync(path.join(stateDir, "pid"), "utf8")), 0)).not.toThrow(); writeFileSync(path.join(stateDir, "complete"), "done"); for (let i = 0; i < 80 && isAgentAccountClaimDrained(); i++) await Bun.sleep(50); expect(isAgentAccountClaimDrained()).toBe(false); expect(() => readFileSync(path.join(stateDir, "killed"))).toThrow(); } finally { stop(); createCursorAccountAdapter().finishReauth(); globalThis.fetch = originalFetch; clearAgentAccountDrain(); if (previousBin === undefined) delete process.env.CURSOR_BIN; else process.env.CURSOR_BIN = previousBin; if (previousState === undefined) delete process.env.SECURITY_TELEMETRY_DIR; else process.env.SECURITY_TELEMETRY_DIR = previousState; if (previousDir === undefined) delete process.env.CURSOR_TEST_LOGIN_DIR; else process.env.CURSOR_TEST_LOGIN_DIR = previousDir; } }, 10_000); test("after login exits unauthenticated, sends a replacement card and leaves its new login alive", async () => { const stateDir = tempState(); const fake = path.join(stateDir, "cursor-agent"); const countFile = path.join(stateDir, "login-count"); writeFileSync(fake, `#!/bin/sh case "$1" in logout) exit 0 ;; login) count=0 test ! -f "$CURSOR_TEST_LOGIN_COUNT" || count=$(cat "$CURSOR_TEST_LOGIN_COUNT") count=$((count + 1)) printf '%s\\n' "$count" > "$CURSOR_TEST_LOGIN_COUNT" printf 'Open https://cursor.example/authorize?id=%s\\n' "$count" if [ "$count" -eq 1 ]; then exit 17; fi sleep 30 ;; status|whoami) printf 'Not logged in\\n'; exit 1 ;; esac `, "utf8"); chmodSync(fake, 0o755); const previousBin = process.env.CURSOR_BIN; const previousState = process.env.SECURITY_TELEMETRY_DIR; const previousCount = process.env.CURSOR_TEST_LOGIN_COUNT; process.env.CURSOR_BIN = fake; process.env.SECURITY_TELEMETRY_DIR = stateDir; process.env.CURSOR_TEST_LOGIN_COUNT = countFile; const originalFetch = globalThis.fetch; const cards: Array> = []; globalThis.fetch = (async (_input: string | URL | Request, init?: RequestInit) => { cards.push(JSON.parse(String(init?.body || "{}")) as Record); return new Response("", { status: 204 }); }) as typeof fetch; const logs: string[] = []; const stop = startAgentAccountRecoveryMonitor((_level, message) => logs.push(message), 20); try { await handleSecurityAccountDwindling( { security: { id: "sec-login-exit", attempts: 0, clusters: ["security"] }, phase: "run", provider: "cursor", nodeId: "sat-1", }, identity, lowQuota, (_level, message) => logs.push(message), ); for (let i = 0; i < 60 && !cards.some((card) => JSON.stringify(card).includes("authorize?id=2")); i++) { await Bun.sleep(50); } expect(readAgentAccountDrain()).toMatchObject({ login_url: "https://cursor.example/authorize?id=2", login_process_status: "waiting", login_exit_code: null, }); expect(Number(readFileSync(countFile, "utf8").trim())).toBe(2); expect(logs.some((message) => message.includes("login process exited"))).toBe(true); // Once the replacement is waiting, concurrent calls must reuse it. expect(await createCursorAccountAdapter().beginReauth({ resetCredentials: true })) .toMatchObject({ verification_uri: "https://cursor.example/authorize?id=2" }); expect(Number(readFileSync(countFile, "utf8").trim())).toBe(2); const refreshedCards = cards.filter((card) => String((card as any).card_info?.message) .includes("login_url=https://cursor.example/authorize?id=2")); expect(refreshedCards.length).toBe(1); // 首发卡片仍应发出且带首次的 URL(id=1)。 expect(cards.some((card) => String((card as any).card_info?.message) .includes("login_url=https://cursor.example/authorize?id=1"))).toBe(true); } finally { stop(); createCursorAccountAdapter().finishReauth(); globalThis.fetch = originalFetch; clearAgentAccountDrain(); if (previousBin === undefined) delete process.env.CURSOR_BIN; else process.env.CURSOR_BIN = previousBin; if (previousState === undefined) delete process.env.SECURITY_TELEMETRY_DIR; else process.env.SECURITY_TELEMETRY_DIR = previousState; if (previousCount === undefined) delete process.env.CURSOR_TEST_LOGIN_COUNT; else process.env.CURSOR_TEST_LOGIN_COUNT = previousCount; } }); test("keeps the node drained and requests login when the authenticated account still has low quota", async () => { const stateDir = tempState(); const fake = path.join(stateDir, "cursor-agent"); writeFileSync(fake, `#!/bin/sh case "$1" in logout) exit 0 ;; login) printf 'Open https://cursor.example/authorize?id=poll\\n'; sleep 30 ;; status|whoami) printf '✓ Logged in as old@example.com\\n'; exit 0 ;; esac `, "utf8"); chmodSync(fake, 0o755); const previousBin = process.env.CURSOR_BIN; const previousState = process.env.SECURITY_TELEMETRY_DIR; process.env.CURSOR_BIN = fake; process.env.SECURITY_TELEMETRY_DIR = stateDir; writeAgentAccountDrain({ schema_version: 1, provider: "cursor", reason: "TOKEN_DWINDLING", task_id: "sec-same", execution_id: "sec-same:run:1", phase: "run", cluster_name: "security", node_id: "sat-1", account: "old@example.com", card_id: "sec-same:run:1", recovery_id: "recovery-same", login_url: null, drained_at: new Date().toISOString(), updated_at: new Date().toISOString(), }); // Polling must remain observational even if the same account is still present. const originalFetch = globalThis.fetch; globalThis.fetch = (async () => new Response("", { status: 204 })) as typeof fetch; const logs: Array<{ level: string; message: string }> = []; const stop = startAgentAccountRecoveryMonitor((level, message) => logs.push({ level, message }), 10, { adapter: recoveryAdapter("old@example.com", 4) }); try { // Wait for the observable decision instead of a fixed wall-clock delay: // this test also runs beside typecheck/build in CI, where a 300 ms sleep // can expire before the first child-process status check is scheduled. for (let i = 0; i < 40 && !readAgentAccountDrain()?.login_url; i++) { await Bun.sleep(50); } expect(isAgentAccountClaimDrained()).toBe(true); expect(logs.some((entry) => entry.message.includes("below 5%"))).toBe(true); expect(readAgentAccountDrain()?.login_url).toBe("https://cursor.example/authorize?id=poll"); } finally { stop(); globalThis.fetch = originalFetch; clearAgentAccountDrain(); if (previousBin === undefined) delete process.env.CURSOR_BIN; else process.env.CURSOR_BIN = previousBin; if (previousState === undefined) delete process.env.SECURITY_TELEMETRY_DIR; else process.env.SECURITY_TELEMETRY_DIR = previousState; } }); test("requests another login card when whoami cannot confirm the account identity", async () => { const stateDir = tempState(); const fake = path.join(stateDir, "cursor-agent"); const authFile = path.join(stateDir, "auth-status.json"); writeFileSync(authFile, JSON.stringify({ status: "authenticated", isAuthenticated: true })); writeFileSync(fake, `#!/bin/sh case "$1" in logout) exit 0 ;; login) printf 'Open https://cursor.example/authorize?id=new\\n'; sleep 30 ;; status|whoami) cat "$CURSOR_TEST_AUTH_FILE"; exit 0 ;; esac `, "utf8"); chmodSync(fake, 0o755); const previousBin = process.env.CURSOR_BIN; const previousState = process.env.SECURITY_TELEMETRY_DIR; const previousAuthFile = process.env.CURSOR_TEST_AUTH_FILE; process.env.CURSOR_BIN = fake; process.env.SECURITY_TELEMETRY_DIR = stateDir; process.env.CURSOR_TEST_AUTH_FILE = authFile; writeAgentAccountDrain({ schema_version: 1, provider: "cursor", reason: "TOKEN_DWINDLING", task_id: "sec-swap", execution_id: "sec-swap:run:1", phase: "run", cluster_name: "security", node_id: "sat-1", account: "old@example.com", card_id: "sec-swap:run:1", recovery_id: "recovery-swap", login_url: null, drained_at: new Date().toISOString(), updated_at: new Date().toISOString(), }); const originalFetch = globalThis.fetch; globalThis.fetch = (async () => new Response("", { status: 204 })) as typeof fetch; const logs: string[] = []; const stop = startAgentAccountRecoveryMonitor((_level, message) => logs.push(message), 10, { adapter: recoveryAdapter("fresh@example.com") }); try { for (let i = 0; i < 40 && !readAgentAccountDrain()?.login_url; i++) await Bun.sleep(50); expect(logs.some((message) => message.includes("did not return an account identity"))).toBe(true); expect(isAgentAccountClaimDrained()).toBe(true); expect(createCursorAccountAdapter().reauthProcessState?.()).toMatchObject({ state: "waiting" }); expect(readAgentAccountDrain()?.login_url).toBe("https://cursor.example/authorize?id=new"); expect(logs.some((message) => message.includes("global task claiming resumed"))).toBe(false); } finally { stop(); globalThis.fetch = originalFetch; if (previousBin === undefined) delete process.env.CURSOR_BIN; else process.env.CURSOR_BIN = previousBin; if (previousState === undefined) delete process.env.SECURITY_TELEMETRY_DIR; else process.env.SECURITY_TELEMETRY_DIR = previousState; if (previousAuthFile === undefined) delete process.env.CURSOR_TEST_AUTH_FILE; else process.env.CURSOR_TEST_AUTH_FILE = previousAuthFile; } }); });