Files
gstack/browse/test/windows-spawn-hide.test.ts
T
Garry Tan a84b0b5b6d v1.90.0.0 feat: make browser cookie imports explicit and safe (#2964)
* fix(browse): prepare reliable cookie import wave for validation

* ci: sequence quality and behavior for validation branch

* fix(browse): isolate Windows qualification and preserve native diagnostics

* test(browse): cover cookie workflow quality and isolate Windows user paths

* test(browse): trace native member startup and initialize fresh folders

* fix(browse): keep Windows member stdin alive through EOF

* fix(browse): latch native timeouts and compare contained Edge startup

* test(browse): verify native version metadata and actual Windows argv

* test(browse): qualify Dia import on isolated macOS CI

* fix(browse): require picker origin for session mutations

* fix(browse): bound credential reads through stream completion

* test(browse): inspect owned Windows process arguments natively

* test(evals): preserve passing coverage during cookie repair reruns

* test(browse): isolate Dia qualification in a fresh macOS account

* test(browse): pass bounded integer timeouts to native Mac probes

* test(browse): distinguish Windows profile initialization from containment

* test(browse): await descendant pipe readiness before parent exit

* test(browse): initialize and restore isolated macOS Keychain state

* test(browse): initialize Windows fixture folders before qualification

* test(ci): pin the same Node runtime across Windows checks

* test(browse): distinguish native macOS browser preflight stages

* test(browse): isolate Windows descendant console lifetime

* test(browse): preserve native receipts and identify fixture lock holders

* test(browse): prepare dependency resolution before native Mac worker startup

* test(ci): include lock and close checks in native diagnostics

* test(browse): preserve native owner probe stages and subprocess deadlines

* fix(browse): classify Chromium profile-in-use exit precisely

* test(browse): retain Mac qualification evidence through cleanup failures

* test(browse): bound Mac fixture paths and retire its owned user domain

* test(browse): accept vanished fixture entries without weakening cleanup

* test(browse): identify probe-created macOS user domains safely

* test(browse): observe Mac user domains without targeting them first

* test(browse): use passive fresh-user ownership throughout Mac qualification

* test(browse): distinguish profile and registered-home Keychain lookups

* test(browse): qualify Dia under one registered account home

* test(browse): identify Dia startup and owned process-group failures

* test(browse): classify bounded Dia startup diagnostics without leaking output

* fix(test): preserve native Mac sandboxing and reap owned browser children

* fix(browse): preserve Chromium sandboxing for native profile imports

* test(browse): inspect signed Mach-O architecture without launching Xcode tools

* test(browse): sample pending Dia startup and reap on all cleanup paths

* test(browse): compare protected Dia launches in fresh Bun and Node accounts

* test(browse): inspect isolated Mac GUI readiness without browser access

* v1.90.0.0 fix: bind cookie picker actions to their document

* test: validate cookie guards and fit nested launch fixtures

* ci: configure the bundled Chromium sandbox helper

* fix(browse): classify Playwright authentication timeouts

* test: retain bounded Windows lifecycle diagnostics

* test(cso): reuse bounded NTFS precision candidates

* test(review): handle explicit preservation choices safely

* test(browse): remove owned fixture directories with explicit primitives

* test(review): distinguish descriptive reuse from edit commitments

* test: admit only the approved unscored cookie workflow refusal

* test: keep the Office Hours judge mock export-complete

* fix: keep dependency-free CI planners independent of the model SDK

* test: observe the exact holder after a native fixture unlink failure

* fix: start seeded PTY observations at owned readiness

* test: acquire identity-bound Windows deletion admission before profile resets

* test: preserve qualified Git index bits without authorizing mutations
2026-09-25 12:06:45 -04:00

162 lines
7.7 KiB
TypeScript

/**
* Static tripwire for #1835: child spawns reachable on Windows must pass
* windowsHide, or every daemon relaunch / taskkill / icacls / powershell
* invocation flashes a black console window (and can steal focus).
*
* Source-level, same style as server-auth.test.ts / cdp-session-cleanup.test.ts:
* cheap, deterministic, runs on every platform.
*/
import { describe, expect, test } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
const SRC = (f: string) => fs.readFileSync(path.join(import.meta.dir, '../src', f), 'utf-8');
/** Every occurrence of `needle` in `src` must have `windowsHide` within the
* next `window` chars (the spawn's options object). */
function expectHideNearEvery(src: string, needle: string, window = 400): void {
let idx = src.indexOf(needle);
expect(idx).toBeGreaterThanOrEqual(0);
while (idx !== -1) {
const slice = src.slice(idx, idx + window);
expect(slice).toMatch(/windowsHide:\s*true/);
idx = src.indexOf(needle, idx + needle.length);
}
}
describe('windowsHide on Windows-reachable spawns (#1835)', () => {
test('daemon launch paths in cli.ts pass windowsHide', () => {
const cli = SRC('cli.ts');
// Installed path: node -e launcher — both the outer spawnSync and the
// inner detached daemon spawn (inside the launcher code string).
expect(cli).toContain('detached:true,windowsHide:true');
expectHideNearEvery(cli, "'-e', launcherCode]");
// Dev fallback: detached bun spawn.
expectHideNearEvery(cli, "nodeSpawn('bun'");
// taskkill (killServer).
expectHideNearEvery(cli, "'taskkill'");
});
test('Windows-only process probes pass windowsHide', () => {
// isProcessAlive no longer spawns anything (signal-0 on every platform,
// #1952) — process-liveness-windows.test.ts pins that it stays
// subprocess-free, which is stronger than hiding a window.
const cookie = SRC('cookie-import-browser.ts');
expectHideNearEvery(cookie, "'powershell'");
expect(cookie).not.toContain("'tasklist'");
expectHideNearEvery(SRC('cookie-import-native.ts'), 'spawn(bunExecutable');
const worker = SRC('cookie-import-native-worker.ts');
expectHideNearEvery(worker, 'spawn(process.execPath');
expectHideNearEvery(worker, 'spawn(input.request.nodeExecutable');
});
test('icacls calls in file-permissions.ts pass windowsHide', () => {
const perms = SRC('file-permissions.ts');
expect((perms.match(/'icacls'/g) || []).length).toBeGreaterThanOrEqual(3);
expectHideNearEvery(perms, "'icacls'");
});
test('terminal-agent respawn in terminal-agent-control.ts passes windowsHide', () => {
// The CLI cold-start + v1.44 watchdog respawn path. On Windows it runs
// through the Node polyfill (dist/bun-polyfill.cjs) whose host default is
// the opposite of Bun's — a visible console window on every watchdog
// respawn is the symptom when the flag is dropped. Wider window: the
// spawn's options object carries the full env wiring before the flag.
expectHideNearEvery(SRC('terminal-agent-control.ts'), '(Bun as any).spawn(', 700);
});
test('SWEEP: every direct child_process call in src/ passes windowsHide (#2160, #2415)', () => {
// Full-census tripwire: a NEW child_process call site without windowsHide
// fails CI. Each exemption carries a reason — an interactive console
// child must NOT get CREATE_NO_WINDOW.
const EXEMPT: Array<{ file: string; needle: string; reason: string }> = [
{
file: 'domain-skill-commands.ts',
// tripwire-exempt: grep NEEDLE string for this census, not a call
needle: 'spawnSync(editor',
reason: "interactive $EDITOR with stdio:'inherit' — windowsHide would detach a console editor into an invisible console",
},
];
const srcDir = path.join(import.meta.dir, '../src');
const offenders: string[] = [];
for (const file of fs.readdirSync(srcDir).filter((f) => f.endsWith('.ts'))) {
const raw = fs.readFileSync(path.join(srcDir, file), 'utf-8');
if (!raw.includes('child_process')) continue;
// Strip comments so documented history doesn't trip the census.
const code = raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
// Collect the callable names this file binds to child_process:
// import { spawn as nodeSpawn } from 'child_process'
// const { execSync } = await import('child_process') / require(...)
// import * as cp from 'child_process' → cp.<fn>( pattern
const names = new Set<string>();
const namespaces = new Set<string>();
const importRe = /import\s*\{([^}]*)\}\s*from\s*['"](?:node:)?child_process['"]/g;
const dynRe = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:await\s+import\(|require\()['"](?:node:)?child_process['"]\)/g;
const nsRe = /import\s*\*\s*as\s*(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
for (const m of code.matchAll(importRe)) {
for (const part of m[1].split(',')) {
const alias = part.split(/\s+as\s+/).map((s) => s.trim()).filter(Boolean);
const name = alias[alias.length - 1];
if (name && /^(spawn|spawnSync|exec|execSync|execFile|execFileSync|nodeSpawn|cpSpawn)/.test(alias[0].trim())) names.add(name);
}
}
for (const m of code.matchAll(dynRe)) {
for (const part of m[1].split(',')) {
const alias = part.split(':').map((s) => s.trim()).filter(Boolean);
const name = alias[alias.length - 1];
if (name && /^(spawn|spawnSync|exec|execSync|execFile|execFileSync)/.test(alias[0].trim())) names.add(name);
}
}
for (const m of code.matchAll(nsRe)) namespaces.add(m[1]);
const patterns: RegExp[] = [];
for (const n of names) patterns.push(new RegExp(`(?<![.\\w'"\`])${n}\\(`, 'g'));
for (const ns of namespaces) {
patterns.push(new RegExp(`(?<![\\w'"\`])${ns}\\.(?:spawn|spawnSync|exec|execSync|execFile|execFileSync)\\(`, 'g'));
}
for (const re of patterns) {
for (const m of code.matchAll(re)) {
const slice = code.slice(m.index!, m.index! + 700);
const exempt = EXEMPT.some((e) => e.file === file && slice.startsWith(e.needle));
if (exempt) continue;
if (!/windowsHide:\s*true/.test(slice)) {
offenders.push(`${file}: ${slice.split('\n')[0].slice(0, 100)}`);
}
}
}
}
expect(offenders).toEqual([]);
});
test('SWEEP: every Bun.spawn call in src/ passes windowsHide (#2575 residual)', () => {
// Bun.spawn sites are structurally outside the child_process sweep above.
// Native Bun hides consoles by default and the Node polyfill
// (bun-polyfill.cjs) defaults windowsHide !== false since #2523/#2539 —
// this census exists so an explicit flag documents the intent at every
// site AND catches a regression if either default ever flips. Exemptions
// carry reasons, same contract as the child_process sweep.
const EXEMPT: Array<{ file: string; needle: string; reason: string }> = [];
const srcDir = path.join(import.meta.dir, '../src');
const offenders: string[] = [];
for (const file of fs.readdirSync(srcDir).filter((f) => f.endsWith('.ts'))) {
const raw = fs.readFileSync(path.join(srcDir, file), 'utf-8');
const code = raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
const re = /(?:\(Bun as any\)|Bun)\.spawn(?:Sync)?\(/g;
for (const m of code.matchAll(re)) {
const slice = code.slice(m.index!, m.index! + 900);
const exempt = EXEMPT.some((e) => e.file === file && slice.includes(e.needle));
if (exempt) continue;
if (!/windowsHide:\s*true/.test(slice)) {
offenders.push(`${file}: ${slice.split('\n')[0].slice(0, 100)}`);
}
}
}
expect(offenders).toEqual([]);
});
});