centralu 0.1.0-beta.7 → 0.1.0-beta.71

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.
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Stopping the host `serve` runs for a data folder, and moving one that runs in a network logon into the person's
3
+ * Windows sign-in (#1224). One module so the foreground `serve` (serve-run.mjs) and `--stop` (serve-detach.mjs) share
4
+ * the stop without importing each other.
5
+ */
6
+ import { readServeState, heldHere, startedByServe, foreignHolder, holderWho, lockHolderIsAlive, lockHolderPid, readServePid } from './serve-files.mjs'
7
+ import { DEFAULT_SERVE_PORT, listensHere } from './serve-port.mjs'
8
+ import { protocolVersionOf, probeHost, askHostToStop, askHostRpc } from './serve-host.mjs'
9
+ import { ownLogon } from './serve-windows.mjs'
10
+ import { isAlive, say, sleep, waitUntil } from './serve-util.mjs'
11
+
12
+ /**
13
+ * Asks the host serve runs for `dataDir` to stop over its own socket and waits until it has, so its shutdown runs (its
14
+ * agents, terminals and app processes stopped in order, the store closed). Measured on Windows: killing the
15
+ * WMI-started launcher ended the host 143 ms later with no "shutting down" line, because the host sits in libuv's
16
+ * kill-on-close job object; so on Windows killing is the last resort, not the way.
17
+ *
18
+ * Then, only for a host that did not go: posix SIGTERM to the launcher (which passes it to the host, the same clean
19
+ * stop), and on Windows ending the host. A host from before `host.stop` gets that too. The launcher ends with its host;
20
+ * one still there afterwards is ended.
21
+ *
22
+ * Only the processes serve.pid and host.lock name, and only while they agree with each other and the host answered
23
+ * with this folder's token, or nothing listens on the port while the process host.lock names is the one that wrote it
24
+ * (`heldSilently`, #1903: a host that took the lock and hung before it listened; never under `ifIdle`): a stale pid is
25
+ * never signalled.
26
+ * And only a host `serve` started (`startedByServe`, #1722): a lock held by the app's or the keeper's host is theirs,
27
+ * whatever answers on the port, so `--stop` says whose it is and leaves it.
28
+ *
29
+ * `{ ok, wasRunning, how?, heldByOther?, message? }`, the `--stop` line's `stop`. With `ifIdle` (#1224, the hand-over) the host stops only
30
+ * when nothing runs there, and `{ ok: false, busy: true }` says it did not. `forUpdate` (#1618): a hub's update stops it, and
31
+ * the host writes the turns it ends for the next one (`host.stop { forUpdate }`); a host that does not take the request is
32
+ * ended as any is, and lists nothing.
33
+ */
34
+ export async function stopServedHost({ dataDir, entry, platform = process.platform, ifIdle = false, forUpdate = false, timeoutMs = 30_000, graceMs = 15_000, kill = (pid, sig) => process.kill(pid, sig) }) {
35
+ const state = readServeState(dataDir)
36
+ if (!state) return { ok: true, wasRunning: false, message: `no centralu serve has run for ${dataDir}` }
37
+ const port = state.port ?? DEFAULT_SERVE_PORT
38
+ const installed = protocolVersionOf(entry) ?? 0
39
+ // The limited credential is enough to probe and to stop it (#1405, `host.stop` is everyday)
40
+ const own = { token: state.token, proofKey: state.proofKey }
41
+ const probe = () => probeHost({ port, ...own, protocolVersion: installed })
42
+ const first = await probe()
43
+ const silent = !first.running && !first.unproven && (await heldSilently(dataDir, port))
44
+ if (!silent && !heldHere(first, dataDir, undefined, state.port != null)) {
45
+ // The folder is held, but not by a serve (#1722): the app's or the keeper's host, whatever answered on the port
46
+ const other = foreignHolder(dataDir)
47
+ const whose = other ? `. It belongs to another Centralu host (pid ${other.pid}), ${holderWho(other.by)}; not stopping it` : ''
48
+ // `heldByOther`: the folder is held by a host that is not this serve's, which this left alone (the window's quit says so rather than claim a stop)
49
+ return { ok: true, wasRunning: false, ...(other ? { heldByOther: true } : {}), message: `centralu serve is not running for ${dataDir}${whose}` }
50
+ }
51
+
52
+ const hostPid = lockHolderPid(dataDir)
53
+ // Only a host `serve` started is ever signalled, whoever answered with this folder's token
54
+ const mayKill = startedByServe(dataDir)
55
+ const launcher = readServePid(dataDir)
56
+ // serve.pid is only believed when it names the host that holds the folder now
57
+ const launcherPid = mayKill && launcher && hostPid && launcher.hostPid === hostPid ? launcher.pid : null
58
+ const down = async () => !(await probe()).running && !(hostPid && isAlive(hostPid))
59
+
60
+ let how = 'asked'
61
+ let stopped = false
62
+ let note = silent ? 'nothing listens on its port' : null
63
+ // The hand-over stops only a host that said it is idle: one that cannot say so is left
64
+ if (silent && ifIdle) return { ok: false, wasRunning: true, message: `the host holds the folder but ${note}` }
65
+ if (!silent) {
66
+ let asked = await askHostToStop({ port, ...own, protocolVersion: first.protocolVersion ?? installed, ifIdle, forUpdate })
67
+ if (!asked.ok && asked.protocolVersion !== undefined) asked = await askHostToStop({ port, ...own, protocolVersion: asked.protocolVersion, ifIdle, forUpdate })
68
+ // `ifIdle` and it has work running (#1224): it was left as it is
69
+ if (asked.busy) return { ok: false, wasRunning: true, busy: true, message: asked.message }
70
+ stopped = asked.ok && (await waitUntil(down, timeoutMs))
71
+ if (!asked.ok) note = `the host did not take the request to stop (${asked.message})`
72
+ }
73
+ if (!stopped) {
74
+ const target = platform !== 'win32' && launcherPid ? launcherPid : mayKill ? hostPid : null
75
+ if (hostPid && !mayKill) note = `${note ? `${note}; ` : ''}the lock names pid ${hostPid}, which centralu serve did not start, so it was not signalled`
76
+ if (target) {
77
+ how = platform === 'win32' ? 'ended' : 'signal'
78
+ try {
79
+ kill(target, 'SIGTERM')
80
+ } catch {
81
+ // gone in the meantime
82
+ }
83
+ stopped = await waitUntil(down, platform === 'win32' ? 5_000 : graceMs)
84
+ if (!stopped && hostPid && isAlive(hostPid)) {
85
+ how = 'ended'
86
+ try {
87
+ kill(hostPid, 'SIGKILL')
88
+ } catch {
89
+ // gone in the meantime
90
+ }
91
+ stopped = await waitUntil(down, 5_000)
92
+ }
93
+ }
94
+ if (how === 'ended') note = `${note ? `${note}; ` : ''}ended the host without its shutdown`
95
+ }
96
+ if (launcherPid && launcherPid !== process.pid && !(await waitUntil(() => !isAlive(launcherPid), 5_000))) {
97
+ try {
98
+ kill(launcherPid, 'SIGKILL')
99
+ } catch {
100
+ // gone in the meantime
101
+ }
102
+ }
103
+ if (!stopped) return { ok: false, wasRunning: true, how, message: `the host on 127.0.0.1:${port} is still running${note ? ` (${note})` : ''}` }
104
+ return { ok: true, wasRunning: true, how, ...(note ? { message: note } : {}) }
105
+ }
106
+
107
+ /**
108
+ * A host `serve` started that holds the folder's lock while nothing listens on its port (#1903): it took the lock and hung
109
+ * before it listened, or is still starting. Told by a listen on the port, not by the probe: a host that listens but whose
110
+ * event loop is stalled answers no probe in time either, and is running (#1906 review). Not part of `heldHere`, which
111
+ * `--connection` and `--detach`'s wait read: there a host still starting must not count as one that answers
112
+ */
113
+ async function heldSilently(dataDir, port) {
114
+ return startedByServe(dataDir) && lockHolderIsAlive(dataDir) && !(await listensHere(port))
115
+ }
116
+
117
+ /** How long the hand-over waits for the host's work to end before it gives up and says so (#1224 review) */
118
+ export const HANDOVER_WAIT_MS = 30 * 60_000
119
+
120
+ /**
121
+ * The hand-over (#1224): a `serve` started in the person's Windows sign-in (the scheduled task, at sign-in or from
122
+ * `--detach`) found the folder held by a host that runs in a network logon, the one a hub's ssh started before anyone
123
+ * signed in. Git there cannot use the credentials saved in Windows, so the sign-in's host takes over, but only while that
124
+ * host has nothing running a person would lose. Windows has no keeper, so stopping a host ends what runs in it.
125
+ *
126
+ * The stop is `host.stop {ifIdle}`: the host itself checks and stops in one step, and from its yes on takes no new call,
127
+ * so a turn the hub starts cannot slip in between a check here and the stop (`lifecycle/stop-gate.ts` in agent-host).
128
+ * Until it says yes this asks again every `pollMs`, for `maxWaitMs` at most (30 minutes), and tells the host what it is
129
+ * doing (`host.handover`: `waiting`, then `gave_up`), which a hub linked to it shows on the machine's row. It ends early
130
+ * when that host goes by itself.
131
+ *
132
+ * Resolves true once the folder is free for this serve to start its host, false when there is nothing to move (not
133
+ * Windows, a host in any other logon or too old to say, this serve not in an interactive logon itself) or it gave up.
134
+ * The hub's link loses the machine between the stop and the new host's start, and reconnects by its usual backoff to the
135
+ * same port and token.
136
+ *
137
+ * `existing` is `probeHost`'s answer for the running host. `logonOf`, `stop`, `tell`, `pollMs`, `maxWaitMs` and `now` are
138
+ * parameters for tests.
139
+ */
140
+ export async function moveIntoSignIn({
141
+ dataDir,
142
+ entry,
143
+ env,
144
+ existing,
145
+ platform = process.platform,
146
+ logonOf = () => ownLogon(env),
147
+ stop = () => stopServedHost({ dataDir, entry, platform, ifIdle: true }),
148
+ tell = null,
149
+ pollMs = 30_000,
150
+ maxWaitMs = HANDOVER_WAIT_MS,
151
+ now = Date.now,
152
+ }) {
153
+ if (platform !== 'win32' || existing?.logon !== 'network') return false
154
+ if ((await logonOf()) !== 'interactive') return false
155
+ const state = readServeState(dataDir)
156
+ if (!state) return false
157
+ const port = state.port ?? DEFAULT_SERVE_PORT
158
+ const protocolVersion = existing.protocolVersion ?? protocolVersionOf(entry) ?? 0
159
+ const own = { token: state.token, proofKey: state.proofKey }
160
+ /*
161
+ * `host.handover` takes everyday rights (#1711, docs/plans/key-pairing.md §4.4): said with the credentials this
162
+ * launcher holds for its own host (the limited credential, after a proof under the key), and no credential is made for
163
+ * it. Before, a full one made for this call went to whatever answered that proof, which a reader of serve.json can. A
164
+ * host from #1405 to key pairing refuses it (`link`): no note on the row while this waits, and the move goes on
165
+ */
166
+ const sayHandover = (h) => askHostRpc({ port, ...own, protocolVersion, method: 'host.handover', params: { handover: h } })
167
+ const report = (handover) => (tell ?? sayHandover)(handover)
168
+ const pid = lockHolderPid(dataDir)
169
+ say(`the host running for ${dataDir}${pid ? ` (pid ${pid})` : ''} runs in a network logon (started over ssh), where Git cannot use the credentials saved in Windows; moving it into this Windows sign-in once nothing runs there`)
170
+ const t0 = now()
171
+ let waiting = false
172
+ for (;;) {
173
+ if (!(await probeHost({ port, ...own, protocolVersion })).running) return true
174
+ const r = await stop()
175
+ if (r.ok) {
176
+ say(`stopped it${r.how && r.how !== 'asked' ? ` (${r.how})` : ''}; starting the host in this sign-in`)
177
+ return true
178
+ }
179
+ if (!r.busy) say(`could not stop it: ${r.message ?? 'no reason given'}; asking again later`)
180
+ if (!waiting) {
181
+ say('it has work running (a turn, an approval, a terminal or a command); waiting until it has none')
182
+ await report({ state: 'waiting', since: t0 })
183
+ waiting = true
184
+ }
185
+ if (now() - t0 >= maxWaitMs) {
186
+ await report({ state: 'gave_up', since: now() })
187
+ say(`gave up after ${Math.round(maxWaitMs / 60_000)} minutes: it still had work running. It moves into the sign-in at the next sign-in, or when a linked computer starts it again`)
188
+ return false
189
+ }
190
+ await sleep(pollMs)
191
+ }
192
+ }
@@ -0,0 +1,467 @@
1
+ /**
2
+ * The host `centralu serve` runs: how it is started, and talking to a running one over its own socket
3
+ * (a proof, then a hello with the token, `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
+ import { LINK_NONCE_BYTES, signedHostKey } from './serve-keys.mjs'
10
+
11
+ /**
12
+ * The protocol a host folder speaks, from the `bundle-info.json` the bundler writes next to
13
+ * `main.mjs`. For a host run from source (`CENTRALU_HOST_ENTRY=…/src/main.ts`) there is no bundle
14
+ * info, so the constant is read where the bundler reads it. null when neither is there.
15
+ */
16
+ export function protocolVersionOf(entry) {
17
+ try {
18
+ const v = JSON.parse(readFileSync(join(dirname(entry), 'bundle-info.json'), 'utf8')).protocolVersion
19
+ if (Number.isInteger(v)) return v
20
+ } catch {
21
+ // not a bundle; try the source below
22
+ }
23
+ try {
24
+ const src = readFileSync(join(dirname(entry), '..', '..', 'protocol', 'src', 'envelope.ts'), 'utf8')
25
+ const m = /export const PROTOCOL_VERSION = (\d+)/.exec(src)
26
+ if (m) return Number(m[1])
27
+ } catch {
28
+ // nothing to read
29
+ }
30
+ return null
31
+ }
32
+
33
+ /**
34
+ * The `--connection` answer. The shape is the client's interface (docs/agent-host/remote/serve.md).
35
+ * `install` (additive, the line stays `v: 1`) says what runs this command (`installInfo`); `detach`
36
+ * is added by `--detach` only.
37
+ */
38
+ export function connectionLine({ port, token, credential, limited, others, version, protocolVersion, dataDir, hostRunning, install, autostart, detach, stopped, hostKey, keyId }) {
39
+ /*
40
+ * The options this serve takes that an older one refuses (#1223): a hub up to 0.1.0-beta.45's adds `--from <its name>`
41
+ * to `--detach` only when the line says so, since an older serve answers an option it does not know with an error. `window`: the
42
+ * desktop window on Windows uses this serve's host through `--window` only when it is listed (#1223 review)
43
+ */
44
+ /*
45
+ * `pair` (#1405): `--connection --pair <label>` hands out a full credential of its own; without it the line carries the
46
+ * limited credential only
47
+ */
48
+ /*
49
+ * `pairKey` (#1711, docs/plans/key-pairing.md §4.2): `--pair-key` made a key pairing, said only on a line that is one
50
+ * (`hostKey` and `keyId`, and no `token`). A line from `--pair-key` without it is a verifier pairing
51
+ */
52
+ const takes = ['from', 'window', 'pair', ...(hostKey && keyId ? ['pairKey'] : [])]
53
+ return JSON.stringify({
54
+ v: 1,
55
+ port,
56
+ // The key the running host signs with, and the hub's key entry it signs for (#1711); never with a credential
57
+ ...(hostKey && keyId ? { hostKey, keyId } : {}),
58
+ // A full credential only to `--pair` (#1405), with its id for the proof; an older serve always printed its token
59
+ ...(token ? { token } : {}),
60
+ ...(credential ? { credential } : {}),
61
+ // What a process of this user gets without pairing (#1405): everyday calls only
62
+ ...(limited ? { limited } : {}),
63
+ // The full credentials this folder holds besides the one just paired, as `{ id, label, created }` (#1405)
64
+ ...(others ? { others } : {}),
65
+ version,
66
+ protocolVersion,
67
+ dataDir,
68
+ hostRunning,
69
+ ...(install ? { install } : {}),
70
+ ...(autostart ? { autostart } : {}),
71
+ ...(detach ? { detach } : {}),
72
+ // The running host proves it holds the token before the hub sends it (#838): every host from 0.1.0-beta.45 on does
73
+ proof: true,
74
+ // The person stopped the host here, and when (#1143, `readStopped`); absent: an older serve, or no such stop
75
+ ...(stopped ? { stopped } : {}),
76
+ takes,
77
+ })
78
+ }
79
+
80
+ /**
81
+ * Where a `serve` was asked for from (#1223), for the host's `host.lock` (`CC_SERVE_FROM`): the hub's name `--from`
82
+ * gave, and the ssh client's address when this runs in an ssh session (OpenSSH's `SSH_CLIENT`, on Windows too). What a
83
+ * `--detach` found is carried to the launcher it starts (`CENTRALU_STARTED_FROM`), which runs outside the ssh session.
84
+ * Null when neither is known.
85
+ */
86
+ export function serveFrom(env, hub = null) {
87
+ const carried = parseStartedFrom(env.CENTRALU_STARTED_FROM)
88
+ if (carried) return carried
89
+ const ssh = String(env.SSH_CLIENT ?? env.SSH_CONNECTION ?? '').trim().split(/\s+/)[0] ?? ''
90
+ const from = {
91
+ ...(typeof hub === 'string' && FROM_NAME_RE.test(hub) ? { hub } : {}),
92
+ ...(SSH_ADDRESS_RE.test(ssh) ? { ssh } : {}),
93
+ }
94
+ return from.hub || from.ssh ? from : null
95
+ }
96
+
97
+ const FROM_NAME_RE = /^[A-Za-z0-9._-]{1,64}$/
98
+ /** An IPv4 or IPv6 address as OpenSSH writes it: digits, hex, dots and colons */
99
+ const SSH_ADDRESS_RE = /^[0-9A-Fa-f.:]{2,64}$/
100
+
101
+ function parseStartedFrom(raw) {
102
+ if (!raw) return null
103
+ try {
104
+ const v = JSON.parse(raw)
105
+ const from = {
106
+ ...(typeof v?.hub === 'string' && FROM_NAME_RE.test(v.hub) ? { hub: v.hub } : {}),
107
+ ...(typeof v?.ssh === 'string' && SSH_ADDRESS_RE.test(v.ssh) ? { ssh: v.ssh } : {}),
108
+ }
109
+ return from.hub || from.ssh ? from : null
110
+ } catch {
111
+ return null
112
+ }
113
+ }
114
+
115
+ /**
116
+ * The host's environment.
117
+ *
118
+ * - The key is in neither: arguments are readable by every user on the machine (`ps`), and a
119
+ * process's start environment by every process of its user for as long as it runs (`ps eww`,
120
+ * #502). `CC_HOST_TOKEN_ON_STDIN=1` tells the host its key comes as the first line on its stdin
121
+ * (`keyLine`, #538), which is a pipe to this launcher anyway (`--watch-parent`).
122
+ * - `CC_HOST_SOURCE` is the record `hello_ok.build` is made from (keeper-link.ts); without it a
123
+ * client could not see which version the host it reached is.
124
+ * - Headless: no `DISPLAY` / `WAYLAND_DISPLAY`. Nothing the host or an agent starts gets a screen
125
+ * to open a window or a keyring prompt on, so a tool that would ask falls back to its file store
126
+ * or fails with a message in the log instead of waiting on a dialog nobody can see.
127
+ * - The keeper's and dev mode's variables are dropped: this host is neither. So is
128
+ * `CENTRALU_MANAGED`, which is the launcher's business and would otherwise reach every agent.
129
+ * - `CC_SERVE=1` lets the host take `host.stop` (`--stop`); a host the app runs refuses it.
130
+ */
131
+ export function hostEnv(env, { dataDir, version, hostDir, from = null, serveState = null }) {
132
+ const out = { ...env }
133
+ 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', 'CC_SERVE_STATE', 'CENTRALU_MANAGED', 'CENTRALU_STARTED_FROM', 'CC_SERVE_FROM', 'CC_STARTED_BY']) delete out[k]
134
+ /*
135
+ * The host checks full credentials against serve.json's verifiers (#1405): the file it reads at each hello. A path,
136
+ * not a secret: the file is the user's own, 0600. Its key comes on stdin (`keyLine`)
137
+ */
138
+ if (serveState) out.CC_SERVE_STATE = serveState
139
+ // Who asked for this host, for its host.lock (#1223): a second host on the folder names it when refused
140
+ if (from) out.CC_SERVE_FROM = JSON.stringify(from)
141
+ out.CC_DATA_DIR = dataDir
142
+ // The host `host.stop` may end (`centralu serve --stop`): nothing else stops it in order on Windows
143
+ out.CC_SERVE = '1'
144
+ out.CC_HOST_TOKEN_ON_STDIN = '1'
145
+ out.CC_HOST_SOURCE = JSON.stringify({ version, bundlePath: hostDir })
146
+ return out
147
+ }
148
+
149
+ /**
150
+ * The first line on the host's stdin (#538, #1405; the host's `readHandedToken`): its key, from which it derives what it
151
+ * hands out. Not a full credential: the host never takes it as one (`CC_SERVE_STATE` says where the full ones' verifiers are)
152
+ */
153
+ export function keyLine(key) {
154
+ return `${JSON.stringify({ key })}\n`
155
+ }
156
+
157
+ /**
158
+ * How to start the host.
159
+ *
160
+ * `--watch-parent` with stdin a pipe: if this launcher dies however it dies (SIGKILL included), the
161
+ * pipe closes and the host shuts down with its children, instead of living on unsupervised.
162
+ * `detached` on POSIX puts the host in its own process group, so the terminal's Ctrl+C reaches
163
+ * only this launcher, which passes one SIGINT to the host alone; the host then stops its own
164
+ * children in order. Without it the terminal would signal every agent at the same time as the
165
+ * host. Not on Windows: there `detached` means a new console, and Ctrl+C reaches the host through
166
+ * the console it shares with this launcher.
167
+ */
168
+ export function hostCommand(execPath, entry, { port, dataDir, platform }) {
169
+ return {
170
+ command: execPath,
171
+ args: [
172
+ // A source entry (development, tests) needs the TypeScript loader; a bundle does not.
173
+ ...(entry.endsWith('.ts') ? ['--import', 'tsx'] : []),
174
+ entry,
175
+ '--port',
176
+ String(port),
177
+ '--db',
178
+ join(dataDir, 'store.db'),
179
+ '--watch-parent',
180
+ ],
181
+ detached: platform !== 'win32',
182
+ }
183
+ }
184
+
185
+ /** The port from the host's ready line (`{"ready":true,"port":…,"token":…}`), null for any other line */
186
+ export function readyPort(line) {
187
+ try {
188
+ const v = JSON.parse(line)
189
+ return v?.ready === true && Number.isInteger(v.port) ? v.port : null
190
+ } catch {
191
+ return null
192
+ }
193
+ }
194
+
195
+ /**
196
+ * The protocol a host's `version_mismatch` refusal names, from either wording: this one's
197
+ * ("this host speaks protocol 2") or the one before it ("server 2, client 1"). null if neither.
198
+ */
199
+ export function mismatchServerVersion(message) {
200
+ const m = /host speaks protocol (\d+)|\bserver (\d+)/.exec(String(message ?? ''))
201
+ return m ? Number(m[1] ?? m[2]) : null
202
+ }
203
+
204
+ /**
205
+ * The protocol a `version_mismatch` refusal says the host speaks: `data.protocolVersion`, which the host sends for a
206
+ * program to read (server.ts), else the sentence (`mismatchServerVersion`). null when neither names one.
207
+ */
208
+ function mismatchProtocolOf(error) {
209
+ if (Number.isInteger(error?.data?.protocolVersion)) return error.data.protocolVersion
210
+ return mismatchServerVersion(error?.message)
211
+ }
212
+
213
+ /**
214
+ * Whether the host at `entry` takes a hub's key hello (#1711): a bundle says so in `bundle-info.json` (`keyPairing`), a
215
+ * host run from source has `transport/link-proof.ts`. `--pair-key` reports a key derived from serve.json only for a host
216
+ * started next that will sign with it (docs/plans/key-pairing.md §4.2)
217
+ */
218
+ export function takesKeyHellos(entry) {
219
+ try {
220
+ return JSON.parse(readFileSync(join(dirname(entry), 'bundle-info.json'), 'utf8')).keyPairing === 1
221
+ } catch {
222
+ // not a bundle; try the source below
223
+ }
224
+ return existsSync(join(dirname(entry), 'transport', 'link-proof.ts'))
225
+ }
226
+
227
+ /**
228
+ * Asks the host on `port` to sign for the key entry `keyId` (#1711, docs/plans/key-pairing.md §4.2 step 3), as a hub
229
+ * would: a `prove` naming it, with a nonce of this launcher's, and the answer's signature checked against the key it
230
+ * carries, the hub's key `hubKey` and the address `127.0.0.1:<port>`. No hello follows. One of:
231
+ *
232
+ * - `{ outcome: 'signed', hostKey }`: the running host signs, with `hostKey` (after `--rotate-token`, still its old one);
233
+ * - `{ outcome: 'unsigned' }`: a proof with no signature at all, from a host from before key pairing still running;
234
+ * - `{ outcome: 'none' }`: the connection was refused, so nothing listens there;
235
+ * - `{ outcome: 'unknown' }`: anything else (no answer within `timeoutMs`, a socket closed before a proof, a proof that is
236
+ * malformed or does not verify, no WebSocket in this Node), which pairs as a host that does not sign does.
237
+ */
238
+ export async function probeKeyProof({ port, keyId, hubKey, timeoutMs = 2000, WebSocketImpl = globalThis.WebSocket, connectTo = connect }) {
239
+ // Refused at once: nothing listens. Told apart from a socket that opens and says nothing, which is not known to be nothing
240
+ const reach = await new Promise((resolve) => {
241
+ const s = connectTo({ host: '127.0.0.1', port })
242
+ const done = (r) => {
243
+ s.destroy()
244
+ resolve(r)
245
+ }
246
+ s.setTimeout(timeoutMs, () => done('unknown'))
247
+ s.once('connect', () => done('open'))
248
+ s.once('error', (e) => done(e?.code === 'ECONNREFUSED' ? 'none' : 'unknown'))
249
+ })
250
+ if (reach !== 'open') return { outcome: reach }
251
+ if (typeof WebSocketImpl !== 'function') return { outcome: 'unknown' }
252
+ const nonce = randomBytes(LINK_NONCE_BYTES).toString('base64url')
253
+ return new Promise((resolve) => {
254
+ let ws = null
255
+ let settled = false
256
+ const done = (r) => {
257
+ if (settled) return
258
+ settled = true
259
+ clearTimeout(timer)
260
+ try {
261
+ ws?.close()
262
+ } catch {
263
+ // already closed
264
+ }
265
+ resolve(r)
266
+ }
267
+ const timer = setTimeout(() => done({ outcome: 'unknown' }), timeoutMs)
268
+ try {
269
+ ws = new WebSocketImpl(`ws://127.0.0.1:${port}`)
270
+ } catch {
271
+ return done({ outcome: 'unknown' })
272
+ }
273
+ ws.onopen = () => ws.send(JSON.stringify({ kind: 'prove', nonce, key: keyId }))
274
+ ws.onmessage = (ev) => {
275
+ let m = null
276
+ try {
277
+ m = JSON.parse(String(ev.data))
278
+ } catch {
279
+ // not a frame
280
+ }
281
+ const hostKey = signedHostKey(m, { hubNonce: nonce, hubKey, keyId, port })
282
+ if (hostKey) return done({ outcome: 'signed', hostKey })
283
+ // A proof without any of the three fields: a host that does not sign. One with some of them and no valid signature is not known
284
+ const unsigned = m?.kind === 'proof' && m.nonce === nonce && m.hostNonce === undefined && m.hostKey === undefined && m.sig === undefined
285
+ done({ outcome: unsigned ? 'unsigned' : 'unknown' })
286
+ }
287
+ ws.onerror = () => done({ outcome: 'unknown' })
288
+ ws.onclose = () => done({ outcome: 'unknown' })
289
+ })
290
+ }
291
+
292
+ /** The answer a host holding `token` gives to a `prove` of `nonce` (the host's `hostProof`) */
293
+ function proofOf(token, nonce) {
294
+ return createHmac('sha256', token).update(`centralu host proof v1\0${nonce}`).digest('base64url')
295
+ }
296
+
297
+ /**
298
+ * Opens a socket to the host and says hello with the token, the way `probeHost` and `askHostToStop` do. The host first
299
+ * proves it holds the token (#838), and the token goes out only then: whatever else listens on the port (another
300
+ * account's program, while the host is down) never sees it.
301
+ * `on.message(m, ws)` gets every frame after the hello; `on.unproven()` runs when the proof did not come, `on.gone()`
302
+ * when the socket failed or closed.
303
+ */
304
+ function helloSocket({ port, token, proofKey, protocolVersion, WebSocketImpl, on }) {
305
+ const ws = new WebSocketImpl(`ws://127.0.0.1:${port}`)
306
+ const nonce = randomBytes(24).toString('base64url')
307
+ // Proving only once the socket is open: a port where nothing listens is gone, not unproven
308
+ let proving = false
309
+ const hello = () => ws.send(JSON.stringify({ kind: 'hello', token, protocolVersion: protocolVersion ?? 0 }))
310
+ ws.onopen = () => {
311
+ proving = true
312
+ ws.send(JSON.stringify({ kind: 'prove', nonce }))
313
+ }
314
+ ws.onmessage = (ev) => {
315
+ let m
316
+ try {
317
+ m = JSON.parse(String(ev.data))
318
+ } catch {
319
+ m = null
320
+ }
321
+ if (proving) {
322
+ proving = false
323
+ // A host that takes verifiers proves with its key, which is not the credential this says hello with (#1405)
324
+ if (m?.kind === 'proof' && m.nonce === nonce && m.mac === proofOf(proofKey ?? token, nonce)) return hello()
325
+ return on.unproven()
326
+ }
327
+ if (m) on.message(m, ws)
328
+ }
329
+ ws.onerror = () => (proving ? on.unproven() : on.gone())
330
+ ws.onclose = () => (proving ? on.unproven() : on.gone())
331
+ return ws
332
+ }
333
+
334
+ /**
335
+ * Whether a host that holds this token answers on the port: a real hello, not a TCP connect, so a
336
+ * stranger's program on the same port does not count, and the answer carries the running host's
337
+ * own protocol and version (which differ from the installed package's after an `npm i -g` the
338
+ * host was not restarted for). The host proves it holds the token first (#838).
339
+ *
340
+ * `{ running, protocolVersion?, version?, unproven? }`. `unproven`: something answered on the port but did not prove
341
+ * it holds the token, so it was not sent: another program, or a host still on its old key after `--rotate-token`
342
+ * (`heldHere` tells those apart by the data folder's lock). Node 22.4+ has a global WebSocket; on an older 22 this falls
343
+ * back to a TCP connect and reports only `running`.
344
+ */
345
+ export function probeHost({ port, token, proofKey, protocolVersion, timeoutMs = 2000, WebSocketImpl = globalThis.WebSocket }) {
346
+ if (typeof WebSocketImpl !== 'function') return tcpProbe(port, timeoutMs)
347
+ return helloExchange({
348
+ port, token, proofKey, protocolVersion, WebSocketImpl, timeoutMs,
349
+ timedOut: { running: false },
350
+ failed: () => ({ running: false }),
351
+ on: (done) => ({
352
+ unproven: () => done({ running: false, unproven: true }),
353
+ gone: () => done({ running: false }),
354
+ message: (m) => {
355
+ if (m.kind === 'hello_ok') {
356
+ done({
357
+ running: true,
358
+ protocolVersion: Number.isInteger(m.protocolVersion) ? m.protocolVersion : undefined,
359
+ version: typeof m.build?.version === 'string' ? m.build.version : undefined,
360
+ // Which Windows logon it runs in (#1224): a `network` one is moved into the sign-in (serve-handover.mjs)
361
+ ...(HOST_LOGONS.includes(m.logon) ? { logon: m.logon } : {}),
362
+ })
363
+ } else if (m.kind === 'res' && m.ok === false && m.error?.code === 'version_mismatch') {
364
+ // The token was right (it is checked first), so this is our host, on another protocol
365
+ done({ running: true, protocolVersion: mismatchProtocolOf(m.error) ?? undefined })
366
+ }
367
+ },
368
+ }),
369
+ })
370
+ }
371
+
372
+ /**
373
+ * One `helloSocket` exchange that ends once: with the first `done(result)` an `on` handler calls, with `timedOut`
374
+ * after `timeoutMs`, or with `failed(error)` when the socket cannot even be made. The socket is closed in every case.
375
+ */
376
+ function helloExchange({ timeoutMs, timedOut, failed, on, ...hello }) {
377
+ return new Promise((resolve) => {
378
+ let ws = null
379
+ let settled = false
380
+ const done = (result) => {
381
+ if (settled) return
382
+ settled = true
383
+ clearTimeout(timer)
384
+ try {
385
+ ws?.close()
386
+ } catch {
387
+ // already closed
388
+ }
389
+ resolve(result)
390
+ }
391
+ const timer = setTimeout(() => done(timedOut), timeoutMs)
392
+ try {
393
+ ws = helloSocket({ ...hello, on: on(done) })
394
+ } catch (e) {
395
+ done(failed(e))
396
+ }
397
+ })
398
+ }
399
+
400
+ function tcpProbe(port, timeoutMs) {
401
+ return new Promise((resolve) => {
402
+ const s = connect({ host: '127.0.0.1', port })
403
+ const done = (running) => {
404
+ s.destroy()
405
+ resolve({ running })
406
+ }
407
+ s.setTimeout(timeoutMs, () => done(false))
408
+ s.once('connect', () => done(true))
409
+ s.once('error', () => done(false))
410
+ })
411
+ }
412
+
413
+ /** The logons a host's `hello_ok.logon` may name (#1224) */
414
+ const HOST_LOGONS = ['interactive', 'network', 'batch', 'service']
415
+
416
+ /**
417
+ * One call to a running host (`method` with `params`), as `askHostToStop` makes it: a hello with the token, then the
418
+ * call. Its result, or null when it did not answer or refused. For `host.handover` (#1224)
419
+ */
420
+ export function askHostRpc({ port, token, proofKey, protocolVersion, method, params = {}, timeoutMs = 5000, WebSocketImpl = globalThis.WebSocket }) {
421
+ if (typeof WebSocketImpl !== 'function') return Promise.resolve(null)
422
+ return helloExchange({
423
+ port, token, proofKey, protocolVersion, WebSocketImpl, timeoutMs,
424
+ timedOut: null,
425
+ failed: () => null,
426
+ on: (done) => ({
427
+ unproven: () => done(null),
428
+ gone: () => done(null),
429
+ message: (m, ws) => {
430
+ if (m.kind === 'hello_ok') ws.send(JSON.stringify({ kind: 'rpc', id: 'call', method, params }))
431
+ else if (m.kind === 'res' && m.id === 'call') done(m.ok && m.result && typeof m.result === 'object' ? m.result : null)
432
+ else if (m.kind === 'res' && m.ok === false) done(null)
433
+ },
434
+ }),
435
+ })
436
+ }
437
+
438
+ /**
439
+ * Asks a running host to stop (`host.stop`, an additive RPC): a hello with the token, then the call.
440
+ * `{ ok: true }` once the host took it, `{ ok: false, message, protocolVersion? }` otherwise; the
441
+ * last names the host's protocol when the hello was refused for it, so the caller can ask again.
442
+ * `ifIdle` (#1224): only if nothing runs there, checked and acted on by the host in one step; `{ ok: false, busy: true }`
443
+ * when something does. `forUpdate` (#1618): a hub's update stops it, and the host lists the turns it ends for the next one.
444
+ */
445
+ export function askHostToStop({ port, token, proofKey, protocolVersion, ifIdle = false, forUpdate = false, timeoutMs = 5000, WebSocketImpl = globalThis.WebSocket }) {
446
+ if (typeof WebSocketImpl !== 'function') return Promise.resolve({ ok: false, message: `Node ${process.version} has no WebSocket to ask with` })
447
+ return helloExchange({
448
+ port, token, proofKey, protocolVersion, WebSocketImpl, timeoutMs,
449
+ timedOut: { ok: false, message: 'no answer in time' },
450
+ failed: (e) => ({ ok: false, message: e.message }),
451
+ on: (done) => ({
452
+ unproven: () => done({ ok: false, message: 'what answers on the port did not prove it holds the token' }),
453
+ gone: () => done({ ok: false, message: 'the connection closed' }),
454
+ message: (m, ws) => {
455
+ if (m.kind === 'hello_ok') ws.send(JSON.stringify({ kind: 'rpc', id: 'stop', method: 'host.stop', params: { ...(ifIdle ? { ifIdle: true } : {}), ...(forUpdate ? { forUpdate: true } : {}) } }))
456
+ else if (m.kind === 'res' && m.id === 'stop' && m.ok && m.result?.ok === false) {
457
+ // `ifIdle` and something runs there (#1224): nothing was changed
458
+ done({ ok: false, busy: true, message: 'it has work running', activity: m.result.busy ?? null, calls: m.result.calls ?? 0 })
459
+ } else if (m.kind === 'res' && m.id === 'stop') done(m.ok ? { ok: true } : { ok: false, message: m.error?.message ?? 'refused' })
460
+ else if (m.kind === 'res' && m.ok === false) {
461
+ const pv = m.error?.code === 'version_mismatch' ? mismatchProtocolOf(m.error) : null
462
+ done({ ok: false, message: m.error?.message ?? 'refused', ...(pv !== null ? { protocolVersion: pv } : {}) })
463
+ }
464
+ },
465
+ }),
466
+ })
467
+ }