Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/claude/connection-projection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { inspectDesktopFirstParty, observeClaudeDesktopMode, resolveClaudeDeskto
import { previewClaudeFirstPartySettings } from "./first-party-preview";
import { firstPartyDesired, firstPartyProxyStatus } from "./first-party-settings";
import { claudeInterceptEnabled } from "./intercept/runtime";
import { claudeSettingsFileState } from "./intercept/settings";
import { claudeSettingsFileState, MAX_STATUS_SETTINGS_BYTES } from "./intercept/settings";

export interface ClaudeConnectionInput {
live: OcxConfig;
Expand All @@ -31,7 +31,8 @@ export interface ClaudeConnectionInput {

function claudeCodeRow(input: ClaudeConnectionInput, dir: string, source: "default" | "extra", ordinal?: number): ConnectionView {
const { live } = input;
const options = { claudeConfigDir: dir, ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) };
const options = { claudeConfigDir: dir, settingsReadLimit: MAX_STATUS_SETTINGS_BYTES,
...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) };
const settingsPath = join(dir, "settings.json");
const fileState = claudeSettingsFileState(dir);
if (fileState === "unsafe") {
Expand Down Expand Up @@ -84,7 +85,8 @@ function claudeCodeRow(input: ClaudeConnectionInput, dir: string, source: "defau

function claudeDesktopRow(input: ClaudeConnectionInput): ConnectionView {
const { live } = input;
const options = input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {};
const options = { settingsReadLimit: MAX_STATUS_SETTINGS_BYTES,
...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) };
const wanted = claudeDesktopIntegrationEnabled(live);
const observation = observeClaudeDesktopMode(live, options);
const mode = resolveClaudeDesktopMode(live, observation);
Expand All @@ -97,7 +99,8 @@ function claudeDesktopRow(input: ClaudeConnectionInput): ConnectionView {
case "broken": case "unsafe": observed = "unknown"; break;
case "standard": case "no_owned_state": {
const settings = mode === "first-party" ? inspectDesktopFirstParty(live, options).settings : null;
observed = settings && (settings.kind === "applied" || settings.kind === "stale") ? "proxy" : "native";
observed = settings?.kind === "unreadable" ? "unknown"
: settings?.kind === "applied" || settings?.kind === "stale" ? "proxy" : "native";
break;
}
default: {
Expand Down
5 changes: 4 additions & 1 deletion src/claude/desktop-first-party.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ export interface DesktopFirstPartyInspection {
export interface DesktopFirstPartyOptions {
opencodexConfigDir?: string;
claudeConfigDir?: string;
/** Read-only projections cap settings bytes and validate the opened descriptor. */
settingsReadLimit?: number;
}

/** Prepare rollback before replacing a gateway, without changing settings. */
Expand All @@ -176,7 +178,8 @@ export function inspectDesktopFirstParty(
// so an owned env can never match the empty credential — it classifies stale, and a real
// apply is what refreshes it.
const target = firstPartyTarget(config, opencodexConfigDir, readClaudeInterceptProxyToken(opencodexConfigDir) ?? "");
const settings = inspectClaudeInterceptSettings(target.env, options.claudeConfigDir);
const settings = inspectClaudeInterceptSettings(target.env, options.claudeConfigDir,
{ maxBytes: options.settingsReadLimit });
return {
interceptEnabled: claudeInterceptEnabled(config),
proxyPort: target.proxyPort,
Expand Down
15 changes: 11 additions & 4 deletions src/claude/first-party-preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { claudeFirstPartyTransition } from "./first-party-transition";
import { claudeInterceptCaCertPath } from "./intercept/local-ca";
import { readClaudeInterceptProxyToken } from "./intercept/proxy-auth";
import { claudeInterceptEnabled } from "./intercept/runtime";
import { claudeInterceptProxyUrl, claudeSettingsFileState, isClaudeInterceptProxyUrl, readClaudeSettingsEnv } from "./intercept/settings";
import { claudeInterceptProxyUrl, claudeSettingsFileState, isClaudeInterceptProxyUrl, MAX_STATUS_SETTINGS_BYTES, readClaudeSettingsEnv } from "./intercept/settings";
import { mergeClaudeInterceptNoProxy, noProxyMergeable, readNoProxyReceipt } from "./intercept/settings-no-proxy";

export type SettingsChangeKind = "add" | "update" | "remove";
Expand Down Expand Up @@ -60,14 +60,16 @@ export interface FirstPartyPreviewInput {
}

const MANAGED_KEYS = ["HTTPS_PROXY", "NODE_EXTRA_CA_CERTS"] as const;
// A receipt stores both the old and written NO_PROXY strings, plus its JSON fields.
const MAX_PREVIEW_RECEIPT_BYTES = 2 * MAX_STATUS_SETTINGS_BYTES + 1024;

function change(key: string, kind: SettingsChangeKind): FirstPartySettingsChange {
return { file: "settings.json", key: `env.${key}`, change: kind };
}

export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): FirstPartyPreview {
const { live, persisted, enabled } = input;
const options = input.options ?? {};
const options = { ...input.options, settingsReadLimit: MAX_STATUS_SETTINGS_BYTES };
const dir = options.claudeConfigDir ?? claudeConfigDir();
const path = join(dir, "settings.json");
const refuse = (reason: FirstPartyPreviewRefusal): FirstPartyPreview => ({ ok: false, enabled, reason, path });
Expand All @@ -90,7 +92,7 @@ export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput):
const reconciled: OcxConfig = { ...live, claudeCode: nextBlock };
const desired = firstPartyDesired(reconciled, observeClaudeDesktopMode(reconciled, options));

const read = readClaudeSettingsEnv(dir);
const read = readClaudeSettingsEnv(dir, { maxBytes: MAX_STATUS_SETTINGS_BYTES });
if (read.kind === "unreadable") return refuse("unreadable");
const env = read.kind === "env" ? read.env : {};

Expand All @@ -101,7 +103,12 @@ export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput):
if (typeof ca !== "string" || ca.trim() !== ownedCa) return accept([]);
const changes = [change("NODE_EXTRA_CA_CERTS", "remove")];
if (isClaudeInterceptProxyUrl(env.HTTPS_PROXY)) changes.push(change("HTTPS_PROXY", "remove"));
const receipt = readNoProxyReceipt(dir);
let receipt;
try {
receipt = readNoProxyReceipt(dir, MAX_PREVIEW_RECEIPT_BYTES);
} catch { // no-excuse-ok: catch -- a bounded read failure leaves the restoration undetermined.
return refuse("unreadable");
}
if (receipt && env.NO_PROXY === receipt.written) {
const restored = receipt.hadKey ? receipt.previous : undefined;
if (restored === undefined) changes.push(change("NO_PROXY", "remove"));
Expand Down
17 changes: 14 additions & 3 deletions src/claude/intercept/settings-no-proxy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { readFileSync, unlinkSync } from "node:fs";
import { join } from "node:path";
import { atomicWriteFile } from "../../config/atomic-write";
import { readBoundedRegularFileSync } from "../../lib/bounded-file-read";
import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard";

/**
Expand Down Expand Up @@ -98,11 +99,21 @@ export function setNoProxyReceiptIoForTests(io: Partial<ReceiptIo>): () => void
}

/** The receipt, or null when it is missing or malformed (both mean: no provenance). */
export function readNoProxyReceipt(configDir: string): NoProxyReceipt | null {
export function readNoProxyReceipt(configDir: string, maxBytes?: number): NoProxyReceipt | null {
const path = noProxyReceiptPath(configDir);
let raw: string;
try {
raw = maxBytes === undefined ? readFileSync(path, "utf8")
: readBoundedRegularFileSync(path, maxBytes, { followFinalSymlink: true }).toString("utf8");
} catch (error) {
// The preview cannot predict a restoration from a receipt it could not safely read.
if (maxBytes !== undefined && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(readFileSync(noProxyReceiptPath(configDir), "utf8"));
} catch { // no-excuse-ok: catch -- a missing or corrupt receipt is the no-provenance state.
parsed = JSON.parse(raw);
} catch { // no-excuse-ok: catch -- a corrupt receipt is the no-provenance state.
return null;
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
Expand Down
22 changes: 16 additions & 6 deletions src/claude/intercept/settings.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { mkdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { atomicWriteFile } from "../../config/atomic-write";
import { readBoundedRegularFileSync } from "../../lib/bounded-file-read";
import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard";
import { claudeConfigDir } from "../auth-detect";
import { invalidateClaudeCodeServedCatalog } from "./cli-catalog";
Expand Down Expand Up @@ -70,15 +71,20 @@ export type ClaudeInterceptSettingsState =
| { kind: "unreadable"; path: string };

type SettingsDoc = Record<string, unknown> & { env?: Record<string, unknown> };
interface SettingsReadOptions { maxBytes?: number }

function settingsPath(configDir: string): string {
return join(configDir, "settings.json");
}

function readSettings(path: string): { doc: SettingsDoc } | { error: "missing" | "unreadable" } {
function readSettings(
path: string,
options: SettingsReadOptions = {},
): { doc: SettingsDoc } | { error: "missing" | "unreadable" } {
let raw: string;
try {
raw = readFileSync(path, "utf8");
raw = options.maxBytes === undefined ? readFileSync(path, "utf8")
: readBoundedRegularFileSync(path, options.maxBytes, { followFinalSymlink: true }).toString("utf8");
} catch (error) { // no-excuse-ok: catch -- an absent settings file is the fresh-install state.
return { error: (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unreadable" };
}
Expand All @@ -100,7 +106,7 @@ export type ClaudeSettingsEnvRead =
| { kind: "unreadable" }
| { kind: "env"; env: Readonly<Record<string, unknown>> };

const MAX_STATUS_SETTINGS_BYTES = 1024 * 1024;
export const MAX_STATUS_SETTINGS_BYTES = 1024 * 1024;

/**
* Read-only status guard for a settings.json a status GET is about to read: `unsafe` for a
Expand All @@ -118,8 +124,11 @@ export function claudeSettingsFileState(configDir = claudeConfigDir()): "missing
}

/** Read-only: the settings.json env block the writers below start from. Never writes. */
export function readClaudeSettingsEnv(configDir = claudeConfigDir()): ClaudeSettingsEnvRead {
const read = readSettings(settingsPath(configDir));
export function readClaudeSettingsEnv(
configDir = claudeConfigDir(),
options: SettingsReadOptions = {},
): ClaudeSettingsEnvRead {
const read = readSettings(settingsPath(configDir), options);
if ("error" in read) return { kind: read.error };
return { kind: "env", env: { ...envRecord(read.doc) } };
}
Expand All @@ -142,9 +151,10 @@ function setOrDelete(env: Record<string, unknown>, key: string, value: unknown):
export function inspectClaudeInterceptSettings(
expected: ClaudeInterceptEnv,
configDir = claudeConfigDir(),
options: SettingsReadOptions = {},
): ClaudeInterceptSettingsState {
const path = settingsPath(configDir);
const read = readSettings(path);
const read = readSettings(path, options);
if ("error" in read) return read.error === "missing" ? { kind: "absent" } : { kind: "unreadable", path };
const env = envRecord(read.doc);
const proxy = env.HTTPS_PROXY;
Expand Down
26 changes: 19 additions & 7 deletions src/lib/bounded-file-read.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,30 @@
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs";
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, statSync } from "node:fs";
import { sameFileIdentity } from "./file-identity";

const MAX_BOUNDED_READ_BYTES = 64 * 1024 * 1024;
const READ_CHUNK_BYTES = 64 * 1024;

export function readBoundedRegularFileSync(path: string, limit: number): Buffer {
export interface BoundedRegularFileReadOptions {
/** Follow the final symlink while still requiring its opened target to be bounded regular data. */
followFinalSymlink?: boolean;
}

export function readBoundedRegularFileSync(
path: string,
limit: number,
options: BoundedRegularFileReadOptions = {},
): Buffer {
if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_BOUNDED_READ_BYTES) {
throw new RangeError("invalid bounded file read limit");
}

const windows = process.platform === "win32";
const flags = constants.O_RDONLY | (windows ? 0 : constants.O_NONBLOCK | constants.O_NOFOLLOW);
const entryBefore = windows ? lstatSync(path, { bigint: true }) : undefined;
if (entryBefore && (entryBefore.isSymbolicLink() || !entryBefore.isFile())) {
const followFinalSymlink = options.followFinalSymlink === true;
const posixFlags = constants.O_NONBLOCK | (followFinalSymlink ? 0 : constants.O_NOFOLLOW);
const flags = constants.O_RDONLY | (windows ? 0 : posixFlags);
const inspectEntry = followFinalSymlink ? statSync : lstatSync;
const entryBefore = windows || followFinalSymlink ? inspectEntry(path, { bigint: true }) : undefined;
if (entryBefore && !entryBefore.isFile()) {
throw new Error("not a regular file");
}
const fd = openSync(path, flags);
Expand Down Expand Up @@ -40,8 +52,8 @@ export function readBoundedRegularFileSync(path: string, limit: number): Buffer
if (length > limit) throw new Error("file exceeds byte limit");

if (entryBefore) {
const entryAfter = lstatSync(path, { bigint: true });
if (entryAfter.isSymbolicLink() || !entryAfter.isFile() || !sameFileIdentity(opened, entryAfter)) {
const entryAfter = inspectEntry(path, { bigint: true });
if (!entryAfter.isFile() || !sameFileIdentity(opened, entryAfter)) {
throw new Error("file entry changed while reading");
}
}
Expand Down
12 changes: 8 additions & 4 deletions structure/clients/connections.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,14 @@ prefix becomes `~`, a drive letter stays, and only the fixed directory and file
and Claude use are shown; any other segment (a user name, account id or token used as a folder name)
becomes `…`, and an extra home is identified by `homeOrdinal` instead of its path. No setting value,
token or email is returned; an unexpected failure answers a fixed `connections_failed` body. Reads are
bounded: at most 16 extra homes (`MAX_EXTRA_CLAUDE_CONFIG_DIRS`), a `settings.json` that is not a
regular file of at most 1 MiB is never opened (`claudeSettingsFileState`; the row reads `unknown` and
the preview refuses `unreadable`), and the Codex profile goes through the same bounded reader as
config.toml. The Codex
bounded: at most 16 extra homes (`MAX_EXTRA_CLAUDE_CONFIG_DIRS`), and status/preview settings reads
validate and size-cap the opened descriptor at 1 MiB, with nonblocking opens on POSIX, then parse only
those bounded bytes. A final symlink remains compatible with Claude Code when its opened target is a
regular file; a FIFO, device, directory, oversized file or unsafe replacement reads `unknown` in the
row and makes the preview refuse `unreadable`. The switch-off preview applies the same descriptor
checks to the optional NO_PROXY receipt, allowing space for both stored values and its JSON fields.
The Codex profile goes through the same bounded reader
as config.toml. The Codex
toggle envelopes in `native-integration-routes.ts` carry `connections: "/api/connections"`.

CLI verb: owed. The route registry declares it `deferred-verb` with owner "proxy catch-up 020
Expand Down
9 changes: 9 additions & 0 deletions tests/claude-integration/claude-first-party-preview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ describe("enabling CLI first-party", () => {
});

describe("turning CLI first-party off", () => {
test("a missing receipt is optional and an oversized receipt makes the preview unreadable", () => {
writeEnv({ NODE_EXTRA_CA_CERTS: claudeInterceptCaCertPath(root) });
const config = cfg({ cli: true, desktopMode: "gateway" });
const input = { live: config, persisted: config, enabled: false, options: options() };
expect(previewClaudeFirstPartySettings(input).ok).toBe(true);
writeFileSync(join(claudeHome, "opencodex-no-proxy.json"), "{}".padEnd(2 * 1024 * 1024 + 1025));
expect(previewClaudeFirstPartySettings(input)).toMatchObject({ ok: false, reason: "unreadable" });
});

test("a CLI-only env is removed, restoring NO_PROXY from its receipt", () => {
expect(realSwitch(cfg({ desktopMode: "gateway" }), cfg({ desktopMode: "gateway" }), true).ok).toBe(true);
const on = cfg({ cli: true, desktopMode: "gateway" });
Expand Down
9 changes: 9 additions & 0 deletions tests/lib/bounded-file-read.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,15 @@ describe("readBoundedRegularFileSync", () => {
expect(() => readBoundedRegularFileSync(link, 64)).toThrow();
});

test.skipIf(!canCreateFileSymlink())("follows a final symlink only when requested", () => {
const path = join(root, "target.json");
writeFileSync(path, "fixture");
const link = join(root, "linked.json");
symlinkSync(path, link, "file");
expect(readBoundedRegularFileSync(link, 64, { followFinalSymlink: true }).toString("utf8"))
.toBe("fixture");
});

test.skipIf(process.platform === "win32")("rejects a FIFO without blocking", () => {
const fifo = join(root, "input.pipe");
const created = spawnSync("mkfifo", [fifo], { timeout: 2_000 });
Expand Down
Loading
Loading