unplugin-https-reverse-proxy 4.1.0-beta.9 → 4.1.0

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.
@@ -342,6 +342,8 @@ export interface NodeHelperDepsOptions {
342
342
  hostsPath?: string
343
343
  caddyBin: string
344
344
  caddyConfigPath: string
345
+ /** Admin API socket; `ca.trust` talks to it instead of the TCP default. */
346
+ caddyAdminSocket?: string
345
347
  caddyCwd?: string
346
348
  caddyEnv?: Record<string, string>
347
349
  /** Caddy storage directory; handed back to the user when Caddy stops. */
@@ -391,13 +393,19 @@ async function reclaimTree(target: string, uid: number, gid: number): Promise<st
391
393
  }
392
394
 
393
395
  /** Installs the Caddy root CA using helper-owned commands. */
394
- async function trustLocalCaWithSystemTools(caddyBin: string): Promise<{ trusted: boolean, output: string }> {
396
+ async function trustLocalCaWithSystemTools(
397
+ caddyBin: string,
398
+ adminSocket: string | undefined,
399
+ ): Promise<{ trusted: boolean, output: string }> {
395
400
  // `caddy trust` reads the CA through the admin API, which only exists while
396
- // Caddy is serving; the plugin calls this after Caddy is up.
401
+ // Caddy is serving; the plugin calls this after Caddy is up. The admin API is
402
+ // a unix socket when the template enabled one, so the address follows it
403
+ // instead of the old TCP default.
404
+ const address = adminSocket ? `unix/${adminSocket}` : '127.0.0.1:2019'
397
405
  try {
398
406
  const { stdout, stderr } = await execFileAsync(
399
407
  caddyBin,
400
- ['trust', '--ca', 'local', '--address', '127.0.0.1:2019'],
408
+ ['trust', '--ca', 'local', '--address', address],
401
409
  { timeout: 120_000 },
402
410
  )
403
411
  return { trusted: true, output: `${stdout}${stderr}`.trim() }
@@ -475,7 +483,7 @@ export function createNodeHelperDeps(options: NodeHelperDepsOptions): HelperDeps
475
483
  caddyConfigPath: options.caddyConfigPath,
476
484
  caddyCwd: options.caddyCwd ?? process.cwd(),
477
485
  caddyEnv: options.caddyEnv ?? {},
478
- trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin),
486
+ trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin, options.caddyAdminSocket),
479
487
  caddyStoragePath: options.caddyStoragePath,
480
488
  storageOwner: options.storageOwner,
481
489
  startCaddy: (emit) => {
@@ -25,6 +25,8 @@ export interface SessionScope {
25
25
  caddyBin: string
26
26
  /** Caddyfile the helper may load. */
27
27
  caddyConfigPath: string
28
+ /** Admin API socket; used by `ca.trust` instead of the TCP default. */
29
+ caddyAdminSocket?: string
28
30
  /** Shown before the password prompt so the request is not a surprise. */
29
31
  reason?: { target: string, https: boolean }
30
32
  log?: (message: string) => void
@@ -108,6 +110,7 @@ async function startNew(socketPath: string, scope: SessionScope): Promise<Opened
108
110
  caddyStoragePath: scope.caddyStoragePath,
109
111
  caddyBin: scope.caddyBin,
110
112
  caddyConfigPath: scope.caddyConfigPath,
113
+ caddyAdminSocket: scope.caddyAdminSocket,
111
114
  reason: scope.reason,
112
115
  log: scope.log,
113
116
  })
@@ -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
 
@@ -10,6 +13,7 @@ interface ParsedArgs {
10
13
  ownerUid?: number
11
14
  ownerGid?: number
12
15
  caddyStorage?: string
16
+ caddyAdmin?: string
13
17
  }
14
18
 
15
19
  function parseArgs(argv: string[]): ParsedArgs {
@@ -21,6 +25,7 @@ function parseArgs(argv: string[]): ParsedArgs {
21
25
  let ownerUid: number | undefined
22
26
  let ownerGid: number | undefined
23
27
  let caddyStorage: string | undefined
28
+ let caddyAdmin: string | undefined
24
29
 
25
30
  for (let index = 0; index < argv.length; index++) {
26
31
  const current = argv[index]
@@ -40,6 +45,8 @@ function parseArgs(argv: string[]): ParsedArgs {
40
45
  ownerGid = Number(argv[++index])
41
46
  else if (current === '--caddy-storage')
42
47
  caddyStorage = argv[++index] ?? undefined
48
+ else if (current === '--caddy-admin')
49
+ caddyAdmin = argv[++index] ?? undefined
43
50
  }
44
51
 
45
52
  if (!socket || !token)
@@ -56,6 +63,7 @@ function parseArgs(argv: string[]): ParsedArgs {
56
63
  ownerUid: Number.isInteger(ownerUid) ? ownerUid : undefined,
57
64
  ownerGid: Number.isInteger(ownerGid) ? ownerGid : undefined,
58
65
  caddyStorage,
66
+ caddyAdmin,
59
67
  }
60
68
  }
61
69
 
@@ -78,6 +86,7 @@ async function main(): Promise<void> {
78
86
  ownerUid: args.ownerUid,
79
87
  ownerGid: args.ownerGid,
80
88
  caddyStoragePath: args.caddyStorage,
89
+ caddyAdminSocket: args.caddyAdmin,
81
90
  caddyEnv: {
82
91
  HOME: process.env.HOME ?? '',
83
92
  // Keep Caddy's storage next to the invoking user's home even though the
@@ -113,5 +122,28 @@ async function main(): Promise<void> {
113
122
 
114
123
  main().catch((error: Error) => {
115
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
+ }
116
132
  process.exit(1)
117
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
+ }