unplugin-https-reverse-proxy 4.1.0-beta.11 → 4.1.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import type { ChildProcess } from 'node:child_process'
1
+ import type { Buffer } from 'node:buffer'
2
2
  import { spawn } from 'node:child_process'
3
3
  import process from 'node:process'
4
4
 
@@ -7,8 +7,8 @@ import process from 'node:process'
7
7
  * is a new process that cannot inherit the parent's stdio. The helper talks
8
8
  * over a named pipe, so it only needs to be started detached.
9
9
  *
10
- * `Start-Process -Verb RunAs` is the documented way to trigger the UAC prompt
11
- * without a helper binary or a dependency on `sudo-prompt`.
10
+ * ShellExecute with the `runas` verb is the documented way to trigger the UAC
11
+ * prompt without a helper binary or a dependency on `sudo-prompt`.
12
12
  */
13
13
  export interface WindowsElevationOptions {
14
14
  /** Executable to run elevated; normally the node runtime. */
@@ -19,58 +19,116 @@ export interface WindowsElevationOptions {
19
19
  cwd?: string
20
20
  }
21
21
 
22
+ export type WindowsElevationResult
23
+ = | { ok: true, pid?: number }
24
+ | { ok: false, denied: boolean, message: string }
25
+
26
+ /** ShellExecute reports a dismissed UAC prompt as `ERROR_CANCELLED`. */
27
+ const ERROR_CANCELLED = 1223
28
+
22
29
  /** Quotes an argument for PowerShell's single-quoted string syntax. */
23
30
  export function quotePowerShell(value: string): string {
24
31
  return `'${value.replace(/'/g, '\'\'')}'`
25
32
  }
26
33
 
27
34
  /**
28
- * Builds the PowerShell command that starts `file` elevated. Exported so the
35
+ * Quotes one argument so the C runtime's command-line parser, which node uses
36
+ * for `process.argv`, reads it back unchanged. ShellExecute takes a single
37
+ * command line, so a path with a space would otherwise split in two.
38
+ */
39
+ export function quoteWindowsArg(arg: string): string {
40
+ if (arg === '')
41
+ return '""'
42
+ if (!/[\s"]/.test(arg))
43
+ return arg
44
+
45
+ let quoted = '"'
46
+ let backslashes = 0
47
+ for (const char of arg) {
48
+ if (char === '\\') {
49
+ backslashes++
50
+ continue
51
+ }
52
+ // Backslashes are literal unless they precede a quote.
53
+ quoted += char === '"'
54
+ ? `${'\\'.repeat(backslashes * 2 + 1)}"`
55
+ : `${'\\'.repeat(backslashes)}${char}`
56
+ backslashes = 0
57
+ }
58
+ return `${quoted}${'\\'.repeat(backslashes * 2)}"`
59
+ }
60
+
61
+ /**
62
+ * Builds the PowerShell script that starts `file` elevated. Exported so the
29
63
  * escaping can be unit-tested without touching a real UAC prompt.
64
+ *
65
+ * `Start-Process` is not used: it joins `-ArgumentList` with spaces without
66
+ * quoting, and it hides the Win32 error code that tells a dismissed prompt
67
+ * apart from a real failure.
30
68
  */
31
69
  export function buildElevationCommand(options: WindowsElevationOptions): string {
32
- const argumentList = options.args.map(quotePowerShell).join(',')
33
- const parts = [
34
- 'Start-Process',
35
- '-FilePath',
36
- quotePowerShell(options.file),
70
+ const lines = [
71
+ // The message read back on failure is localized; keep it readable as UTF-8.
72
+ '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
73
+ '$psi = New-Object System.Diagnostics.ProcessStartInfo',
74
+ `$psi.FileName = ${quotePowerShell(options.file)}`,
75
+ `$psi.Arguments = ${quotePowerShell(options.args.map(quoteWindowsArg).join(' '))}`,
37
76
  ]
38
77
 
39
- if (argumentList)
40
- parts.push('-ArgumentList', argumentList)
41
-
42
78
  if (options.cwd)
43
- parts.push('-WorkingDirectory', quotePowerShell(options.cwd))
79
+ lines.push(`$psi.WorkingDirectory = ${quotePowerShell(options.cwd)}`)
44
80
 
45
- parts.push('-Verb', 'RunAs')
46
- parts.push('-WindowStyle', 'Hidden')
81
+ lines.push(
82
+ '$psi.Verb = \'runas\'',
83
+ '$psi.UseShellExecute = $true',
84
+ '$psi.WindowStyle = \'Hidden\'',
85
+ 'try { $p = [System.Diagnostics.Process]::Start($psi); if ($p) { [Console]::Out.Write($p.Id) } }',
86
+ `catch { $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; if ($e.NativeErrorCode -eq ${ERROR_CANCELLED}) { exit ${ERROR_CANCELLED} }; [Console]::Error.Write($e.Message); exit 1 }`,
87
+ )
47
88
 
48
- return parts.join(' ')
89
+ return lines.join('\n')
49
90
  }
50
91
 
51
92
  /**
52
- * Starts the helper elevated on Windows. Resolves once PowerShell has accepted
53
- * the request; the helper's own readiness is observed through the named pipe.
93
+ * Starts the helper elevated on Windows. Resolves once UAC has been answered;
94
+ * the helper's own readiness is observed through the named pipe.
54
95
  */
55
- export function spawnElevatedOnWindows(options: WindowsElevationOptions): Promise<ChildProcess> {
56
- return new Promise((resolve, reject) => {
57
- const script = buildElevationCommand(options)
96
+ export function spawnElevatedOnWindows(options: WindowsElevationOptions): Promise<WindowsElevationResult> {
97
+ return new Promise((resolve) => {
58
98
  const child = spawn(
59
99
  'powershell.exe',
60
- ['-NoProfile', '-NonInteractive', '-Command', script],
61
- { stdio: 'ignore', windowsHide: true },
100
+ ['-NoProfile', '-NonInteractive', '-Command', buildElevationCommand(options)],
101
+ { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true },
62
102
  )
63
103
 
64
- // PowerShell exits once UAC is answered; a non-zero code means the user
65
- // dismissed the prompt or elevation was denied.
66
- child.once('error', reject)
67
- child.once('exit', (code) => {
68
- if (code === 0)
69
- return resolve(child)
70
- reject(new Error(
71
- `administrator permission was not granted (PowerShell exited with ${code}). `
72
- + 'Accept the UAC prompt to let the plugin edit the hosts file and bind ports 80/443.',
73
- ))
104
+ let stdout = ''
105
+ let stderr = ''
106
+ child.stdout.on('data', (data: Buffer) => {
107
+ stdout += data.toString()
108
+ })
109
+ child.stderr.on('data', (data: Buffer) => {
110
+ stderr = (stderr + data.toString()).slice(-4096)
111
+ })
112
+
113
+ child.once('error', error => resolve({
114
+ ok: false,
115
+ denied: false,
116
+ message: `could not start PowerShell to request administrator permission: ${error.message}`,
117
+ }))
118
+ child.once('close', (code) => {
119
+ if (code === 0) {
120
+ const pid = Number(stdout.trim())
121
+ return resolve({ ok: true, pid: Number.isSafeInteger(pid) && pid > 0 ? pid : undefined })
122
+ }
123
+
124
+ if (code === ERROR_CANCELLED)
125
+ return resolve({ ok: false, denied: true, message: 'administrator permission was cancelled' })
126
+
127
+ resolve({
128
+ ok: false,
129
+ denied: false,
130
+ message: `could not start the privileged helper as administrator (PowerShell exited with ${code}).${stderr.trim() ? ` ${stderr.trim()}` : ''}`,
131
+ })
74
132
  })
75
133
  })
76
134
  }
@@ -1,3 +1,6 @@
1
+ import { writeFileSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { basename, dirname, resolve } from 'node:path'
1
4
  import process from 'node:process'
2
5
  import { startHelper } from './privileged/bootstrap'
3
6
 
@@ -119,5 +122,28 @@ async function main(): Promise<void> {
119
122
 
120
123
  main().catch((error: Error) => {
121
124
  process.stderr.write(`[uhrp-helper] fatal: ${error.message}\n`)
125
+ const errorFile = errorFileFrom(process.argv.slice(2))
126
+ if (errorFile) {
127
+ try {
128
+ writeFileSync(errorFile, error.message, { flag: 'wx' })
129
+ }
130
+ catch {}
131
+ }
122
132
  process.exit(1)
123
133
  })
134
+
135
+ /**
136
+ * Where to leave the fatal error for the client on Windows, where the elevated
137
+ * helper has no stdio the client can read.
138
+ *
139
+ * The path comes from an unprivileged process, so only a new file with the
140
+ * expected name directly in this user's temp directory is accepted; it must
141
+ * not become a way to write files elsewhere as administrator.
142
+ */
143
+ function errorFileFrom(argv: string[]): string | undefined {
144
+ const index = argv.indexOf('--error-file')
145
+ const path = index >= 0 ? argv[index + 1] : undefined
146
+ if (!path || !/^uhrp-helper-[0-9a-f]+\.log$/.test(basename(path)))
147
+ return undefined
148
+ return resolve(dirname(path)) === resolve(tmpdir()) ? path : undefined
149
+ }