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,290 @@
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, readStopped, markStarting, clearStarting, serveDataDir, ensureServeState, recordServePort, rotateServeToken, heldHere, lockHolder, lockHolderPid, holderWho, removeServePid, pairServe, pairKeyServe, dropVerifierUnder, revokeServe } 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, probeHost, probeKeyProof, serveFrom, keyLine, takesKeyHellos } from './serve-host.mjs'
11
+ import { hostLinkPublicKey } from './serve-keys.mjs'
12
+ import { autostartInfo } from './serve-autostart.mjs'
13
+ import { moveIntoSignIn } from './serve-handover.mjs'
14
+
15
+ /**
16
+ * The data folder a command that may start or describe a host works in: its state, created on first use, and the
17
+ * launcher serve keeps there brought up to date (`keepLauncher`).
18
+ */
19
+ export function serveFolder({ env, home, cliPath, platform = process.platform }) {
20
+ const dataDir = serveDataDir(env, home)
21
+ const state = ensureServeState(dataDir, platform)
22
+ keepLauncher(dataDir, cliPath, env)
23
+ return { dataDir, state }
24
+ }
25
+
26
+ /**
27
+ * What `--connection` answers, as fields: the running host's versions when one answers, else the installed ones.
28
+ *
29
+ * The credentials (#1405): `paired` (`--pair`, `{ token, id }`) is a full credential just made for whoever asked, and
30
+ * the only one this ever prints; without it the line carries the limited credential, which reads and does the everyday
31
+ * things.
32
+ * `others` names the full credentials the folder holds besides the one just paired, never their values, each marked
33
+ * `replaced` when its pairing took the place of an earlier one of its label.
34
+ */
35
+ export async function describe({ env, dataDir, state, entry, version, paired = null, keyPaired = null }) {
36
+ const port = state.port ?? DEFAULT_SERVE_PORT
37
+ const installed = protocolVersionOf(entry)
38
+ const probe = await probeHost({ port, token: state.token, proofKey: state.proofKey, protocolVersion: installed })
39
+ const protocolVersion = (probe.running ? probe.protocolVersion : undefined) ?? installed
40
+ if (protocolVersion === null) return null
41
+ const hostRunning = heldHere(probe, dataDir, undefined, state.port != null)
42
+ // The person stopped it here (#1143): said while no host runs, so a hub starts none by itself
43
+ const stopped = hostRunning ? null : readStopped(dataDir)
44
+ return {
45
+ port,
46
+ ...(paired ? { token: paired.token, credential: paired.id } : {}),
47
+ // A key pairing (#1711): the key the running host signs with and the entry it signs for, never a credential
48
+ ...(keyPaired ? { hostKey: keyPaired.hostKey, keyId: keyPaired.keyId } : {}),
49
+ limited: state.token,
50
+ /*
51
+ * The hubs' key entries are listed too, with their public keys (#1711, §4.4), which a hub compares with its own; the
52
+ * one this line pairs is left out, as the full credential just paired is
53
+ */
54
+ others: [
55
+ ...state.full.filter((e) => e.id !== paired?.id).map(({ id, label, created, replaced }) => ({ id, label, created, ...(replaced ? { replaced: true } : {}) })),
56
+ ...(state.keys ?? []).filter((k) => k.id !== keyPaired?.keyId).map(({ id, label, created, replaced, publicKey }) => ({ id, label, created, publicKey, ...(replaced ? { replaced: true } : {}) })),
57
+ ],
58
+ version: (probe.running ? probe.version : undefined) ?? version,
59
+ protocolVersion,
60
+ dataDir,
61
+ hostRunning,
62
+ install: installInfo(dataDir, env),
63
+ autostart: autostartInfo(dataDir, process.platform, env),
64
+ ...(stopped ? { stopped } : {}),
65
+ }
66
+ }
67
+
68
+ /**
69
+ * `centralu serve --connection`. stdout carries exactly one line, the JSON; everything else goes to
70
+ * stderr. Exit 1 when there is no host to describe.
71
+ */
72
+ export async function printConnection({ env, home, entry, version, cliPath, pair = null, pairKey = null, keyPaired = false, probeKey = probeKeyProof }) {
73
+ const folder = serveFolder({ env, home, cliPath })
74
+ const { dataDir } = folder
75
+ let { state } = folder
76
+ // `--pair <label>` (#1405): a full credential for whoever asked, printed once and written down as its verifier only
77
+ let paired = null
78
+ // `--pair-key <label> <key>` (#1711): a key pairing when the host that will check it signs; else a verifier pairing as `--pair`
79
+ let keyLine = null
80
+ if (pairKey !== null) {
81
+ const made = pairKeyServe(dataDir, pairKey.label, pairKey.publicKey)
82
+ state = made.state
83
+ const hostKey = await signingHostKey({ dataDir, state, entry, keyId: made.entry.id, hubKey: pairKey.publicKey, probeKey })
84
+ if (hostKey) {
85
+ keyLine = { hostKey, keyId: made.entry.id }
86
+ // The hub paired by key here before (§4.2): its verifier entry under the label is no longer its own, and goes now
87
+ if (keyPaired) state = dropVerifierUnder(dataDir, pairKey.label)
88
+ say(`paired the key of ${JSON.stringify(pairKey.label)} (${made.entry.id}); serve --revoke ${made.entry.id} withdraws it`)
89
+ } else {
90
+ // The key entry stays: it is public, and a host that signs uses it once one runs here
91
+ pair = pairKey.label
92
+ }
93
+ }
94
+ if (pair !== null) {
95
+ const made = pairServe(dataDir, pair)
96
+ state = made.state
97
+ paired = { token: made.token, id: made.id }
98
+ say(`made a full credential for ${JSON.stringify(pair)} (${made.id}); serve --revoke ${made.id} withdraws it`)
99
+ }
100
+ const d = await describe({ env, dataDir, state, entry, version, paired, keyPaired: keyLine })
101
+ if (!d) {
102
+ say(`cannot read the protocol version of the host at ${entry}`)
103
+ return 1
104
+ }
105
+ process.stdout.write(`${connectionLine(d)}\n`)
106
+ return 0
107
+ }
108
+
109
+ /**
110
+ * The key the host that checks a key hello signs with (#1711, docs/plans/key-pairing.md §4.2), or null when a key
111
+ * pairing cannot be made now and the line pairs by verifier:
112
+ *
113
+ * - the running host signs a `prove` for the entry: the key it signs with, which after `--rotate-token` is still its old
114
+ * one until it restarts;
115
+ * - nothing listens on the port (the connection refused), nothing holds the data folder (`host.lock`: no keeper's host,
116
+ * no host starting) and the installed host takes key hellos: the key derived from serve.json's `key`, which the host
117
+ * started next is handed;
118
+ * - otherwise (a host that does not sign, no answer in time, a proof that does not verify, a holder of the folder):
119
+ * null. A slow old host never gets a key line, and no line reports a key the running host does not sign with.
120
+ */
121
+ async function signingHostKey({ dataDir, state, entry, keyId, hubKey, probeKey }) {
122
+ const port = state.port ?? DEFAULT_SERVE_PORT
123
+ const probe = await probeKey({ port, keyId, hubKey })
124
+ if (probe.outcome === 'signed') return probe.hostKey
125
+ if (probe.outcome !== 'none' || !takesKeyHellos(entry)) return null
126
+ const holder = lockHolder(dataDir)
127
+ if (holder && isAlive(holder.pid)) return null
128
+ return hostLinkPublicKey(state.key)
129
+ }
130
+
131
+ /**
132
+ * `centralu serve`. Resolves with the exit code once the host has exited.
133
+ *
134
+ * The host's stdout is read here and never passed on: its ready line carries the token, which is
135
+ * printed nowhere but `--connection`. Every other line the host writes to stdout (a lock conflict,
136
+ * a store from a newer build) it also writes to stderr, which is passed through untouched.
137
+ *
138
+ * `logFd` is serve.log of a detached launcher (`runDetachedChild`): the host's stderr goes there
139
+ * until it is ready, so a host that dies while starting (a native module that does not load, a store
140
+ * from a newer build) says why in a file `--detach` can quote. From then on host.log has every line,
141
+ * and serve.log stops growing.
142
+ */
143
+ export async function runServe({ env, home, entry, version, cliPath, port: askedPort, from = null, platform = process.platform, execPath = process.execPath, logFd = null, handOver = moveIntoSignIn }) {
144
+ const { dataDir, state } = serveFolder({ env, home, cliPath, platform })
145
+ const protocolVersion = protocolVersionOf(entry)
146
+ // A serve that is already up answers on the port it recorded; say so before starting a host that
147
+ // would only fail on the data folder's lock with a less specific message.
148
+ const recorded = state.port ?? DEFAULT_SERVE_PORT
149
+ const existing = await probeHost({ port: recorded, token: state.token, proofKey: state.proofKey, protocolVersion })
150
+ // A host the hub's ssh started before anyone signed in moves into this sign-in, once idle (#1224, serve-handover.mjs)
151
+ if (heldHere(existing, dataDir, undefined, state.port != null) && !(await handOver({ dataDir, entry, env, existing, platform }))) {
152
+ const pid = lockHolderPid(dataDir)
153
+ say(`centralu serve is already running for ${dataDir} on 127.0.0.1:${recorded}${pid ? ` (pid ${pid})` : ''}. Not starting a second one.`)
154
+ return 1
155
+ }
156
+
157
+ const onWindows = await windowsListening(env, platform)
158
+ const chosen = await chooseServePort({ asked: askedPort, recorded: state.port, taken: async (p) => onWindows.has(p) || (await listensHere(p)) })
159
+ if (chosen === null) {
160
+ 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>.`)
161
+ return 1
162
+ }
163
+ const port = chosen.port
164
+ if (chosen.from !== null) {
165
+ const who = onWindows.has(chosen.from) ? 'Windows' : 'another program'
166
+ say(`127.0.0.1:${chosen.from} is in use by ${who}; starting on ${port} instead (kept for the next start)`)
167
+ }
168
+
169
+ const plan = hostCommand(execPath, entry, { port, dataDir, platform })
170
+ // A start in progress (#2150): this launcher's own record, removed once its host is ready or has exited (below)
171
+ markStarting(dataDir)
172
+ /*
173
+ * The host gets the key on stdin and the path of serve.json, whose full credentials it checks at each hello (#1405);
174
+ * nothing it gets opens it whole
175
+ */
176
+ const child = spawn(plan.command, plan.args, {
177
+ stdio: ['pipe', 'pipe', logFd === null ? 'inherit' : 'pipe'],
178
+ env: hostEnv(env, {
179
+ dataDir,
180
+ version,
181
+ hostDir: dirname(entry),
182
+ from: serveFrom(env, from),
183
+ serveState: join(dataDir, SERVE_STATE_FILE),
184
+ }),
185
+ detached: plan.detached,
186
+ windowsHide: true,
187
+ })
188
+ // What the host holds, before anything else on the pipe it watches (#538); stdin stays open for --watch-parent
189
+ child.stdin.write(keyLine(state.key))
190
+
191
+ let ready = false
192
+ if (logFd !== null) {
193
+ // Read to the end in any case: a pipe nobody drains stops the host once its buffer is full
194
+ child.stderr.on('data', (b) => {
195
+ if (ready) return
196
+ try {
197
+ writeSync(logFd, b)
198
+ } catch {
199
+ // the log is a convenience
200
+ }
201
+ })
202
+ }
203
+ if (child.pid) {
204
+ try {
205
+ writeFileSync(join(dataDir, SERVE_PID_FILE), `${JSON.stringify({ pid: process.pid, hostPid: child.pid, port })}\n`)
206
+ } catch (e) {
207
+ say(`could not write ${SERVE_PID_FILE}: ${e.message}`)
208
+ }
209
+ }
210
+ createInterface({ input: child.stdout }).on('line', (line) => {
211
+ const p = readyPort(line)
212
+ if (p === null || ready) return
213
+ ready = true
214
+ // A start `--detach` handed to this launcher is over (#2150)
215
+ clearStarting(dataDir)
216
+ try {
217
+ recordServePort(dataDir, p, platform)
218
+ } catch (e) {
219
+ say(`could not record the port in ${join(dataDir, SERVE_STATE_FILE)}: ${e.message}`)
220
+ }
221
+ say(`listening on 127.0.0.1:${p} (Centralu ${version}, protocol ${protocolVersion ?? 'unknown'}, data ${dataDir})`)
222
+ 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`)
223
+ else say(`the host's own log continues in ${join(dataDir, 'host.log')}`)
224
+ })
225
+
226
+ /*
227
+ * One signal to the host alone, whatever reached this launcher. SIGHUP (the terminal closed) is
228
+ * passed as SIGTERM: the host has no SIGHUP handler, and Node's default for it is to exit on the
229
+ * spot, skipping the shutdown that stops the agents. A second signal changes nothing on the host
230
+ * side (its shutdown runs once), so forwarding every one is safe.
231
+ */
232
+ const forward = (sig) => {
233
+ if (child.exitCode !== null || child.signalCode !== null) return
234
+ if (platform === 'win32') return // the host shares the console and received Ctrl+C itself
235
+ try {
236
+ child.kill(sig === 'SIGHUP' ? 'SIGTERM' : sig)
237
+ } catch {
238
+ // already gone
239
+ }
240
+ }
241
+ const signals = platform === 'win32' ? ['SIGINT'] : ['SIGINT', 'SIGTERM', 'SIGHUP']
242
+ for (const s of signals) process.on(s, forward)
243
+
244
+ return await new Promise((resolve) => {
245
+ child.on('error', (e) => {
246
+ removeServePid(dataDir, process.pid)
247
+ clearStarting(dataDir)
248
+ say(`could not start the host (${plan.command}): ${e.message}`)
249
+ resolve(1)
250
+ })
251
+ child.on('exit', (code, signal) => {
252
+ for (const s of signals) process.off(s, forward)
253
+ removeServePid(dataDir, process.pid)
254
+ clearStarting(dataDir)
255
+ if (!ready && code !== 0) {
256
+ const holder = lockHolder(dataDir)
257
+ if (holder && holder.pid !== child.pid && isAlive(holder.pid)) {
258
+ // Who it is, when its host.lock says (#1223)
259
+ say(`the host did not start. ${dataDir} belongs to another Centralu host (pid ${holder.pid}), ${holderWho(holder.by)}. Quit it, or point CC_DATA_DIR at another folder.`)
260
+ }
261
+ }
262
+ if (logFd !== null) say(`the host exited (${signal ?? code})`)
263
+ resolve(code ?? (signal ? 1 : 0))
264
+ })
265
+ })
266
+ }
267
+
268
+ /** `centralu serve --rotate-token`: a new key, and every full credential withdrawn (#1405) */
269
+ export function rotateToken({ env, home }) {
270
+ const dataDir = serveDataDir(env, home)
271
+ rotateServeToken(dataDir)
272
+ say(`replaced the key and withdrew every full credential in ${join(dataDir, SERVE_STATE_FILE)}.`)
273
+ say('A linked computer pairs again at its next connection, and a window at its next start. A serve that is running keeps its old key until it restarts: the limited credential --connection prints works once it has.')
274
+ return 0
275
+ }
276
+
277
+ /** `centralu serve --revoke <id>`: one full credential withdrawn (#1405); its next hello is refused, and the host closes a socket already in with it */
278
+ export function revokeCredential({ env, home, id, write = (line) => process.stdout.write(line) }) {
279
+ const dataDir = serveDataDir(env, home)
280
+ const revoked = revokeServe(dataDir, id)
281
+ // One JSON line on stdout, as every serve command a hub runs prints one: whether there was one to withdraw
282
+ write(`${JSON.stringify({ v: 1, revoked, id })}
283
+ `)
284
+ if (!revoked) {
285
+ say(`no credential ${id} in ${join(dataDir, SERVE_STATE_FILE)}; --connection lists them under others.`)
286
+ return 1
287
+ }
288
+ say(`withdrew ${id}. A running host refuses its next hello with it and closes a connection already open with it within a second.`)
289
+ return 0
290
+ }