unplugin-https-reverse-proxy 4.1.0-beta.8 → 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.
- package/README.md +2 -2
- package/dist/{chunk-ICH7VY4H.js → chunk-U6J2RMIR.js} +211 -109
- package/dist/esbuild.cjs +223 -121
- package/dist/esbuild.js +1 -1
- package/dist/index.cjs +223 -121
- package/dist/index.js +1 -1
- package/dist/nuxt.cjs +221 -121
- package/dist/nuxt.js +1 -1
- package/dist/privileged-helper.cjs +154 -56
- package/dist/privileged-helper.js +144 -46
- package/dist/rollup.cjs +223 -121
- package/dist/rollup.js +1 -1
- package/dist/rspack.cjs +223 -121
- package/dist/rspack.js +1 -1
- package/dist/vite.cjs +223 -121
- package/dist/vite.js +1 -1
- package/dist/webpack.cjs +223 -121
- package/dist/webpack.js +1 -1
- package/package.json +1 -1
- package/src/caddy/caddyfile.ts +2 -0
- package/src/caddy/config.ts +57 -34
- package/src/caddy/constants.ts +30 -1
- package/src/caddy/index.ts +44 -49
- package/src/caddy/privileged.ts +3 -0
- package/src/index.ts +5 -0
- package/src/privileged/bootstrap.ts +27 -7
- package/src/privileged/client.ts +1 -1
- package/src/privileged/launch.ts +95 -11
- package/src/privileged/path-guard.ts +106 -0
- package/src/privileged/server.ts +36 -4
- package/src/privileged/session.ts +3 -0
- package/src/privileged/windows-elevation.ts +91 -33
- package/src/privileged-helper.ts +49 -9
package/src/caddy/config.ts
CHANGED
|
@@ -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(
|
|
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(
|
|
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,72 +77,95 @@ 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 = `${
|
|
82
|
+
const temp = `${path}.${process.pid}.tmp`
|
|
83
83
|
writeFileSync(temp, content)
|
|
84
|
-
renameSync(temp,
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** Applies `mutate` under the file lock, re-reading the latest state first. */
|
|
88
|
-
async function mutateConfig(
|
|
89
|
-
lock: ConfigLock,
|
|
90
|
-
mutate: (proxies: ProxyMap) => void,
|
|
91
|
-
): Promise<ProxyMap> {
|
|
92
|
-
const release = await lock.acquire()
|
|
93
|
-
try {
|
|
94
|
-
const proxies = readConfig()
|
|
95
|
-
mutate(proxies)
|
|
96
|
-
writeConfig(proxies)
|
|
97
|
-
return proxies
|
|
98
|
-
}
|
|
99
|
-
finally {
|
|
100
|
-
release()
|
|
101
|
-
}
|
|
84
|
+
renameSync(temp, path)
|
|
102
85
|
}
|
|
103
86
|
|
|
104
87
|
export interface CaddyConfigOptions {
|
|
105
88
|
/** Injected in tests so they do not need the real lock. */
|
|
106
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
|
|
97
|
+
/**
|
|
98
|
+
* Renders the Caddyfile from the routes, called inside the config lock.
|
|
99
|
+
*
|
|
100
|
+
* Rendering here rather than in the caller is what keeps the file in step
|
|
101
|
+
* with the JSON: two projects writing concurrently would otherwise render
|
|
102
|
+
* from their own stale view and the later write would win.
|
|
103
|
+
*/
|
|
104
|
+
renderCaddyfile?: (proxies: ProxyMap) => Promise<void>
|
|
107
105
|
}
|
|
108
106
|
|
|
109
107
|
export function useCaddyConfig(options: CaddyConfigOptions = {}): CaddyConfigApi {
|
|
110
108
|
const lock = options.lock ?? createFileLock()
|
|
109
|
+
const configPath = options.configPath ?? caddyConfigPath
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Applies the change, then re-renders while still holding the lock.
|
|
113
|
+
*
|
|
114
|
+
* The Caddyfile has to follow every change: leaving a stopped project's site
|
|
115
|
+
* in it would keep proxying to an upstream that is gone. Doing it inside the
|
|
116
|
+
* lock also picks up routes whose owner process died, since `readConfig`
|
|
117
|
+
* drops those.
|
|
118
|
+
*/
|
|
119
|
+
async function mutate(
|
|
120
|
+
apply: (proxies: ProxyMap) => void,
|
|
121
|
+
): Promise<ProxyMap> {
|
|
122
|
+
const release = await lock.acquire()
|
|
123
|
+
try {
|
|
124
|
+
const proxies = readConfig(configPath)
|
|
125
|
+
apply(proxies)
|
|
126
|
+
writeConfig(proxies, configPath)
|
|
127
|
+
await options.renderCaddyfile?.(proxies)
|
|
128
|
+
return proxies
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
release()
|
|
132
|
+
}
|
|
133
|
+
}
|
|
111
134
|
|
|
112
135
|
return {
|
|
113
|
-
configJsonRef: () => (existsSync(
|
|
136
|
+
configJsonRef: () => (existsSync(configPath) ? readConfig(configPath) : undefined),
|
|
114
137
|
|
|
115
138
|
async writeCaddyConfig(_proxies, key) {
|
|
116
|
-
await
|
|
139
|
+
await mutate((proxies) => {
|
|
117
140
|
for (const p of _proxies)
|
|
118
141
|
proxies[routeKey(p, key)] = { ...p, base: normalizeBase(p.base), ownerPid: process.pid }
|
|
119
142
|
})
|
|
120
143
|
},
|
|
121
144
|
|
|
122
145
|
async removeProxy(key) {
|
|
123
|
-
|
|
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) => {
|
|
124
150
|
for (const route of Object.keys(current)) {
|
|
125
151
|
if (route.endsWith(`#${key}`))
|
|
126
152
|
delete current[route]
|
|
127
153
|
}
|
|
128
154
|
})
|
|
129
|
-
|
|
130
|
-
if (Object.keys(proxies).length === 0)
|
|
131
|
-
removeConfigFile()
|
|
132
155
|
},
|
|
133
156
|
|
|
134
|
-
readProxies: () => readConfig(),
|
|
157
|
+
readProxies: () => readConfig(configPath),
|
|
135
158
|
|
|
136
159
|
async cleanUp() {
|
|
137
|
-
removeConfigFile()
|
|
160
|
+
removeConfigFile(configPath)
|
|
138
161
|
},
|
|
139
162
|
}
|
|
140
163
|
}
|
|
141
164
|
|
|
142
|
-
function removeConfigFile(): void {
|
|
165
|
+
function removeConfigFile(path: string = caddyConfigPath): void {
|
|
143
166
|
try {
|
|
144
|
-
if (existsSync(
|
|
145
|
-
unlinkSync(
|
|
167
|
+
if (existsSync(path))
|
|
168
|
+
unlinkSync(path)
|
|
146
169
|
}
|
|
147
170
|
catch {}
|
|
148
171
|
}
|
package/src/caddy/constants.ts
CHANGED
|
@@ -13,13 +13,42 @@ function resolvePath(path: string): string {
|
|
|
13
13
|
return path
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
|
|
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',
|
package/src/caddy/index.ts
CHANGED
|
@@ -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'
|
|
@@ -106,11 +106,44 @@ interface RunOptions {
|
|
|
106
106
|
healthCheck?: boolean
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/** Where Caddy keeps the local CA; the template serves it for device installs. */
|
|
110
|
+
function caddyRootPath(): string {
|
|
111
|
+
return join(
|
|
112
|
+
process.platform === 'win32'
|
|
113
|
+
? `${process.env.AppData!}/Caddy`
|
|
114
|
+
: `${process.env.HOME!}/Library/Application Support/Caddy`,
|
|
115
|
+
'./pki/authorities/local',
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Renders the Caddyfile from the routes currently on disk and writes it.
|
|
121
|
+
*
|
|
122
|
+
* Called from inside the config lock, so two projects writing at once cannot
|
|
123
|
+
* render from their own stale view of the routes.
|
|
124
|
+
*/
|
|
125
|
+
async function renderCaddyfile(proxies: Record<string, unknown>): Promise<void> {
|
|
126
|
+
const ctx = validateTemplateContext({
|
|
127
|
+
caddy_root: caddyRootPath(),
|
|
128
|
+
admin_socket: caddyAdminSocketPath,
|
|
129
|
+
proxies: Object.values(proxies) as never,
|
|
130
|
+
})
|
|
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)
|
|
140
|
+
}
|
|
141
|
+
|
|
109
142
|
let caddyConfig: ReturnType<typeof useCaddyConfig> | undefined
|
|
110
143
|
|
|
111
144
|
function getCaddyConfig(): ReturnType<typeof useCaddyConfig> {
|
|
112
145
|
if (!caddyConfig) {
|
|
113
|
-
caddyConfig = useCaddyConfig()
|
|
146
|
+
caddyConfig = useCaddyConfig({ renderCaddyfile: renderCaddyfile as never })
|
|
114
147
|
}
|
|
115
148
|
return caddyConfig
|
|
116
149
|
}
|
|
@@ -142,6 +175,7 @@ const defaultDependencies: CaddyDependencies = {
|
|
|
142
175
|
// helper must never execute something named in a request.
|
|
143
176
|
caddyBin: caddyPath,
|
|
144
177
|
caddyConfigPath: caddyFilePath,
|
|
178
|
+
caddyAdminSocket: caddyAdminSocketPath,
|
|
145
179
|
reason,
|
|
146
180
|
}),
|
|
147
181
|
config: () => getCaddyConfig(),
|
|
@@ -178,8 +212,10 @@ export class CaddyInstant {
|
|
|
178
212
|
if (this._session && !this._session.client.connected)
|
|
179
213
|
this._session = undefined
|
|
180
214
|
|
|
181
|
-
if (!this._session)
|
|
215
|
+
if (!this._session) {
|
|
216
|
+
await this.deps.config().writeCaddyConfig([], this.proxyKey)
|
|
182
217
|
this._session = await this.deps.openSession(TEMP_DIR, reason)
|
|
218
|
+
}
|
|
183
219
|
return this._session
|
|
184
220
|
}
|
|
185
221
|
|
|
@@ -194,12 +230,7 @@ export class CaddyInstant {
|
|
|
194
230
|
}
|
|
195
231
|
|
|
196
232
|
get caddyRoot(): string {
|
|
197
|
-
return
|
|
198
|
-
process.platform === 'win32'
|
|
199
|
-
? `${process.env.AppData!}/Caddy`
|
|
200
|
-
: `${process.env.HOME!}/Library/Application Support/Caddy`,
|
|
201
|
-
'./pki/authorities/local',
|
|
202
|
-
)
|
|
233
|
+
return caddyRootPath()
|
|
203
234
|
}
|
|
204
235
|
|
|
205
236
|
async writeCaddyfile(): Promise<void> {
|
|
@@ -249,43 +280,6 @@ export class CaddyInstant {
|
|
|
249
280
|
throw new Error(formatTlsHealthFailure(targetHost, health))
|
|
250
281
|
}
|
|
251
282
|
|
|
252
|
-
/**
|
|
253
|
-
* Regenerates the Caddyfile from the config on disk.
|
|
254
|
-
*
|
|
255
|
-
* Reading the file rather than a cached view matters here: another project
|
|
256
|
-
* may have added its route since this instance last looked.
|
|
257
|
-
*/
|
|
258
|
-
private async updateCaddyfile(): Promise<void> {
|
|
259
|
-
const { readProxies } = this.deps.config()
|
|
260
|
-
const proxies = Object.values(readProxies())
|
|
261
|
-
const ctx = validateTemplateContext({
|
|
262
|
-
caddy_root: this.caddyRoot,
|
|
263
|
-
proxies,
|
|
264
|
-
})
|
|
265
|
-
|
|
266
|
-
this.caddyfile = await genCaddyfile(ctx)
|
|
267
|
-
await this.writeCaddyfile()
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
private async stopCaddy(): Promise<void> {
|
|
271
|
-
try {
|
|
272
|
-
await got.post('http://127.0.0.1:2019/stop', {
|
|
273
|
-
headers: {
|
|
274
|
-
Origin: 'http://localhost:2019',
|
|
275
|
-
},
|
|
276
|
-
retry: {
|
|
277
|
-
limit: 0,
|
|
278
|
-
},
|
|
279
|
-
timeout: {
|
|
280
|
-
request: 2000,
|
|
281
|
-
},
|
|
282
|
-
})
|
|
283
|
-
}
|
|
284
|
-
catch {}
|
|
285
|
-
|
|
286
|
-
this._caddyChild?.kill()
|
|
287
|
-
}
|
|
288
|
-
|
|
289
283
|
/**
|
|
290
284
|
* @param source like `127.0.0.1:8080`
|
|
291
285
|
* @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
|
|
@@ -337,11 +331,12 @@ export class CaddyInstant {
|
|
|
337
331
|
},
|
|
338
332
|
]
|
|
339
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.
|
|
340
337
|
const { writeCaddyConfig } = this.deps.config()
|
|
341
338
|
await writeCaddyConfig(proxies, this.proxyKey)
|
|
342
339
|
|
|
343
|
-
await this.updateCaddyfile()
|
|
344
|
-
|
|
345
340
|
// Ports 80/443 may still be held by a previous, uncleanly stopped run.
|
|
346
341
|
// The helper skips its own Caddy, so this never kills a proxy another
|
|
347
342
|
// project is already using.
|
package/src/caddy/privileged.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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
|
}
|
package/src/privileged/client.ts
CHANGED
|
@@ -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))
|
package/src/privileged/launch.ts
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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
|
-
|
|
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 =>
|
|
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
|
-
//
|
|
284
|
-
//
|
|
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
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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
|
|
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. */
|