fix: resolve installed Codex for startup and isolated login

Share qualified dependency resolution while preserving explicit and recorded session commands. Isolate login homes and report runtime or terminal prerequisites.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-08 07:02:49 -05:00
1 parent f8e2bee66e
commit 7bc9b64944
10 files changed
+345 -26

No files matched your search

@@ -1,13 +1,24 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { mkdtemp, mkdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { startLocalBrowserLogin } from "./local-ai-browser-login.js";
import { resolvePinnedCodexCommand } from "../vendor/paperclip-runner/index.js";
vi.mock("../vendor/paperclip-runner/index.js", () => ({
resolvePinnedCodexCommand: vi.fn(),
}));
const initialPath = process.env.PATH;
const initialPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;
const initialArchitecture = Object.getOwnPropertyDescriptor(process, "arch")!;
let root: string | undefined;
afterEach(async () => {
Object.defineProperty(process, "platform", initialPlatform);
Object.defineProperty(process, "arch", initialArchitecture);
process.env.PATH = initialPath;
vi.unstubAllEnvs();
vi.clearAllMocks();
if (root) await rm(root, { recursive: true, force: true });
root = undefined;
});
@@ -17,13 +28,83 @@ async function fakeCli(name: string, source: string) {
const bin = path.join(root, "bin");
await mkdir(bin, { recursive: true });
await writeFile(path.join(bin, name), `#!/bin/sh\n${source}\n`, { mode: 0o700 });
if (name === "codex") vi.mocked(resolvePinnedCodexCommand).mockReturnValue(path.join(bin, name));
process.env.PATH = `${bin}${path.delimiter}${initialPath}`;
const home = path.join(root, "credential-home");
await mkdir(home, { mode: 0o700 });
return home;
return realpath(home);
}
function targetPlatform(platform: string, architecture: string) {
Object.defineProperty(process, "platform", { ...initialPlatform, value: platform });
Object.defineProperty(process, "arch", { ...initialArchitecture, value: architecture });
}
describe.skipIf(process.platform === "win32")("local browser subscription login", () => {
it.each([false, true])("uses the selected Codex command with isolated credential homes (legacy Linux ARM64: %s)", async (legacy) => {
if (legacy) targetPlatform("linux", "arm64");
const home = await fakeCli("codex", [
'[ "$1 $2" = "login --device-auth" ] || exit 11',
'[ "$HOME" = "$CODEX_HOME" ] && [ "$HOME" = "$CLAUDE_CONFIG_DIR" ] || exit 12',
'[ "$PWD" = "$HOME" ] || exit 13',
'[ -z "$OPENAI_API_KEY$CODEX_API_KEY$ANTHROPIC_API_KEY$ANTHROPIC_AUTH_TOKEN$CLAUDE_CODE_OAUTH_TOKEN" ] || exit 14',
'printf "1. Open this link in your browser and sign in to your account\\nhttps://auth.openai.com/codex/device\\n2. Enter this one-time code (expires in 15 minutes)\\nABCD-EFGHJ\\n"',
].join("\n"));
if (legacy) vi.mocked(resolvePinnedCodexCommand).mockImplementation(() => { throw new Error("native artifact is unavailable"); });
else process.env.PATH = "/usr/bin:/bin";
const ambientHome = path.join(root!, "unrelated-host-home");
await mkdir(ambientHome, { mode: 0o700 });
for (const key of ["HOME", "CODEX_HOME", "CLAUDE_CONFIG_DIR"]) vi.stubEnv(key, ambientHome);
for (const key of ["OPENAI_API_KEY", "CODEX_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"])
vi.stubEnv(key, "unrelated-host-value");
const login = startLocalBrowserLogin("openai", home);
await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5000 });
if (legacy) expect(resolvePinnedCodexCommand).not.toHaveBeenCalled();
else expect(resolvePinnedCodexCommand).toHaveBeenCalledOnce();
expect(login.code).toBe("ABCD-EFGHJ");
});
it.each([["linux", "x64"], ["darwin", "arm64"], ["darwin", "x64"]] as const)("fails closed on missing qualified Codex artifacts on %s/%s", async (platform, architecture) => {
targetPlatform(platform, architecture);
const home = await fakeCli("codex", 'echo invoked > "$CODEX_HOME/unreviewed-cli"');
const failure = new Error("private-installation-path-or-provider-output");
vi.mocked(resolvePinnedCodexCommand).mockImplementation(() => { throw failure; });
const login = startLocalBrowserLogin("openai", home);
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5000 });
expect(login.error).toMatch(/requires the qualified runtime.*Reinstall Paperclip/);
expect(JSON.stringify(login)).not.toContain(failure.message);
await expect(readFile(path.join(home, "unreviewed-cli"))).rejects.toMatchObject({ code: "ENOENT" });
expect(login.authorizationUrl).toBeUndefined();
});
it("reports a missing Linux ARM64 Codex CLI without revealing the host PATH", async () => {
targetPlatform("linux", "arm64");
const home = await fakeCli("codex", "exit 0");
process.env.PATH = "/usr/bin:/bin";
const login = startLocalBrowserLogin("openai", home);
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5000 });
expect(login.error).toMatch(/requires the Codex CLI.*Install Codex.*Paperclip's PATH/);
expect(JSON.stringify(login)).not.toContain(process.env.PATH);
expect(resolvePinnedCodexCommand).not.toHaveBeenCalled();
});
it("reports a missing terminal prerequisite without exposing spawn details", async () => {
const home = await fakeCli("codex", "exit 0");
process.env.PATH = path.join(root!, "no-python");
const login = startLocalBrowserLogin("openai", home);
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5000 });
expect(login.error).toMatch(/requires Python 3.*Install Python 3/);
expect(JSON.stringify(login)).not.toContain(process.env.PATH);
});
it("cancels before launching the resolved Codex command", async () => {
const home = await fakeCli("codex", 'echo invoked > "$CODEX_HOME/cancelled-cli"');
const login = startLocalBrowserLogin("openai", home);
login.abort();
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5000 });
await expect(readFile(path.join(home, "cancelled-cli"))).rejects.toMatchObject({ code: "ENOENT" });
});
it("surfaces a Codex device link and code from a local PTY without a user shell command", async () => {
const home = await fakeCli("codex", [
'printf "1. Open this link in your browser and sign in to your account\\n"',
+31 -6
View File
@@ -4,11 +4,14 @@ import { constants } from "node:fs";
import path from "node:path";
import { runSetupTokenLogin } from "@paperclipai/adapter-claude-local/server";
import { runDeviceLogin } from "@paperclipai/adapter-codex-local/server";
import { ensureCommandResolvable, resolveCommandForLogs } from "@paperclipai/adapter-utils/server-utils";
import { resolvePinnedCodexCommand } from "../vendor/paperclip-runner/index.js";
export type LocalBrowserLoginState = {
authorizationUrl?: string;
code?: string;
outcome?: "success" | "failure";
error?: string;
submitCode?: (code: string) => void;
abort: () => void;
};
@@ -47,24 +50,46 @@ sys.exit(os.waitstatus_to_exitcode(status))
export function startLocalBrowserLogin(provider: "anthropic" | "openai", home: string): LocalBrowserLoginState {
const controller = new AbortController();
const state: LocalBrowserLoginState = { abort: () => controller.abort() };
const executable = provider === "anthropic" ? "claude" : "codex";
const args = provider === "anthropic" ? ["setup-token"] : ["login", "--device-auth"];
let child: ChildProcessWithoutNullStreams | null = null;
const driver = {
start(_command: string, onData: (chunk: string) => void): Promise<{ exitCode: number | null }> {
async start(_command: string, onData: (chunk: string) => void): Promise<{ exitCode: number | null }> {
let executable = "claude";
if (provider === "openai") {
// Linux ARM64 retains its supported legacy CLI path; it is not a
// qualified native runner target. Missing qualified artifacts elsewhere
// never authorize a fallback to a different installation.
const legacyPlatform = process.platform === "linux" && process.arch === "arm64";
try {
if (legacyPlatform) {
await ensureCommandResolvable("codex", home, process.env);
executable = path.resolve(home, await resolveCommandForLogs("codex", home, process.env));
} else {
executable = resolvePinnedCodexCommand();
}
} catch {
state.error = legacyPlatform
? "Codex browser sign-in requires the Codex CLI on this platform. Install Codex on this execution host and ensure codex is on Paperclip's PATH, then start sign-in again."
: "Codex browser sign-in requires the qualified runtime for this platform. Reinstall Paperclip's runtime dependencies, then start sign-in again.";
throw new Error("Browser login runtime unavailable");
}
}
if (controller.signal.aborted) throw new Error("Local sign-in cancelled before launch");
const env = { ...process.env,
ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "",
OPENAI_API_KEY: "", CODEX_API_KEY: "",
CLAUDE_CONFIG_DIR: provider === "anthropic" ? home : process.env.CLAUDE_CONFIG_DIR,
CODEX_HOME: provider === "openai" ? home : process.env.CODEX_HOME,
HOME: home, CLAUDE_CONFIG_DIR: home, CODEX_HOME: home,
BROWSER: "true",
};
return new Promise((resolve, reject) => {
child = spawn("python3", ["-u", "-c", PYTHON_PTY_BRIDGE, executable, ...args], { env, stdio: ["pipe", "pipe", "pipe"] });
child = spawn("python3", ["-u", "-c", PYTHON_PTY_BRIDGE, executable, ...args], { env, cwd: home, stdio: ["pipe", "pipe", "pipe"] });
child.stdout.on("data", (bytes: Buffer) => onData(bytes.toString("utf8")));
// Provider output may contain secrets. Never log or retain stderr.
child.stderr.resume();
child.once("error", reject);
child.once("error", () => {
state.error = "Browser sign-in requires Python 3 and a working local terminal. Install Python 3 on this execution host, then start sign-in again.";
reject(new Error("Browser login terminal unavailable"));
});
child.once("close", (exitCode) => resolve({ exitCode }));
});
},
+1 -1
View File
@@ -171,7 +171,7 @@ export function localAiLoginService(db: Db) {
...(!login && intent.provider !== "xai"
? { error: "The server restarted during sign-in. Start sign-in again." }
: login?.outcome === "failure"
? { error: "Sign-in ended before the account was connected. Start sign-in again." }
? { error: login.error ?? "Sign-in ended before the account was connected. Start sign-in again." }
: {}) };
}
}
+1
View File
@@ -133,6 +133,7 @@ export const QUALIFIED_ACPX_PROFILES = runner.QUALIFIED_ACPX_PROFILES;
export const QUALIFIED_ACPX_VERSION = runner.QUALIFIED_ACPX_VERSION;
export const CURSOR_DISTRIBUTION_PINS = runner.CURSOR_DISTRIBUTION_PINS;
export const resolveSourceCodexHome = runner.resolveSourceCodexHome;
export const resolvePinnedCodexCommand = runner.resolvePinnedCodexCommand;
export const validatePrpEvent = runner.validatePrpEvent;
export const validatePrpStructuredRunResult =
runner.validatePrpStructuredRunResult;