Files
codex-security/github-action/src/process.ts
0cdb22a6db feat(action): add Codex Security GitHub Action (#1015)
* feat(action): integrate GitHub Action alongside the CLI

* fix(action): update pinned CLI to 0.1.29

* fix(action): omit estimated cost from scan summaries

* docs(action): simplify setup and usage guide

* docs(action): schedule weekly scans in quick start

* docs(action): minimize quick-start scan configuration

* docs(action): configure Luna PR scans and verify annotations

* Update README.md

* fix(action): update pinned CLI to 0.1.30

* fix(action): normalize paths and preserve results on summary failure

* refactor(action): remove fixed-value public inputs

* refactor(action): use job check with explicit scan outcomes

* refactor(action): use runtime manifest as single CLI version source

* fix(action): explain incomplete scan coverage in summaries

* docs: add GitHub Actions quick start to main README

* Update README.md

* fix(action): defer policy and knowledge-base handling to CLI

* refactor(action): consume validated CLI results

* fix(action): preserve scan outcomes when SARIF is unavailable

* fix(action): allow configured Dependabot scans

* test(action): add hosted dry-run smoke job

* fix(action): ignore unrelated input environment variables

* refactor(action): simplify runtime setup

* refactor(action): simplify inputs for repository and PR scans

* chore(action): update Codex Security CLI to 0.1.31

* feat(action): restore deep scan mode and time budget

* fix(action): warn on valid partial scans

* fix(action): refresh audited dependencies and preserve diagnostics

* fix(action): escape legacy runner commands in diagnostics

* fix(action): preserve result and SARIF reporting semantics

* fix(action): keep report text and selected paths literal

* fix(action): accept existing literal scope filenames

* fix(action): check large diffs without capturing path lists

* test(action): wait for child readiness before timeout

* refactor(action): delegate scanner behavior to the CLI

* fix(action): preserve runner tools and bind scan reports to the requested commit

* fix(action): preserve runner tool selection and process cleanup

* fix(action): clean up descendants before draining process output

* fix(action): preserve Python loading and inspect worktree configuration

* fix(action): preserve runner tracking through MCP launchers

* test(plugin): preserve interpreter loader settings in worker fixtures

* test(action): create the CLI integration runtime temp directory

---------

Co-authored-by: dans-oai <321942207+dans-oai@users.noreply.github.com>
Co-authored-by: mldangelo-oai <269034524+mldangelo-oai@users.noreply.github.com>
Co-authored-by: Michael D'Angelo <mdangelo@openai.com>
2026-10-05 23:50:02 -04:00

107 lines
4.3 KiB
TypeScript

import { spawn } from 'node:child_process';
import { isAbsolute } from 'node:path';
import { StringDecoder } from 'node:string_decoder';
export interface ProcessOptions {
cwd: string;
env: NodeJS.ProcessEnv;
log?: (line: string) => void;
timeoutMs?: number;
signal?: AbortSignal;
}
export interface ProcessResult {
exitCode: number;
signal: NodeJS.Signals | null;
stdout: string;
stderr: string;
timedOut: boolean;
interrupted: boolean;
}
/** Prefix modern runner commands and escape legacy commands, which match anywhere. */
export function safeLogLines(value: string): string[] {
const clean = value.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
.replace(/\r\n?/g, '\n')
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '')
.replace(/[\u2028\u2029]/g, '\n')
.replace(/##\[/g, '##\\[');
return clean.split('\n').filter(Boolean).map((line) => `[codex-security] ${line}`);
}
/** Direct execution only. No shell and no inherited environment fallback. */
export async function runProcess(executable: string, args: readonly string[], options: ProcessOptions): Promise<ProcessResult> {
if (!isAbsolute(executable) || !isAbsolute(options.cwd)) throw new Error('Process executable and working directory must be absolute paths.');
options.signal?.throwIfAborted();
return new Promise((resolve, reject) => {
const child = spawn(executable, [...args], {
cwd: options.cwd, env: { ...options.env }, shell: false,
detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'],
});
const buffers: Record<'stdout' | 'stderr', Buffer[]> = { stdout: [], stderr: [] };
let timedOut = false;
let interrupted = false;
const stderrDecoder = new StringDecoder('utf8');
let pendingStderr = '';
const log = (value: string): void => {
for (const line of safeLogLines(value)) {
try { options.log?.(line); }
catch { /* Optional diagnostics must not interrupt the child process. */ }
}
};
const logStderr = (text: string): void => {
pendingStderr += text;
const boundary = pendingStderr.lastIndexOf('\n');
if (boundary < 0) return;
// Wait for complete lines so chunk boundaries cannot split UTF-8 or runner-command prefixes.
log(pendingStderr.slice(0, boundary + 1));
pendingStderr = pendingStderr.slice(boundary + 1);
};
let killTimer: NodeJS.Timeout | undefined;
let stopped = false;
const kill = (signal: NodeJS.Signals): void => {
if (!child.pid) return;
try {
if (process.platform !== 'win32') process.kill(-child.pid, signal);
else child.kill(signal);
} catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') child.kill(signal); }
};
const stop = (): void => {
if (stopped) return;
stopped = true;
kill('SIGTERM');
killTimer = setTimeout(() => kill('SIGKILL'), 2000);
killTimer.unref();
};
const timer = options.timeoutMs === undefined ? undefined : setTimeout(() => { timedOut = true; stop(); }, options.timeoutMs);
timer?.unref();
const interrupt = (): void => { interrupted = true; stop(); };
process.once('SIGINT', interrupt);
process.once('SIGTERM', interrupt);
options.signal?.addEventListener('abort', interrupt, { once: true });
for (const name of ['stdout', 'stderr'] as const) child[name].on('data', (chunk: Buffer) => {
buffers[name].push(chunk);
if (name === 'stderr' && options.log) logStderr(stderrDecoder.write(chunk));
});
const finish = (): void => {
clearTimeout(timer);
if (killTimer) clearTimeout(killTimer);
process.removeListener('SIGINT', interrupt);
process.removeListener('SIGTERM', interrupt);
options.signal?.removeEventListener('abort', interrupt);
// Terminate background descendants still in the owned process group.
kill('SIGKILL');
};
child.once('error', (error) => { finish(); reject(error); });
child.once('exit', finish);
child.once('close', (code, signal) => {
const stdout = Buffer.concat(buffers.stdout).toString('utf8');
const stderr = Buffer.concat(buffers.stderr).toString('utf8');
if (options.log) {
log(pendingStderr + stderrDecoder.end());
}
resolve({ exitCode: code ?? 1, signal, stdout, stderr, timedOut, interrupted });
});
});
}