Skip to content
Closed
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
103 changes: 102 additions & 1 deletion src/claude/desktop-policy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/** Read-only, privacy-safe Windows policy diagnosis for Claude Desktop 3P. */
import { spawnSync } from "node:child_process";
import { execFile, spawnSync } from "node:child_process";
import { win32 } from "node:path";
import { resolveTrustedWindowsSystemDirectory } from "../lib/windows-elevation";
import { decodeWindowsTextBytes } from "../lib/windows-text";
Expand All @@ -23,6 +23,11 @@ export type ClaudeDesktopPolicyProbeRunner = (
args: readonly string[],
) => ClaudeDesktopPolicyProbeResult;

export type ClaudeDesktopPolicyAsyncProbeRunner = (
file: string,
args: readonly string[],
) => Promise<ClaudeDesktopPolicyProbeResult>;

export interface ClaudeDesktopPolicyProbeOptions {
readonly platform?: NodeJS.Platform;
readonly run?: ClaudeDesktopPolicyProbeRunner;
Expand Down Expand Up @@ -54,6 +59,35 @@ const defaultPolicyProbeRunner: ClaudeDesktopPolicyProbeRunner = (file, args) =>
};
};

/**
* Translates an `execFile` callback into the probe contract. Exit codes arrive
* as numeric `error.code`; spawn failures carry a string errno; a timeout kill
* surfaces as `killed`/`SIGTERM` rather than `ETIMEDOUT`.
*/
export function classifyExecFileProbeResult(
error: (Error & { readonly code?: number | string; readonly killed?: boolean }) | null,
stdout: Uint8Array | undefined,
): ClaudeDesktopPolicyProbeResult {
const errorCode = error?.code;
return {
status: error === null ? 0 : typeof errorCode === "number" ? errorCode : null,
stdout: stdout === undefined ? "" : decodeWindowsTextBytes(stdout),
timedOut: errorCode === "ETIMEDOUT" || error?.killed === true,
spawnFailed: error !== null && typeof errorCode !== "number" && errorCode !== "ETIMEDOUT",
};
}

const defaultAsyncPolicyProbeRunner: ClaudeDesktopPolicyAsyncProbeRunner = (file, args) => new Promise((resolve) => {
execFile(file, [...args], {
encoding: "buffer",
maxBuffer: 64 * 1024,
timeout: POLICY_PROBE_TIMEOUT_MS,
windowsHide: true,
}, (error, stdout) => {
resolve(classifyExecFileProbeResult(error, stdout));
});
});

function usable(result: ClaudeDesktopPolicyProbeResult): boolean {
return !result.timedOut && !result.spawnFailed && result.status !== null;
}
Expand Down Expand Up @@ -108,6 +142,73 @@ export function probeClaudeDesktopPolicy(
return parentListsPolicyKey(parent.stdout) ? "unknown" : "absent";
}

/** Non-blocking variant for the long-lived server request path. */
export async function probeClaudeDesktopPolicyAsync(
options: Omit<ClaudeDesktopPolicyProbeOptions, "run"> & { readonly run?: ClaudeDesktopPolicyAsyncProbeRunner } = {},
): Promise<ClaudeDesktopPolicyState> {
const platform = options.platform ?? process.platform;
if (platform !== "win32") return "not_applicable";

let regExe: string;
try {
const systemDirectory = (options.resolveSystemDirectory ?? resolveTrustedWindowsSystemDirectory)();
regExe = win32.join(systemDirectory, "reg.exe");
} catch {
return "unknown";
}

const run = options.run ?? defaultAsyncPolicyProbeRunner;
try {
const policy = await run(regExe, ["query", CLAUDE_POLICY_KEY, "/reg:64"]);
if (!usable(policy)) return "unknown";
if (policy.status === 0) return "present";
if (policy.status !== 1) return "unknown";

const parent = await run(regExe, ["query", CLAUDE_POLICY_PARENT_KEY, "/reg:64"]);
if (!usable(parent) || parent.status !== 0) return "unknown";
return parentListsPolicyKey(parent.stdout) ? "unknown" : "absent";
} catch {
return "unknown";
}
}

