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
2 changes: 2 additions & 0 deletions .changeset/runtime-env-test-isolation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
5 changes: 5 additions & 0 deletions .changeset/tidy-rivers-smile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"hunkdiff": minor
---

Add `HUNK_RUNTIME_DIR` as an override for session runtime state and credentials, ahead of `XDG_RUNTIME_DIR`.
5 changes: 3 additions & 2 deletions docs/session-broker-sdk.md
Original file line number Diff line number Diff line change
Expand Up @@ -583,8 +583,9 @@ of becoming a second restart owner. Daemons too old to retire while idle, or hun
require manual termination. Preservation means paths, selectors, outputs, and automatic credential
discovery for upgraded clients—not interoperability with pre-authentication binaries.

Hunk's fixed-endpoint Phase-1 credential store uses a home-local `.hunk` parent when
`XDG_RUNTIME_DIR` is unavailable, rather than a predictable name in a shared temporary directory.
Hunk's fixed-endpoint Phase-1 credential store uses `HUNK_RUNTIME_DIR` when set, then
`XDG_RUNTIME_DIR`, and otherwise a home-local `.hunk` parent rather than a predictable name in a
shared temporary directory.
It inherits the current user's ACL when it creates the `hunk-mcp/security-v1` directory
on Windows and rejects symbolic-link redirection. Node does not
provide a portable owner/DACL or general reparse-point inspection API, so this integration cannot
Expand Down
12 changes: 12 additions & 0 deletions packages/hunk/src/session/broker/brokerClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const originalHost = process.env.HUNK_MCP_HOST;
const originalPort = process.env.HUNK_MCP_PORT;
const originalDisable = process.env.HUNK_MCP_DISABLE;
const originalUnsafeRemote = process.env.HUNK_MCP_UNSAFE_ALLOW_REMOTE;
const originalHunkRuntimeDir = process.env.HUNK_RUNTIME_DIR;
const originalRuntimeDir = process.env.XDG_RUNTIME_DIR;
// Clients that launch daemons or mint credentials write here unless a test chooses its own dir.
const { path: testRuntimeDir, cleanup: cleanupTestRuntimeDir } = createTestRuntimeDir(
Expand Down Expand Up @@ -259,6 +260,7 @@ function prepareDirectConnectTest(client: SessionBrokerClient) {
/** Authenticate observed sockets with real signed hellos while keeping retry time deterministic. */
async function createRefusalLifecycleTest(withMetadata = false, subscribe = false) {
const runtimeDir = mkdtempSync(join(tmpdir(), "hunk-payload-refusal-"));
delete process.env.HUNK_RUNTIME_DIR;
process.env.XDG_RUNTIME_DIR = runtimeDir;
const nativeFetch = globalThis.fetch;
const clock = new DeterministicLifecycleClockTest();
Expand Down Expand Up @@ -354,6 +356,7 @@ async function createRefusalLifecycleTest(withMetadata = false, subscribe = fals
}

beforeAll(() => {
delete process.env.HUNK_RUNTIME_DIR;
process.env.XDG_RUNTIME_DIR = testRuntimeDir;
});

Expand Down Expand Up @@ -385,6 +388,7 @@ afterEach(() => {
}

// Undo per-test runtime overrides without exposing the real runtime dir between tests.
delete process.env.HUNK_RUNTIME_DIR;
process.env.XDG_RUNTIME_DIR = testRuntimeDir;

console.error = originalConsoleError;
Expand All @@ -393,6 +397,11 @@ afterEach(() => {
afterAll(async () => {
// Restore the ambient runtime dir only after the file, so a stray timer between tests still
// resolves the private one.
if (originalHunkRuntimeDir === undefined) {
delete process.env.HUNK_RUNTIME_DIR;
} else {
process.env.HUNK_RUNTIME_DIR = originalHunkRuntimeDir;
}
if (originalRuntimeDir === undefined) {
delete process.env.XDG_RUNTIME_DIR;
} else {
Expand Down Expand Up @@ -845,6 +854,7 @@ describe("Hunk session daemon client", () => {

test("recovers an actual daemon file-limit rejection after explicit smaller-review replacement", async () => {
const runtimeDir = mkdtempSync(join(tmpdir(), "hunk-file-limit-recovery-"));
delete process.env.HUNK_RUNTIME_DIR;
process.env.XDG_RUNTIME_DIR = runtimeDir;
process.env.HUNK_MCP_HOST = "127.0.0.1";
delete process.env.HUNK_MCP_DISABLE;
Expand Down Expand Up @@ -1309,6 +1319,7 @@ describe("Hunk session daemon client", () => {
});
const port = incumbent.port;
if (!port) throw new Error("Expected Bun to select an ephemeral incumbent port.");
delete process.env.HUNK_RUNTIME_DIR;
process.env.XDG_RUNTIME_DIR = runtimeDir;
process.env.HUNK_MCP_HOST = "127.0.0.1";
process.env.HUNK_MCP_PORT = String(port);
Expand Down Expand Up @@ -1396,6 +1407,7 @@ describe("Hunk session daemon client", () => {
const address = listener.address();
const port = typeof address === "object" && address ? address.port : 0;
await new Promise<void>((resolve) => listener.close(() => resolve()));
delete process.env.HUNK_RUNTIME_DIR;
process.env.XDG_RUNTIME_DIR = runtimeDir;
process.env.HUNK_MCP_HOST = "127.0.0.1";
process.env.HUNK_MCP_PORT = String(port);
Expand Down
22 changes: 11 additions & 11 deletions packages/hunk/src/session/broker/brokerLauncher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ afterEach(() => {
describe("session daemon launcher", () => {
test("reads only bounded exact launch metadata as a generation hint", () => {
const runtime = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtime };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtime };
const paths = resolveSessionBrokerRuntimePaths(testConfig, env);
mkdirSync(paths.runtimeDir, { recursive: true });
const metadata = {
Expand Down Expand Up @@ -400,7 +400,7 @@ describe("session daemon launcher", () => {

test("coordinates concurrent ensure calls so only one launcher runs", async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const clock = new DeterministicLifecycleClockTest();
let healthy = false;
let launchCount = 0;
Expand Down Expand Up @@ -445,7 +445,7 @@ describe("session daemon launcher", () => {

test("polls daemon health on the injected lifecycle clock", async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const clock = new DeterministicLifecycleClockTest();
let launchCount = 0;
let settled = false;
Expand Down Expand Up @@ -486,7 +486,7 @@ describe("session daemon launcher", () => {

test("uses the injected polling deadline without wall-clock waits", async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const clock = new DeterministicLifecycleClockTest();
let settled = false;
const outcome = ensureSessionBrokerAvailable({
Expand Down Expand Up @@ -524,7 +524,7 @@ describe("session daemon launcher", () => {
for (const outcome of ["resolve", "reject"] as const) {
test(`lost authority fences protected health ${outcome} and still releases the launch lock`, async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const paths = resolveSessionBrokerRuntimePaths(testConfig, env);
const protectedHealth = createDeferredTest<boolean>();
let healthCalls = 0;
Expand Down Expand Up @@ -561,7 +561,7 @@ describe("session daemon launcher", () => {

test(`lost authority fences final port ${outcome} without a late conflict or timeout`, async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const portProbe = createDeferredTest<boolean>();
let portStarted = false;
let authorized = true;
Expand All @@ -587,7 +587,7 @@ describe("session daemon launcher", () => {

test("fences a synchronous foreign throw after authority changes", async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const paths = resolveSessionBrokerRuntimePaths(testConfig, env);
let authorized = true;
let launchCount = 0;
Expand Down Expand Up @@ -633,7 +633,7 @@ describe("session daemon launcher", () => {

test("suppresses a synchronous launch error after the callback revokes authority", async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const paths = resolveSessionBrokerRuntimePaths(testConfig, env);
let authorized = true;
let healthCalls = 0;
Expand Down Expand Up @@ -661,7 +661,7 @@ describe("session daemon launcher", () => {

test("preserves a synchronous launch error while authority remains current", async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const paths = resolveSessionBrokerRuntimePaths(testConfig, env);
const launchFailure = new Error("current synchronous launch failure");
const ensuring = ensureSessionBrokerAvailable({
Expand All @@ -683,7 +683,7 @@ describe("session daemon launcher", () => {

test("does not clean stale metadata after authority is already lost", async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const paths = resolveSessionBrokerRuntimePaths(testConfig, env);
mkdirSync(paths.runtimeDir, { recursive: true });
writeFileSync(
Expand All @@ -710,7 +710,7 @@ describe("session daemon launcher", () => {

test("recovers a stale launch lock from a dead launcher and overwrites stale metadata", async () => {
const runtimeDir = createRuntimeDir();
const env = { ...process.env, XDG_RUNTIME_DIR: runtimeDir };
const env = { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: runtimeDir };
const paths = resolveSessionBrokerRuntimePaths(testConfig, env);
mkdirSync(paths.runtimeDir, { recursive: true });

Expand Down
2 changes: 1 addition & 1 deletion packages/hunk/src/session/broker/brokerLauncher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ function safeRuntimeToken(value: string) {
}

function resolveRuntimeBaseDir(env: NodeJS.ProcessEnv = process.env) {
const configured = env.XDG_RUNTIME_DIR?.trim();
const configured = env.HUNK_RUNTIME_DIR?.trim() || env.XDG_RUNTIME_DIR?.trim();
if (configured) return configured;
// Unix temporary directories are commonly shared across users. Keep the fallback beneath the
// current home directory instead of a predictable shared-/tmp name another account can pre-own.
Expand Down
8 changes: 8 additions & 0 deletions packages/hunk/src/session/broker/brokerServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { HUNK_SESSION_BROKER_APP_ID, HUNK_SESSION_BROKER_APP_REVISION } from "./
const originalHost = process.env.HUNK_MCP_HOST;
const originalPort = process.env.HUNK_MCP_PORT;
const originalUnsafeRemote = process.env.HUNK_MCP_UNSAFE_ALLOW_REMOTE;
const originalHunkRuntimeDir = process.env.HUNK_RUNTIME_DIR;
const originalRuntimeDir = process.env.XDG_RUNTIME_DIR;
// Served daemons and minted credentials write here instead of the developer's runtime dir.
const { path: testRuntimeDir, cleanup: cleanupTestRuntimeDir } = createTestRuntimeDir(
Expand Down Expand Up @@ -306,6 +307,7 @@ async function waitForSocketClose(socket: WebSocket) {
}

beforeAll(() => {
delete process.env.HUNK_RUNTIME_DIR;
process.env.XDG_RUNTIME_DIR = testRuntimeDir;
});

Expand All @@ -329,12 +331,18 @@ afterEach(() => {
}

// Undo per-test runtime overrides without exposing the real runtime dir between tests.
delete process.env.HUNK_RUNTIME_DIR;
process.env.XDG_RUNTIME_DIR = testRuntimeDir;
});

afterAll(async () => {
// Restore the ambient runtime dir only after the file, so a stray timer between tests still
// resolves the private one.
if (originalHunkRuntimeDir === undefined) {
delete process.env.HUNK_RUNTIME_DIR;
} else {
process.env.HUNK_RUNTIME_DIR = originalHunkRuntimeDir;
}
if (originalRuntimeDir === undefined) {
delete process.env.XDG_RUNTIME_DIR;
} else {
Expand Down
17 changes: 15 additions & 2 deletions packages/hunk/src/session/broker/credentials.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ import { loadOrCreateHunkSessionBrokerCredentials } from "./credentials";

const roots: string[] = [];

function isolatedEnv() {
/** Build an environment that cannot inherit the developer's runtime override. */
function isolatedEnv(): NodeJS.ProcessEnv {
const root = mkdtempSync(join(tmpdir(), "hunk-credentials-test-"));
roots.push(root);
return { ...process.env, XDG_RUNTIME_DIR: root };
return { ...process.env, HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: root };
}

afterEach(() => {
Expand Down Expand Up @@ -46,6 +47,18 @@ describe("Hunk session broker credential store", () => {
expect(callerFile).not.toContain("hunk-review-capability");
});

test("uses HUNK_RUNTIME_DIR ahead of XDG_RUNTIME_DIR for credentials", async () => {
const env = isolatedEnv();
const override = mkdtempSync(join(tmpdir(), "hunk-runtime-override-"));
roots.push(override);
env.HUNK_RUNTIME_DIR = override;

await loadOrCreateHunkSessionBrokerCredentials({ env });

expect(lstatSync(join(override, "hunk-mcp", "security-v1", "caller.json")).isFile()).toBe(true);
expect(() => lstatSync(join(env.XDG_RUNTIME_DIR!, "hunk-mcp"))).toThrow();
});

test("adopts one complete winner under concurrent first use", async () => {
const env = isolatedEnv();
const results = await Promise.all(
Expand Down
3 changes: 3 additions & 0 deletions packages/hunk/src/session/broker/reviewPageServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ describe("review page server encoding and availability", () => {
describe("review page inside the daemon", () => {
const originalPort = process.env.HUNK_MCP_PORT;
const originalHost = process.env.HUNK_MCP_HOST;
const originalHunkRuntimeDir = process.env.HUNK_RUNTIME_DIR;
const originalRuntimeDir = process.env.XDG_RUNTIME_DIR;
const runtime = createTestRuntimeDir("hunk-page-daemon-runtime-");
let stop: (() => void) | undefined;
Expand All @@ -257,6 +258,7 @@ describe("review page inside the daemon", () => {
const port = typeof address === "object" && address ? address.port : 0;
await new Promise<void>((resolve) => listener.close(() => resolve()));

delete process.env.HUNK_RUNTIME_DIR;
process.env.XDG_RUNTIME_DIR = runtime.path;
process.env.HUNK_MCP_HOST = "127.0.0.1";
process.env.HUNK_MCP_PORT = String(port);
Expand All @@ -272,6 +274,7 @@ describe("review page inside the daemon", () => {
["HUNK_MCP_PORT", originalPort],
["HUNK_MCP_HOST", originalHost],
["XDG_RUNTIME_DIR", originalRuntimeDir],
["HUNK_RUNTIME_DIR", originalHunkRuntimeDir],
] as const) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
Expand Down
3 changes: 3 additions & 0 deletions scripts/generate/generate-docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,12 @@ export function renderCliReference() {
"",
"| Variable | Purpose |",
"| --- | --- |",
"| `HUNK_RUNTIME_DIR` | Runtime base directory for daemon metadata, locks, and credentials; overrides `XDG_RUNTIME_DIR` and the platform fallback. |",
`| \`${SESSION_BROKER_HOST_ENV}\` | Bind host; defaults to loopback \`${DEFAULT_SESSION_BROKER_HOST}\`. |`,
`| \`${SESSION_BROKER_PORT_ENV}\` | Bind port; defaults to \`${DEFAULT_SESSION_BROKER_PORT}\`. |`,
`| \`${UNSAFE_ALLOW_REMOTE_SESSION_BROKER_ENV}\` | Set to \`1\` to allow unsafe non-loopback binding. |`,
"",
"Hunk, the daemon, and agents running `hunk session` commands must all see the same `HUNK_RUNTIME_DIR` value so they share credentials and launch metadata. As with `HUNK_MCP_PORT`, set it consistently in every shell or process that participates in the review.",
);
}

Expand Down
1 change: 1 addition & 0 deletions test/cli/compiled-headless-native-lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ function createTestEnvironment(port?: number) {
USERPROFILE: home,
XDG_CACHE_HOME: cache,
XDG_CONFIG_HOME: config,
HUNK_RUNTIME_DIR: undefined,
XDG_RUNTIME_DIR: runtime,
TMPDIR: temp,
BUN_TMPDIR: temp,
Expand Down
9 changes: 6 additions & 3 deletions test/cli/web-entry-points.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@ import { createTestRuntimeDir } from "../helpers/runtime-dir";
const repoRoot = process.cwd();
const sourceEntrypoint = join(repoRoot, "packages/hunk/src/main.tsx");
const testConfigHome = createTestConfigHome();
const { path: testRuntimeDir, cleanup: cleanupTestRuntimeDir } =
createTestRuntimeDir("hunk-web-entry-runtime-");
const {
path: testRuntimeDir,
env: testRuntimeEnv,
cleanup: cleanupTestRuntimeDir,
} = createTestRuntimeDir("hunk-web-entry-runtime-");
const tempDirs: string[] = [];
const ports: number[] = [];
// Every web review a test starts, so a failed or timed-out test cannot leak a session.
Expand Down Expand Up @@ -74,7 +77,7 @@ function testEnv(port: number, extra: Record<string, string> = {}) {
return {
...process.env,
XDG_CONFIG_HOME: testConfigHome,
XDG_RUNTIME_DIR: testRuntimeDir,
...testRuntimeEnv,
HUNK_MCP_PORT: String(port),
HUNK_DISABLE_UPDATE_NOTICE: "1",
// A run that forgets --no-open must still never start a real browser.
Expand Down
18 changes: 18 additions & 0 deletions test/helpers/runtime-dir.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { expect, test } from "bun:test";
import { join } from "node:path";
import { resolveSessionBrokerRuntimePaths } from "../../packages/hunk/src/session/broker/brokerLauncher";
import { createTestRuntimeDir } from "./runtime-dir";

test("runtime overrides ignore an inherited HUNK_RUNTIME_DIR", async () => {
const runtime = createTestRuntimeDir();
try {
const inherited: NodeJS.ProcessEnv = { ...process.env, HUNK_RUNTIME_DIR: "developer-runtime" };
const env = { ...inherited, ...runtime.env };
const paths = resolveSessionBrokerRuntimePaths({ host: "127.0.0.1", port: 47657 }, env);

expect(env.HUNK_RUNTIME_DIR).toBeUndefined();
expect(paths.runtimeDir).toBe(join(runtime.path, "hunk-mcp"));
} finally {
await runtime.cleanup();
}
});
11 changes: 9 additions & 2 deletions test/helpers/runtime-dir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,25 @@ import { removeTestDirectory } from "./filesystem";
export interface TestRuntimeDir {
/** Private directory to pass as XDG_RUNTIME_DIR. */
readonly path: string;
/** Environment overrides that isolate both runtime directory selectors. */
readonly env: { HUNK_RUNTIME_DIR: undefined; XDG_RUNTIME_DIR: string };
/** Remove the directory after transient Windows process handles are released. */
readonly cleanup: () => Promise<void>;
}

/**
* Create a private XDG_RUNTIME_DIR so daemon launch metadata, locks, and session credentials a
* test writes never land in the developer's real runtime dir.
* test writes never land in the developer's real runtime dir. Spread `env` after the inherited
* process environment to clear the higher-precedence HUNK_RUNTIME_DIR override.
*
* Callers create the dir at module scope, so pair it with `afterAll(cleanup)`; Bun's test runner
* does not emit `process.on("exit")`, so the helper cannot sweep after itself.
*/
export function createTestRuntimeDir(prefix = "hunk-test-runtime-"): TestRuntimeDir {
const path = mkdtempSync(join(tmpdir(), prefix));
return { path, cleanup: () => removeTestDirectory(path) };
return {
path,
env: { HUNK_RUNTIME_DIR: undefined, XDG_RUNTIME_DIR: path },
cleanup: () => removeTestDirectory(path),
};
}
Loading
Loading