Skip to content

Commit 188e618

Browse files
committed
fix(service): bind scheduler recovery to exact SID
1 parent b727f8f commit 188e618

4 files changed

Lines changed: 49 additions & 25 deletions

File tree

‎src/service.ts‎

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -739,14 +739,15 @@ async function reportServiceServing(
739739
verb: "installed" | "started" | "repaired",
740740
deps: Parameters<typeof confirmServiceServing>[0] = {},
741741
): Promise<void> {
742-
const serving = await confirmServiceServing(deps);
742+
const healthBudgetMs = deps.timeoutMs ?? serviceInstallHealthMs();
743+
const serving = await confirmServiceServing({ ...deps, timeoutMs: healthBudgetMs });
743744
if (serving.ok) {
744745
console.log(`✅ opencodex service ${verb} and serving on port ${serving.port}.`);
745746
return;
746747
}
747748
console.error(
748749
`⚠️ Service ${verb}, but no proxy answered on port ${serving.port} within `
749-
+ `${Math.trunc(SERVICE_INSTALL_HEALTH_MS / 1000)}s.\n`
750+
+ `${Math.trunc(healthBudgetMs / 1000)}s.\n`
750751
+ ` The manager registered the job; that is not the same as serving.\n`
751752
+ ` Log: ${serviceLogPath()}\n`
752753
+ ` Meanwhile: ocx start (serves in the foreground)`,
@@ -1832,7 +1833,7 @@ export function buildWindowsTaskXml(
18321833
script = windowsServiceScriptPath(),
18331834
launcher = windowsLauncherVbsPath(),
18341835
attemptNonce?: string,
1835-
sessionTriggerUserId = cachedCurrentWindowsIdentity()?.name,
1836+
sessionTriggerUserId = cachedCurrentWindowsIdentity()?.sid,
18361837
): string {
18371838
const escapedWscript = taskXmlString(windowsWscript());
18381839
// Escape the launcher path independently for the <Arguments> element; quoting it
@@ -2086,14 +2087,12 @@ function windowsTaskTriggerScopeAcceptable(element: string, expectedUserId: stri
20862087
if (userIdCount === 0) return true;
20872088
if (userIdCount !== 1) return false;
20882089
if (expectedUserId === undefined) return false;
2089-
// Same tolerance as Command and Arguments, and for the same reason:
2090-
// buildWindowsTaskXml writes the live account name here, so an account named
2091-
// outside the console code page comes back mangled and an exact comparison
2092-
// rejects a task that is in fact correctly scoped (#3064). The literal-ASCII
2093-
// requirement is what keeps this safe -- a DOMAIN\\User scope keeps its backslash
2094-
// verified, so a substitution run can never swallow the domain and let another
2095-
// domain's account match.
2096-
return taskXmlDecodedLossyValueEquals(element, "UserId", expectedUserId);
2090+
// Scope is an identity boundary, unlike the launcher path. Newly generated tasks
2091+
// use the locale-independent SID from cachedCurrentWindowsIdentity(), so there is
2092+
// no reason to forgive code-page substitutions here. A lossy account-name compare
2093+
// lets two non-ASCII users collapse to the same `???` value and can make repair
2094+
// start another account's fixed-name task.
2095+
return taskXmlDecodedValueEquals(element, "UserId", expectedUserId);
20972096
}
20982097

20992098
/** Validate the stable OpenCodex action, principal, settings, and logon trigger. */
@@ -2139,7 +2138,7 @@ export function windowsTaskRegistrationHealthy(
21392138
xml: string,
21402139
wscript = windowsWscript(),
21412140
launcher = windowsLauncherVbsPath(),
2142-
expectedUserId: string | null = cachedCurrentWindowsIdentity()?.name ?? null,
2141+
expectedUserId: string | null = cachedCurrentWindowsIdentity()?.sid ?? null,
21432142
): boolean {
21442143
const scrubbed = taskXmlWithoutCommentsAndCdata(xml);
21452144
const triggers = taskXmlSection(scrubbed, "Triggers");
@@ -2178,7 +2177,7 @@ export function readWindowsSchedulerXmlState(
21782177
xml: string,
21792178
wscript?: string,
21802179
launcher?: string,
2181-
expectedUserId: string | null = cachedCurrentWindowsIdentity()?.name ?? null,
2180+
expectedUserId: string | null = cachedCurrentWindowsIdentity()?.sid ?? null,
21822181
): WindowsSchedulerXmlState {
21832182
const installed = xml.length > 0;
21842183
if (!installed) return { installed: false, enabled: false, registrationHealthy: false };
@@ -3830,7 +3829,7 @@ export function serviceStartableFromTray(service: ServiceDiagnostic): boolean {
38303829
}
38313830

38323831
export interface WindowsTaskDiagnosticIdentityDeps {
3833-
currentIdentity?: () => Readonly<{ name: string }> | null;
3832+
currentIdentity?: () => Readonly<{ sid: string; name: string }> | null;
38343833
resolvePrincipal?: (timeoutMs: number) => string;
38353834
}
38363835

@@ -3845,7 +3844,7 @@ export function resolveWindowsTaskDiagnosticUserId(
38453844
): string | null {
38463845
const currentIdentity = deps.currentIdentity ?? cachedCurrentWindowsIdentity;
38473846
const cached = currentIdentity();
3848-
if (cached) return cached.name;
3847+
if (cached) return cached.sid;
38493848

38503849
const scrubbed = taskXmlWithoutCommentsAndCdata(schedulerXml);
38513850
const triggers = taskXmlSection(scrubbed, "Triggers");
@@ -3856,7 +3855,7 @@ export function resolveWindowsTaskDiagnosticUserId(
38563855
} catch {
38573856
return null;
38583857
}
3859-
return currentIdentity()?.name ?? null;
3858+
return currentIdentity()?.sid ?? null;
38603859
}
38613860

38623861
export interface WindowsServiceDiagnosticInputs {
@@ -3880,7 +3879,7 @@ export interface WindowsServiceDiagnosticInputs {
38803879

38813880
export function deriveWindowsServiceDiagnostic(inputs: WindowsServiceDiagnosticInputs): ServiceDiagnostic {
38823881
const expectedUserId = inputs.schedulerExpectedUserId === undefined
3883-
? cachedCurrentWindowsIdentity()?.name ?? null
3882+
? cachedCurrentWindowsIdentity()?.sid ?? null
38843883
: inputs.schedulerExpectedUserId;
38853884
const schedulerState = readWindowsSchedulerXmlState(
38863885
inputs.schedulerXml,

‎src/update/job.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ const RELEASE_NOTES_URL = "https://github.com/lidge-jun/opencodex/releases/lates
5151
const UPDATE_JOB_FILENAME = "update-job.json";
5252
const UPDATE_TIMEOUT_MS = 180_000;
5353
const RESTART_TIMEOUT_MS = 60_000;
54+
// A Windows `service repair` can spend up to 45s in its own serving probe after
55+
// Task Scheduler/ACL work. The generic 60s child ceiling can kill that valid repair
56+
// and launch a competing foreground proxy. Keep this below the update worker's 180s
57+
// ceiling while covering the measured probe plus bounded Windows setup work.
58+
const WINDOWS_SERVICE_REPAIR_TIMEOUT_MS = 150_000;
5459
const RESTART_HEALTH_TIMEOUT_MS = 30_000;
5560
const RESTART_STABILITY_WINDOW_MS = 15_000;
5661
/** Legacy active records did not persist a worker PID, so age is their only safe recovery signal. */
@@ -987,6 +992,7 @@ export interface RestartIo {
987992
job: UpdateJobState,
988993
bin: string,
989994
args: string[],
995+
timeoutMs: number,
990996
) => { status: number | null; signal?: NodeJS.Signals | null };
991997
/** Override the explicit restart path (used by finishGuiUpdateRestart tests). */
992998
restartAfterUpdateFn?: (
@@ -1155,8 +1161,11 @@ async function restartAfterUpdate(
11551161
process.env.OCX_BAKE_PORT = String(Math.trunc(port));
11561162
let serviceOk = false;
11571163
try {
1158-
const run = io.runService ?? ((j, bin, args) => runLoggedCommand(j, bin, args, RESTART_TIMEOUT_MS));
1159-
const result = run(job, cmd.bin, cmd.args);
1164+
const repairTimeoutMs = (io.platform ?? process.platform) === "win32"
1165+
? WINDOWS_SERVICE_REPAIR_TIMEOUT_MS
1166+
: RESTART_TIMEOUT_MS;
1167+
const run = io.runService ?? ((j, bin, args, timeoutMs) => runLoggedCommand(j, bin, args, timeoutMs));
1168+
const result = run(job, cmd.bin, cmd.args, repairTimeoutMs);
11601169
serviceOk = result.status === 0;
11611170
if (!serviceOk) {
11621171
// The refresh that just failed was `ocx service repair` (serviceReinstallArgs).

‎tests/service.test.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,18 @@ describe("Windows service task", () => {
588588
expect(windowsTaskRegistrationHealthy(unscoped, wscript, launcher, null)).toBe(true);
589589
});
590590

591+
test("never code-page-folds an explicit session identity", () => {
592+
const wscript = "C:\\Windows\\System32\\wscript.exe";
593+
const launcher = "C:\\Users\\Test\\.opencodex\\service-launcher.vbs";
594+
const expected = "MACHINE\\김병준";
595+
const scoped = buildWindowsTaskXml("ignored.cmd", launcher, undefined, expected)
596+
.replace(/<Command>.*?<\/Command>/, `<Command>${wscript}</Command>`);
597+
const mangled = scoped.replaceAll(expected, "MACHINE\\???");
598+
599+
expect(windowsTaskRegistrationHealthy(scoped, wscript, launcher, expected)).toBe(true);
600+
expect(windowsTaskRegistrationHealthy(mangled, wscript, launcher, expected)).toBe(false);
601+
});
602+
591603
test("validates the registered scheduler action, trigger, principal, and settings", () => {
592604
// Guard first: a prefixed <t:UserId> is a real scope the unprefixed element counter cannot
593605
// see. Treating it as ABSENT would accept a task bound to somebody else's session as
@@ -2176,18 +2188,19 @@ describe("service diagnostics", () => {
21762188
const installedDisabled = { schedulerXml: disabledTaskXml() };
21772189

21782190
test("resolves an explicit scheduler scope once at the Windows diagnostic boundary", () => {
2179-
const scoped = buildWindowsTaskXml(undefined, undefined, undefined, "MACHINE\\installer");
2180-
const foreign = scoped.replaceAll("MACHINE\\installer", "OTHER\\account");
2191+
const sid = "S-1-5-21-111-222-333-1001";
2192+
const scoped = buildWindowsTaskXml(undefined, undefined, undefined, sid);
2193+
const foreign = scoped.replaceAll(sid, "S-1-5-21-999-888-777-1002");
21812194
const unscoped = buildWindowsTaskXml(undefined, undefined, undefined, "");
2182-
let identity: Readonly<{ name: string }> | null = null;
2195+
let identity: Readonly<{ sid: string; name: string }> | null = null;
21832196
let resolutions = 0;
21842197
const timeouts: number[] = [];
21852198
const deps = {
21862199
currentIdentity: () => identity,
21872200
resolvePrincipal: (timeoutMs: number) => {
21882201
timeouts.push(timeoutMs);
21892202
resolutions += 1;
2190-
identity = { name: "MACHINE\\installer" };
2203+
identity = { sid, name: "MACHINE\\installer" };
21912204
return "*S-1-5-21-111-222-333-1001";
21922205
},
21932206
};
@@ -2197,7 +2210,7 @@ describe("service diagnostics", () => {
21972210
schedulerXml: scoped,
21982211
recordedBackend: "scheduler",
21992212
}, deps);
2200-
expect(identity).toEqual({ name: "MACHINE\\installer" });
2213+
expect(identity).toEqual({ sid, name: "MACHINE\\installer" });
22012214
expect(resolutions).toBe(1);
22022215
expect(matching).toMatchObject({ viable: true, stale: false });
22032216
expect(deriveWindowsServiceDiagnosticForCurrentUser({

‎tests/update-job.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -755,6 +755,7 @@ describe("GUI update execution decisions", () => {
755755
// runService is then never called and this goes red.
756756
test("a non-elevated Windows update worker repairs the service instead of skipping it", async () => {
757757
const ranService: string[][] = [];
758+
const serviceTimeouts: number[] = [];
758759
const spawned: Array<{ port: number }> = [];
759760
const job: UpdateJobState = {
760761
id: "svc-win-repair",
@@ -779,8 +780,9 @@ describe("GUI update execution decisions", () => {
779780
serviceViableFn: () => true,
780781
waitForPort: async () => true,
781782
probeProxy: async () => true,
782-
runService: (_j, _bin, args) => {
783+
runService: (_j, _bin, args, timeoutMs) => {
783784
ranService.push(args);
785+
serviceTimeouts.push(timeoutMs);
784786
return { status: 0 };
785787
},
786788
spawnStart: (_job, _installer, port) => {
@@ -791,6 +793,7 @@ describe("GUI update execution decisions", () => {
791793
expect(ranService.length).toBe(1);
792794
expect(ranService[0]).toContain("repair");
793795
expect(ranService[0]).not.toContain("install");
796+
expect(serviceTimeouts).toEqual([150_000]);
794797
} finally {
795798
if (prevService === undefined) delete process.env.OCX_SERVICE;
796799
else process.env.OCX_SERVICE = prevService;

0 commit comments

Comments
 (0)