centralu 0.1.0-beta.26 → 0.1.0-beta.28
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/bin/platform.mjs +10 -1
- package/bin/serve-args.mjs +97 -0
- package/bin/serve-autostart.mjs +358 -0
- package/bin/serve-detach.mjs +277 -0
- package/bin/serve-files.mjs +218 -0
- package/bin/serve-host.mjs +317 -0
- package/bin/serve-install.mjs +204 -0
- package/bin/serve-port.mjs +79 -0
- package/bin/serve-run.mjs +192 -0
- package/bin/serve-util.mjs +127 -0
- package/bin/serve-windows.mjs +156 -0
- package/bin/serve.mjs +18 -1833
- package/package.json +5 -5
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/** `centralu serve` in the foreground, `--connection` and `--rotate-token` */
|
|
2
|
+
import { spawn } from 'node:child_process'
|
|
3
|
+
import { writeFileSync, writeSync } from 'node:fs'
|
|
4
|
+
import { dirname, join } from 'node:path'
|
|
5
|
+
import { createInterface } from 'node:readline'
|
|
6
|
+
import { isAlive, say } from './serve-util.mjs'
|
|
7
|
+
import { SERVE_STATE_FILE, SERVE_PID_FILE, serveDataDir, ensureServeState, recordServePort, rotateServeToken, heldHere, lockHolderPid, removeServePid } from './serve-files.mjs'
|
|
8
|
+
import { DEFAULT_SERVE_PORT, SERVE_PORT_TRIES, chooseServePort, listensHere, windowsListening } from './serve-port.mjs'
|
|
9
|
+
import { keepLauncher, installInfo } from './serve-install.mjs'
|
|
10
|
+
import { protocolVersionOf, connectionLine, hostEnv, hostCommand, readyPort, hostProvesOf, probeHost, takesTokenOnStdin, tokenLine } from './serve-host.mjs'
|
|
11
|
+
import { autostartInfo } from './serve-autostart.mjs'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The data folder a command that may start or describe a host works in: its state, created on first use, and the
|
|
15
|
+
* launcher serve keeps there brought up to date (`keepLauncher`).
|
|
16
|
+
*/
|
|
17
|
+
export function serveFolder({ env, home, cliPath, platform = process.platform }) {
|
|
18
|
+
const dataDir = serveDataDir(env, home)
|
|
19
|
+
const state = ensureServeState(dataDir, platform)
|
|
20
|
+
keepLauncher(dataDir, cliPath, env)
|
|
21
|
+
return { dataDir, state }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** What `--connection` answers, as fields: the running host's versions when one answers, else the installed ones */
|
|
25
|
+
export async function describe({ env, dataDir, state, entry, version }) {
|
|
26
|
+
const port = state.port ?? DEFAULT_SERVE_PORT
|
|
27
|
+
const installed = protocolVersionOf(entry)
|
|
28
|
+
// Whether the installed host proves it holds the token (#838): asked of the running one before its hello, and said in the line
|
|
29
|
+
const proof = hostProvesOf(entry)
|
|
30
|
+
const probe = await probeHost({ port, token: state.token, protocolVersion: installed, prove: proof })
|
|
31
|
+
const protocolVersion = (probe.running ? probe.protocolVersion : undefined) ?? installed
|
|
32
|
+
if (protocolVersion === null) return null
|
|
33
|
+
return {
|
|
34
|
+
proof,
|
|
35
|
+
port,
|
|
36
|
+
token: state.token,
|
|
37
|
+
version: (probe.running ? probe.version : undefined) ?? version,
|
|
38
|
+
protocolVersion,
|
|
39
|
+
dataDir,
|
|
40
|
+
hostRunning: heldHere(probe, dataDir),
|
|
41
|
+
install: installInfo(dataDir, env),
|
|
42
|
+
autostart: autostartInfo(dataDir, process.platform, env),
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* `centralu serve --connection`. stdout carries exactly one line, the JSON; everything else goes to
|
|
48
|
+
* stderr. Exit 1 when there is no host to describe.
|
|
49
|
+
*/
|
|
50
|
+
export async function printConnection({ env, home, entry, version, cliPath }) {
|
|
51
|
+
const { dataDir, state } = serveFolder({ env, home, cliPath })
|
|
52
|
+
const d = await describe({ env, dataDir, state, entry, version })
|
|
53
|
+
if (!d) {
|
|
54
|
+
say(`cannot read the protocol version of the host at ${entry}`)
|
|
55
|
+
return 1
|
|
56
|
+
}
|
|
57
|
+
process.stdout.write(`${connectionLine(d)}\n`)
|
|
58
|
+
return 0
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* `centralu serve`. Resolves with the exit code once the host has exited.
|
|
63
|
+
*
|
|
64
|
+
* The host's stdout is read here and never passed on: its ready line carries the token, which is
|
|
65
|
+
* printed nowhere but `--connection`. Every other line the host writes to stdout (a lock conflict,
|
|
66
|
+
* a store from a newer build) it also writes to stderr, which is passed through untouched.
|
|
67
|
+
*
|
|
68
|
+
* `logFd` is serve.log of a detached launcher (`runDetachedChild`): the host's stderr goes there
|
|
69
|
+
* until it is ready, so a host that dies while starting (a native module that does not load, a store
|
|
70
|
+
* from a newer build) says why in a file `--detach` can quote. From then on host.log has every line,
|
|
71
|
+
* and serve.log stops growing.
|
|
72
|
+
*/
|
|
73
|
+
export async function runServe({ env, home, entry, version, cliPath, port: askedPort, platform = process.platform, execPath = process.execPath, logFd = null }) {
|
|
74
|
+
const { dataDir, state } = serveFolder({ env, home, cliPath, platform })
|
|
75
|
+
const protocolVersion = protocolVersionOf(entry)
|
|
76
|
+
|
|
77
|
+
// A serve that is already up answers on the port it recorded; say so before starting a host that
|
|
78
|
+
// would only fail on the data folder's lock with a less specific message.
|
|
79
|
+
const recorded = state.port ?? DEFAULT_SERVE_PORT
|
|
80
|
+
const existing = await probeHost({ port: recorded, token: state.token, protocolVersion, prove: hostProvesOf(entry) })
|
|
81
|
+
if (heldHere(existing, dataDir)) {
|
|
82
|
+
const pid = lockHolderPid(dataDir)
|
|
83
|
+
say(`centralu serve is already running for ${dataDir} on 127.0.0.1:${recorded}${pid ? ` (pid ${pid})` : ''}. Not starting a second one.`)
|
|
84
|
+
return 1
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const onWindows = await windowsListening(env, platform)
|
|
88
|
+
const chosen = await chooseServePort({ asked: askedPort, recorded: state.port, taken: async (p) => onWindows.has(p) || (await listensHere(p)) })
|
|
89
|
+
if (chosen === null) {
|
|
90
|
+
say(`another program listens on 127.0.0.1:${recorded} and on the ${SERVE_PORT_TRIES - 1} ports above it. Give a free one with --port <n>.`)
|
|
91
|
+
return 1
|
|
92
|
+
}
|
|
93
|
+
const port = chosen.port
|
|
94
|
+
if (chosen.from !== null) {
|
|
95
|
+
const who = onWindows.has(chosen.from) ? 'Windows' : 'another program'
|
|
96
|
+
say(`127.0.0.1:${chosen.from} is in use by ${who}; starting on ${port} instead (kept for the next start)`)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const plan = hostCommand(execPath, entry, { port, dataDir, platform })
|
|
100
|
+
const onStdin = takesTokenOnStdin(entry)
|
|
101
|
+
const child = spawn(plan.command, plan.args, {
|
|
102
|
+
stdio: ['pipe', 'pipe', logFd === null ? 'inherit' : 'pipe'],
|
|
103
|
+
env: hostEnv(env, { dataDir, version, hostDir: dirname(entry), ...(onStdin ? {} : { legacyToken: state.token }) }),
|
|
104
|
+
detached: plan.detached,
|
|
105
|
+
windowsHide: true,
|
|
106
|
+
})
|
|
107
|
+
// The token, before anything else on the pipe the host watches (#538); stdin stays open for --watch-parent
|
|
108
|
+
if (onStdin) child.stdin.write(tokenLine(state.token))
|
|
109
|
+
|
|
110
|
+
let ready = false
|
|
111
|
+
if (logFd !== null) {
|
|
112
|
+
// Read to the end in any case: a pipe nobody drains stops the host once its buffer is full
|
|
113
|
+
child.stderr.on('data', (b) => {
|
|
114
|
+
if (ready) return
|
|
115
|
+
try {
|
|
116
|
+
writeSync(logFd, b)
|
|
117
|
+
} catch {
|
|
118
|
+
// the log is a convenience
|
|
119
|
+
}
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
if (child.pid) {
|
|
123
|
+
try {
|
|
124
|
+
writeFileSync(join(dataDir, SERVE_PID_FILE), `${JSON.stringify({ pid: process.pid, hostPid: child.pid, port })}\n`)
|
|
125
|
+
} catch (e) {
|
|
126
|
+
say(`could not write ${SERVE_PID_FILE}: ${e.message}`)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
createInterface({ input: child.stdout }).on('line', (line) => {
|
|
130
|
+
const p = readyPort(line)
|
|
131
|
+
if (p === null || ready) return
|
|
132
|
+
ready = true
|
|
133
|
+
try {
|
|
134
|
+
recordServePort(dataDir, p, platform)
|
|
135
|
+
} catch (e) {
|
|
136
|
+
say(`could not record the port in ${join(dataDir, SERVE_STATE_FILE)}: ${e.message}`)
|
|
137
|
+
}
|
|
138
|
+
say(`listening on 127.0.0.1:${p} (Centralu ${version}, protocol ${protocolVersion ?? 'unknown'}, data ${dataDir})`)
|
|
139
|
+
if (logFd === null) say(`from your computer: ssh -N -L ${p}:127.0.0.1:${p} <this machine>, or let the app connect over SSH`)
|
|
140
|
+
else say(`the host's own log continues in ${join(dataDir, 'host.log')}`)
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
/*
|
|
144
|
+
* One signal to the host alone, whatever reached this launcher. SIGHUP (the terminal closed) is
|
|
145
|
+
* passed as SIGTERM: the host has no SIGHUP handler, and Node's default for it is to exit on the
|
|
146
|
+
* spot, skipping the shutdown that stops the agents. A second signal changes nothing on the host
|
|
147
|
+
* side (its shutdown runs once), so forwarding every one is safe.
|
|
148
|
+
*/
|
|
149
|
+
const forward = (sig) => {
|
|
150
|
+
if (child.exitCode !== null || child.signalCode !== null) return
|
|
151
|
+
if (platform === 'win32') return // the host shares the console and received Ctrl+C itself
|
|
152
|
+
try {
|
|
153
|
+
child.kill(sig === 'SIGHUP' ? 'SIGTERM' : sig)
|
|
154
|
+
} catch {
|
|
155
|
+
// already gone
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const signals = platform === 'win32' ? ['SIGINT'] : ['SIGINT', 'SIGTERM', 'SIGHUP']
|
|
159
|
+
for (const s of signals) process.on(s, forward)
|
|
160
|
+
|
|
161
|
+
return await new Promise((resolve) => {
|
|
162
|
+
child.on('error', (e) => {
|
|
163
|
+
removeServePid(dataDir, process.pid)
|
|
164
|
+
say(`could not start the host (${plan.command}): ${e.message}`)
|
|
165
|
+
resolve(1)
|
|
166
|
+
})
|
|
167
|
+
child.on('exit', (code, signal) => {
|
|
168
|
+
for (const s of signals) process.off(s, forward)
|
|
169
|
+
removeServePid(dataDir, process.pid)
|
|
170
|
+
if (!ready && code !== 0) {
|
|
171
|
+
const pid = lockHolderPid(dataDir)
|
|
172
|
+
if (pid && pid !== child.pid && isAlive(pid)) {
|
|
173
|
+
say(
|
|
174
|
+
`the host did not start. ${dataDir} belongs to another Centralu host (pid ${pid}), ` +
|
|
175
|
+
'probably the Centralu app on this machine. Quit it, or point CC_DATA_DIR at another folder.',
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (logFd !== null) say(`the host exited (${signal ?? code})`)
|
|
180
|
+
resolve(code ?? (signal ? 1 : 0))
|
|
181
|
+
})
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** `centralu serve --rotate-token` */
|
|
186
|
+
export function rotateToken({ env, home }) {
|
|
187
|
+
const dataDir = serveDataDir(env, home)
|
|
188
|
+
rotateServeToken(dataDir)
|
|
189
|
+
say(`replaced the token in ${join(dataDir, SERVE_STATE_FILE)}.`)
|
|
190
|
+
say('A serve that is running keeps the old one until it restarts; clients read the new one with --connection.')
|
|
191
|
+
return 0
|
|
192
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small helpers every `centralu serve` command uses: the log line (`say`), running a program for its
|
|
3
|
+
* output, a process check, and waiting.
|
|
4
|
+
*/
|
|
5
|
+
import { spawn } from 'node:child_process'
|
|
6
|
+
import { closeSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { renameWaitsForReaders } from './platform.mjs'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Where `say` writes: stderr, except in a detached launcher, which nobody reads the stderr of and
|
|
11
|
+
* which writes serve.log instead (`runDetachedChild`).
|
|
12
|
+
*/
|
|
13
|
+
let sink = (text) => process.stderr.write(text)
|
|
14
|
+
|
|
15
|
+
/** Writes a line to stderr, prefixed so it reads apart from the host's own log lines */
|
|
16
|
+
export function say(line) {
|
|
17
|
+
sink(`[centralu serve] ${line}\n`)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The one line `--detach`, `--stop` and `--autostart` answer with on stdout, `{ v: 1, [key]: value }`, its `message` said
|
|
22
|
+
* on stderr as well. Returns the exit code: 0 when `value.ok`, else 1.
|
|
23
|
+
*/
|
|
24
|
+
export function answerLine(write, key, value) {
|
|
25
|
+
if (value.message) say(value.message)
|
|
26
|
+
write(`${JSON.stringify({ v: 1, [key]: value })}\n`)
|
|
27
|
+
return value.ok ? 0 : 1
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Points `say` at `write` from here on (a detached launcher's serve.log) */
|
|
31
|
+
export function sayTo(write) {
|
|
32
|
+
sink = write
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Blocks this thread for `ms`, for the synchronous callers that cannot await (a rename that is retried) */
|
|
36
|
+
export function sleepSync(ms) {
|
|
37
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What a rename over a file says on Windows while another handle has the target open (a reader, a virus scanner) */
|
|
41
|
+
const BUSY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES'])
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* `rename`, tried again for up to `budgetMs` while the system refuses it because someone has the target open (#1041;
|
|
45
|
+
* `retry`: Windows only, `renameWaitsForReaders`). With `retry` off, and for any other error, it is one try. Backs off 10, 20, 40 ... 200 ms between tries; the last
|
|
46
|
+
* error is thrown when the budget is spent.
|
|
47
|
+
*/
|
|
48
|
+
export function renameRetrying(from, to, { retry = renameWaitsForReaders(), rename = renameSync, sleep = sleepSync, budgetMs = 5_000, now = Date.now } = {}) {
|
|
49
|
+
const t0 = now()
|
|
50
|
+
for (let delay = 10; ; delay = Math.min(delay * 2, 200)) {
|
|
51
|
+
try {
|
|
52
|
+
return rename(from, to)
|
|
53
|
+
} catch (e) {
|
|
54
|
+
if (!retry || !BUSY_CODES.has(e?.code) || now() - t0 + delay > budgetMs) throw e
|
|
55
|
+
}
|
|
56
|
+
sleep(delay)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Replaces `file` with `text` at once: written to a temporary file beside it, then renamed over it, so a reader finds
|
|
62
|
+
* the old file or the new one and never half of one. `mode` and `flag` are the temporary file's: a private file is
|
|
63
|
+
* created with its mode from the first byte, and with `wx`, never written into a file that is already there.
|
|
64
|
+
* On Windows a rename fails while a reader has the target open, so it is retried (`renameRetrying`); when it still
|
|
65
|
+
* fails, the temporary file is removed and the error thrown, the old file untouched.
|
|
66
|
+
*/
|
|
67
|
+
export function replaceFile(file, text, { mode = 0o666, flag = 'w', ...rename } = {}) {
|
|
68
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
69
|
+
const fd = openSync(tmp, flag, mode)
|
|
70
|
+
try {
|
|
71
|
+
writeFileSync(fd, text)
|
|
72
|
+
} finally {
|
|
73
|
+
closeSync(fd)
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
renameRetrying(tmp, file, rename)
|
|
77
|
+
} catch (e) {
|
|
78
|
+
rmSync(tmp, { force: true })
|
|
79
|
+
throw e
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function runCaptured(command, args, env) {
|
|
84
|
+
return new Promise((resolve) => {
|
|
85
|
+
let stdout = ''
|
|
86
|
+
let stderr = ''
|
|
87
|
+
let child
|
|
88
|
+
try {
|
|
89
|
+
child = spawn(command, args, { env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
|
|
90
|
+
} catch (e) {
|
|
91
|
+
return resolve({ code: null, stdout, stderr: e.message })
|
|
92
|
+
}
|
|
93
|
+
child.stdout.on('data', (b) => (stdout += String(b)))
|
|
94
|
+
child.stderr.on('data', (b) => (stderr += String(b)))
|
|
95
|
+
child.once('error', (e) => resolve({ code: null, stdout, stderr: e.message }))
|
|
96
|
+
child.once('close', (code) => resolve({ code, stdout, stderr }))
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The last lines of a file, for a reason; empty when it cannot be read */
|
|
101
|
+
export function tail(file, n = 15) {
|
|
102
|
+
try {
|
|
103
|
+
return readFileSync(file, 'utf8').trimEnd().split(/\r?\n/).slice(-n).join('\n')
|
|
104
|
+
} catch {
|
|
105
|
+
return ''
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
110
|
+
|
|
111
|
+
export async function waitUntil(pred, ms) {
|
|
112
|
+
const t0 = Date.now()
|
|
113
|
+
while (Date.now() - t0 < ms) {
|
|
114
|
+
if (await pred()) return true
|
|
115
|
+
await sleep(200)
|
|
116
|
+
}
|
|
117
|
+
return pred()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function isAlive(pid) {
|
|
121
|
+
try {
|
|
122
|
+
process.kill(pid, 0)
|
|
123
|
+
return true
|
|
124
|
+
} catch (e) {
|
|
125
|
+
return e?.code === 'EPERM'
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows and WSL for `centralu serve`: which way a start outlives the ssh session, a Windows command
|
|
3
|
+
* line, the PowerShell that asks WMI to create a process, and the Windows programs reached by full path
|
|
4
|
+
* (from Windows itself, or through the drive a WSL distro mounts).
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
7
|
+
import { systemRoot } from './platform.mjs'
|
|
8
|
+
import { runCaptured } from './serve-util.mjs'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* How `--detach` starts the launcher so that it outlives the session that asked (measured,
|
|
12
|
+
* docs/plans/remote-hub.md §10.4):
|
|
13
|
+
*
|
|
14
|
+
* setsid posix: a new session, no terminal, nothing from the ssh session's process group. Once
|
|
15
|
+
* `--detach` returns, the launcher is reparented to init (the second fork of the usual
|
|
16
|
+
* double fork); it opens no terminal, so it can never get a controlling one back
|
|
17
|
+
* wmi Windows: `Win32_Process.Create`. Windows' OpenSSH ends every process of a session with
|
|
18
|
+
* it, `Start-Process` included; a process WMI creates is not part of the session
|
|
19
|
+
* wsl inside WSL: the same WMI call from the Windows side, creating `wsl.exe -d <distro>
|
|
20
|
+
* --exec <launcher>`. A `setsid` launcher inside the distro survives the session but not the
|
|
21
|
+
* distro, which WSL stops about 15 s after its last `wsl.exe` client exits; this
|
|
22
|
+
* `wsl.exe` is a client for as long as the host runs, and ending it ends the host
|
|
23
|
+
*/
|
|
24
|
+
export function detachHow(platform, env, interop = wslInterop) {
|
|
25
|
+
if (platform === 'win32') return 'wmi'
|
|
26
|
+
if (platform === 'linux' && env.WSL_DISTRO_NAME && interop()) return 'wsl'
|
|
27
|
+
return 'setsid'
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function wslInterop() {
|
|
31
|
+
return existsSync('/proc/sys/fs/binfmt_misc/WSLInterop') || existsSync('/proc/sys/fs/binfmt_misc/WSLInterop-late')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A WSL distro's name for `wsl.exe -d`, refused when it could be read as anything else */
|
|
35
|
+
export function wslDistro(distro) {
|
|
36
|
+
if (!/^[A-Za-z0-9._-]{1,64}$/.test(distro ?? '')) throw new Error(`not a WSL distro name: ${distro}`)
|
|
37
|
+
return distro
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A Linux user's name for `wsl.exe -u`, refused when it could be read as anything else */
|
|
41
|
+
export function wslUser(user) {
|
|
42
|
+
if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/.test(user ?? '')) throw new Error(`cannot name the user ${user} to wsl.exe`)
|
|
43
|
+
return user
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* One argument for a Windows command line, as `CommandLineToArgvW` and the C runtime read it: always
|
|
48
|
+
* quoted, backslashes before the closing quote doubled. A double quote or a line break cannot be a
|
|
49
|
+
* path on Windows and is refused rather than escaped.
|
|
50
|
+
*/
|
|
51
|
+
export function windowsArg(arg) {
|
|
52
|
+
const s = String(arg)
|
|
53
|
+
if (/["\r\n\0]/.test(s)) throw new Error(`cannot pass ${JSON.stringify(s)} on a Windows command line`)
|
|
54
|
+
return `"${s.replace(/(\\+)$/, '$1$1')}"`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The first line of a script run by Windows PowerShell 5.1: its own module path. Started from
|
|
59
|
+
* PowerShell 7 (pwsh, a `DefaultShell` of it, a CI runner), 5.1 inherits pwsh's `PSModulePath`, whose
|
|
60
|
+
* first folder holds 7.x copies of the built-in modules that 5.1 cannot load: `Invoke-CimMethod` and
|
|
61
|
+
* `Get-ScheduledTask` are then "found in the module … but the module could not be loaded". Same line as
|
|
62
|
+
* the hub's (links/tunnel.ts, `PS_PREAMBLE`)
|
|
63
|
+
*/
|
|
64
|
+
export const PS_MODULE_PATH = "if ($env:PSModulePath -match '\\x5cPowerShell\\x5c') { $env:PSModulePath = \"$env:ProgramFiles\\WindowsPowerShell\\Modules;$PSHOME\\Modules\" }"
|
|
65
|
+
|
|
66
|
+
/** A PowerShell expression for `s`: base64 decoded there, so no quote reaches PowerShell's parser */
|
|
67
|
+
export function psText(s) {
|
|
68
|
+
return `([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(String(s), 'utf8').toString('base64')}')))`
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The PowerShell that asks WMI to create `commandLine`. Values cross as base64, so no quoting can break */
|
|
72
|
+
export function wmiScript({ commandLine, cwd = null }) {
|
|
73
|
+
return [
|
|
74
|
+
"$ErrorActionPreference = 'Stop'",
|
|
75
|
+
PS_MODULE_PATH,
|
|
76
|
+
'[Console]::OutputEncoding = [Text.Encoding]::UTF8',
|
|
77
|
+
`$a = @{ CommandLine = ${psText(commandLine)} }`,
|
|
78
|
+
...(cwd ? [`$a.CurrentDirectory = ${psText(cwd)}`] : []),
|
|
79
|
+
// No console window when this runs from a desktop session; left out where it cannot be built
|
|
80
|
+
'try { $a.ProcessStartupInformation = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0 } } catch { }',
|
|
81
|
+
'try {',
|
|
82
|
+
' $r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments $a',
|
|
83
|
+
" if ($r.ReturnValue -eq 21 -and $a.ContainsKey('ProcessStartupInformation')) { $a.Remove('ProcessStartupInformation'); $r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments $a }",
|
|
84
|
+
' "CENTRALU-WMI $($r.ReturnValue) $($r.ProcessId)"',
|
|
85
|
+
'} catch { "CENTRALU-WMI-ERROR $($_.Exception.Message)" }',
|
|
86
|
+
].join('\n')
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** `Win32_Process.Create`'s return values (Microsoft's documentation of the method) */
|
|
90
|
+
const WMI_CODES = { 2: 'access denied', 3: 'insufficient privilege', 8: 'unknown failure', 9: 'path not found', 21: 'invalid parameter' }
|
|
91
|
+
|
|
92
|
+
/** What the WMI script said: `{ ok: true, pid }` or `{ ok: false, message }` */
|
|
93
|
+
export function parseWmiAnswer(stdout) {
|
|
94
|
+
const text = String(stdout ?? '')
|
|
95
|
+
const m = /CENTRALU-WMI (\d+) (\d*)/.exec(text)
|
|
96
|
+
if (m) {
|
|
97
|
+
const rv = Number(m[1])
|
|
98
|
+
if (rv === 0 && Number(m[2]) > 0) return { ok: true, pid: Number(m[2]) }
|
|
99
|
+
return { ok: false, message: `WMI's Win32_Process.Create returned ${rv}${WMI_CODES[rv] ? ` (${WMI_CODES[rv]})` : ''}` }
|
|
100
|
+
}
|
|
101
|
+
const e = /CENTRALU-WMI-ERROR (.*)/.exec(text)
|
|
102
|
+
if (e) return { ok: false, message: `WMI refused to create the process: ${e[1].trim()}` }
|
|
103
|
+
return { ok: false, message: 'PowerShell did not answer the WMI request' }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The sentence for a start WMI did not make. Some managed machines block process creation through
|
|
108
|
+
* WMI (Microsoft Defender's attack surface reduction rule "Block process creations originating from
|
|
109
|
+
* PSExec and WMI commands", off by default); the hub then runs the host bound to its link
|
|
110
|
+
* (docs/plans/remote-hub.md §10.9, decision 3).
|
|
111
|
+
*/
|
|
112
|
+
export function wmiBlockedMessage(detail) {
|
|
113
|
+
return (
|
|
114
|
+
`Windows did not start Centralu through WMI (${detail}). Some managed Windows machines block it ` +
|
|
115
|
+
'(Microsoft Defender\'s attack surface reduction rule "Block process creations originating from PSExec and WMI commands"). ' +
|
|
116
|
+
'Centralu can run there while this computer is linked instead, and stops when the link does.'
|
|
117
|
+
)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Windows PowerShell 5.1, by full path: under %SystemRoot% on Windows, through the drive WSL mounts inside a distro */
|
|
121
|
+
export function windowsPowershell(how, env, mounts) {
|
|
122
|
+
return windowsTool(how, env, ['System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'], mounts)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A program under the Windows folder, by full path, from Windows or from inside a WSL distro; null when unreachable */
|
|
126
|
+
export function windowsTool(how, env, rel, mounts = () => readFileSync('/proc/mounts', 'utf8')) {
|
|
127
|
+
if (how === 'wmi') return [systemRoot(env), ...rel].join('\\')
|
|
128
|
+
let text = ''
|
|
129
|
+
try {
|
|
130
|
+
text = mounts()
|
|
131
|
+
} catch {
|
|
132
|
+
// no /proc: not WSL after all
|
|
133
|
+
}
|
|
134
|
+
for (const line of text.split('\n')) {
|
|
135
|
+
const [, at, type] = line.split(' ')
|
|
136
|
+
if (!at || !(type === '9p' || type === 'drvfs')) continue
|
|
137
|
+
const candidate = [at, 'Windows', ...rel].join('/')
|
|
138
|
+
if (existsSync(candidate)) return candidate
|
|
139
|
+
}
|
|
140
|
+
return null
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** A script as `-EncodedCommand` takes it: UTF-16LE, in base64 */
|
|
144
|
+
export function encodedCommand(script) {
|
|
145
|
+
return Buffer.from(script, 'utf16le').toString('base64')
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Runs `script` in the Windows PowerShell at `ps` and reads what it printed with `parse` (`{ ok, … }`). When it printed
|
|
150
|
+
* nothing and PowerShell itself complained (a policy, a module it could not load), the answer is the last line of that.
|
|
151
|
+
*/
|
|
152
|
+
export async function askPowershell(ps, script, env, parse, run = runCaptured) {
|
|
153
|
+
const r = await run(ps, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encodedCommand(script)], env)
|
|
154
|
+
const a = parse(r.stdout)
|
|
155
|
+
return a.ok || r.stdout.trim() || !r.stderr.trim() ? a : { ok: false, message: r.stderr.trim().split(/\r?\n/).at(-1) }
|
|
156
|
+
}
|