11import { spawn , type ChildProcess , type SpawnOptions } from "node:child_process" ;
2- import { existsSync } from "node:fs" ;
2+ import { existsSync , readFileSync , unlinkSync } from "node:fs" ;
3+ import { tmpdir } from "node:os" ;
34import { join } from "node:path" ;
5+ import { randomBytes } from "node:crypto" ;
46
57type ElevationSpawn = (
68 command : string ,
@@ -19,6 +21,9 @@ export function setWindowsElevationSpawnForTests(next: ElevationSpawn | null): v
1921export const WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED_MARKER =
2022 "OCX_ERROR_CODE=WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED" ;
2123
24+ export const OCX_SCHTASKS_CREATE_EXIT_PREFIX = "OCX_SCHTASKS_CREATE_EXIT=" ;
25+ export const OCX_SCHTASKS_RUN_EXIT_PREFIX = "OCX_SCHTASKS_RUN_EXIT=" ;
26+
2227export type WindowsSchtasksOperation = "create" | "run" | "query" | "delete" | "end" | "other" ;
2328export type WindowsSchtasksFailureReason = "access-denied" | "other" ;
2429
@@ -189,30 +194,21 @@ export interface WindowsElevationResult {
189194 stderr : string ;
190195}
191196
192- /**
193- * Launch a file with UAC elevation and wait for it to exit.
194- * Throws WindowsElevationError for cancellation, timeout, launch failure, or signal termination.
195- * Returns the elevated process exit code for completed launches (including non-zero).
196- */
197- export function runWindowsElevated ( file : string , args : string [ ] , timeoutMs = 120_000 ) : Promise < number > {
197+ function parsePrefixedExit ( output : string , prefix : string ) : number | null {
198+ const match = output . match ( new RegExp ( `${ prefix } (-?\\d+)` , "m" ) ) ;
199+ if ( ! match ) return null ;
200+ const value = Number ( match [ 1 ] ) ;
201+ return Number . isFinite ( value ) ? value : null ;
202+ }
203+
204+ /** Spawn non-elevated PowerShell to run a -Command script; classify UAC/cancel/timeout outcomes. */
205+ function runPowerShellCommand ( commandScript : string , timeoutMs : number ) : Promise < WindowsElevationResult > {
198206 if ( process . platform !== "win32" ) {
199207 return Promise . reject ( new WindowsElevationError (
200208 "launch-failed" ,
201209 "Windows elevation is only supported on Windows." ,
202210 ) ) ;
203211 }
204- const argumentList = buildWindowsElevatedArgumentList ( args ) ;
205- // Touch .Handle so Windows PowerShell 5.1 keeps a process handle; ExitCode can
206- // otherwise stay $null after -Wait and `exit $null` becomes exit 0 (false success).
207- const script = [
208- `$p = Start-Process -FilePath ${ psSingleQuote ( file ) } ` ,
209- argumentList . length > 0 ? ` -ArgumentList ${ psSingleQuote ( argumentList ) } ` : "" ,
210- " -Verb RunAs -WindowStyle Hidden -PassThru -Wait;" ,
211- "if ($null -eq $p) { exit 1223 }" ,
212- "$null = $p.Handle" ,
213- "if ($null -eq $p.ExitCode) { exit 1 }" ,
214- "exit $p.ExitCode" ,
215- ] . join ( "" ) ;
216212
217213 return new Promise ( ( resolve , reject ) => {
218214 let settled = false ;
@@ -231,7 +227,7 @@ export function runWindowsElevated(file: string, args: string[], timeoutMs = 120
231227 try {
232228 child = elevationSpawn (
233229 windowsPowerShell ( ) ,
234- [ "-NoProfile" , "-NonInteractive" , "-ExecutionPolicy" , "Bypass" , "-Command" , script ] ,
230+ [ "-NoProfile" , "-NonInteractive" , "-ExecutionPolicy" , "Bypass" , "-Command" , commandScript ] ,
235231 {
236232 windowsHide : true ,
237233 stdio : [ "ignore" , "pipe" , "pipe" ] ,
@@ -275,7 +271,7 @@ export function runWindowsElevated(file: string, args: string[], timeoutMs = 120
275271
276272 child . once ( "close" , ( code , signal ) => {
277273 if ( timedOut ) return ;
278- const detail = stderr . trim ( ) || stdout . trim ( ) ;
274+ const detail = [ stderr . trim ( ) , stdout . trim ( ) ] . filter ( Boolean ) . join ( "\n" ) ;
279275 if ( typeof code === "number" ) {
280276 if ( code === 1223 || windowsUacCancelledText ( detail ) ) {
281277 settle ( ( ) => reject ( new WindowsElevationError (
@@ -284,7 +280,7 @@ export function runWindowsElevated(file: string, args: string[], timeoutMs = 120
284280 ) ) ) ;
285281 return ;
286282 }
287- settle ( ( ) => resolve ( code ) ) ;
283+ settle ( ( ) => resolve ( { exitCode : code , stdout , stderr } ) ) ;
288284 return ;
289285 }
290286 settle ( ( ) => reject ( new WindowsElevationError (
@@ -294,3 +290,128 @@ export function runWindowsElevated(file: string, args: string[], timeoutMs = 120
294290 } ) ;
295291 } ) ;
296292}
293+
294+ /**
295+ * Launch a file with UAC elevation and wait for it to exit.
296+ * Throws WindowsElevationError for cancellation, timeout, launch failure, or signal termination.
297+ * Returns the elevated process exit code for completed launches (including non-zero).
298+ */
299+ export function runWindowsElevated ( file : string , args : string [ ] , timeoutMs = 120_000 ) : Promise < number > {
300+ const argumentList = buildWindowsElevatedArgumentList ( args ) ;
301+ // Touch .Handle so Windows PowerShell 5.1 keeps a process handle; ExitCode can
302+ // otherwise stay $null after -Wait and `exit $null` becomes exit 0 (false success).
303+ const script = [
304+ `$p = Start-Process -FilePath ${ psSingleQuote ( file ) } ` ,
305+ argumentList . length > 0 ? ` -ArgumentList ${ psSingleQuote ( argumentList ) } ` : "" ,
306+ " -Verb RunAs -WindowStyle Hidden -PassThru -Wait;" ,
307+ "if ($null -eq $p) { exit 1223 }" ,
308+ "$null = $p.Handle" ,
309+ "if ($null -eq $p.ExitCode) { exit 1 }" ,
310+ "exit $p.ExitCode" ,
311+ ] . join ( "" ) ;
312+
313+ return runPowerShellCommand ( script , timeoutMs ) . then ( result => result . exitCode ) ;
314+ }
315+
316+ export interface ElevatedSchtasksCreateAndRunResult {
317+ createExitCode : number ;
318+ /** null when /run was not attempted because /create failed. */
319+ runExitCode : number | null ;
320+ stdout : string ;
321+ stderr : string ;
322+ }
323+
324+ /** Build the elevated (post-UAC) script that runs schtasks /create then /run without a second prompt. */
325+ export function buildElevatedSchtasksCreateAndRunScript (
326+ schtasksPath : string ,
327+ createArgs : string [ ] ,
328+ runArgs : string [ ] ,
329+ resultPath : string ,
330+ ) : string {
331+ const createList = buildWindowsElevatedArgumentList ( createArgs ) ;
332+ const runList = buildWindowsElevatedArgumentList ( runArgs ) ;
333+ const createPrefix = OCX_SCHTASKS_CREATE_EXIT_PREFIX ;
334+ const runPrefix = OCX_SCHTASKS_RUN_EXIT_PREFIX ;
335+ return [
336+ `$schtasks = ${ psSingleQuote ( schtasksPath ) } ` ,
337+ `$resultPath = ${ psSingleQuote ( resultPath ) } ` ,
338+ "function Invoke-OcxSchtasks([string]$ArgList) {" ,
339+ " $p = Start-Process -FilePath $schtasks -ArgumentList $ArgList -Wait -PassThru -WindowStyle Hidden" ,
340+ " if ($null -eq $p) { return 1 }" ,
341+ " $null = $p.Handle" ,
342+ " if ($null -eq $p.ExitCode) { return 1 }" ,
343+ " return [int]$p.ExitCode" ,
344+ "}" ,
345+ "function Write-OcxResult([int]$CreateCode, $RunCode) {" ,
346+ ` $lines = @('${ createPrefix } ' + $CreateCode)` ,
347+ ` if ($null -ne $RunCode) { $lines += ('${ runPrefix } ' + $RunCode) }` ,
348+ " Set-Content -LiteralPath $resultPath -Value ($lines -join [Environment]::NewLine) -Encoding ascii" ,
349+ "}" ,
350+ `$createCode = Invoke-OcxSchtasks ${ psSingleQuote ( createList ) } ` ,
351+ "if ($createCode -ne 0) { Write-OcxResult $createCode $null; exit $createCode }" ,
352+ `$runCode = Invoke-OcxSchtasks ${ psSingleQuote ( runList ) } ` ,
353+ "Write-OcxResult $createCode $runCode" ,
354+ "exit $runCode" ,
355+ ] . join ( "; " ) ;
356+ }
357+
358+ function readElevatedResultFile ( resultPath : string ) : string {
359+ try {
360+ if ( ! existsSync ( resultPath ) ) return "" ;
361+ return readFileSync ( resultPath , "utf8" ) ;
362+ } catch {
363+ return "" ;
364+ } finally {
365+ try { if ( existsSync ( resultPath ) ) unlinkSync ( resultPath ) ; } catch { /* ignore */ }
366+ }
367+ }
368+
369+ /**
370+ * Create and run the scheduler task inside one elevated PowerShell process (one UAC prompt).
371+ * Throws WindowsElevationError for UAC cancel/timeout/launch/signal failures.
372+ */
373+ export async function runElevatedSchtasksCreateAndRun (
374+ schtasksPath : string ,
375+ createArgs : string [ ] ,
376+ runArgs : string [ ] ,
377+ timeoutMs = 120_000 ,
378+ ) : Promise < ElevatedSchtasksCreateAndRunResult > {
379+ const resultPath = join ( tmpdir ( ) , `ocx-elev-schtasks-${ randomBytes ( 8 ) . toString ( "hex" ) } .txt` ) ;
380+ const inner = buildElevatedSchtasksCreateAndRunScript ( schtasksPath , createArgs , runArgs , resultPath ) ;
381+ // One Start-Process -Verb RunAs elevates PowerShell; create and run execute inside that process.
382+ const launcher = [
383+ `$p = Start-Process -FilePath ${ psSingleQuote ( windowsPowerShell ( ) ) } ` ,
384+ ` -ArgumentList ${ psSingleQuote ( buildWindowsElevatedArgumentList ( [
385+ "-NoProfile" ,
386+ "-NonInteractive" ,
387+ "-ExecutionPolicy" ,
388+ "Bypass" ,
389+ "-Command" ,
390+ inner ,
391+ ] ) ) } `,
392+ " -Verb RunAs -WindowStyle Hidden -PassThru -Wait;" ,
393+ "if ($null -eq $p) { exit 1223 }" ,
394+ "$null = $p.Handle" ,
395+ "if ($null -eq $p.ExitCode) { exit 1 }" ,
396+ "exit $p.ExitCode" ,
397+ ] . join ( "" ) ;
398+
399+ try {
400+ const result = await runPowerShellCommand ( launcher , timeoutMs ) ;
401+ const markerText = readElevatedResultFile ( resultPath ) ;
402+ const combined = `${ markerText } \n${ result . stdout } \n${ result . stderr } ` ;
403+ const createExitCode = parsePrefixedExit ( combined , OCX_SCHTASKS_CREATE_EXIT_PREFIX ) ?? result . exitCode ;
404+ const runExitCode = createExitCode === 0
405+ ? ( parsePrefixedExit ( combined , OCX_SCHTASKS_RUN_EXIT_PREFIX ) ?? result . exitCode )
406+ : null ;
407+ return {
408+ createExitCode,
409+ runExitCode,
410+ stdout : result . stdout ,
411+ stderr : result . stderr ,
412+ } ;
413+ } catch ( error ) {
414+ readElevatedResultFile ( resultPath ) ;
415+ throw error ;
416+ }
417+ }
0 commit comments