const POLICY_CACHE_TTL_MS = 30_000;

export function createCachedClaudeDesktopPolicyProbe(
probe: () => Promise<ClaudeDesktopPolicyState>,
ttlMs = POLICY_CACHE_TTL_MS,
now = performance.now,
): () => Promise<ClaudeDesktopPolicyState> {
let cached: { state: ClaudeDesktopPolicyState; expiresAt: number } | undefined;
let refresh: Promise<ClaudeDesktopPolicyState> | undefined;
return () => {
const currentTime = now();
if (cached && cached.expiresAt > currentTime) return Promise.resolve(cached.state);
if (refresh) return refresh;
refresh = probe().then((state) => {
cached = { state, expiresAt: now() + ttlMs };
return state;
}).finally(() => {
refresh = undefined;
});
return refresh;
};
}

const cachedProductionProbe = createCachedClaudeDesktopPolicyProbe(
() => probeClaudeDesktopPolicyAsync(),
);

/** Coalesces status polling and bounds registry refreshes to one per cache interval. */
export function getCachedClaudeDesktopPolicy(
options: Omit<ClaudeDesktopPolicyProbeOptions, "run"> = {},
): Promise<ClaudeDesktopPolicyState> {
const cacheable = options.resolveSystemDirectory === undefined
&& (options.platform === undefined || options.platform === process.platform);
if (cacheable) return cachedProductionProbe();
return probeClaudeDesktopPolicyAsync(options);
}

