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,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host `centralu serve` runs: how it is started, and talking to a running one over its own socket
|
|
3
|
+
* (a hello with the token, a proof first where the host gives one, `host.stop`).
|
|
4
|
+
*/
|
|
5
|
+
import { createHmac, randomBytes } from 'node:crypto'
|
|
6
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
7
|
+
import { connect } from 'node:net'
|
|
8
|
+
import { dirname, join } from 'node:path'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The protocol a host folder speaks, from the `bundle-info.json` the bundler writes next to
|
|
12
|
+
* `main.mjs`. For a host run from source (`CENTRALU_HOST_ENTRY=…/src/main.ts`) there is no bundle
|
|
13
|
+
* info, so the constant is read where the bundler reads it. null when neither is there.
|
|
14
|
+
*/
|
|
15
|
+
export function protocolVersionOf(entry) {
|
|
16
|
+
try {
|
|
17
|
+
const v = JSON.parse(readFileSync(join(dirname(entry), 'bundle-info.json'), 'utf8')).protocolVersion
|
|
18
|
+
if (Number.isInteger(v)) return v
|
|
19
|
+
} catch {
|
|
20
|
+
// not a bundle; try the source below
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
const src = readFileSync(join(dirname(entry), '..', '..', 'protocol', 'src', 'envelope.ts'), 'utf8')
|
|
24
|
+
const m = /export const PROTOCOL_VERSION = (\d+)/.exec(src)
|
|
25
|
+
if (m) return Number(m[1])
|
|
26
|
+
} catch {
|
|
27
|
+
// nothing to read
|
|
28
|
+
}
|
|
29
|
+
return null
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The `--connection` answer. The shape is the client's interface (docs/agent-host.md §4.7).
|
|
34
|
+
* `install` (additive, the line stays `v: 1`) says what runs this command (`installInfo`); `detach`
|
|
35
|
+
* is added by `--detach` only.
|
|
36
|
+
*/
|
|
37
|
+
export function connectionLine({ port, token, version, protocolVersion, dataDir, hostRunning, install, autostart, detach, proof }) {
|
|
38
|
+
return JSON.stringify({
|
|
39
|
+
v: 1,
|
|
40
|
+
port,
|
|
41
|
+
token,
|
|
42
|
+
version,
|
|
43
|
+
protocolVersion,
|
|
44
|
+
dataDir,
|
|
45
|
+
hostRunning,
|
|
46
|
+
...(install ? { install } : {}),
|
|
47
|
+
...(autostart ? { autostart } : {}),
|
|
48
|
+
...(detach ? { detach } : {}),
|
|
49
|
+
// The running host proves it holds the token before the hub sends it (#838); absent: the hub sends hello as before
|
|
50
|
+
...(proof ? { proof: true } : {}),
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The host's environment.
|
|
56
|
+
*
|
|
57
|
+
* - The token is in neither: arguments are readable by every user on the machine (`ps`), and a
|
|
58
|
+
* process's start environment by every process of its user for as long as it runs (`ps eww`,
|
|
59
|
+
* #502). `CC_HOST_TOKEN_ON_STDIN=1` tells the host it comes as the first line on its stdin
|
|
60
|
+
* (`tokenLine`, #538), which is a pipe to this launcher anyway (`--watch-parent`). A host bundle
|
|
61
|
+
* from before #538 reads only `CC_HOST_TOKEN`: given `legacyToken` (`takesTokenOnStdin` said no),
|
|
62
|
+
* it gets the token there, as before.
|
|
63
|
+
* - `CC_HOST_SOURCE` is the record `hello_ok.build` is made from (keeper-link.ts); without it a
|
|
64
|
+
* client could not see which version the host it reached is.
|
|
65
|
+
* - Headless: no `DISPLAY` / `WAYLAND_DISPLAY`. Nothing the host or an agent starts gets a screen
|
|
66
|
+
* to open a window or a keyring prompt on, so a tool that would ask falls back to its file store
|
|
67
|
+
* or fails with a message in the log instead of waiting on a dialog nobody can see.
|
|
68
|
+
* - The keeper's and dev mode's variables are dropped: this host is neither. So is
|
|
69
|
+
* `CENTRALU_MANAGED`, which is the launcher's business and would otherwise reach every agent.
|
|
70
|
+
* - `CC_SERVE=1` lets the host take `host.stop` (`--stop`); a host the app runs refuses it.
|
|
71
|
+
*/
|
|
72
|
+
export function hostEnv(env, { dataDir, version, hostDir, legacyToken }) {
|
|
73
|
+
const out = { ...env }
|
|
74
|
+
for (const k of ['DISPLAY', 'WAYLAND_DISPLAY', 'CC_KEEPER', 'CC_FRONT_DOOR', 'CC_DEV', 'CC_HOST_TOKEN', 'CC_HOST_TOKEN_ON_STDIN', 'CC_HOST_SOURCE', 'CENTRALU_MANAGED']) delete out[k]
|
|
75
|
+
out.CC_DATA_DIR = dataDir
|
|
76
|
+
// The host `host.stop` may end (`centralu serve --stop`): nothing else stops it in order on Windows
|
|
77
|
+
out.CC_SERVE = '1'
|
|
78
|
+
if (legacyToken === undefined) out.CC_HOST_TOKEN_ON_STDIN = '1'
|
|
79
|
+
else out.CC_HOST_TOKEN = legacyToken
|
|
80
|
+
out.CC_HOST_SOURCE = JSON.stringify({ version, bundlePath: hostDir })
|
|
81
|
+
return out
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Whether the host at `entry` reads its token from stdin (#538): a bundle says so in `bundle-info.json`
|
|
86
|
+
* (`tokenOnStdin`), as the keeper reads it; a host run from source always does. `CENTRALU_HOST_ENTRY` can point at an
|
|
87
|
+
* older bundle, which would otherwise get no token and refuse every hello.
|
|
88
|
+
*/
|
|
89
|
+
export function takesTokenOnStdin(entry) {
|
|
90
|
+
try {
|
|
91
|
+
return JSON.parse(readFileSync(join(dirname(entry), 'bundle-info.json'), 'utf8')).tokenOnStdin === 1
|
|
92
|
+
} catch {
|
|
93
|
+
// not a bundle: the source, which reads it
|
|
94
|
+
}
|
|
95
|
+
return !existsSync(join(dirname(entry), 'bundle-info.json'))
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The first line on the host's stdin: the token (#538, the host's `readHandedToken`) */
|
|
99
|
+
export function tokenLine(token) {
|
|
100
|
+
return `${JSON.stringify({ token })}\n`
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* How to start the host.
|
|
105
|
+
*
|
|
106
|
+
* `--watch-parent` with stdin a pipe: if this launcher dies however it dies (SIGKILL included), the
|
|
107
|
+
* pipe closes and the host shuts down with its children, instead of living on unsupervised.
|
|
108
|
+
* `detached` on POSIX puts the host in its own process group, so the terminal's Ctrl+C reaches
|
|
109
|
+
* only this launcher, which passes one SIGINT to the host alone; the host then stops its own
|
|
110
|
+
* children in order. Without it the terminal would signal every agent at the same time as the
|
|
111
|
+
* host. Not on Windows: there `detached` means a new console, and Ctrl+C reaches the host through
|
|
112
|
+
* the console it shares with this launcher.
|
|
113
|
+
*/
|
|
114
|
+
export function hostCommand(execPath, entry, { port, dataDir, platform }) {
|
|
115
|
+
return {
|
|
116
|
+
command: execPath,
|
|
117
|
+
args: [
|
|
118
|
+
// A source entry (development, tests) needs the TypeScript loader; a bundle does not.
|
|
119
|
+
...(entry.endsWith('.ts') ? ['--import', 'tsx'] : []),
|
|
120
|
+
entry,
|
|
121
|
+
'--port',
|
|
122
|
+
String(port),
|
|
123
|
+
'--db',
|
|
124
|
+
join(dataDir, 'store.db'),
|
|
125
|
+
'--watch-parent',
|
|
126
|
+
],
|
|
127
|
+
detached: platform !== 'win32',
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The port from the host's ready line (`{"ready":true,"port":…,"token":…}`), null for any other line */
|
|
132
|
+
export function readyPort(line) {
|
|
133
|
+
try {
|
|
134
|
+
const v = JSON.parse(line)
|
|
135
|
+
return v?.ready === true && Number.isInteger(v.port) ? v.port : null
|
|
136
|
+
} catch {
|
|
137
|
+
return null
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The protocol a host's `version_mismatch` refusal names, from either wording: this one's
|
|
143
|
+
* ("this host speaks protocol 2") or the one before it ("server 2, client 1"). null if neither.
|
|
144
|
+
*/
|
|
145
|
+
export function mismatchServerVersion(message) {
|
|
146
|
+
const m = /host speaks protocol (\d+)|\bserver (\d+)/.exec(String(message ?? ''))
|
|
147
|
+
return m ? Number(m[1] ?? m[2]) : null
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The protocol a `version_mismatch` refusal says the host speaks: `data.protocolVersion`, which the host sends for a
|
|
152
|
+
* program to read (server.ts), else the sentence (`mismatchServerVersion`). null when neither names one.
|
|
153
|
+
*/
|
|
154
|
+
function mismatchProtocolOf(error) {
|
|
155
|
+
if (Number.isInteger(error?.data?.protocolVersion)) return error.data.protocolVersion
|
|
156
|
+
return mismatchServerVersion(error?.message)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Whether the installed host answers a `prove` (#838): a bundle says so in `bundle-info.json` (`hostProof`), a host run
|
|
161
|
+
* from source has `transport/host-proof.ts`. The connection line's `proof` is this, not a live answer: a program another
|
|
162
|
+
* account put on the port could otherwise answer the probe so as to make the line say no, and the hub send the token.
|
|
163
|
+
*/
|
|
164
|
+
export function hostProvesOf(entry) {
|
|
165
|
+
try {
|
|
166
|
+
return JSON.parse(readFileSync(join(dirname(entry), 'bundle-info.json'), 'utf8')).hostProof === 1
|
|
167
|
+
} catch {
|
|
168
|
+
// not a bundle; try the source below
|
|
169
|
+
}
|
|
170
|
+
return existsSync(join(dirname(entry), 'transport', 'host-proof.ts'))
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The answer a host holding `token` gives to a `prove` of `nonce` (the host's `hostProof`) */
|
|
174
|
+
function proofOf(token, nonce) {
|
|
175
|
+
return createHmac('sha256', token).update(`centralu host proof v1\0${nonce}`).digest('base64url')
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Opens a socket to the host and says hello with the token, the way `probeHost` and `askHostToStop` do. With `prove`
|
|
180
|
+
* (the installed host can, `hostProvesOf`), the host first proves it holds the token (#838), and the token goes out only
|
|
181
|
+
* then: whatever else listens on the port (another account's program, while the host is down) never sees it.
|
|
182
|
+
* `on.message(m, ws)` gets every frame after the hello; `on.unproven()` runs when the proof did not come, `on.gone()`
|
|
183
|
+
* when the socket failed or closed.
|
|
184
|
+
*/
|
|
185
|
+
function helloSocket({ port, token, protocolVersion, prove, WebSocketImpl, on }) {
|
|
186
|
+
const ws = new WebSocketImpl(`ws://127.0.0.1:${port}`)
|
|
187
|
+
const nonce = prove ? randomBytes(24).toString('base64url') : null
|
|
188
|
+
// Proving only once the socket is open: a port where nothing listens is gone, not unproven
|
|
189
|
+
let proving = false
|
|
190
|
+
const hello = () => ws.send(JSON.stringify({ kind: 'hello', token, protocolVersion: protocolVersion ?? 0 }))
|
|
191
|
+
ws.onopen = () => {
|
|
192
|
+
if (!prove) return hello()
|
|
193
|
+
proving = true
|
|
194
|
+
ws.send(JSON.stringify({ kind: 'prove', nonce }))
|
|
195
|
+
}
|
|
196
|
+
ws.onmessage = (ev) => {
|
|
197
|
+
let m
|
|
198
|
+
try {
|
|
199
|
+
m = JSON.parse(String(ev.data))
|
|
200
|
+
} catch {
|
|
201
|
+
m = null
|
|
202
|
+
}
|
|
203
|
+
if (proving) {
|
|
204
|
+
proving = false
|
|
205
|
+
if (m?.kind === 'proof' && m.nonce === nonce && m.mac === proofOf(token, nonce)) return hello()
|
|
206
|
+
return on.unproven()
|
|
207
|
+
}
|
|
208
|
+
if (m) on.message(m, ws)
|
|
209
|
+
}
|
|
210
|
+
ws.onerror = () => (proving ? on.unproven() : on.gone())
|
|
211
|
+
ws.onclose = () => (proving ? on.unproven() : on.gone())
|
|
212
|
+
return ws
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Whether a host that holds this token answers on the port: a real hello, not a TCP connect, so a
|
|
217
|
+
* stranger's program on the same port does not count, and the answer carries the running host's
|
|
218
|
+
* own protocol and version (which differ from the installed package's after an `npm i -g` the
|
|
219
|
+
* host was not restarted for). With `prove` the host proves it holds the token first (#838).
|
|
220
|
+
*
|
|
221
|
+
* `{ running, protocolVersion?, version?, unproven? }`. `unproven`: something answered on the port but did not prove
|
|
222
|
+
* it holds the token, so it was not sent: another program, or a host from before #838 still running after an update
|
|
223
|
+
* (`heldHere` tells those apart by the data folder's lock). Node 22.4+ has a global WebSocket; on an older 22 this falls
|
|
224
|
+
* back to a TCP connect and reports only `running`.
|
|
225
|
+
*/
|
|
226
|
+
export function probeHost({ port, token, protocolVersion, prove = false, timeoutMs = 2000, WebSocketImpl = globalThis.WebSocket }) {
|
|
227
|
+
if (typeof WebSocketImpl !== 'function') return tcpProbe(port, timeoutMs)
|
|
228
|
+
return helloExchange({
|
|
229
|
+
port, token, protocolVersion, prove, WebSocketImpl, timeoutMs,
|
|
230
|
+
timedOut: { running: false },
|
|
231
|
+
failed: () => ({ running: false }),
|
|
232
|
+
on: (done) => ({
|
|
233
|
+
unproven: () => done({ running: false, unproven: true }),
|
|
234
|
+
gone: () => done({ running: false }),
|
|
235
|
+
message: (m) => {
|
|
236
|
+
if (m.kind === 'hello_ok') {
|
|
237
|
+
done({
|
|
238
|
+
running: true,
|
|
239
|
+
protocolVersion: Number.isInteger(m.protocolVersion) ? m.protocolVersion : undefined,
|
|
240
|
+
version: typeof m.build?.version === 'string' ? m.build.version : undefined,
|
|
241
|
+
})
|
|
242
|
+
} else if (m.kind === 'res' && m.ok === false && m.error?.code === 'version_mismatch') {
|
|
243
|
+
// The token was right (it is checked first), so this is our host, on another protocol
|
|
244
|
+
done({ running: true, protocolVersion: mismatchProtocolOf(m.error) ?? undefined })
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
}),
|
|
248
|
+
})
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* One `helloSocket` exchange that ends once: with the first `done(result)` an `on` handler calls, with `timedOut`
|
|
253
|
+
* after `timeoutMs`, or with `failed(error)` when the socket cannot even be made. The socket is closed in every case.
|
|
254
|
+
*/
|
|
255
|
+
function helloExchange({ timeoutMs, timedOut, failed, on, ...hello }) {
|
|
256
|
+
return new Promise((resolve) => {
|
|
257
|
+
let ws = null
|
|
258
|
+
let settled = false
|
|
259
|
+
const done = (result) => {
|
|
260
|
+
if (settled) return
|
|
261
|
+
settled = true
|
|
262
|
+
clearTimeout(timer)
|
|
263
|
+
try {
|
|
264
|
+
ws?.close()
|
|
265
|
+
} catch {
|
|
266
|
+
// already closed
|
|
267
|
+
}
|
|
268
|
+
resolve(result)
|
|
269
|
+
}
|
|
270
|
+
const timer = setTimeout(() => done(timedOut), timeoutMs)
|
|
271
|
+
try {
|
|
272
|
+
ws = helloSocket({ ...hello, on: on(done) })
|
|
273
|
+
} catch (e) {
|
|
274
|
+
done(failed(e))
|
|
275
|
+
}
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function tcpProbe(port, timeoutMs) {
|
|
280
|
+
return new Promise((resolve) => {
|
|
281
|
+
const s = connect({ host: '127.0.0.1', port })
|
|
282
|
+
const done = (running) => {
|
|
283
|
+
s.destroy()
|
|
284
|
+
resolve({ running })
|
|
285
|
+
}
|
|
286
|
+
s.setTimeout(timeoutMs, () => done(false))
|
|
287
|
+
s.once('connect', () => done(true))
|
|
288
|
+
s.once('error', () => done(false))
|
|
289
|
+
})
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Asks a running host to stop (`host.stop`, an additive RPC): a hello with the token, then the call.
|
|
294
|
+
* `{ ok: true }` once the host took it, `{ ok: false, message, protocolVersion? }` otherwise; the
|
|
295
|
+
* last names the host's protocol when the hello was refused for it, so the caller can ask again.
|
|
296
|
+
*/
|
|
297
|
+
export function askHostToStop({ port, token, protocolVersion, prove = false, timeoutMs = 5000, WebSocketImpl = globalThis.WebSocket }) {
|
|
298
|
+
if (typeof WebSocketImpl !== 'function') return Promise.resolve({ ok: false, message: `Node ${process.version} has no WebSocket to ask with` })
|
|
299
|
+
// With `prove`, the token goes out only to a host that proved it holds it (#838)
|
|
300
|
+
return helloExchange({
|
|
301
|
+
port, token, protocolVersion, prove, WebSocketImpl, timeoutMs,
|
|
302
|
+
timedOut: { ok: false, message: 'no answer in time' },
|
|
303
|
+
failed: (e) => ({ ok: false, message: e.message }),
|
|
304
|
+
on: (done) => ({
|
|
305
|
+
unproven: () => done({ ok: false, message: 'what answers on the port did not prove it holds the token' }),
|
|
306
|
+
gone: () => done({ ok: false, message: 'the connection closed' }),
|
|
307
|
+
message: (m, ws) => {
|
|
308
|
+
if (m.kind === 'hello_ok') ws.send(JSON.stringify({ kind: 'rpc', id: 'stop', method: 'host.stop', params: {} }))
|
|
309
|
+
else if (m.kind === 'res' && m.id === 'stop') done(m.ok ? { ok: true } : { ok: false, message: m.error?.message ?? 'refused' })
|
|
310
|
+
else if (m.kind === 'res' && m.ok === false) {
|
|
311
|
+
const pv = m.error?.code === 'version_mismatch' ? mismatchProtocolOf(m.error) : null
|
|
312
|
+
done({ ok: false, message: m.error?.message ?? 'refused', ...(pv !== null ? { protocolVersion: pv } : {}) })
|
|
313
|
+
}
|
|
314
|
+
},
|
|
315
|
+
}),
|
|
316
|
+
})
|
|
317
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two launchers and the install they reach: `<data>/bin/centralu` that `serve` keeps for an npm
|
|
3
|
+
* install, and the managed install the hub writes over ssh (`<data>/remote/`, docs/plans/remote-hub.md
|
|
4
|
+
* §10.1), with the launcher that never changes and the pointers it reads.
|
|
5
|
+
*/
|
|
6
|
+
import { chmodSync, mkdirSync, readFileSync, statSync } from 'node:fs'
|
|
7
|
+
import { dirname, join } from 'node:path'
|
|
8
|
+
import { replaceFile, say } from './serve-util.mjs'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The launcher `serve` keeps at `<data folder>/bin/centralu` (`centralu.cmd` on Windows).
|
|
12
|
+
*
|
|
13
|
+
* The client runs `ssh -T -o BatchMode=yes <target> centralu …`, and a non-interactive SSH shell
|
|
14
|
+
* reads no profile: npm's global bin under nvm, fnm, volta or `~/.npm-global` is not on its PATH,
|
|
15
|
+
* and often neither is `node`. So the plain name fails with exit 127, and the person, who just ran
|
|
16
|
+
* `centralu serve` in their own shell, sees no reason why. This file names both by absolute path,
|
|
17
|
+
* so `~/.centralu/bin/centralu` works from any shell. It is rewritten whenever it differs from
|
|
18
|
+
* what this run would write, which follows a Node upgrade or a moved npm prefix on the next start.
|
|
19
|
+
*/
|
|
20
|
+
export function launcherScript(platform, execPath, cliPath) {
|
|
21
|
+
if (platform === 'win32') {
|
|
22
|
+
// A batch file reads every % as the start of a variable (`100% cli.mjs" %*` came out as `100*`); %% is a literal one
|
|
23
|
+
const lit = (v) => String(v).replaceAll('%', '%%')
|
|
24
|
+
/*
|
|
25
|
+
* The file is UTF-8, and cmd.exe reads each line of a batch file in the console's code page as it reaches it: 949
|
|
26
|
+
* on a Korean Windows, where a profile folder named in Korean came out as other characters and node found no
|
|
27
|
+
* centralu.mjs there (#849). So the lines before the paths, all ASCII, switch the console to UTF-8 (65001), and the
|
|
28
|
+
* code page it had is put back on the line with the paths, ahead of node: cmd.exe reads and decodes a whole line
|
|
29
|
+
* before it runs any of it, so the paths are already read as UTF-8 by then. The console is the shell's that ran
|
|
30
|
+
* this, and node runs on the page it had; a Ctrl+C answered at "Terminate batch job (Y/N)?" ends this file
|
|
31
|
+
* before any later line, and a restore there was skipped. chcp is named by its full path: the shell's PATH may
|
|
32
|
+
* not have System32 on it.
|
|
33
|
+
*/
|
|
34
|
+
return [
|
|
35
|
+
'@echo off',
|
|
36
|
+
"rem Written by `centralu serve`: reaches this install without npm's folder on PATH.",
|
|
37
|
+
'setlocal',
|
|
38
|
+
'set "CENTRALU_CP="',
|
|
39
|
+
`for /f "tokens=2 delims=:." %%c in ('%SystemRoot%\\System32\\chcp.com') do set /a "CENTRALU_CP=%%c" >nul 2>&1`,
|
|
40
|
+
'%SystemRoot%\\System32\\chcp.com 65001 >nul 2>&1',
|
|
41
|
+
`(if defined CENTRALU_CP %SystemRoot%\\System32\\chcp.com %CENTRALU_CP% >nul 2>&1) & "${lit(execPath)}" "${lit(cliPath)}" %*`,
|
|
42
|
+
'exit /b %ERRORLEVEL%',
|
|
43
|
+
'',
|
|
44
|
+
].join('\r\n')
|
|
45
|
+
}
|
|
46
|
+
const q = (v) => `'${String(v).replaceAll("'", "'\\''")}'`
|
|
47
|
+
return (
|
|
48
|
+
'#!/bin/sh\n' +
|
|
49
|
+
"# Written by `centralu serve`: reaches this install from a shell whose PATH has neither npm's global\n" +
|
|
50
|
+
'# folder nor node (a non-interactive SSH session). Rewritten when node or the package moves.\n' +
|
|
51
|
+
`exec ${q(execPath)} ${q(cliPath)} "$@"\n`
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Writes the launcher if it is missing or out of date. Returns its path. Never fatal to the caller */
|
|
56
|
+
export function ensureLauncher(dataDir, { platform = process.platform, execPath = process.execPath, cliPath }) {
|
|
57
|
+
const file = join(dataDir, 'bin', platform === 'win32' ? 'centralu.cmd' : 'centralu')
|
|
58
|
+
const want = launcherScript(platform, execPath, cliPath)
|
|
59
|
+
let have = null
|
|
60
|
+
try {
|
|
61
|
+
have = readFileSync(file, 'utf8')
|
|
62
|
+
} catch {
|
|
63
|
+
// not there yet
|
|
64
|
+
}
|
|
65
|
+
if (have !== want) {
|
|
66
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
67
|
+
replaceFile(file, want, { mode: 0o755 })
|
|
68
|
+
}
|
|
69
|
+
if (platform !== 'win32' && (statSync(file).mode & 0o777) !== 0o755) chmodSync(file, 0o755)
|
|
70
|
+
return file
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* ensureLauncher, with a failure said on stderr instead of thrown: the launcher is a convenience.
|
|
75
|
+
*
|
|
76
|
+
* Not under the managed launcher (`CENTRALU_MANAGED=1`, docs/plans/remote-hub.md §10.1): an install
|
|
77
|
+
* the hub made over ssh has its own launcher in `<data>/remote/bin/`, which reads `current`. Writing
|
|
78
|
+
* `<data>/bin/centralu` from there would point an npm install's launcher at one managed version, and
|
|
79
|
+
* the two would rewrite each other's file on every start.
|
|
80
|
+
*/
|
|
81
|
+
export function keepLauncher(dataDir, cliPath, env) {
|
|
82
|
+
if (!cliPath || env?.CENTRALU_MANAGED === '1') return
|
|
83
|
+
try {
|
|
84
|
+
ensureLauncher(dataDir, { cliPath })
|
|
85
|
+
} catch (e) {
|
|
86
|
+
say(`could not write the launcher in ${join(dataDir, 'bin')}: ${e.message}`)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The install the hub manages on this machine (docs/plans/remote-hub.md §10.1): side-by-side
|
|
92
|
+
* versions, the pinned Node they run on, and two pointer files naming what runs and what to roll
|
|
93
|
+
* back to. The hub's installer writes it; `serve` only reads it.
|
|
94
|
+
*/
|
|
95
|
+
export function remoteLayout(dataDir) {
|
|
96
|
+
const root = join(dataDir, 'remote')
|
|
97
|
+
return {
|
|
98
|
+
root,
|
|
99
|
+
current: join(root, 'current'),
|
|
100
|
+
previous: join(root, 'previous'),
|
|
101
|
+
versions: join(root, 'versions'),
|
|
102
|
+
node: join(root, 'node'),
|
|
103
|
+
bin: join(root, 'bin'),
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A word a pointer file may hold: a folder name, nothing a path could escape with */
|
|
108
|
+
const POINTER_WORD = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$/
|
|
109
|
+
|
|
110
|
+
/** `current` / `previous`: one line, "<centralu version> <node version>". null for anything else */
|
|
111
|
+
export function parsePointer(text) {
|
|
112
|
+
const m = /^\s*(\S+)[ \t]+(\S+)\s*$/.exec(String(text ?? ''))
|
|
113
|
+
if (!m || !POINTER_WORD.test(m[1]) || !POINTER_WORD.test(m[2])) return null
|
|
114
|
+
return { version: m[1], node: m[2] }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Where a managed version came from, from its `install.json`: `{ kind: 'dev', commit, dirty }` for a dev build put
|
|
119
|
+
* there from a git commit (`pnpm remote-dev`, #1036), null for a release (or anything unreadable). The hub shows it
|
|
120
|
+
* on the machine's row, so a build no release produced is never mistaken for one.
|
|
121
|
+
*/
|
|
122
|
+
export function installSource(versionDir) {
|
|
123
|
+
try {
|
|
124
|
+
const s = JSON.parse(readFileSync(join(versionDir, 'install.json'), 'utf8')).source
|
|
125
|
+
if (s?.kind === 'dev' && typeof s.commit === 'string' && /^[0-9a-f]{7,64}$/.test(s.commit)) return { kind: 'dev', commit: s.commit, dirty: s.dirty === true }
|
|
126
|
+
} catch {
|
|
127
|
+
// no install.json, or not one this reads
|
|
128
|
+
}
|
|
129
|
+
return null
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The connection line's `install` field (docs/plans/remote-hub.md §10.5): whether this command was
|
|
134
|
+
* started by the managed launcher, the managed install's `current` and `previous`, and the Node
|
|
135
|
+
* running this command. Read from the machine at every ask, never kept by the hub (S12).
|
|
136
|
+
*/
|
|
137
|
+
export function installInfo(dataDir, env, nodeVersion = process.versions.node) {
|
|
138
|
+
const l = remoteLayout(dataDir)
|
|
139
|
+
const read = (file) => {
|
|
140
|
+
let p
|
|
141
|
+
try {
|
|
142
|
+
p = parsePointer(readFileSync(file, 'utf8'))
|
|
143
|
+
} catch {
|
|
144
|
+
return null
|
|
145
|
+
}
|
|
146
|
+
const source = p && installSource(join(l.versions, p.version))
|
|
147
|
+
return p && source ? { ...p, source } : p
|
|
148
|
+
}
|
|
149
|
+
return { managed: env.CENTRALU_MANAGED === '1', current: read(l.current), previous: read(l.previous), node: nodeVersion }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The managed launcher, `<data>/remote/bin/centralu` (`centralu.cmd` on Windows), as the installer
|
|
154
|
+
* writes it (docs/plans/remote-hub.md §10.1, S8).
|
|
155
|
+
*
|
|
156
|
+
* **Its text never changes.** It reads `current` at every start and runs that version's
|
|
157
|
+
* `centralu.mjs` on that version's Node, so switching versions is one file replaced by a rename,
|
|
158
|
+
* atomic on both systems. A launcher rewritten per version would be replaced while it may be
|
|
159
|
+
* running, and cmd.exe reads a batch file by offset as it runs. It sets `CENTRALU_MANAGED=1`, so
|
|
160
|
+
* the `serve` it starts leaves `<data>/bin/` to an npm install on the same machine.
|
|
161
|
+
*
|
|
162
|
+
* Both refuse a pointer that holds anything but plain version words, so an edited `current` cannot
|
|
163
|
+
* point it outside the install.
|
|
164
|
+
*/
|
|
165
|
+
export function managedLauncherScript(platform) {
|
|
166
|
+
if (platform === 'win32') {
|
|
167
|
+
return (
|
|
168
|
+
[
|
|
169
|
+
'@echo off',
|
|
170
|
+
'rem The Centralu launcher for the install the app manages over SSH. It never changes: it reads',
|
|
171
|
+
'rem "current" at every start, so switching versions replaces that file and never this one.',
|
|
172
|
+
'setlocal',
|
|
173
|
+
'set "CENTRALU_REMOTE=%~dp0.."',
|
|
174
|
+
'set "CENTRALU_LINE="',
|
|
175
|
+
'set "CENTRALU_V="',
|
|
176
|
+
'set "CENTRALU_N="',
|
|
177
|
+
'set /p CENTRALU_LINE=<"%CENTRALU_REMOTE%\\current"',
|
|
178
|
+
'for /f "tokens=1,2" %%a in ("%CENTRALU_LINE%") do (set "CENTRALU_V=%%a" & set "CENTRALU_N=%%b")',
|
|
179
|
+
'if not defined CENTRALU_N goto none',
|
|
180
|
+
'echo %CENTRALU_V% %CENTRALU_N%| findstr /r /c:"^[0-9A-Za-z][0-9A-Za-z.+-]* [0-9A-Za-z][0-9A-Za-z.+-]*$" >nul || goto none',
|
|
181
|
+
'set CENTRALU_MANAGED=1',
|
|
182
|
+
'"%CENTRALU_REMOTE%\\node\\v%CENTRALU_N%\\node.exe" "%CENTRALU_REMOTE%\\versions\\%CENTRALU_V%\\node_modules\\centralu\\bin\\centralu.mjs" %*',
|
|
183
|
+
'exit /b %ERRORLEVEL%',
|
|
184
|
+
':none',
|
|
185
|
+
'echo Centralu: no version is installed in %CENTRALU_REMOTE% 1>&2',
|
|
186
|
+
'exit /b 1',
|
|
187
|
+
].join('\r\n') + '\r\n'
|
|
188
|
+
)
|
|
189
|
+
}
|
|
190
|
+
return [
|
|
191
|
+
'#!/bin/sh',
|
|
192
|
+
'# The Centralu launcher for the install the app manages over SSH. It never changes: it reads',
|
|
193
|
+
'# `current` at every start, so switching versions replaces that file and never this one.',
|
|
194
|
+
'remote=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P) || exit 1',
|
|
195
|
+
'v= n=',
|
|
196
|
+
'read -r v n < "$remote/current" 2>/dev/null',
|
|
197
|
+
'case "$v" in ""|[!0-9A-Za-z]*|*[!0-9A-Za-z.+-]*) echo "Centralu: no version is installed in $remote" >&2; exit 1 ;; esac',
|
|
198
|
+
'case "$n" in ""|[!0-9A-Za-z]*|*[!0-9A-Za-z.+-]*) echo "Centralu: no version is installed in $remote" >&2; exit 1 ;; esac',
|
|
199
|
+
'CENTRALU_MANAGED=1',
|
|
200
|
+
'export CENTRALU_MANAGED',
|
|
201
|
+
'exec "$remote/node/v$n/bin/node" "$remote/versions/$v/node_modules/centralu/bin/centralu.mjs" "$@"',
|
|
202
|
+
'',
|
|
203
|
+
].join('\n')
|
|
204
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** The port `centralu serve` listens on: the default, the recorded one, and the next free one (#482) */
|
|
2
|
+
import { createServer } from 'node:net'
|
|
3
|
+
import { runCaptured } from './serve-util.mjs'
|
|
4
|
+
import { detachHow, windowsTool } from './serve-windows.mjs'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The port `serve` listens on unless told otherwise, and keeps across restarts.
|
|
8
|
+
*
|
|
9
|
+
* Stable, because the client is told it once per connection and the person may write it into an
|
|
10
|
+
* SSH config or a systemd unit. Below 20000 on purpose: every OS lends ports from its ephemeral
|
|
11
|
+
* range to outgoing connections (Linux 32768–60999, macOS and Windows 49152–65535), and the host
|
|
12
|
+
* itself hands out per-app view origins from 20000–32767 (views/origin-ports.ts). A default inside
|
|
13
|
+
* either range could be taken by something transient the day the host restarts.
|
|
14
|
+
*/
|
|
15
|
+
export const DEFAULT_SERVE_PORT = 17175
|
|
16
|
+
|
|
17
|
+
/** How many ports from the recorded one `serve` tries when it is taken (#482); none at or above 20000 */
|
|
18
|
+
export const SERVE_PORT_TRIES = 20
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The port `serve` starts the host on (#482): `{ port, from }`, `from` being the port it moved away
|
|
22
|
+
* from (null when it did not), or null when every candidate is taken.
|
|
23
|
+
*
|
|
24
|
+
* A port the person gave (`--port`) is used as given: they asked for that one. Otherwise the recorded
|
|
25
|
+
* port (else the default) when it is free, and when another program listens there, the next free
|
|
26
|
+
* one above it, below 20000 (the ranges `DEFAULT_SERVE_PORT` keeps out of). The host's ready line
|
|
27
|
+
* then records the port it got, so `--connection` reports it and the hub forwards to it.
|
|
28
|
+
*
|
|
29
|
+
* The usual other program is the other half of one Windows laptop: WSL2 relays a distro's
|
|
30
|
+
* 127.0.0.1 ports to Windows (`wslrelay.exe`), so a Windows install and a WSL install linked as two
|
|
31
|
+
* machines both wanted 17175, and whichever started second could not start at all.
|
|
32
|
+
* `taken(port)` answers whether something listens there.
|
|
33
|
+
*/
|
|
34
|
+
export async function chooseServePort({ asked, recorded, taken }) {
|
|
35
|
+
if (asked !== null && asked !== undefined) return { port: asked, from: null }
|
|
36
|
+
const first = recorded ?? DEFAULT_SERVE_PORT
|
|
37
|
+
for (let p = first; p < first + SERVE_PORT_TRIES && p <= 65535; p++) {
|
|
38
|
+
if (p !== first && p >= 20000) break
|
|
39
|
+
if (!(await taken(p))) return { port: p, from: p === first ? null : first }
|
|
40
|
+
}
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Whether something listens on 127.0.0.1:`port` here: a listen that fails with EADDRINUSE (or EACCES) */
|
|
45
|
+
export function listensHere(port) {
|
|
46
|
+
return new Promise((resolve) => {
|
|
47
|
+
const srv = createServer()
|
|
48
|
+
srv.once('error', (e) => resolve(e?.code === 'EADDRINUSE' || e?.code === 'EACCES'))
|
|
49
|
+
srv.listen({ host: '127.0.0.1', port, exclusive: true }, () => srv.close(() => resolve(false)))
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The TCP ports Windows listens on, from `netstat.exe -an -p TCP` output: a listening socket is the
|
|
55
|
+
* row whose foreign address is `0.0.0.0:0` (or `[::]:0`). Read that way rather than by the state
|
|
56
|
+
* column, which Windows translates (a Korean Windows does not print LISTENING everywhere).
|
|
57
|
+
*/
|
|
58
|
+
export function parseNetstatListening(text) {
|
|
59
|
+
const ports = new Set()
|
|
60
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
61
|
+
const m = /^\s*TCP\s+(?:127\.0\.0\.1|0\.0\.0\.0|\[::1?\]):(\d+)\s+(?:0\.0\.0\.0:0|\[::\]:0)\s/i.exec(line)
|
|
62
|
+
if (m) ports.add(Number(m[1]))
|
|
63
|
+
}
|
|
64
|
+
return ports
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The ports the Windows side listens on, seen from inside a WSL distro (empty elsewhere, or when
|
|
69
|
+
* Windows cannot be asked). Inside the distro a port Windows holds looks free, yet a host there
|
|
70
|
+
* would be unreachable from the hub: the hub's forward ends on Windows' 127.0.0.1, where the
|
|
71
|
+
* Windows program answers instead (#482).
|
|
72
|
+
*/
|
|
73
|
+
export async function windowsListening(env, platform) {
|
|
74
|
+
if (detachHow(platform, env) !== 'wsl') return new Set()
|
|
75
|
+
const netstat = windowsTool('wsl', env, ['System32', 'netstat.exe'])
|
|
76
|
+
if (!netstat) return new Set()
|
|
77
|
+
const r = await runCaptured(netstat, ['-an', '-p', 'TCP'], env)
|
|
78
|
+
return r.code === 0 ? parseNetstatListening(r.stdout) : new Set()
|
|
79
|
+
}
|