OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(processes): preserve cancellation and child diagnostics (#1508)
mldangelo-oai6f6458729e74
diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.tsindex 41ec1b544..17dbe0518 100644--- a/sdk/typescript/src/auth.ts+++ b/sdk/typescript/src/auth.ts@@ -147,7 +147,9 @@ export class CodexLoginHandle {};this.#settleInstructionWaiters(result);if (result.success) {- Promise.resolve(onSuccess()).then(() => resolve(result), reject);+ Promise.resolve()+ .then(onSuccess)+ .then(() => resolve(result), reject);} else {resolve(result);}diff --git a/sdk/typescript/src/deduplication/codex-review.ts b/sdk/typescript/src/deduplication/codex-review.tsindex 4f6802269..a13c7e147 100644--- a/sdk/typescript/src/deduplication/codex-review.ts+++ b/sdk/typescript/src/deduplication/codex-review.ts@@ -344,10 +344,26 @@ export class CodexReviewRunner {inputError = error;lines.close();});- child.stderr.setEncoding("utf8");- child.stderr.on("data", (message: string) =>- emitDiagnostic(onDiagnostic, { event: "review.stderr", message }),- );+ const releaseCanceledPipes = () => {+ if (!this.signal?.aborted) return;+ lines.close();+ if (child.exitCode === null && child.signalCode === null) return;+ child.stdin.destroy();+ child.stdout.destroy();+ child.stderr.destroy();+ };+ this.signal?.addEventListener("abort", releaseCanceledPipes, {+ once: true,+ });+ child.once("exit", releaseCanceledPipes);+ let diagnostic = "";+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => {+ diagnostic += chunk;+ emitDiagnostic(onDiagnostic, {+ event: "review.stderr",+ message: chunk,+ });+ });const send = (message: object) =>child.stdin.write(`${JSON.stringify(message)}\n`);const startThread = () =>@@ -669,19 +685,25 @@ export class CodexReviewRunner {return accepted;}}- if (processError) throw processError;- throw new ReviewAttemptError(- "transport",- inputError?.message ?? "Codex exited before completing the review",- "Codex review transport failed.",- true,- );} finally {lines.close();child.stdin.end();if (child.exitCode === null) child.kill();- await closed;+ try {+ await closed;+ } finally {+ this.signal?.removeEventListener("abort", releaseCanceledPipes);+ child.removeListener("exit", releaseCanceledPipes);+ }}+ if (processError) throw processError;+ throw new ReviewAttemptError(+ "transport",+ [inputError?.message, diagnostic].filter(Boolean).join("\n") ||+ "Codex exited before completing the review",+ "Codex review transport failed.",+ true,+ );} finally {await rm(directory, { recursive: true, force: true });}diff --git a/sdk/typescript/src/feedback.ts b/sdk/typescript/src/feedback.tsindex db0966e47..71c69f852 100644--- a/sdk/typescript/src/feedback.ts+++ b/sdk/typescript/src/feedback.ts@@ -90,20 +90,42 @@ export async function sendFeedback(},);const uploaded = Promise.withResolvers<string>();+ let stderr = "";+ let stdinError: Error | undefined;const closed = new Promise<void>((resolve) => {child.once("close", () => {uploaded.reject(- new CodexSecurityError("Codex exited before feedback was uploaded."),+ new CodexSecurityError(+ stderr || "Codex exited before feedback was uploaded.",+ ),);resolve();});});child.once("error", uploaded.reject);- child.stdin.on("error", uploaded.reject);- child.stderr.resume();+ child.stdin.on("error", (error: Error) => {+ stdinError ??= error;+ uploaded.reject(error);+ });+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => {+ stderr += chunk;+ });const send = (message: object) =>child.stdin.write(`${JSON.stringify(message)}\n`);const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });+ const releaseCanceledPipes = () => {+ if (!options.signal?.aborted) return;+ uploaded.reject(options.signal.reason);+ if (child.exitCode === null && child.signalCode === null) return;+ lines.close();+ child.stdin.destroy();+ child.stdout.destroy();+ child.stderr.destroy();+ };+ options.signal?.addEventListener("abort", releaseCanceledPipes, {+ once: true,+ });+ child.once("exit", releaseCanceledPipes);lines.on("line", (line) => {try {const message = JSON.parse(line) as {@@ -155,26 +177,35 @@ export async function sendFeedback(}});try {- send({- id: 1,- method: "initialize",- params: { clientInfo: { name: "codex-security", version: VERSION } },- });- return {- feedbackId: await uploaded.promise,- scanId: scan?.scanId ?? null,- includedLogs: includeLogs,- };- } finally {- lines.close();- child.stdin.end();- child.kill();- const timer = setTimeout(() => child.kill("SIGKILL"), 1_000);try {- await closed;+ send({+ id: 1,+ method: "initialize",+ params: { clientInfo: { name: "codex-security", version: VERSION } },+ });+ return {+ feedbackId: await uploaded.promise,+ scanId: scan?.scanId ?? null,+ includedLogs: includeLogs,+ };} finally {- clearTimeout(timer);+ lines.close();+ child.stdin.end();+ child.kill();+ const timer = setTimeout(() => child.kill("SIGKILL"), 1_000);+ try {+ await closed;+ } finally {+ clearTimeout(timer);+ options.signal?.removeEventListener("abort", releaseCanceledPipes);+ child.removeListener("exit", releaseCanceledPipes);+ }}+ } catch (error) {+ options.signal?.throwIfAborted();+ if (error === stdinError && stderr)+ throw new CodexSecurityError(stderr, { cause: error });+ throw error;}} finally {if (directory !== undefined)diff --git a/sdk/typescript/src/security-policy.ts b/sdk/typescript/src/security-policy.tsindex ce6b8f7fe..a40da768b 100644--- a/sdk/typescript/src/security-policy.ts+++ b/sdk/typescript/src/security-policy.ts@@ -1013,6 +1013,7 @@ export async function securityPolicyDiff(" if not line.endswith('\\n'): sys.stdout.buffer.write(b'\\n\\\\ No newline at end of file\\n')",].join("\n");const diff = await new Promise<string>((resolve, reject) => {+ let inputError: Error | undefined;const child = execFile(interpreter,["-I", "-c", script],@@ -1021,9 +1022,26 @@ export async function securityPolicyDiff(maxBuffer: Infinity,signal,},- (error, stdout) => (error === null ? resolve(stdout) : reject(error)),+ (error, stdout) => {+ const failure = error ?? inputError;+ if (failure === undefined) resolve(stdout);+ else reject(failure);+ },);- child.stdin!.on("error", reject);+ const releaseFailedInput = () => {+ if (inputError === undefined) return;+ if (child.exitCode === null && child.signalCode === null) {+ if (child.pid !== undefined) reject(inputError);+ return;+ }+ child.stdout!.destroy();+ child.stderr!.destroy();+ };+ child.once("exit", releaseFailedInput);+ child.stdin!.on("error", (error: Error) => {+ inputError = error;+ releaseFailedInput();+ });child.stdin!.end(JSON.stringify([draft.previousContent ?? "",diff --git a/sdk/typescript/tests-ts/auth.test.ts b/sdk/typescript/tests-ts/auth.test.tsindex 10188aa73..9f7d03559 100644--- a/sdk/typescript/tests-ts/auth.test.ts+++ b/sdk/typescript/tests-ts/auth.test.ts@@ -190,6 +190,24 @@ describe("Codex authentication process boundary", () => {expect(observeSucceeded).toHaveBeenCalled();});+ test.each(["sync", "async"])(+ "rejects wait when required login completion fails: %s",+ async (mode) => {+ const { command, environment } = await fakeCodex();+ const failure = new Error("Synthetic credential persistence failed");+ const handle = new CodexLoginHandle(+ command,+ ["login", "--device-auth"],+ environment,+ () => {+ if (mode === "sync") throw failure;+ return Promise.reject(failure);+ },+ );+ await expect(handle.wait()).rejects.toBe(failure);+ },+ );+test.each(["User code: RIGHT-CODE", "Code: RIGHT-CODE", "RIGHT-CODE"])("ignores URL parameters when reading device instructions: %s",async (instruction) => {diff --git a/sdk/typescript/tests-ts/codex-process-cancellation.test.ts b/sdk/typescript/tests-ts/codex-process-cancellation.test.tsnew file mode 100644index 000000000..0a7685d7c--- /dev/null+++ b/sdk/typescript/tests-ts/codex-process-cancellation.test.ts@@ -0,0 +1,284 @@+import {+ spawn,+ type ChildProcessWithoutNullStreams,+ type SpawnOptions,+} from "node:child_process";+import { getEventListeners } from "node:events";+import { existsSync } from "node:fs";+import { mkdir, writeFile } from "node:fs/promises";+import { join } from "node:path";+import {+ setImmediate as nextTurn,+ setTimeout as delay,+} from "node:timers/promises";+import { fileURLToPath } from "node:url";+import { afterEach, expect, test } from "bun:test";+import { CodexReviewRunner } from "../src/deduplication/codex-review.js";+import { sendFeedback } from "../src/feedback.js";+import { nodeCommand } from "./support/shell.js";+import { createApiTestFixtures } from "./support/temporary-directories.js";++const { temporaryDirectory, cleanup } = createApiTestFixtures();+afterEach(cleanup);+const fixture = fileURLToPath(+ new URL("fixtures/inherited-codex-pipes.mjs", import.meta.url),+);+const node = nodeCommand().command;++for (const surface of ["review", "feedback"] as const) {+ for (const mode of [+ "abandoned",+ "success",+ "error",+ "unterminated",+ "late",+ "active",+ "spawn-error",+ ]) {+ test.skipIf(mode === "active" && process.platform === "win32")(+ `${surface} settles inherited pipes: ${mode}`,+ async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ await mkdir(repository);+ const release = join(root, "release");+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_HOME: join(root, "home"),+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ OPENAI_API_KEY: "synthetic-review-key",+ };+ await mkdir(environment.CODEX_HOME, { mode: 0o700 });+ const controller = new AbortController();+ const reason = mode === "active" ? "synthetic interruption" : { mode };+ const ready = Promise.withResolvers<void>();+ const ignored = Promise.withResolvers<void>();+ const exited = Promise.withResolvers<void>();+ let child: ChildProcessWithoutNullStreams | undefined;+ let holderStarted = false;+ let holderPid: number | undefined;+ let nativeSpawnOptions: SpawnOptions | undefined;+ let starts = 0;+ let retries = 0;+ let retryDiagnostic: string | undefined;+ const start: NonNullable<Parameters<typeof sendFeedback>[1]> = (+ _command,+ _args,+ options,+ ) => {+ starts++;+ nativeSpawnOptions = {+ ...options,+ stdio: ["pipe", "pipe", "pipe", "ipc"],+ };+ child = spawn(+ mode === "spawn-error" ? join(root, "missing-codex") : node,+ [fixture, mode, release],+ nativeSpawnOptions,+ ) as ChildProcessWithoutNullStreams;+ child.on("message", (message) => {+ if (+ message &&+ typeof message === "object" &&+ "holderPid" in message+ )+ holderPid = message.holderPid as number;+ if (message === "ready") {+ holderStarted = true;+ ready.resolve();+ }+ if (message === "ignored-term") ignored.resolve();+ });+ if (mode !== "spawn-error")+ child.once("exit", () => {+ exited.resolve();+ if (!["late", "active"].includes(mode)) controller.abort(reason);+ });+ return child;+ };+ const task =+ surface === "feedback"+ ? sendFeedback(+ {+ reason: "Synthetic feedback",+ includeLogs: false,+ environment,+ workingDirectory: repository,+ signal: controller.signal,+ },+ start,+ )+ : new CodexReviewRunner(+ environment,+ start,+ controller.signal,+ repository,+ {+ wait: async () => {+ retries++;+ throw new Error("Stop the synthetic transport retry");+ },+ },+ (event) => {+ if (event.event === "review.retry")+ retryDiagnostic = event.message;+ },+ ).run({+ stage: "pair-review",+ model: "synthetic-model",+ effort: "high",+ prompt: "Review synthetic findings.",+ schema: { type: "object" },+ validate: (value) => value,+ });+ let settled = false;+ const result = task.then(+ (value) => ({ value, error: undefined }),+ (error: unknown) => ({ value: undefined, error }),+ );+ void result.then(() => {+ settled = true;+ });+ const deadline = new AbortController();+ const bounded = <T>(operation: Promise<T>, phase: string): Promise<T> =>+ Promise.race([+ operation,+ delay(5000, undefined, { signal: deadline.signal }).then(() => {+ throw new Error(`${phase} did not settle before holder release`);+ }),+ ]);+ let primaryFailure: unknown;+ try {+ if (mode !== "spawn-error") {+ await bounded(+ Promise.race([+ ready.promise,+ result.then((outcome) => {+ throw outcome.error ?? new Error("Fixture did not start");+ }),+ ]),+ "fixture readiness",+ );+ if (mode === "active") {+ controller.abort(reason);+ await bounded(ignored.promise, "SIGTERM observation");+ expect(child!.exitCode).toBeNull();+ expect(child!.signalCode).toBeNull();+ expect(child!.stdout.destroyed).toBe(false);+ expect(child!.stderr.destroyed).toBe(false);+ if (surface === "review") child!.kill("SIGKILL");+ }+ await bounded(exited.promise, "direct child exit");+ if (mode === "active" && surface === "feedback")+ expect(child!.signalCode).toBe("SIGKILL");+ }+ if (mode === "late") {+ await nextTurn();+ expect(settled).toBe(false);+ expect(child!.stdout.destroyed).toBe(false);+ expect(child!.stderr.destroyed).toBe(false);+ await writeFile(release, "released");+ }+ const outcome = await bounded(result, "operation completion");+ if (mode === "success") {+ expect(outcome).toMatchObject({+ value:+ surface === "feedback"+ ? { feedbackId: "synthetic-feedback" }+ : { decision: "SAME" },+ error: undefined,+ });+ } else if (mode === "late") {+ expect(+ surface === "feedback"+ ? (outcome.error as Error).message+ : retryDiagnostic,+ ).toContain("late café 日本語 😀");+ } else if (mode !== "spawn-error") {+ expect(outcome.error).toBe(reason);+ }+ expect(starts).toBe(1);+ expect(retries).toBe(mode === "late" && surface === "review" ? 1 : 0);+ const remaining = getEventListeners(controller.signal, "abort");+ if (mode === "spawn-error") {+ // Compare native ownership without depending on its callback identities.+ const controlAbort = new AbortController();+ let control: ReturnType<typeof spawn> | undefined;+ let controlError: unknown;+ try {+ control = spawn(+ join(root, "missing-codex"),+ [fixture, mode, release],+ { ...nativeSpawnOptions, signal: controlAbort.signal },+ );+ control.once("error", (error: Error) => {+ controlError = error;+ });+ await new Promise<void>((resolve) =>+ control!.once("close", resolve),+ );+ } catch (error) {+ controlError = error;+ }+ expect(controlError).toBeInstanceOf(Error);+ expect((outcome.error as Error).message).toContain(+ (controlError as Error).message,+ );+ expect(remaining).toHaveLength(+ getEventListeners(controlAbort.signal, "abort").length,+ );+ expect(child?.listenerCount("exit") ?? 0).toBe(+ control?.listenerCount("exit") ?? 0,+ );+ } else {+ expect(remaining).toHaveLength(0);+ expect(child!.listenerCount("exit")).toBe(0);+ }+ } catch (error) {+ primaryFailure = error;+ throw error;+ } finally {+ try {+ await writeFile(release, "released");+ if (child?.exitCode === null && child.signalCode === null)+ child.kill("SIGKILL");+ await result;+ if (holderStarted)+ await bounded(+ (async () => {+ while (!existsSync(`${release}.done`))+ await delay(10, undefined, { signal: deadline.signal });+ })(),+ "holder cleanup",+ );+ } catch (error) {+ let holderStatus = "not announced";+ if (holderPid !== undefined) {+ try {+ process.kill(holderPid, 0);+ holderStatus = "alive";+ } catch (probeError) {+ holderStatus =+ (probeError as NodeJS.ErrnoException).code ??+ String(probeError);+ }+ }+ const cleanupError = new Error(+ `Holder cleanup failed (holder ${holderPid ?? "unknown"}: ${holderStatus}; completion marker: ${existsSync(`${release}.done`)})`,+ { cause: error },+ );+ if (primaryFailure !== undefined)+ throw new AggregateError(+ [primaryFailure, cleanupError],+ "The cancellation test and holder cleanup both failed",+ );+ throw cleanupError;+ } finally {+ deadline.abort();+ }+ }+ },+ );+ }+}diff --git a/sdk/typescript/tests-ts/codex-review.test.ts b/sdk/typescript/tests-ts/codex-review.test.tsindex c0ad53fd5..506201a92 100644--- a/sdk/typescript/tests-ts/codex-review.test.ts+++ b/sdk/typescript/tests-ts/codex-review.test.ts@@ -246,6 +246,8 @@ const failureReasons: Record<string, string> = {"invalid-review-error":"Required review check could not be completed: Required source revision could not be read.",exit: "Codex exited before completing the review",+ "exit-diagnostic":+ "Permission profile synthetic_profile was rejected: café 🔒\n",};const retriedFailures = new Set(["text-only",@@ -255,6 +257,7 @@ const retriedFailures = new Set(["invalid-json","invalid-submission","exit",+ "exit-diagnostic",]);const recoveredScenarios: Record<string, string> = {"recover-rate-limit": "failed-turn",diff --git a/sdk/typescript/tests-ts/feedback.test.ts b/sdk/typescript/tests-ts/feedback.test.tsindex fe5cd2abd..87325d259 100644--- a/sdk/typescript/tests-ts/feedback.test.ts+++ b/sdk/typescript/tests-ts/feedback.test.ts@@ -1,9 +1,11 @@import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { EventEmitter } from "node:events";import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { existsSync } from "node:fs";import { tmpdir } from "node:os";import { join, toNamespacedPath } from "node:path";import { fileURLToPath } from "node:url";+import { PassThrough } from "node:stream";import { afterEach, expect, test } from "bun:test";import { sendFeedback } from "../src/feedback.js";import { codexSecurityCredentialHome } from "../src/runtime.js";@@ -14,6 +16,7 @@ const fixture = fileURLToPath(new URL("fixtures/feedback.mjs", import.meta.url),);const directories: string[] = [];+const diagnostic = "Synthetic configuration failure: café 日本語";afterEach(async () => {for (const directory of directories.splice(0))await rm(directory, { recursive: true, force: true });@@ -28,6 +31,7 @@ async function setup() {CODEX_CLI_PATH: process.execPath,FEEDBACK_REQUEST_FILE: join(directory, "requests.json"),FEEDBACK_SCENARIO: "success",+ FEEDBACK_STDERR: `${diagnostic}\n`,};const home = codexSecurityCredentialHome(environment);await mkdir(join(home, "sessions"), { recursive: true });@@ -245,15 +249,18 @@ test("without log opt-in, does not read or attach saved sessions", async () => {expect(attachments).toEqual([]);});-for (const [scenario, message] of [+for (const [index, [scenario, message, stderr]] of [["error", "Upload failed"],- ["exit", "Codex exited before feedback was uploaded"],+ ["exit", "Codex exited before feedback was uploaded", ""],+ ["exit-diagnostic", ` ${diagnostic}\n `, ` ${diagnostic}\n `],+ ["exit-diagnostic", " \n\t", " \n\t"],["missing-id", "Codex did not return a feedback ID"],["malformed", "JSON"],-]) {- test(`upload ${scenario} leaves no temporary logs or running child`, async () => {+].entries()) {+ test(`upload ${scenario} case ${index + 1} leaves no temporary logs or running child`, async () => {const context = await setup();context.environment.FEEDBACK_SCENARIO = scenario!;+ if (stderr !== undefined) context.environment.FEEDBACK_STDERR = stderr;await expect(sendFeedback(context.options, context.startCodex),).rejects.toThrow(message);@@ -263,6 +270,52 @@ for (const [scenario, message] of [});}+for (const [index, stderr] of [+ diagnostic,+ ` ${diagnostic}\n `,+ " \n\t",+ "",+].entries()) {+ test(`stdin failure case ${index + 1} preserves ${stderr ? "stderr through cleanup" : "the transport error without stderr"}`, async () => {+ const context = await setup();+ const error = Object.assign(new Error("write EPIPE"), { code: "EPIPE" });+ const bytes = Buffer.from(stderr);+ const split = bytes.indexOf(0xc3) + 1;+ let closed = false;+ const child = Object.assign(new EventEmitter(), {+ stdin: new PassThrough(),+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ kill: () => {+ queueMicrotask(() => {+ child.stderr.end(bytes.subarray(split));+ child.stdout.end();+ closed = true;+ child.emit("close", 1, null);+ });+ return true;+ },+ });+ const operation = sendFeedback(context.options, () => {+ queueMicrotask(() => {+ child.stderr.write(bytes.subarray(0, split));+ child.stdin.emit("error", error);+ });+ return child as unknown as ChildProcessWithoutNullStreams;+ });+ if (stderr) {+ await expect(operation).rejects.toMatchObject({+ name: "CodexSecurityError",+ message: stderr,+ cause: error,+ });+ } else {+ await expect(operation).rejects.toBe(error);+ }+ expect(closed).toBe(true);+ });+}+test("respects disabled feedback without starting Codex", async () => {const context = await setup();await mkdir(context.environment.CODEX_HOME);diff --git a/sdk/typescript/tests-ts/fixtures/codex-review.mjs b/sdk/typescript/tests-ts/fixtures/codex-review.mjsindex 71141d565..e9dd92189 100644--- a/sdk/typescript/tests-ts/fixtures/codex-review.mjs+++ b/sdk/typescript/tests-ts/fixtures/codex-review.mjs@@ -166,6 +166,14 @@ for await (const line of createInterface({ input: process.stdin })) {});}if (scenario === "exit") process.exit(1);+ if (scenario === "exit-diagnostic") {+ process.stdout.end();+ process.stderr.write(+ "Permission profile synthetic_profile was rejected: café 🔒\n",+ () => process.exit(7),+ );+ continue;+ }if (scenario === "diagnostics") {process.stderr.write("Native diagnostic: Bearer synthetic-review-key\n");send({diff --git a/sdk/typescript/tests-ts/fixtures/feedback.mjs b/sdk/typescript/tests-ts/fixtures/feedback.mjsindex 09d025c95..4fadc8807 100644--- a/sdk/typescript/tests-ts/fixtures/feedback.mjs+++ b/sdk/typescript/tests-ts/fixtures/feedback.mjs@@ -2,6 +2,8 @@ import { createInterface } from "node:readline";import { readFile, writeFile } from "node:fs/promises";const requests = [];+if (process.env.FEEDBACK_STDERR)+ process.stderr.write(process.env.FEEDBACK_STDERR);for await (const line of createInterface({ input: process.stdin })) {const request = JSON.parse(line);requests.push(request);@@ -28,6 +30,7 @@ for await (const line of createInterface({ input: process.stdin })) {);break;case "exit":+ case "exit-diagnostic":process.exit(1);break;case "missing-id":diff --git a/sdk/typescript/tests-ts/fixtures/inherited-codex-pipes.mjs b/sdk/typescript/tests-ts/fixtures/inherited-codex-pipes.mjsnew file mode 100644index 000000000..b42eb62ef--- /dev/null+++ b/sdk/typescript/tests-ts/fixtures/inherited-codex-pipes.mjs@@ -0,0 +1,103 @@+import { spawn } from "node:child_process";+import { existsSync, writeFileSync } from "node:fs";+import { dirname } from "node:path";+import { createInterface } from "node:readline";+import { fileURLToPath } from "node:url";++const [mode, release, role] = process.argv.slice(2);+if (role === "holder") {+ process.send("ready");+ const finish = () => {+ writeFileSync(`${release}.done`, "released");+ process.exit(0);+ };+ const interval = setInterval(() => {+ if (!existsSync(release)) return;+ clearInterval(interval);+ if (mode !== "late") finish();+ const diagnostic = Buffer.from("late café 日本語 😀\n");+ process.stderr.write(diagnostic.subarray(0, 9), () => {+ setImmediate(() => {+ process.stderr.write(diagnostic.subarray(9), finish);+ });+ });+ }, 10);+} else {+ const holder = spawn(+ process.execPath,+ [fileURLToPath(import.meta.url), mode, release, "holder"],+ {+ // The holder must outlive the direct child on Windows.+ detached: process.platform === "win32",+ cwd: dirname(fileURLToPath(import.meta.url)),+ stdio: ["ignore", 1, 2, "ipc"],+ },+ );+ await new Promise((resolve) => holder.once("message", resolve));+ process.on("SIGTERM", () => {+ if (mode === "active") process.send("ignored-term");+ else process.exit(0);+ });+ process.send({ holderPid: holder.pid });+ process.send("ready");+ if (mode === "abandoned" || mode === "late") process.exit(0);+ setInterval(() => {}, 1000);+ const send = (message, completeLine = true) => {+ process.stdout.write(+ `${JSON.stringify(message)}${completeLine ? "\n" : ""}`,+ () => {+ if (!completeLine) process.exit(0);+ },+ );+ };+ for await (const line of createInterface({ input: process.stdin })) {+ if (mode === "active") continue;+ const message = JSON.parse(line);+ if (["initialize", "account/login/start"].includes(message.method)) {+ send({ id: message.id, result: {} });+ } else if (message.method === "feedback/upload") {+ send(+ mode === "error"+ ? { id: message.id, error: { message: "Synthetic upload failure" } }+ : { id: message.id, result: { threadId: "synthetic-feedback" } },+ mode !== "unterminated",+ );+ } else if (message.method === "thread/start") {+ send({+ id: message.id,+ result: { thread: { id: "thread", ephemeral: true, path: null } },+ });+ } else if (message.method === "turn/start" && mode !== "active") {+ if (mode === "error") {+ send({+ id: message.id,+ error: { message: "Synthetic review failure" },+ });+ } else {+ send({ id: message.id, result: { turn: { id: "turn" } } });+ send({+ id: "decision",+ method: "item/tool/call",+ params: {+ threadId: "thread",+ turnId: "turn",+ tool: "submit_decisions",+ namespace: "review_validator",+ arguments: { decision: "SAME" },+ },+ });+ }+ } else if (message.id === "decision") {+ send(+ {+ method: "turn/completed",+ params: {+ threadId: "thread",+ turn: { id: "turn", status: "completed" },+ },+ },+ mode !== "unterminated",+ );+ }+ }+}diff --git a/sdk/typescript/tests-ts/security-policy.test.ts b/sdk/typescript/tests-ts/security-policy.test.tsindex 71c5426c6..5168e3d05 100644--- a/sdk/typescript/tests-ts/security-policy.test.ts+++ b/sdk/typescript/tests-ts/security-policy.test.ts@@ -1085,19 +1085,113 @@ describe("security policy preview", () => {expect(diff.match(/No newline at end of file/gu)).toHaveLength(2);});- test("reports an early diff subprocess exit without an unhandled stdin error", async () => {- const name =- "reports an early diff subprocess exit without an unhandled stdin error";- if (runTestInSubprocess(import.meta.path, name)) return;+ test("preserves native launch errors and settles failed diff input", async () => {const f = await fixture();const draft = await f.generate();- const node = nodeCommand().command;- await expect(- securityPolicyDiff(- { ...draft, content: `# Policy\n${"x".repeat(900_000)}` },- node,+ const source = new URL("../src/security-policy.ts", import.meta.url);+ const built = await Bun.build({+ entrypoints: [fileURLToPath(source)],+ target: "node",+ format: "esm",+ define: { "import.meta.url": JSON.stringify(source.href) },+ });+ expect(built.success).toBe(true);+ const module = join(f.root, "policy.mjs");+ await writeFile(module, await built.outputs[0]!.text());+ const ignoreInput = join(f.root, "ignore-input");+ const deniedInterpreter = join(f.root, "denied-interpreter");+ if (process.platform !== "win32") {+ await writeFile(ignoreInput, "#!/bin/sh\nexit 0\n", { mode: 0o700 });+ await writeFile(deniedInterpreter, "#!/bin/sh\nexit 0\n", {+ mode: 0o600,+ });+ }+ const result = JSON.parse(+ execFileSync(+ nodeCommand().command,+ [+ "--input-type=module",+ "--eval",+ `+import { readFileSync, writeFileSync, existsSync } from "node:fs";+import { setTimeout as delay } from "node:timers/promises";+const { securityPolicyDiff } = await import(process.argv[1]);+const draft = JSON.parse(readFileSync(0, "utf8"));+const failures = [];+for (const [interpreter, size] of [[process.execPath, 100], [process.argv[3], 900000], [process.argv[4], 900000], [process.argv[2], 900000]].filter(([interpreter]) => interpreter)) {+ try { await securityPolicyDiff({ ...draft, content: '# Policy\\n' + 'x'.repeat(size) }, interpreter); failures.push(null); }+ catch (error) { failures.push({ code: error.code, message: error.message }); }+}+if (process.argv[2]) {+ const wrapper = process.argv[2];+ const release = wrapper + '-held';+ const diagnostic = ' synthetic café 日本語 😀 error\\n ';+ const holder = "const fs = require('fs'); process.send('ready'); const timer = setInterval(() => { if (fs.existsSync(process.argv[1])) { clearInterval(timer); fs.writeFileSync(process.argv[1] + '.done', 'done'); process.exit(0); } }, 10); setTimeout(() => process.exit(2), 10000).unref();";+ const launcher = [+ '#!' + process.execPath,+ "require('fs').closeSync(0);",+ "const child = require('child_process').spawn(process.execPath, ['-e', " + JSON.stringify(holder) + ", " + JSON.stringify(release) + "], { stdio: ['ignore', 1, 2, 'ipc'] });",+ "child.once('message', () => process.stderr.write(" + JSON.stringify(diagnostic) + ", () => process.exit(0)));",+ ].join('\\n');+ writeFileSync(wrapper, launcher, { mode: 0o700 });+ const task = securityPolicyDiff({ ...draft, content: '# Policy\\n' + 'x'.repeat(900000) }, wrapper).then(+ () => ({ code: null }), error => ({ code: error.code, message: error.message }));+ let outcome;+ try {+ outcome = await Promise.race([task, delay(2000).then(() => null)]);+ } finally {+ writeFileSync(release, 'release');+ await task;+ while (!existsSync(release + '.done')) await delay(10);+ }+ failures.push({ ...outcome, settledBeforeRelease: outcome !== null });+ for (const live of [true, false]) {+ const release = wrapper + '-live-' + live;+ const pid = release + '.pid';+ const finish = "require('fs').writeFileSync(" + JSON.stringify(release + '.done') + ", 'done'); process.stderr.write(" + JSON.stringify(diagnostic) + ", () => process.exit(7));";+ const body = live+ ? "const fs=require('fs'); fs.writeFileSync(" + JSON.stringify(pid) + ", String(process.pid)); fs.closeSync(0); const timer=setInterval(() => { if (fs.existsSync(" + JSON.stringify(release) + ")) { clearInterval(timer); " + finish + " } }, 10);"+ : "process.stdin.resume(); process.stdin.once('end', () => { " + finish + " });";+ writeFileSync(wrapper, ['#!' + process.execPath, body].join('\\n'), { mode: 0o700 });+ const task = securityPolicyDiff({ ...draft, content: '# Policy\\n' + 'x'.repeat(900000) }, wrapper).then(+ () => ({ code: null }), error => ({ code: error.code, message: error.message }));+ let outcome;+ let childAlive = false;+ try {+ outcome = await Promise.race([task, delay(2000).then(() => null)]);+ if (live) {+ process.kill(Number(readFileSync(pid, 'utf8')), 0);+ childAlive = true;+ }+ } finally {+ writeFileSync(release, 'release');+ await task;+ while (!existsSync(release + '.done')) await delay(10);+ }+ failures.push({ ...outcome, settledBeforeRelease: outcome !== null, childAlive, preservedDiagnostic: live || outcome?.message.endsWith(diagnostic) });+ }+}+console.log(JSON.stringify(failures));`,+ pathToFileURL(module).href,+ process.platform === "win32" ? "" : ignoreInput,+ join(f.root, "missing-interpreter"),+ process.platform === "win32" ? "" : deniedInterpreter,+ ],+ { encoding: "utf8", input: JSON.stringify(draft), timeout: 20_000 },),- ).rejects.toThrow();+ );+ expect(result[0].code).toBe(9);+ expect(result[0].message).toContain("bad option: -I");+ expect(result[1].code).toBe("ENOENT");+ if (process.platform !== "win32") {+ expect(result[2].code).toBe("EACCES");+ expect(result[3].code).toBe("EPIPE");+ expect(result.slice(4)).toMatchObject([+ { code: "EPIPE", settledBeforeRelease: true },+ { code: "EPIPE", settledBeforeRelease: true, childAlive: true },+ { code: 7, settledBeforeRelease: true, preservedDiagnostic: true },+ ]);+ }expect(await readdir(f.repository)).toEqual([]);});