/** State-only health projection shared by CLI, apply, and management status. */
export function claudeDesktopPolicyHealth(
state: ClaudeDesktopPolicyState,
Expand Down
8 changes: 4 additions & 4 deletions src/server/management/agent-settings-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1237,10 +1237,10 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
// a stale apply the operator should refresh.
const stale = desiredEnabled && (mode === "first-party" ? firstPartySeen.stale : observed.kind === "gateway_drifted");
const { getDesktopHealth } = await import("../../claude/desktop-health");
const { claudeDesktopPolicyHealth, probeClaudeDesktopPolicy } = await import("../../claude/desktop-policy");
const policyState = (deps.probeClaudeDesktopPolicy ?? probeClaudeDesktopPolicy)({
platform: deps.platform ?? process.platform,
});
const { claudeDesktopPolicyHealth, getCachedClaudeDesktopPolicy } = await import("../../claude/desktop-policy");
const policyState = deps.probeClaudeDesktopPolicy
? deps.probeClaudeDesktopPolicy({ platform: deps.platform ?? process.platform })
: await getCachedClaudeDesktopPolicy({ platform: deps.platform ?? process.platform });
// Managed-policy conflicts only matter for the gateway profile; first-party mode never
// touches Desktop's own configuration.
const policy = claudeDesktopPolicyHealth(mode === "first-party" ? "absent" : policyState);
Expand Down
121 changes: 121 additions & 0 deletions tests/claude-integration/claude-desktop-policy.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { expect, test } from "bun:test";
import {
claudeDesktopPolicyHealth,
classifyExecFileProbeResult,
createCachedClaudeDesktopPolicyProbe,
getCachedClaudeDesktopPolicy,
probeClaudeDesktopPolicyAsync,
probeClaudeDesktopPolicy,
type ClaudeDesktopPolicyProbeRunner,
} from "../../src/claude/desktop-policy";
Expand Down Expand Up @@ -122,3 +126,120 @@ test("non-Windows policy probing is not applicable and never spawns", () => {
expect(spawned).toBe(false);
expect(resolved).toBe(false);
});

test("the asynchronous policy probe does not synchronously block the caller", async () => {
let release!: (value: ReturnType<typeof result>) => void;
const pending = new Promise<ReturnType<typeof result>>((resolve) => { release = resolve; });
const probe = probeClaudeDesktopPolicyAsync({
platform: "win32",
resolveSystemDirectory: () => "C:\\trusted\\System32",
run: () => pending,
});

let settled = false;
void probe.then(() => { settled = true; });
await Promise.resolve();
expect(settled).toBe(false);
release(result({ status: 0 }));
expect(await probe).toBe("present");
});

test("the execFile translation classifies exit codes, timeouts, and spawn failures", () => {
const probeError = (code: number | string, extra = {}) =>
Object.assign(new Error("probe failed"), { code, ...extra });

expect(classifyExecFileProbeResult(null, Buffer.from("output"))).toEqual({
status: 0, stdout: "output", timedOut: false, spawnFailed: false,
});
// A missing key and a query failure surface as numeric exit codes, not errno names.
expect(classifyExecFileProbeResult(probeError(1), undefined))
.toEqual({ status: 1, stdout: "", timedOut: false, spawnFailed: false });
expect(classifyExecFileProbeResult(probeError(5), undefined))
.toEqual({ status: 5, stdout: "", timedOut: false, spawnFailed: false });
expect(classifyExecFileProbeResult(probeError("ENOENT"), undefined))
.toEqual({ status: null, stdout: "", timedOut: false, spawnFailed: true });
expect(classifyExecFileProbeResult(probeError("ETIMEDOUT"), undefined))
.toEqual({ status: null, stdout: "", timedOut: true, spawnFailed: false });
expect(classifyExecFileProbeResult(Object.assign(new Error("killed"), { killed: true }), undefined))
.toEqual({ status: null, stdout: "", timedOut: true, spawnFailed: true });
});

test("the asynchronous probe confirms a missing key through its readable parent", async () => {
const calls: string[] = [];
const state = await probeClaudeDesktopPolicyAsync({
platform: "win32",
resolveSystemDirectory: () => "C:\\trusted\\System32",
run: (_file, args) => {
calls.push(args[1]!);
return Promise.resolve(args[1] === "HKLM\\SOFTWARE\\Policies"
? result({ status: 0, stdout: "HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies" })
: result({ status: 1 }));
},
});

expect(calls).toEqual(["HKLM\\SOFTWARE\\Policies\\Claude", "HKLM\\SOFTWARE\\Policies"]);
expect(state).toBe("absent");
});

test("the asynchronous probe keeps an unreadable key unknown when its parent lists it", async () => {
const state = await probeClaudeDesktopPolicyAsync({
platform: "win32",
resolveSystemDirectory: () => "C:\\trusted\\System32",
run: (_file, args) => Promise.resolve(args[1] === "HKLM\\SOFTWARE\\Policies"
? result({
status: 0,
stdout: [
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies",
" privatePolicyName REG_SZ private-value",
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude",
].join("\r\n"),
})
: result({ status: 1 })),
});

expect(state).toBe("unknown");
});

test("the asynchronous probe reports unknown when the spawn itself fails", async () => {
const state = await probeClaudeDesktopPolicyAsync({
platform: "win32",
resolveSystemDirectory: () => "C:\\trusted\\System32",
run: () => Promise.resolve(result({ status: null, spawnFailed: true })),
});

expect(state).toBe("unknown");
});

test("cached status probes still honor a custom system-directory resolver", async () => {
let resolved = false;
const state = await getCachedClaudeDesktopPolicy({
platform: "win32",
resolveSystemDirectory: () => {
resolved = true;
return "C:\\nonexistent-opencodex-test-dir";
},
});

expect(resolved).toBe(true);
expect(state).toBe("unknown");
});

test("status policy probes coalesce concurrent refreshes and cache the result", async () => {
let calls = 0;
let clock = 0;
let release!: (state: "present") => void;
const pending = new Promise<"present">((resolve) => { release = resolve; });
const cachedProbe = createCachedClaudeDesktopPolicyProbe(async () => {
calls += 1;
return pending;
}, 30_000, () => clock);

const first = cachedProbe();
const concurrent = cachedProbe();
expect(calls).toBe(1);
release("present");
expect(await Promise.all([first, concurrent])).toEqual(["present", "present"]);
clock = 29_999;
expect(await cachedProbe()).toBe("present");
expect(calls).toBe(1);
});
Loading