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.
@@ -51,13 +51,13 @@ function isAlive(pid: number | undefined): boolean {
51
51
  * A SIGKILLed dev server cannot remove its own route, so without this sweep its
52
52
  * domain would keep resolving to a proxy with no upstream behind it.
53
53
  */
54
- function readConfig(): ProxyMap {
55
- if (!existsSync(caddyConfigPath))
54
+ function readConfig(path: string = caddyConfigPath): ProxyMap {
55
+ if (!existsSync(path))
56
56
  return {}
57
57
 
58
58
  let parsed: ProxyMap
59
59
  try {
60
- parsed = JSON.parse(readFileSync(caddyConfigPath, 'utf-8')) as ProxyMap
60
+ parsed = JSON.parse(readFileSync(path, 'utf-8')) as ProxyMap
61
61
  }
62
62
  catch {
63
63
  // A half-written file is not worth preserving: it has no usable routes.
@@ -77,16 +77,23 @@ function readConfig(): ProxyMap {
77
77
  * document. `rename` is atomic within a filesystem, which keeps the shared
78
78
  * config readable at all times.
79
79
  */
80
- function writeConfig(proxies: ProxyMap): void {
80
+ function writeConfig(proxies: ProxyMap, path: string = caddyConfigPath): void {
81
81
  const content = JSON.stringify(proxies, null, 2)
82
- const temp = `${caddyConfigPath}.${process.pid}.tmp`
82
+ const temp = `${path}.${process.pid}.tmp`
83
83
  writeFileSync(temp, content)
84
- renameSync(temp, caddyConfigPath)
84
+ renameSync(temp, path)
85
85
  }
86
86
 
87
87
  export interface CaddyConfigOptions {
88
88
  /** Injected in tests so they do not need the real lock. */
89
89
  lock?: ConfigLock
90
+ /**
91
+ * Config file to operate on; defaults to the shared runtime path.
92
+ *
93
+ * Injectable so a test can own a file without racing every other test that
94
+ * happens to run against the same module-level constant.
95
+ */
96
+ configPath?: string
90
97
  /**
91
98
  * Renders the Caddyfile from the routes, called inside the config lock.
92
99
  *
@@ -99,6 +106,7 @@ export interface CaddyConfigOptions {
99
106
 
100
107
  export function useCaddyConfig(options: CaddyConfigOptions = {}): CaddyConfigApi {
101
108
  const lock = options.lock ?? createFileLock()
109
+ const configPath = options.configPath ?? caddyConfigPath
102
110
 
103
111
  /**
104
112
  * Applies the change, then re-renders while still holding the lock.
@@ -113,9 +121,9 @@ export function useCaddyConfig(options: CaddyConfigOptions = {}): CaddyConfigApi
113
121
  ): Promise<ProxyMap> {
114
122
  const release = await lock.acquire()
115
123
  try {
116
- const proxies = readConfig()
124
+ const proxies = readConfig(configPath)
117
125
  apply(proxies)
118
- writeConfig(proxies)
126
+ writeConfig(proxies, configPath)
119
127
  await options.renderCaddyfile?.(proxies)
120
128
  return proxies
121
129
  }
@@ -125,7 +133,7 @@ export function useCaddyConfig(options: CaddyConfigOptions = {}): CaddyConfigApi
125
133
  }
126
134
 
127
135
  return {
128
- configJsonRef: () => (existsSync(caddyConfigPath) ? readConfig() : undefined),
136
+ configJsonRef: () => (existsSync(configPath) ? readConfig(configPath) : undefined),
129
137
 
130
138
  async writeCaddyConfig(_proxies, key) {
131
139
  await mutate((proxies) => {
@@ -135,29 +143,29 @@ export function useCaddyConfig(options: CaddyConfigOptions = {}): CaddyConfigApi
135
143
  },
136
144
 
137
145
  async removeProxy(key) {
138
- const proxies = await mutate((current) => {
146
+ // The empty config is written inside the lock rather than unlinked after
147
+ // it: between the release and the unlink another project can add its
148
+ // route, and the unlink would then drop a route that is in use.
149
+ await mutate((current) => {
139
150
  for (const route of Object.keys(current)) {
140
151
  if (route.endsWith(`#${key}`))
141
152
  delete current[route]
142
153
  }
143
154
  })
144
-
145
- if (Object.keys(proxies).length === 0)
146
- removeConfigFile()
147
155
  },
148
156
 
149
- readProxies: () => readConfig(),
157
+ readProxies: () => readConfig(configPath),
150
158
 
151
159
  async cleanUp() {
152
- removeConfigFile()
160
+ removeConfigFile(configPath)
153
161
  },
154
162
  }
155
163
  }
156
164
 
157
- function removeConfigFile(): void {
165
+ function removeConfigFile(path: string = caddyConfigPath): void {
158
166
  try {
159
- if (existsSync(caddyConfigPath))
160
- unlinkSync(caddyConfigPath)
167
+ if (existsSync(path))
168
+ unlinkSync(path)
161
169
  }
162
170
  catch {}
163
171
  }
@@ -13,13 +13,42 @@ function resolvePath(path: string): string {
13
13
  return path
14
14
  }
15
15
 
16
- export const TEMP_DIR = resolvePath(process.env.UHRP_CADDY_PATH || process.env.TEMP || process.env.TMPDIR || '/tmp')
16
+ /**
17
+ * Directory for the Caddy binary, Caddyfile and the admin socket.
18
+ *
19
+ * The Caddy binary is executed as root, so this must not be a directory other
20
+ * users can write to. macOS gives every user a private `TMPDIR`, and `TEMP` on
21
+ * Windows is per-user too. On Linux `TMPDIR` is usually unset and `/tmp` is
22
+ * world-writable (sticky bit only prevents deleting other users' files, not
23
+ * creating `/tmp/caddy` first), so the fallback goes under the user's own cache
24
+ * directory instead.
25
+ */
26
+ function defaultTempDir(): string {
27
+ const fromEnv = process.env.TEMP || process.env.TMPDIR
28
+ if (fromEnv)
29
+ return resolvePath(fromEnv)
30
+ if (process.platform === 'linux')
31
+ return join(process.env.XDG_CACHE_HOME || join(os.homedir(), '.cache'), 'uhrp')
32
+ return '/tmp'
33
+ }
34
+
35
+ export const TEMP_DIR = resolvePath(process.env.UHRP_CADDY_PATH || defaultTempDir())
17
36
  export const caddyPath = join(TEMP_DIR, `caddy${process.platform === 'win32' ? '.exe' : ''}`)
18
37
  export const caddyFilePath = join(TEMP_DIR, 'CADDYFILE')
19
38
 
20
39
  export const caddyConfigPath = join(TEMP_DIR, '.CADDYFILE.config.json')
21
40
  export const caddyLockFilePath = join(TEMP_DIR, 'caddylock')
22
41
 
42
+ /**
43
+ * Admin API socket, shared by every project using this helper.
44
+ *
45
+ * Caddy runs as root, so its admin API must not listen on a TCP port any local
46
+ * user can reach: `POST /load` there reconfigures the proxy with no further
47
+ * check. A unix socket inside the runtime directory is reachable only by whoever
48
+ * can open that directory, and the directory is private on macOS.
49
+ */
50
+ export const caddyAdminSocketPath = join(TEMP_DIR, 'caddy-admin.sock')
51
+
23
52
  export const supportList = [
24
53
  {
25
54
  platform: 'dragonfly',
@@ -2,7 +2,7 @@ import type { Buffer } from 'node:buffer'
2
2
  import type { OpenedPrivilegedSession } from './privileged'
3
3
  import { execFile } from 'node:child_process'
4
4
  import { chmodSync, createWriteStream, existsSync, mkdirSync, unlinkSync } from 'node:fs'
5
- import { readFile, unlink, writeFile } from 'node:fs/promises'
5
+ import { readFile, rename, unlink, writeFile } from 'node:fs/promises'
6
6
  import { platform } from 'node:os'
7
7
  import { join } from 'node:path'
8
8
  import process from 'node:process'
@@ -12,7 +12,7 @@ import { HttpsProxyAgent } from 'https-proxy-agent'
12
12
  import { consola, once } from '../utils'
13
13
  import { genCaddyfile, validateTemplateContext } from './caddyfile'
14
14
  import { useCaddyConfig } from './config'
15
- import { caddyFilePath, caddyPath, supportList, TEMP_DIR } from './constants'
15
+ import { caddyAdminSocketPath, caddyFilePath, caddyPath, supportList, TEMP_DIR } from './constants'
16
16
  import { isCaddyReloadCancellation } from './log'
17
17
  import { HelperCaddyProcess, openPrivilegedSession } from './privileged'
18
18
  import { formatTlsHealthFailure, waitForLocalTls } from './tls-health'
@@ -125,9 +125,18 @@ function caddyRootPath(): string {
125
125
  async function renderCaddyfile(proxies: Record<string, unknown>): Promise<void> {
126
126
  const ctx = validateTemplateContext({
127
127
  caddy_root: caddyRootPath(),
128
+ admin_socket: caddyAdminSocketPath,
128
129
  proxies: Object.values(proxies) as never,
129
130
  })
130
- await writeFile(caddyFilePath, await genCaddyfile(ctx))
131
+ const content = await genCaddyfile(ctx)
132
+
133
+ // Written through a temporary file: Caddy watches this path, and a reload
134
+ // triggered by a half-written file fails to parse. The starter's stderr
135
+ // handler exits the dev server on a parse error, so a partial read would take
136
+ // down an unrelated project.
137
+ const temp = `${caddyFilePath}.${process.pid}.tmp`
138
+ await writeFile(temp, content)
139
+ await rename(temp, caddyFilePath)
131
140
  }
132
141
 
133
142
  let caddyConfig: ReturnType<typeof useCaddyConfig> | undefined
@@ -166,6 +175,7 @@ const defaultDependencies: CaddyDependencies = {
166
175
  // helper must never execute something named in a request.
167
176
  caddyBin: caddyPath,
168
177
  caddyConfigPath: caddyFilePath,
178
+ caddyAdminSocket: caddyAdminSocketPath,
169
179
  reason,
170
180
  }),
171
181
  config: () => getCaddyConfig(),
@@ -202,8 +212,10 @@ export class CaddyInstant {
202
212
  if (this._session && !this._session.client.connected)
203
213
  this._session = undefined
204
214
 
205
- if (!this._session)
215
+ if (!this._session) {
216
+ await this.deps.config().writeCaddyConfig([], this.proxyKey)
206
217
  this._session = await this.deps.openSession(TEMP_DIR, reason)
218
+ }
207
219
  return this._session
208
220
  }
209
221
 
@@ -268,43 +280,6 @@ export class CaddyInstant {
268
280
  throw new Error(formatTlsHealthFailure(targetHost, health))
269
281
  }
270
282
 
271
- /**
272
- * Regenerates the Caddyfile from the config on disk.
273
- *
274
- * Reading the file rather than a cached view matters here: another project
275
- * may have added its route since this instance last looked.
276
- */
277
- private async updateCaddyfile(): Promise<void> {
278
- const { readProxies } = this.deps.config()
279
- const proxies = Object.values(readProxies())
280
- const ctx = validateTemplateContext({
281
- caddy_root: this.caddyRoot,
282
- proxies,
283
- })
284
-
285
- this.caddyfile = await genCaddyfile(ctx)
286
- await this.writeCaddyfile()
287
- }
288
-
289
- private async stopCaddy(): Promise<void> {
290
- try {
291
- await got.post('http://127.0.0.1:2019/stop', {
292
- headers: {
293
- Origin: 'http://localhost:2019',
294
- },
295
- retry: {
296
- limit: 0,
297
- },
298
- timeout: {
299
- request: 2000,
300
- },
301
- })
302
- }
303
- catch {}
304
-
305
- this._caddyChild?.kill()
306
- }
307
-
308
283
  /**
309
284
  * @param source like `127.0.0.1:8080`
310
285
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
@@ -356,11 +331,12 @@ export class CaddyInstant {
356
331
  },
357
332
  ]
358
333
 
334
+ // This also renders the Caddyfile, inside the same lock: rendering here
335
+ // afterwards would read the routes outside the lock and could overwrite a
336
+ // newer Caddyfile written by another project in between.
359
337
  const { writeCaddyConfig } = this.deps.config()
360
338
  await writeCaddyConfig(proxies, this.proxyKey)
361
339
 
362
- await this.updateCaddyfile()
363
-
364
340
  // Ports 80/443 may still be held by a previous, uncleanly stopped run.
365
341
  // The helper skips its own Caddy, so this never kills a proxy another
366
342
  // project is already using.
@@ -82,6 +82,8 @@ export interface PrivilegedSessionOptions {
82
82
  caddyBin: string
83
83
  /** Caddyfile the helper may load. */
84
84
  caddyConfigPath: string
85
+ /** Admin API socket; `ca.trust` talks to it instead of the TCP default. */
86
+ caddyAdminSocket?: string
85
87
  /** Shown before the password prompt so the request is not a surprise. */
86
88
  reason?: { target: string, https: boolean }
87
89
  }
@@ -115,6 +117,7 @@ export function openPrivilegedSession(
115
117
  // execute a path supplied over the socket.
116
118
  caddyBin: options.caddyBin,
117
119
  caddyConfigPath: options.caddyConfigPath,
120
+ caddyAdminSocket: options.caddyAdminSocket,
118
121
  reason: options.reason,
119
122
  log: options.log,
120
123
  })
package/src/index.ts CHANGED
@@ -125,6 +125,11 @@ export const unpluginFactory: UnpluginFactory<Options> = options => ({
125
125
 
126
126
  const _printUrls = server.printUrls.bind(server)
127
127
 
128
+ // Hosts like Nuxt run Vite in middleware mode and never call
129
+ // `printUrls`, so the proxy would silently never start.
130
+ if (server.config.server.middlewareMode)
131
+ consola.warn('Vite runs in middleware mode, so the reverse proxy cannot start from the Vite plugin. In Nuxt, add `unplugin-https-reverse-proxy/nuxt` to `modules` instead.')
132
+
128
133
  let source = `localhost:${config.server.port || 5173}`
129
134
  const url = server.resolvedUrls?.local[0]
130
135
  if (url) {
@@ -6,6 +6,7 @@ import { chmodSync, chownSync, existsSync, readFileSync, rmSync } from 'node:fs'
6
6
  import { createServer } from 'node:net'
7
7
  import { dirname, join } from 'node:path'
8
8
  import process from 'node:process'
9
+ import { checkPrivilegedPath, describeRejection } from './path-guard'
9
10
  import { attachSocket, createHelperRuntime, createNodeHelperDeps } from './server'
10
11
 
11
12
  export interface HelperBootstrapOptions {
@@ -16,6 +17,8 @@ export interface HelperBootstrapOptions {
16
17
  caddyBin: string
17
18
  /** Caddyfile to load; fixed for the same reason. */
18
19
  caddyConfigPath: string
20
+ /** Admin API socket; used by `ca.trust` instead of the TCP default. */
21
+ caddyAdminSocket?: string
19
22
  caddyCwd?: string
20
23
  caddyEnv?: Record<string, string>
21
24
  /**
@@ -66,11 +69,25 @@ export const DEFAULT_IDLE_TIMEOUT_MS = 30_000
66
69
  export async function startHelper(options: HelperBootstrapOptions): Promise<RunningHelper> {
67
70
  const { socketPath, token } = options
68
71
  const log = options.log ?? ((message: string) => process.stdout.write(`[uhrp-helper] ${message}\n`))
72
+
73
+ // The binary and the config travel in as arguments from a process running as
74
+ // the developer. Refuse them when they can be rewritten by someone else:
75
+ // running as root, a swapped binary or Caddyfile is a local privilege gain.
76
+ for (const check of [
77
+ checkPrivilegedPath(options.caddyBin, { label: 'Caddy binary', ownerUid: options.ownerUid }),
78
+ checkPrivilegedPath(options.caddyConfigPath, { label: 'Caddyfile', ownerUid: options.ownerUid }),
79
+ ]) {
80
+ if (check) {
81
+ log(describeRejection(check))
82
+ throw new Error(describeRejection(check))
83
+ }
84
+ }
69
85
  const deps = options.deps ?? createNodeHelperDeps({
70
86
  hostsPath: options.hostsPath,
71
87
  log,
72
88
  caddyBin: options.caddyBin,
73
89
  caddyConfigPath: options.caddyConfigPath,
90
+ caddyAdminSocket: options.caddyAdminSocket,
74
91
  caddyCwd: options.caddyCwd,
75
92
  caddyEnv: options.caddyEnv,
76
93
  caddyStoragePath: options.caddyStoragePath,
@@ -198,7 +215,11 @@ export async function startHelper(options: HelperBootstrapOptions): Promise<Runn
198
215
 
199
216
  await new Promise<void>((resolve, reject) => {
200
217
  server.once('error', reject)
201
- server.listen(socketPath, () => resolve())
218
+ // On Windows the pipe gets the elevated token's default ACL, which leaves
219
+ // the non-elevated dev server read-only access, so `connect()` fails with
220
+ // EPERM. The token handshake is what authenticates a client there.
221
+ const shareWithUser = process.platform === 'win32'
222
+ server.listen({ path: socketPath, readableAll: shareWithUser, writableAll: shareWithUser }, () => resolve())
202
223
  })
203
224
 
204
225
  // A helper nobody ever connects to is as useless as one whose clients left:
@@ -208,12 +229,11 @@ export async function startHelper(options: HelperBootstrapOptions): Promise<Runn
208
229
  try {
209
230
  // The client is not root: hand the socket back to the developer and keep it
210
231
  // private to them. Without the chown, `connect()` fails with EACCES and the
211
- // client only sees a silent retry loop.
212
- if (typeof options.ownerUid === 'number') {
213
- chownSync(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid)
214
- chmodSync(socketPath, 0o600)
215
- }
216
- else {
232
+ // client only sees a silent retry loop. Named pipes have no file mode; their
233
+ // access was set at listen time.
234
+ if (process.platform !== 'win32') {
235
+ if (typeof options.ownerUid === 'number')
236
+ chownSync(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid)
217
237
  chmodSync(socketPath, 0o600)
218
238
  }
219
239
  }
@@ -129,7 +129,7 @@ export async function connectClient(options: ConnectOptions): Promise<Privileged
129
129
  // A permission or protocol error will not resolve by waiting, and
130
130
  // retrying hides the real cause behind a silent hang.
131
131
  const code = (lastError as NodeJS.ErrnoException).code
132
- if (code === 'EACCES' || lastError instanceof HelperConnectionError)
132
+ if (code === 'EACCES' || code === 'EPERM' || lastError instanceof HelperConnectionError)
133
133
  throw lastError
134
134
 
135
135
  await new Promise(resolve => setTimeout(resolve, retryIntervalMs))
@@ -2,7 +2,9 @@ import type { Buffer } from 'node:buffer'
2
2
  import type { PrivilegedClient } from './client'
3
3
  import { spawn, spawnSync } from 'node:child_process'
4
4
  import { randomBytes } from 'node:crypto'
5
- import { platform } from 'node:os'
5
+ import { readFileSync, rmSync } from 'node:fs'
6
+ import { platform, tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
6
8
  import process from 'node:process'
7
9
  import { collectForwardedEnv, connectClient } from './client'
8
10
  import { spawnElevatedOnWindows } from './windows-elevation'
@@ -39,6 +41,8 @@ export interface LaunchOptions {
39
41
  caddyBin: string
40
42
  /** Caddyfile the helper is allowed to load. */
41
43
  caddyConfigPath: string
44
+ /** Admin API socket the helper talks to when installing the CA. */
45
+ caddyAdminSocket?: string
42
46
  /** Shown before the password prompt so the request is not a surprise. */
43
47
  reason?: { target: string, https: boolean }
44
48
  }
@@ -251,15 +255,27 @@ export async function startPrivilegedHelper(options: LaunchOptions): Promise<Pri
251
255
  options.caddyBin,
252
256
  '--caddy-config',
253
257
  options.caddyConfigPath,
258
+ ...(options.caddyAdminSocket ? ['--caddy-admin', options.caddyAdminSocket] : []),
254
259
  ]
255
260
 
256
261
  let child: ReturnType<typeof spawn> | undefined
262
+ let helperExited: { promise: Promise<never>, stop: () => void } | undefined
257
263
 
258
264
  if (!direct && platform() === 'win32') {
259
265
  // UAC: the elevated helper is a separate process and cannot inherit stdio,
260
266
  // so it reports through the named pipe instead. The user's environment is
261
267
  // recovered by the helper from its own process env, which Windows keeps.
262
- await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: process.cwd() })
268
+ // A helper that dies before listening leaves its error in this file.
269
+ const errorFile = join(tmpdir(), `uhrp-helper-${randomBytes(6).toString('hex')}.log`)
270
+ const elevated = await spawnElevatedOnWindows({
271
+ file: helperEntry,
272
+ args: [...childArgv, '--error-file', errorFile],
273
+ cwd: process.cwd(),
274
+ })
275
+ if (!elevated.ok)
276
+ throw elevated.denied ? new PrivilegeDeniedError(elevated.message) : new Error(elevated.message)
277
+ if (elevated.pid !== undefined)
278
+ helperExited = watchWindowsHelper(elevated.pid, errorFile)
263
279
  }
264
280
  else {
265
281
  const command = direct ? helperEntry : sudoCommand
@@ -276,27 +292,42 @@ export async function startPrivilegedHelper(options: LaunchOptions): Promise<Pri
276
292
  })
277
293
 
278
294
  child.stdout?.on('data', (data: Buffer) => log?.(data.toString().trimEnd()))
279
- child.stderr?.on('data', (data: Buffer) => log?.(data.toString().trimEnd()))
295
+ let stderr = ''
296
+ child.stderr?.on('data', (data: Buffer) => {
297
+ stderr = (stderr + data.toString()).slice(-4096)
298
+ log?.(data.toString().trimEnd())
299
+ })
280
300
 
281
- const exited = new Promise<number | null>(resolve => child!.once('exit', code => resolve(code)))
301
+ const exited = new Promise<number | null>((resolve) => {
302
+ child!.once('error', (error) => {
303
+ stderr = error.message
304
+ })
305
+ child!.once('close', code => resolve(code))
306
+ })
282
307
 
283
- // Refused credentials make the helper exit immediately; report that instead
284
- // of waiting for the full connection timeout.
308
+ // A failed helper should report its own diagnostic (or sudo's) before the
309
+ // connection timeout. A nonzero exit does not imply denied permission.
285
310
  const earlyExit = await Promise.race([
286
311
  exited,
287
312
  new Promise<undefined>(resolve => setTimeout(() => resolve(undefined), 500)),
288
313
  ])
289
314
 
290
315
  if (earlyExit !== undefined && earlyExit !== 0) {
291
- throw new Error(
292
- `privileged helper exited with code ${earlyExit}. `
293
- + 'Administrator permission was refused, or sudo is not available.',
294
- )
316
+ const detail = stderr.trim()
317
+ let guidance = ''
318
+ if (/\b(?:EACCES|EPERM)\b/.test(detail))
319
+ guidance = ' Check the path named above and its parent directories. Fix ownership or access manually; do not use chmod 777.'
320
+ else if (!direct && /^sudo:/m.test(detail))
321
+ guidance = ' Retry from a terminal where sudo can request permission, or ask an administrator to grant access.'
322
+ throw new Error(`privileged helper exited with code ${earlyExit}.${detail ? ` ${detail}${guidance}` : ' No diagnostic output from the helper or sudo.'}`)
295
323
  }
296
324
  }
297
325
 
298
326
  try {
299
- const client = await connectClient({ socketPath, token, timeoutMs: connectTimeoutMs })
327
+ const connecting = connectClient({ socketPath, token, timeoutMs: connectTimeoutMs })
328
+ // Losing the race to a dead helper leaves this retrying in the background.
329
+ connecting.catch(() => {})
330
+ const client = await (helperExited ? Promise.race([connecting, helperExited.promise]) : connecting)
300
331
  return {
301
332
  client,
302
333
  async close() {
@@ -312,6 +343,59 @@ export async function startPrivilegedHelper(options: LaunchOptions): Promise<Pri
312
343
  catch {}
313
344
  throw error
314
345
  }
346
+ finally {
347
+ helperExited?.stop()
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Fails as soon as the elevated helper is gone, with the error it left behind.
353
+ *
354
+ * Without this, a helper that refused to start on Windows only shows up as the
355
+ * pipe never appearing, after the whole connect timeout.
356
+ */
357
+ function watchWindowsHelper(pid: number, errorFile: string): { promise: Promise<never>, stop: () => void } {
358
+ let timer: ReturnType<typeof setInterval> | undefined
359
+
360
+ const promise = new Promise<never>((_, reject) => {
361
+ timer = setInterval(() => {
362
+ if (isProcessRunning(pid))
363
+ return
364
+
365
+ clearInterval(timer)
366
+ let detail = ''
367
+ try {
368
+ detail = readFileSync(errorFile, 'utf8').trim().slice(-4096)
369
+ }
370
+ catch {}
371
+ reject(new Error(`privileged helper exited before accepting connections.${detail ? ` ${detail}` : ' No diagnostic output from the helper.'}`))
372
+ }, 250)
373
+ })
374
+
375
+ return {
376
+ promise,
377
+ stop() {
378
+ clearInterval(timer)
379
+ try {
380
+ rmSync(errorFile, { force: true })
381
+ }
382
+ catch {}
383
+ },
384
+ }
385
+ }
386
+
387
+ /**
388
+ * The elevated helper cannot be signalled from a non-elevated process, so
389
+ * `kill(pid, 0)` reports EPERM while it runs; only ESRCH means it is gone.
390
+ */
391
+ function isProcessRunning(pid: number): boolean {
392
+ try {
393
+ process.kill(pid, 0)
394
+ return true
395
+ }
396
+ catch (error) {
397
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH'
398
+ }
315
399
  }
316
400
 
317
401
  /** Reuses a helper that is already running for this runtime directory. */
@@ -0,0 +1,106 @@
1
+ import type { Stats } from 'node:fs'
2
+ import { lstatSync } from 'node:fs'
3
+ import process from 'node:process'
4
+
5
+ /**
6
+ * Why a path is refused before the helper runs it.
7
+ *
8
+ * The helper runs as root while the paths come from a process running as the
9
+ * developer. Anything that process, or any other local user, can rewrite after
10
+ * the check would become root-executed code or root-loaded config, so the
11
+ * checks below run once at startup and the result is trusted for the session.
12
+ */
13
+ export interface PathRejection {
14
+ path: string
15
+ reason: string
16
+ guidance: string
17
+ }
18
+
19
+ export interface PathCheckOptions {
20
+ /**
21
+ * uid allowed to own the path besides root.
22
+ *
23
+ * The helper entry itself lives in the developer's `node_modules`, so the
24
+ * invoking user has to be accepted for the paths that came from there.
25
+ */
26
+ ownerUid?: number
27
+ /** Human-readable role, used in the rejection message. */
28
+ label: string
29
+ }
30
+
31
+ function describe(stats: Stats): string {
32
+ return `uid=${stats.uid} mode=${(stats.mode & 0o777).toString(8)}`
33
+ }
34
+
35
+ /**
36
+ * Rejects a path the helper must not execute or load.
37
+ *
38
+ * Symbolic links are refused outright: the check has to describe the file that
39
+ * will actually be used, and a link can be repointed after the check. Group- or
40
+ * world-writable files are refused because any local user could replace them
41
+ * between the check and the exec.
42
+ */
43
+ export function checkPrivilegedPath(
44
+ path: string,
45
+ options: PathCheckOptions,
46
+ ): PathRejection | undefined {
47
+ let stats: Stats
48
+ try {
49
+ stats = lstatSync(path)
50
+ }
51
+ catch (error) {
52
+ return {
53
+ path,
54
+ reason: `${options.label} is not readable: ${(error as Error).message}`,
55
+ guidance: 'Check that this path exists and that you can access its parent directories. Fix access manually; do not make the path group- or world-writable.',
56
+ }
57
+ }
58
+
59
+ if (stats.isSymbolicLink()) {
60
+ return {
61
+ path,
62
+ reason: `${options.label} is a symbolic link (${describe(stats)})`,
63
+ guidance: 'Replace this symlink with a regular file manually or reinstall the affected file; do not bypass the safety check.',
64
+ }
65
+ }
66
+
67
+ if (!stats.isFile() && !stats.isDirectory()) {
68
+ return {
69
+ path,
70
+ reason: `${options.label} is neither a file nor a directory`,
71
+ guidance: 'Provide a regular file or directory at this path manually.',
72
+ }
73
+ }
74
+
75
+ // Windows has no uid or mode bits: Node reports uid 0 and mode 666 for every
76
+ // writable path, so these checks would refuse everything. Access there is
77
+ // decided by ACLs, and the runtime directory is the per-user `%TEMP%`.
78
+ if (process.platform === 'win32')
79
+ return undefined
80
+
81
+ const allowedOwner = stats.uid === 0 || (options.ownerUid !== undefined && stats.uid === options.ownerUid)
82
+ if (!allowedOwner) {
83
+ return {
84
+ path,
85
+ reason: `${options.label} is owned by another user (${describe(stats)})`,
86
+ guidance: 'Check ownership manually. This path must be owned by root or the user running the dev server.',
87
+ }
88
+ }
89
+
90
+ // Root's own files are fine at 644/755; the point is that no one else can
91
+ // write them.
92
+ if (stats.mode & 0o022) {
93
+ return {
94
+ path,
95
+ reason: `${options.label} is group- or world-writable (${describe(stats)})`,
96
+ guidance: 'Remove group and world write access manually; do not use chmod 777.',
97
+ }
98
+ }
99
+
100
+ return undefined
101
+ }
102
+
103
+ /** Formats a rejection for the helper log; one place keeps the wording stable. */
104
+ export function describeRejection(rejection: PathRejection): string {
105
+ return `refusing to start: ${rejection.reason} (${rejection.path}). ${rejection.guidance}`
106
+ }