Skip to content
Merged
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
46 changes: 40 additions & 6 deletions src/service/windows-checked-stop-live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,25 @@ import type { WindowsListenerIdentity, WindowsPortSample, WindowsStopConfirmDeps
import { windowsSchedulerCsvIncludesTask } from "./windows-scheduler";
import { WINDOWS_TASK_INSTANCE_STOP_SCRIPT, verifyWindowsTaskStopProof } from "./windows-task-instance-stop";

// Only a missing task after connecting to the local root folder establishes absence.
const TASK_REGISTRATION_SCRIPT = String.raw`
$ErrorActionPreference = 'Stop'
try {
$service = [Activator]::CreateInstance([type]::GetTypeFromProgID('Schedule.Service', $true))
$service.Connect()
$folder = $service.GetFolder('\')
} catch { 'unknown'; return }
try {
$task = $folder.GetTask('${TASK}')
if ($null -ne $task) { 'present' } else { 'unknown' }
} catch {
if ($_.Exception.GetBaseException().HResult -eq -2147024894) { 'absent' } else { 'unknown' }
}`;

export interface WindowsStopCommandResult {
status: number | null;
/** Captured from the spawned process handle. Bun's child exit status can contain only the low byte. */
windowsExitCode?: number;
stdout: string;
stderr: string;
timedOut: boolean;
Expand Down Expand Up @@ -83,8 +100,11 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program,
return;
}
let file: string;
let native: WindowsProcessNativeApi | null;
let readExitCode: (() => number | null) | null = null;
try {
file = programPath(program);
native = program === "schtasks" && args.includes("/hresult") ? windowsProcessNative() : null;
} catch (error) {
resolve({ status: null, stdout: "", stderr: error instanceof Error ? error.message : String(error), timedOut: false });
return;
Expand All @@ -94,13 +114,16 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program,
const text = (value: Buffer | string | undefined): string =>
value === undefined ? "" : typeof value === "string" ? value : decodeWindowsTextBytes(value);
const failure = error as (NodeJS.ErrnoException & { killed?: boolean; signal?: string | null; code?: number | string }) | null;
const windowsExitCode = readExitCode?.();
resolve({
status: failure ? (typeof failure.code === "number" ? failure.code : null) : 0,
...(windowsExitCode == null || failure?.killed ? {} : { windowsExitCode }),
stdout: text(stdout),
stderr: text(stderr),
timedOut: !!failure?.killed && failure.signal !== null,
});
});
if (helper.pid !== undefined) readExitCode = native?.captureChildExitCode?.(helper.pid) ?? null;
if (authorizeProof) {
let pending = "";
const onProof = async (chunk: Buffer): Promise<void> => {
Expand Down Expand Up @@ -267,12 +290,23 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption
canonicalPaths: windowsStopCanonicalPaths(),
childPid: windowsStopChildPid(),
async probeScheduler(timeoutMs) {
const started = Date.now();
const direct = await run("schtasks", ["/query", "/tn", TASK], timeoutMs);
if (direct.status === 0 && direct.stdout.includes(TASK)) return { status: "present" };
const listing = await run("schtasks", ["/query", "/fo", "CSV"], Math.max(1, timeoutMs - (Date.now() - started)));
if (listing.status !== 0 || listing.timedOut) return { status: "unknown", detail: "the Task Scheduler query did not answer" };
return windowsSchedulerCsvIncludesTask(listing.stdout, TASK) ? { status: "present" } : { status: "absent" };
const deadline = performance.now() + timeoutMs;
const unknown = { status: "unknown", detail: "the Task Scheduler query did not answer" } as const;
const direct = await run("schtasks", ["/query", "/tn", `\\${TASK}`, "/fo", "CSV", "/nh", "/hresult"], timeoutMs);
if (direct.timedOut || performance.now() >= deadline) return unknown;
if (direct.status === 0 && (direct.windowsExitCode ?? 0) === 0
&& direct.stdout.trimStart().toLowerCase().startsWith(`"\\${TASK}",`)) return { status: "present" };
if (direct.windowsExitCode !== undefined) {
const missing = 0x80070002; // HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
const statusAgrees = direct.status === 2 || (direct.status !== null && (direct.status >>> 0) === missing);
return direct.windowsExitCode === missing && statusAgrees ? { status: "absent" } : unknown;
}
const remaining = wholeTimeoutMs(deadline - performance.now());
if (remaining === null) return unknown;
const probe = await run("powershell", ["-NoProfile", "-NonInteractive", "-Command", TASK_REGISTRATION_SCRIPT], remaining);
if (probe.timedOut || probe.status !== 0 || performance.now() >= deadline) return unknown;
const status = probe.stdout.trim();
return status === "present" || status === "absent" ? { status } : unknown;
},
async probeWinsw(timeoutMs) {
// One cap covers both reads: the ownership query gets only what the state query left.
Expand Down
15 changes: 15 additions & 0 deletions src/service/windows-process-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ export type WindowsProcessWatch =
| { status: "gone" | "reused" | "denied" | "unavailable" };

export interface WindowsProcessNativeApi {
/** Pin a just-spawned child until its completion callback reads its full Windows exit code. */
captureChildExitCode?(pid: number): (() => number | null) | null;
/** Creation time in epoch ms (FILETIME truncated to ms), or null when unreadable. */
creationTime(pid: number): number | null;
/** Creation in .NET ticks at CIM precision from a live process with the same token user. */
Expand Down Expand Up @@ -139,6 +141,7 @@ function loadNativeApi(): WindowsProcessNativeApi | null {
kernel32 = ffi.dlopen(join(systemDirectory, "kernel32.dll"), {
OpenProcess: { args: ["u32", "i32", "u32"], returns: "u64" },
CloseHandle: { args: ["u64"], returns: "i32" },
GetExitCodeProcess: { args: ["u64", "ptr"], returns: "i32" },
GetProcessTimes: { args: ["u64", "ptr", "ptr", "ptr", "ptr"], returns: "i32" },
TerminateProcess: { args: ["u64", "u32"], returns: "i32" },
WaitForSingleObject: { args: ["u64", "u32"], returns: "u32" },
Expand Down Expand Up @@ -199,6 +202,18 @@ function loadNativeApi(): WindowsProcessNativeApi | null {
};

nativeApi = {
captureChildExitCode(pid) {
const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid);
if (!handle) return null;
return () => {
try {
const code = new Uint32Array(1);
return handleExited(handle) === true && k.GetExitCodeProcess(handle, ptr(code)) ? code[0]! : null;
} finally {
k.CloseHandle(handle);
}
};
},
creationTime(pid) {
const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
if (!handle) return null;
Expand Down
7 changes: 7 additions & 0 deletions structure/ops/windows-checked-stop.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,13 @@ asynchronous `schtasks` and `sc.exe` calls through `execFile` (a deadline-derive
floored to whole milliseconds and one that floors to 0 spawns nothing, because `execFile` reads 0
as no timeout), the evidence snapshot `windowsProcessSnapshot` for every bind, the checked
terminate, the exit watch, the Part B port sampler and the listener identity.
For Scheduler registration, Part A queries the exact root task with `schtasks /query /tn` and
`/hresult`. On Windows x64 it prepares native exit-code capture during executable lookup,
then reads the full exit code from the spawned process handle. Only
`0x80070002` establishes absence. Bun's truncated process status cannot prove that result.
Where a full exit code is unavailable, the local Scheduler COM API can still confirm the task
or report `ERROR_FILE_NOT_FOUND` from `GetTask` within the remainder of the same 2 s budget.
Denied access, incomplete evidence, and late answers keep the registration unknown.
`src/service/windows-task-instance-stop.ts` keeps the root registration and its running instances
in one Task Scheduler COM session. It passes the registered XML and the helper's current account as
base64 UTF-8 to preserve Unicode through the console. The live adapter checks the recognized task
Expand Down
99 changes: 98 additions & 1 deletion tests/windows/windows-checked-stop-live.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
winswStatusFromScState,
windowsCheckedStopLiveDeps,
} from "../../src/service/windows-checked-stop-live";
import type { WindowsProcessNativeApi } from "../../src/service/windows-process-native";
import { windowsProcessNative, type WindowsProcessNativeApi } from "../../src/service/windows-process-native";
import { windowsLauncherVbsPath } from "../../src/service/state";
import { WINDOWS_TASK_INSTANCE_STOP_SCRIPT } from "../../src/service/windows-task-instance-stop";
import { buildWindowsTaskXml, windowsTaskRegistrationHealthy } from "../../src/service/windows-taskxml";
Expand Down Expand Up @@ -254,6 +254,103 @@ describe("capped command answers", () => {

const portablePowerShell = Bun.which("pwsh");

describe("the bounded Scheduler registration query", () => {
test("a direct hit avoids PowerShell; only a completed, exact fallback answer is accepted", async () => {
const directHit = result(0, '"\\opencodex-proxy","N/A","Disabled"');
const missing = result(1, "", "지정된 파일을 찾을 수 없습니다.");
for (const [direct, fallback, expected] of [
[directHit, null, "present"],
[{ ...result(2), windowsExitCode: 0x80070002 }, null, "absent"],
[{ ...result(-2147024894), windowsExitCode: 0x80070002 }, null, "absent"],
[{ ...result(1), windowsExitCode: 0x80070002 }, null, "unknown"],
[{ ...result(2), windowsExitCode: 0x80041302 }, null, "unknown"],
[{ ...result(5), windowsExitCode: 0x80070005 }, null, "unknown"],
[{ ...result(null), windowsExitCode: 0x80070002 }, null, "unknown"],
[result(2), result(0, "unknown"), "unknown"],
[result(1, "", "", true), null, "unknown"],
[missing, result(0, "absent\r\n"), "absent"],
[missing, result(0, "present"), "present"],
[missing, result(0, "unknown"), "unknown"],
[missing, result(0, "noise\nabsent"), "unknown"],
[missing, result(1, "absent"), "unknown"],
[missing, result(null, "absent", "", true), "unknown"],
] as const) {
const calls: string[] = [];
const deps = windowsCheckedStopLiveDeps({ run: async (program, args, timeout) => {
calls.push(program);
if (program === "schtasks") {
expect(args).toEqual(["/query", "/tn", "\\opencodex-proxy", "/fo", "CSV", "/nh", "/hresult"]);
return direct;
}
expect(timeout).toBeGreaterThan(0);
expect(timeout).toBeLessThanOrEqual(2_000);
return fallback!;
} });
expect((await deps.probeScheduler(2_000)).status).toBe(expected);
expect(calls).toEqual(fallback ? ["schtasks", "powershell"] : ["schtasks"]);
}
});

test.skipIf(process.platform !== "win32" || process.arch !== "x64")("the child handle preserves distinct HRESULTs with the same low byte", async () => {
const native = windowsProcessNative();
expect(native?.captureChildExitCode).toBeFunction();
for (const code of [0x80070002, 0x80041302]) {
const child = Bun.spawn([resolveTrustedWindowsPowerShellExe(), "-NoProfile", "-NonInteractive", "-Command",
`[Environment]::Exit(${code | 0})`], { stdout: "ignore", stderr: "ignore", windowsHide: true, timeout: SPAWN_BUDGET_MS });
const readExitCode = native!.captureChildExitCode!(child.pid);
await child.exited;
expect(readExitCode?.()).toBe(code);
}
}, 2 * SPAWN_BUDGET_MS + 1_000);

test("the fallback uses only the remaining time and a late answer is unknown", async () => {
let now = 100;
const clock = spyOn(performance, "now").mockImplementation(() => now);
try {
const deps = windowsCheckedStopLiveDeps({ run: async (program, _args, timeout) => {
if (program === "schtasks") { now += 750; return result(1); }
expect(timeout).toBe(1_250);
now += timeout;
return result(0, "absent");
} });
expect((await deps.probeScheduler(2_000)).status).toBe("unknown");
} finally { clock.mockRestore(); }
});

test.skipIf(process.platform !== "win32" && !portablePowerShell)("only a missing task in an accessible root is absent", async () => {
let script = "";
await windowsCheckedStopLiveDeps({ run: async (program, args) => {
if (program === "schtasks") return result(1);
script = args.at(-1)!;
return result(0, "unknown");
} }).probeScheduler(2_000);
const activation = "[Activator]::CreateInstance([type]::GetTypeFromProgID('Schedule.Service', $true))";
expect(script).toContain(activation);
const fixture = String.raw`
class SchedulerFixture {
[void] Connect() { if ($global:scenario -eq 'connect') { throw [IO.FileNotFoundException]::new() } }
[object] GetFolder([string] $path) {
if ($path -cne '\' -or $global:scenario -eq 'folder') { throw [IO.FileNotFoundException]::new() }
return $this
}
[object] GetTask([string] $name) {
if ($name -cne 'opencodex-proxy') { throw 'wrong name' }
if ($global:scenario -eq 'missing') { throw [Runtime.InteropServices.COMException]::new('missing', -2147024894) }
if ($global:scenario -eq 'denied') { throw [UnauthorizedAccessException]::new() }
if ($global:scenario -eq 'empty') { return $null }
return $this
}
}`;
const command = fixture + "\nforeach ($global:scenario in 'found','missing','denied','connect','folder','empty') { & {\n"
+ script.replace(activation, "[SchedulerFixture]::new()") + "\n} }";
const powershell = process.platform === "win32" ? resolveTrustedWindowsPowerShellExe() : portablePowerShell!;
const child = Bun.spawn([powershell, "-NoProfile", "-NonInteractive", "-EncodedCommand",
Buffer.from(command, "utf16le").toString("base64")], { stdout: "pipe", stderr: "pipe", windowsHide: true, timeout: SPAWN_BUDGET_MS });
const [out, err, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
expect({ code, err, lines: out.trim().split(/\r?\n/) }).toEqual({ code: 0, err: "", lines: ["present", "absent", "unknown", "unknown", "unknown", "unknown"] });
}, SPAWN_BUDGET_MS + 1_000);
});

test.skipIf(process.platform !== "win32" && !portablePowerShell)("the PowerShell helper stops captured instances only after every proof succeeds", async () => {
const powershell = process.platform === "win32" ? resolveTrustedWindowsPowerShellExe() : portablePowerShell!;
const fixture = String.raw`
Expand Down
Loading