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,773 @@
1
+ /**
2
+ * The files `centralu serve` keeps in the data folder: the host's key, the verifiers of the full credentials and the
3
+ * port (serve.json, private to the user), the running launcher's pid (serve.pid), and the host's own lock (host.lock),
4
+ * read to tell a live host of this folder from a stale pid.
5
+ */
6
+ import { execFileSync } from 'node:child_process'
7
+ import { createHash, createHmac, randomBytes } from 'node:crypto'
8
+ import { chmodSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeSync, closeSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { isAlive, renameRetrying, replaceFile, sleepSync } from './serve-util.mjs'
11
+ import { CREDENTIAL_ID_RE, PAIR_LABEL_RE } from './serve-args.mjs'
12
+ import { parseLinkPublicKey } from './serve-keys.mjs'
13
+ import { windowsPowershell } from './serve-windows.mjs'
14
+
15
+ /**
16
+ * The file in the data folder that holds the host's key, the full credentials' verifiers and the port, mode 0600.
17
+ *
18
+ * Since #1405 (version 2) it holds **no credential that opens the host whole**:
19
+ *
20
+ * - `key`: 32 random bytes the host derives what it hands out from (the limited credential `--connection` prints, a
21
+ * Codex bridge's, the proof of a launcher's probe). With it a process of this user gets the limited credential;
22
+ * it is never a full one (a hello with it is refused as full).
23
+ * - `full`: one entry per full credential, `{ id, label, verifier, created }`, the verifier being the SHA-256 of the
24
+ * credential. The credential itself is printed once, to whoever asked for it (`--pair`: a hub at each link,
25
+ * `--window` for the person's own window, which the desktop app runs on Windows and which runs on every OS), and written nowhere. The host checks a hello against these,
26
+ * read again at each hello, so a pairing or a revocation applies at once.
27
+ * - `keys` (#1711, docs/plans/key-pairing.md §4.2, additive: still version 2): one entry per hub that paired by key,
28
+ * `{ id, label, publicKey, created, via: 'pair-key' }`, the hub's Ed25519 public key. Public: nothing in it opens the
29
+ * host. A host from before key pairing ignores it, and a launcher from before drops it at its next write.
30
+ *
31
+ * The port is the one the last `serve` actually listened on, which is how `--connection`, a separate process, learns a
32
+ * `--port` given to `serve` in a systemd unit. A version 1 file (`{ token, port }`) is moved to version 2 on first
33
+ * use: its token becomes a full credential labelled `legacy` (a hub or window still holding it keeps working), which the
34
+ * next pairing removes. This is the update path for a machine below `MIN_SUPPORTED_VERSION` (#1143): version 2 first
35
+ * shipped in 0.1.0-beta.45, so the hub's update of an older machine (`serve --detach`) and `npm i -g` run on a version 1 file.
36
+ */
37
+ export const SERVE_STATE_FILE = 'serve.json'
38
+
39
+ /** The label of the full credential a version 1 file's token became; removed by the next pairing */
40
+ export const LEGACY_LABEL = 'legacy'
41
+
42
+ /** A full credential's verifier: the SHA-256 of it, as hex (the host's `serve-credentials.ts` compares the same) */
43
+ export function verifierOf(credential) {
44
+ return createHash('sha256').update(credential).digest('hex')
45
+ }
46
+
47
+ /** The limited credential the host derives from `key` (#1405, the host's `transport/limited-token.ts`) */
48
+ export function limitedOf(key) {
49
+ return `ccl1:${createHmac('sha256', key).update('centralu limited token v1').digest('base64url')}`
50
+ }
51
+
52
+ /** What a detached serve writes: its own lines, and the host's until it is ready (host.log has the rest) */
53
+ export const SERVE_LOG_FILE = 'serve.log'
54
+
55
+ /** The running launcher's pid and port, so `--stop` can find it. Removed when it exits */
56
+ export const SERVE_PID_FILE = 'serve.pid'
57
+
58
+ /** How many earlier starts' serve.log are kept, as serve.log.1 (the last) to serve.log.3 */
59
+ export const SERVE_LOGS_KEPT = 3
60
+
61
+ /**
62
+ * Makes room for a new start's serve.log (#1143): the earlier ones move down a place, and the oldest past
63
+ * `SERVE_LOGS_KEPT` goes. A hub that starts a host again after it stopped makes at most three starts in ten minutes,
64
+ * so the log of the start that failed first is still here when it stops trying. The last one is moved aside with
65
+ * `renameRetrying` (a reader may hold the file on Windows, #1223); one that cannot be moved is removed rather than
66
+ * left to read as the new start's. Never fatal
67
+ */
68
+ export function rotateServeLog(log, kept = SERVE_LOGS_KEPT, rename = renameRetrying) {
69
+ // No log to move aside, no room to make: a second call for the same start (the task's line removed before a WMI start)
70
+ if (!existsSync(log)) return
71
+ for (let i = kept - 1; i >= 1; i--) {
72
+ try {
73
+ renameSync(`${log}.${i}`, `${log}.${i + 1}`)
74
+ } catch {
75
+ // there was none, or a reader holds it: the older log stays where it is
76
+ }
77
+ }
78
+ try {
79
+ rename(log, `${log}.1`)
80
+ } catch (e) {
81
+ if (e?.code === 'ENOENT') return
82
+ try {
83
+ rmSync(log, { force: true, maxRetries: 5 })
84
+ } catch {
85
+ // nothing more to do
86
+ }
87
+ }
88
+ }
89
+
90
+ /**
91
+ * The person's stop, kept in the data folder (#1143): `centralu serve --stop` writes it (`by: 'stop'`), and so does a
92
+ * host that Centralu's own app stops for good when the person quits it there (`by: 'quit'`, the host's
93
+ * lifecycle/stopped-mark.ts, which names the same file). Every host that starts in the folder removes it.
94
+ * `--connection` reports it while no host runs, and a hub then starts none by itself. A hub's own stop (an update)
95
+ * leaves none: it says so with `CENTRALU_STOP_BY=hub`
96
+ */
97
+ export const SERVE_STOPPED_FILE = 'stopped.json'
98
+
99
+ /** Writes the mark; never fatal, a stop that could not note itself still stopped */
100
+ export function markStopped(dataDir, by, now = Date.now()) {
101
+ try {
102
+ replaceFile(join(dataDir, SERVE_STOPPED_FILE), `${JSON.stringify({ v: 1, by, at: now })}\n`)
103
+ } catch {
104
+ // the folder is read-only or gone: nothing to remember it in
105
+ }
106
+ }
107
+
108
+ /** The mark as `{ by, at }`, or null when there is none. One that does not parse is still a stop, by `stop`, at no time */
109
+ export function readStopped(dataDir) {
110
+ let text
111
+ try {
112
+ text = readFileSync(join(dataDir, SERVE_STOPPED_FILE), 'utf8')
113
+ } catch {
114
+ return null
115
+ }
116
+ let o = null
117
+ try {
118
+ o = JSON.parse(text)
119
+ } catch {
120
+ // half written, or written by hand
121
+ }
122
+ return { by: o?.by === 'quit' ? 'quit' : 'stop', at: typeof o?.at === 'number' && Number.isFinite(o.at) ? o.at : null }
123
+ }
124
+
125
+ /**
126
+ * Starts in progress (#2150): each process that is starting a host in the folder writes its own record here, and removes it
127
+ * when its part is over. `--detach` writes one before it starts the launcher and removes it once it has answered, whichever
128
+ * way; the launcher writes its own before it starts the host and removes it once the host is ready or has exited. `--stop`
129
+ * waits while a record names a live process, so a host that is starting is stopped once it is up rather than reported as not
130
+ * running and left to come up after the stop. One file per writer, `<pid>.json`: two starts at once each keep theirs, a
131
+ * writer that was killed (an ssh that dropped) leaves a record of a dead process, which counts for nothing, and a WSL
132
+ * launcher writes its own from inside WSL, where a `--stop` there reads it. Each is `{ pid, started, at }`, as host.lock
133
+ * names its writer, so a pid another process got since is not taken for it
134
+ */
135
+ export const SERVE_STARTING_DIR = 'serve-starting'
136
+
137
+ /**
138
+ * How old a record may be and still count. Longer than any start takes (`--detach`: its sign-in task's 20 s, then 30 s): a
139
+ * record older than this names a start that hung, and a `--stop` goes on and stops what holds the folder, if anything
140
+ */
141
+ export const STARTING_MAX_MS = 120_000
142
+
143
+ const startingFile = (dataDir, pid) => join(dataDir, SERVE_STARTING_DIR, `${pid}.json`)
144
+
145
+ /** Names `pid` (by default this process) as one starting a host in the folder; never fatal */
146
+ export function markStarting(dataDir, pid = process.pid, startOf = processStartTime, now = Date.now()) {
147
+ try {
148
+ mkdirSync(join(dataDir, SERVE_STARTING_DIR), { recursive: true })
149
+ replaceFile(startingFile(dataDir, pid), `${JSON.stringify({ pid, started: startOf(pid), at: now })}\n`)
150
+ } catch {
151
+ // nowhere to write it: a --stop meanwhile reads the folder as before
152
+ }
153
+ }
154
+
155
+ /** Removes `pid`'s record (by default this process's) */
156
+ export function clearStarting(dataDir, pid = process.pid) {
157
+ try {
158
+ rmSync(startingFile(dataDir, pid), { force: true })
159
+ } catch {
160
+ // gone already
161
+ }
162
+ }
163
+
164
+ /** The records as `{ pid, started, at? }`; one that does not parse is left out */
165
+ export function readStarting(dataDir) {
166
+ let names = []
167
+ try {
168
+ names = readdirSync(join(dataDir, SERVE_STARTING_DIR)).filter((n) => /^\d+\.json$/.test(n))
169
+ } catch {
170
+ return []
171
+ }
172
+ return names.flatMap((n) => {
173
+ try {
174
+ const r = parseLockHolder(readFileSync(join(dataDir, SERVE_STARTING_DIR, n), 'utf8'))
175
+ return r ? [r] : []
176
+ } catch {
177
+ return []
178
+ }
179
+ })
180
+ }
181
+
182
+ /**
183
+ * The starts in progress: the records that name the live process that wrote them, no older than `maxAgeMs`. `known` keeps
184
+ * what was learnt of a record between calls (a Windows creation time costs a PowerShell), so a caller that asks again and
185
+ * again pays it once per record.
186
+ */
187
+ export function liveStarts(dataDir, known = new Map(), { maxAgeMs = STARTING_MAX_MS, now = Date.now(), startOf = processStartTime, createdAt = processCreatedAt, writer = (r) => isWriter(r, startOf, createdAt) } = {}) {
188
+ return readStarting(dataDir).filter((r) => {
189
+ if (typeof r.at === 'number' && now - r.at > maxAgeMs) return false
190
+ const key = `${r.pid}:${r.started}:${r.at}`
191
+ // A launcher of another logon (creation unreadable) is a live start for as long as a start takes, as records here are
192
+ if (!known.has(key)) known.set(key, isWriterWithin(r, maxAgeMs, writer))
193
+ return known.get(key) === true && isAlive(r.pid)
194
+ })
195
+ }
196
+
197
+ /** Whether a start is in progress (`liveStarts`) */
198
+ export function startingNow(dataDir, known = new Map(), o = {}) {
199
+ return liveStarts(dataDir, known, o).length > 0
200
+ }
201
+
202
+ /** The data folder: the host's own rule (`dataRoot()` in agent-host), CC_DATA_DIR or ~/.centralu */
203
+ export function serveDataDir(env, home) {
204
+ return env.CC_DATA_DIR || join(home, '.centralu')
205
+ }
206
+
207
+ /**
208
+ * The state, or null when there is none yet or it cannot be read as one. A file that is refused (Windows, while a
209
+ * writer or a scanner has it) or does not parse is read again a few times before it counts as unreadable: a
210
+ * `--detach` waiting for the port reads it while the launcher replaces it (#1041).
211
+ */
212
+ export function readServeState(dataDir, { tries = 5, sleep = sleepSync } = {}) {
213
+ const file = join(dataDir, SERVE_STATE_FILE)
214
+ for (let i = 1; ; i++) {
215
+ let raw
216
+ try {
217
+ raw = readFileSync(file, 'utf8')
218
+ } catch (e) {
219
+ if (e?.code === 'ENOENT' || i >= tries) return null
220
+ sleep(10 * i)
221
+ continue
222
+ }
223
+ const state = parseServeState(raw)
224
+ if (state || i >= tries) return state
225
+ sleep(10 * i)
226
+ }
227
+ }
228
+
229
+ /**
230
+ * The state as the launcher uses it. `token` is the credential the launcher's own probes say hello with, and
231
+ * `proofKey` what the host proves with to them: the limited credential and the key for version 2, the token for a
232
+ * version 1 file not moved yet.
233
+ */
234
+ function parseServeState(raw) {
235
+ try {
236
+ const v = JSON.parse(raw)
237
+ const port = Number.isInteger(v?.port) && v.port >= 1 && v.port <= 65535 ? v.port : null
238
+ if (v?.v !== 2) {
239
+ // A version 1 file, moved by `ensureServeState`: the update path from below the minimum (#1143)
240
+ if (typeof v?.token !== 'string' || v.token.length < 32) return null
241
+ return { v: 1, token: v.token, proofKey: v.token, port, key: null, full: [], keys: [] }
242
+ }
243
+ if (typeof v.key !== 'string' || v.key.length < 32) return null
244
+ // Exactly what the host takes (serve-credentials.ts `isListedEntry`): an entry of another shape is dropped here, so
245
+ // the next write leaves it out too, and the host refuses it meanwhile
246
+ const full = (Array.isArray(v.full) ? v.full : []).filter((e) => isListedEntry(e)).map((e) => ({ id: e.id, label: e.label, verifier: e.verifier, created: Number.isFinite(e.created) ? e.created : 0, ...(PAIRED_VIA.includes(e.via) ? { via: e.via } : {}), ...(e.replaced === true ? { replaced: true } : {}) }))
247
+ // The same for the hubs' key entries (#1711): one with a key the host refuses (§4.1) is dropped at the next write
248
+ const keys = (Array.isArray(v.keys) ? v.keys : []).filter((e) => isKeyEntry(e)).map((e) => ({ id: e.id, label: e.label, publicKey: e.publicKey, created: Number.isFinite(e.created) ? e.created : 0, via: 'pair-key', ...(e.replaced === true ? { replaced: true } : {}) }))
249
+ return { v: 2, key: v.key, port, full, keys, token: limitedOf(v.key), proofKey: v.key }
250
+ } catch {
251
+ return null
252
+ }
253
+ }
254
+
255
+ /** An entry the launcher lists, `--revoke` takes and the host accepts: an 8-hex id, a label `--pair` takes, a hex verifier */
256
+ export function isListedEntry(e) {
257
+ return typeof e?.id === 'string' && CREDENTIAL_ID_RE.test(e.id) && typeof e.label === 'string' && PAIR_LABEL_RE.test(e.label) && typeof e.verifier === 'string' && /^[0-9a-f]{64}$/.test(e.verifier)
258
+ }
259
+
260
+ /** A hub's key entry the launcher lists, `--revoke` takes and the host accepts (#1711): an 8-hex id, a label `--pair` takes, a public key the host takes (§4.1) */
261
+ export function isKeyEntry(e) {
262
+ return typeof e?.id === 'string' && CREDENTIAL_ID_RE.test(e.id) && typeof e.label === 'string' && PAIR_LABEL_RE.test(e.label) && parseLinkPublicKey(e.publicKey) !== null
263
+ }
264
+
265
+ /** What version 2 writes for a state; `keys` only when there are any, so a folder no hub paired by key keeps today's file */
266
+ function stateFile(state) {
267
+ return { v: 2, key: state.key, port: state.port, full: state.full, ...(state.keys?.length ? { keys: state.keys } : {}) }
268
+ }
269
+
270
+ /** A new full credential and its id */
271
+ function mint() {
272
+ return { token: randomBytes(32).toString('base64url'), id: randomBytes(4).toString('hex') }
273
+ }
274
+
275
+ /**
276
+ * The state, created on first use. Never replaces a token that is already there.
277
+ *
278
+ * Created with `wx`, so two first runs at the same moment (a `serve` and a `--connection`) cannot
279
+ * each write a different token: the second one fails to create and reads the first one's. A file
280
+ * that exists but cannot be read as state is refused rather than overwritten: it may be a token
281
+ * the client already holds, and a silent new one would lock that client out with "bad token".
282
+ */
283
+ export function ensureServeState(dataDir, platform = process.platform, now = Date.now()) {
284
+ mkdirSync(dataDir, { recursive: true })
285
+ const file = join(dataDir, SERVE_STATE_FILE)
286
+ if (!existsSync(file)) {
287
+ try {
288
+ writePrivate(file, { v: 2, key: randomBytes(32).toString('base64url'), port: null, full: [] }, 'wx')
289
+ } catch (e) {
290
+ if (e?.code !== 'EEXIST') throw e
291
+ }
292
+ }
293
+ let state = readServeState(dataDir)
294
+ if (!state) throw noState(file)
295
+ // A version 1 file (#1405): its token becomes a full credential no longer written down, and a new key is drawn. Kept as
296
+ // the update path for a machine below `MIN_SUPPORTED_VERSION` (#1143), whose launcher wrote version 1
297
+ if (state.v === 1) {
298
+ state = changeServeState(dataDir, (s) =>
299
+ s.v === 1
300
+ ? { v: 2, key: randomBytes(32).toString('base64url'), port: s.port, full: [{ id: randomBytes(4).toString('hex'), label: LEGACY_LABEL, verifier: verifierOf(s.token), created: now }], keys: [] }
301
+ : s,
302
+ platform,
303
+ )
304
+ }
305
+ keepPrivate(file, platform)
306
+ return state
307
+ }
308
+
309
+ /**
310
+ * Why serve.json gives no state (#1405 review): a file this user may not read is said as that, with what makes it
311
+ * readable again. Moving it aside, the advice for a file that is not a state file, would lock out every hub and window
312
+ * that holds a credential it names.
313
+ */
314
+ export function noState(file, read = readFileSync) {
315
+ try {
316
+ read(file)
317
+ } catch (e) {
318
+ if (e?.code === 'EACCES' || e?.code === 'EPERM') {
319
+ return new Error(`${file} cannot be read by this user (${e.code}). Give this user read and write access to it again (on Linux and macOS: chmod 600 ${file}) and run again; do not move it aside.`)
320
+ }
321
+ if (e?.code === 'ENOENT') return new Error(`${file} is missing`)
322
+ }
323
+ return new Error(`${file} exists but is not a serve state file. Move it aside and run again.`)
324
+ }
325
+
326
+ /** How long a held `serve.json.lock` is waited on before it counts as a crashed writer's (`changeServeState`) */
327
+ export const STATE_LOCK_STALE_MS = 10_000
328
+
329
+ /**
330
+ * How long before `STATE_LOCK_STALE_MS` a writer stops trying to write (#1405 review): the time it leaves itself
331
+ * for the rename, so that a rename it starts lands before any waiter may count its lock as stale
332
+ */
333
+ export const STATE_LOCK_MARGIN_MS = 2_000
334
+
335
+ /**
336
+ * Reads the state, changes it with `change` and writes it back, under a lock (`serve.json.lock`) so two changes at once
337
+ * (a hub pairing while a window starts) do not lose one another. Returns the state written.
338
+ *
339
+ * - A lock whose time is more than `STATE_LOCK_STALE_MS` from now, either way, is a crashed writer's and is taken over.
340
+ * Either way (#1405 review): a lock dated ahead of now (a crashed writer, then the clock set back) blocked every
341
+ * `--pair` and `--revoke` for as long as it was ahead, so a hub could not link.
342
+ * - The lock holds a nonce of its writer's, and the writer reads it back before each try of the rename that replaces
343
+ * the file: a writer stalled past the 10 s, whose lock another took over meanwhile, writes nothing (#1405 review),
344
+ * rather than a state it computed before a `--revoke` that came in between. It throws, and whoever asked tries again
345
+ * (a hub at its next link attempt, a person by running it again).
346
+ * - A writer also writes only within `STATE_LOCK_STALE_MS - STATE_LOCK_MARGIN_MS` of taking its lock, by this
347
+ * process's own clock, which a clock set back does not stretch (#1405 review): on Windows a rename is tried again
348
+ * for up to 5 s while a reader holds the file, and a try seconds after the read-back could land after another writer
349
+ * took the lock over and wrote. Its last try is then at least 2 s before any waiter may take the lock over.
350
+ * - Taking over a stale lock, and removing its own at the end, first move the lock aside under a name of this
351
+ * writer's and look at what was moved: a fresh lock, or another writer's, is put back (`releaseLock`). Before, two
352
+ * waiters taking over one stale lock at once could remove the other's fresh lock, and a writer's end could remove the
353
+ * lock of one that took it over between its read-back and its removal.
354
+ *
355
+ * What is left: a writer suspended for over 2 s between its last read-back and the rename right after it; a
356
+ * system clock set forward by more than 10 s while a writer holds the lock, which makes its lock look stale to a
357
+ * waiter; and the moment a lock is moved aside to be looked at, during which a third writer may create one and read
358
+ * the state while the lock's owner, past its read-back, renames (on a file system without hard links the moved lock is
359
+ * not put back at all, and its owner's next read-back refuses). No lock file can close these.
360
+ */
361
+ export function changeServeState(dataDir, change, platform = process.platform, { sleep = sleepSync, nowMs = Date.now, clock = () => performance.now(), read = readFileSync } = {}) {
362
+ const file = join(dataDir, SERVE_STATE_FILE)
363
+ const lock = `${file}.lock`
364
+ const mine = randomBytes(8).toString('hex')
365
+ for (let i = 0; ; i++) {
366
+ try {
367
+ const fd = openSync(lock, 'wx', 0o600)
368
+ try {
369
+ writeSync(fd, mine)
370
+ } finally {
371
+ closeSync(fd)
372
+ }
373
+ break
374
+ } catch (e) {
375
+ if (e?.code !== 'EEXIST') throw e
376
+ try {
377
+ if (Math.abs(nowMs() - statSync(lock).mtimeMs) > STATE_LOCK_STALE_MS) takeOverStale(lock, mine, nowMs)
378
+ } catch {
379
+ // gone meanwhile: try again
380
+ }
381
+ // Past the 10 s after which a lock counts as a crashed writer's, so a waiter takes it over rather than giving up first
382
+ if (i >= 480) throw new Error(`${lock} is held by another serve; try again`)
383
+ sleep(25)
384
+ }
385
+ }
386
+ const took = clock()
387
+ const held = () => {
388
+ try {
389
+ return read(lock, 'utf8') === mine
390
+ } catch {
391
+ return false
392
+ }
393
+ }
394
+ // Whether this writer may still write: within its time, and the lock still its own
395
+ const mayWrite = () => {
396
+ if (clock() - took >= STATE_LOCK_STALE_MS - STATE_LOCK_MARGIN_MS) return new Error(`${lock} was held too long by this serve to write safely; nothing was written, try again`)
397
+ if (!held()) return new Error(`${lock} was taken over while this serve held it; nothing was written, try again`)
398
+ return null
399
+ }
400
+ try {
401
+ const before = readServeState(dataDir)
402
+ if (!before) throw noState(file)
403
+ const after = change(before)
404
+ if (after !== before) {
405
+ const refusal = mayWrite()
406
+ if (refusal) throw refusal
407
+ replacePrivate(file, stateFile(after), platform, { mayTry: mayWrite })
408
+ }
409
+ // What was written, as a reader reads it: never null once written
410
+ return after !== before ? parseServeState(JSON.stringify(stateFile(after))) : before
411
+ } finally {
412
+ // Only its own: a lock another writer took over is that writer's to keep
413
+ releaseLock(lock, mine, { read })
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Removes `lock` if it is `mine` (#1405 review): moved aside under a name of this writer's first, so what is looked at
419
+ * is what is removed, and put back when it was another writer's. Reading it and then removing it by name could remove
420
+ * a lock another writer took over in between. Never throws: a lock left behind goes stale and is taken over.
421
+ */
422
+ export function releaseLock(lock, mine, { read = readFileSync, rename = renameSync, link = linkSync, rm = rmSync } = {}) {
423
+ const aside = `${lock}.${mine}.release`
424
+ try {
425
+ renameRetrying(lock, aside, { rename, budgetMs: 1_000 })
426
+ } catch {
427
+ // not there (taken over and removed), or held open past the retries: nothing of this writer's to remove now
428
+ return
429
+ }
430
+ let found = null
431
+ try {
432
+ found = read(aside, 'utf8')
433
+ } catch {
434
+ // unreadable (a scanner on Windows): it may be another writer's, so it is put back; if it was this one's, it goes stale
435
+ }
436
+ if (found !== mine) putBack(aside, lock, link)
437
+ try {
438
+ rm(aside, { force: true })
439
+ } catch {
440
+ // a stray file beside the lock, nothing a writer reads
441
+ }
442
+ }
443
+
444
+ /**
445
+ * Takes over a lock that looked stale (`changeServeState`): moved aside first, and put back when what was moved is not
446
+ * stale after all (another waiter's fresh lock, taken over a moment before). The caller then creates its own
447
+ */
448
+ function takeOverStale(lock, mine, nowMs) {
449
+ const aside = `${lock}.${mine}.stale`
450
+ renameSync(lock, aside)
451
+ let stale = true
452
+ try {
453
+ stale = Math.abs(nowMs() - statSync(aside).mtimeMs) > STATE_LOCK_STALE_MS
454
+ } catch {
455
+ // gone: nothing to put back
456
+ }
457
+ if (!stale) putBack(aside, lock, linkSync)
458
+ rmSync(aside, { force: true })
459
+ }
460
+
461
+ /** Puts a moved lock back where it was, unless another writer created one there since (a hard link never replaces) */
462
+ function putBack(aside, lock, link) {
463
+ try {
464
+ link(aside, lock)
465
+ } catch {
466
+ // another holds the lock by now, or links are not possible here: that writer's read-back sees it is not its own
467
+ }
468
+ }
469
+
470
+ /**
471
+ * How a full credential was asked for, kept on its entry as `via` (#1405 review): `pair` (`--connection --pair`, a
472
+ * hub's at each link or any program's), `window` (`--window`, the person's window on Windows at each start), `handover`
473
+ * (the launcher's own, for one `host.handover` call and withdrawn right after)
474
+ */
475
+ export const PAIRED_VIA = ['pair', 'window', 'handover']
476
+
477
+ /**
478
+ * A new full credential for `label` (#1405): written as its verifier only, and returned once. One label holds one
479
+ * credential: a hub pairing again (each link does) replaces its own, and `window` the window's. The `legacy` one a
480
+ * version 1 file left goes with a hub's or the window's pairing: whoever held it was one of the two, which pairs now.
481
+ * `via` is how it was asked for (`PAIRED_VIA`). Returns `{ token, id, state }`.
482
+ *
483
+ * `replaced` (#1405 review): set on the new entry only when the one of its label it takes the place of was asked for
484
+ * another way, or the file does not say how. The window pairing again at each start, and a hub at each link, are the
485
+ * same pairer as before and are not marked: marked at every routine pairing, the flag meant nothing. A `--pair window`
486
+ * taking the window's place, or the window's next start taking that one's, is marked. What this cannot tell is two
487
+ * askers of the same way: a program's `--pair hub:<name>-<key>` against that hub's own. The hub's row tells that one
488
+ * by itself (`hubsName`, and its own credential gone), docs/security-boundaries/remote-host.md.
489
+ */
490
+ export function pairServe(dataDir, label, platform = process.platform, now = Date.now(), via = 'pair') {
491
+ ensureServeState(dataDir, platform, now)
492
+ const { token, id } = mint()
493
+ const state = changeServeState(dataDir, (s) => ({
494
+ ...s,
495
+ /*
496
+ * A hub's or the window's pairing removes the `legacy` one (#1405 review): whoever held it was a hub or the window
497
+ * of before #1405, each of which pairs now, so on a machine no hub links to it does not outlive the window's next
498
+ * start. Any other label leaves it: a program's own `--pair` does not cut off a hub that has not paired yet
499
+ */
500
+ full: [
501
+ ...s.full.filter((e) => e.label !== label && !(takesLegacyPlace(label) && e.label === LEGACY_LABEL)),
502
+ { id, label, verifier: verifierOf(token), created: now, via, ...(s.full.some((e) => e.label === label && e.via !== via) ? { replaced: true } : {}) },
503
+ ],
504
+ }), platform)
505
+ return { token, id, state }
506
+ }
507
+
508
+ /** The pairings that stand for whoever held a version 1 file's token: a hub's and the window's (`pairServe`) */
509
+ function takesLegacyPlace(label) {
510
+ return label === 'window' || label.startsWith('hub:')
511
+ }
512
+
513
+ /**
514
+ * The key entry for `label` with `publicKey` (#1711, docs/plans/key-pairing.md §4.2): `--pair-key`'s write. At most one
515
+ * key entry per label. The same key under the same label keeps its entry and id; another key under it is a new entry
516
+ * with a new id, marked `replaced`, and the old key entry goes, so a socket in under the old key is closed by the sweep
517
+ * (which compares id and key). The label's verifier entry is never touched here. Returns `{ entry, state }`.
518
+ */
519
+ export function pairKeyServe(dataDir, label, publicKey, platform = process.platform, now = Date.now()) {
520
+ if (!parseLinkPublicKey(publicKey)) throw new Error('A refused public key is never written')
521
+ ensureServeState(dataDir, platform)
522
+ let entry = null
523
+ const state = changeServeState(dataDir, (s) => {
524
+ const before = s.keys.find((k) => k.label === label)
525
+ /*
526
+ * The host takes the first key entry of an id (#1717 review, L2), so one written by hand ahead of the hub's, with its id
527
+ * and another key, keeps the hub from linking. Such an id is not kept: the entry gets a fresh one, which the line reports.
528
+ * The same for an id a verifier entry has (#1717 recheck, F1): the host takes no key entry of such an id
529
+ */
530
+ const shared = before !== undefined && (s.keys.some((k) => k !== before && k.id === before.id) || s.full.some((e) => e.id === before.id))
531
+ if (before && before.publicKey === publicKey && !shared) {
532
+ entry = before
533
+ return s
534
+ }
535
+ entry = { id: freshId(s), label, publicKey, created: now, via: 'pair-key', ...(before ? { replaced: true } : {}) }
536
+ return { ...s, keys: [...s.keys.filter((k) => k.label !== label), entry] }
537
+ }, platform)
538
+ return { entry, state }
539
+ }
540
+
541
+ /** An entry id no full credential and no key entry of `state` has: a `--revoke <id>` names one entry */
542
+ function freshId(state) {
543
+ for (;;) {
544
+ const id = randomBytes(4).toString('hex')
545
+ if (!state.full.some((e) => e.id === id) && !state.keys.some((k) => k.id === id)) return id
546
+ }
547
+ }
548
+
549
+ /**
550
+ * Removes the verifier entry under `label` (#1711, `--key-paired`): the hub paired by key with this machine before and
551
+ * now has a key line, so the verifier entry it made under its label is no longer its own. Returns the state written.
552
+ */
553
+ export function dropVerifierUnder(dataDir, label, platform = process.platform) {
554
+ return changeServeState(dataDir, (s) => (s.full.some((e) => e.label === label) ? { ...s, full: s.full.filter((e) => e.label !== label) } : s), platform)
555
+ }
556
+
557
+ /** Removes the full credential or the key entry `id`; true when there was one. A hello with it is refused from then on */
558
+ export function revokeServe(dataDir, id, platform = process.platform) {
559
+ let found = false
560
+ changeServeState(dataDir, (s) => {
561
+ found = s.full.some((e) => e.id === id) || s.keys.some((k) => k.id === id)
562
+ return found ? { ...s, full: s.full.filter((e) => e.id !== id), keys: s.keys.filter((k) => k.id !== id) } : s
563
+ }, platform)
564
+ return found
565
+ }
566
+
567
+ /** Writes the port `serve` listened on, keeping the rest. Atomic: a temp file renamed over it */
568
+ export function recordServePort(dataDir, port, platform = process.platform) {
569
+ changeServeState(dataDir, (s) => (s.port === port ? s : { ...s, port }), platform)
570
+ }
571
+
572
+ /**
573
+ * A new key, and no full credential and no key entry, keeping the port. Only when the person asks (`--rotate-token`):
574
+ * every hub pairs again at its next link, the window at its next start, and a serve already running keeps its old key
575
+ * (what it hands out, and what it signs with, #1711 §7) until it restarts, while the full credentials end at once.
576
+ */
577
+ export function rotateServeToken(dataDir, platform = process.platform) {
578
+ ensureServeState(dataDir, platform)
579
+ return changeServeState(dataDir, (s) => ({ ...s, key: randomBytes(32).toString('base64url'), full: [], keys: [] }), platform)
580
+ }
581
+
582
+ /**
583
+ * Created 0600 from the first byte, not chmod-ed after: a file written with the default mode and
584
+ * narrowed afterwards is readable by everyone on the machine for the moment in between.
585
+ */
586
+ function writePrivate(file, value, flag) {
587
+ const fd = openSync(file, flag, 0o600)
588
+ try {
589
+ writeSync(fd, `${JSON.stringify(value)}\n`)
590
+ } finally {
591
+ closeSync(fd)
592
+ }
593
+ }
594
+
595
+ /** Replaces a private file whole (`replaceFile`), created 0600 as `writePrivate` creates one; `rename` goes to `renameRetrying` */
596
+ function replacePrivate(file, value, platform, rename = {}) {
597
+ replaceFile(file, `${JSON.stringify(value)}\n`, { mode: 0o600, flag: 'wx', ...rename })
598
+ keepPrivate(file, platform)
599
+ }
600
+
601
+ /**
602
+ * 0600 again on every use. A copy, a restore from backup or an editor that rewrites the file can
603
+ * leave it readable by the group; the token in it is the key to every RPC. Windows has no mode
604
+ * bits to set (the profile folder's ACL is what protects it there).
605
+ */
606
+ function keepPrivate(file, platform) {
607
+ if (platform === 'win32') return
608
+ if ((statSync(file).mode & 0o777) !== 0o600) chmodSync(file, 0o600)
609
+ }
610
+
611
+ /** serve.pid: `{ pid, hostPid, port }` of the launcher that runs, or null */
612
+ export function readServePid(dataDir) {
613
+ try {
614
+ const v = JSON.parse(readFileSync(join(dataDir, SERVE_PID_FILE), 'utf8'))
615
+ return Number.isInteger(v?.pid) && v.pid > 0 ? { pid: v.pid, hostPid: Number.isInteger(v.hostPid) ? v.hostPid : null, port: v.port ?? null } : null
616
+ } catch {
617
+ return null
618
+ }
619
+ }
620
+
621
+ export function removeServePid(dataDir, pid) {
622
+ if (readServePid(dataDir)?.pid !== pid) return
623
+ try {
624
+ rmSync(join(dataDir, SERVE_PID_FILE), { force: true })
625
+ } catch {
626
+ // another serve's by now, or gone
627
+ }
628
+ }
629
+
630
+ /**
631
+ * A probe that did not prove the token, while this data folder's `serve` is alive (`host.lock`): a host still on its old
632
+ * key after `--rotate-token`. It is running, and is not sent the token; a hub asking it for a proof is refused until it
633
+ * restarts. Without a live lock holder that `serve` started (`startedByServe`), what answered is not ours: a live holder
634
+ * the app or the keeper started owns the folder, and whatever sits on the recorded port (a hub's ssh forward, #1722) is
635
+ * not that holder.
636
+ *
637
+ * `portRecorded`: serve.json names the port the probe went to (`state.port != null`). A folder that has none was probed
638
+ * on the default port, where whatever listens is as likely another host's (a hub's ssh forward to a linked machine's serve
639
+ * lands there): an unproven answer from it says nothing about this folder, whoever holds the lock.
640
+ */
641
+ export function heldHere(probe, dataDir, startOf = processStartTime, portRecorded = true) {
642
+ if (probe.running) return true
643
+ if (!probe.unproven || !portRecorded) return false
644
+ return lockHolderIsAlive(dataDir, startOf) && startedByServe(dataDir)
645
+ }
646
+
647
+ /**
648
+ * Whether the process `host.lock` names is a host `centralu serve` started (#1722): what lets the launcher signal it.
649
+ * The lock says so itself (`by: 'serve'`, #1223); a lock that names another starter (`app`, `keeper`), or none (a host
650
+ * started by hand), is not serve's.
651
+ */
652
+ export function startedByServe(dataDir) {
653
+ return lockHolder(dataDir)?.by === 'serve'
654
+ }
655
+
656
+ /** Who `by` in host.lock says started the host, as a phrase (#1223); an absent `by` is most likely the app */
657
+ export function holderWho(by) {
658
+ return { app: 'the Centralu window on this machine', keeper: "Centralu's keeper on this machine", serve: 'another centralu serve' }[by] ?? 'probably the Centralu app on this machine'
659
+ }
660
+
661
+ /**
662
+ * The live process that holds this folder's lock and that `centralu serve` did not start, `{ pid, started, by? }`, or
663
+ * null (#1722): `--stop` names it rather than signal it. Only named, so a pid that is alive is enough (no start time:
664
+ * Windows has none), as for the message `serve` itself prints when the lock stops its host.
665
+ */
666
+ export function foreignHolder(dataDir) {
667
+ const holder = lockHolder(dataDir)
668
+ return holder && isAlive(holder.pid) && !startedByServe(dataDir) ? holder : null
669
+ }
670
+
671
+ /**
672
+ * Whether the process `host.lock` names is the one that wrote it (#838 review): alive, and started when the lock says
673
+ * (`ps -o lstart`, as the host writes it, `instance-lock.ts`). A lock left by a host that died, whose pid another
674
+ * process of the same user now has, names a stranger: counted as running, `--stop` would signal it. A lock without a
675
+ * start time and no `at` (its host found no `ps`) cannot be told apart, so it does not count. Windows has no `ps` and its
676
+ * host records no start time (#1723), only `at`, when it took the folder: the process that wrote the lock was created by
677
+ * then, and one given its number afterwards was created later. Both times come from one clock and the host writes `at`
678
+ * 17 ms or more after its process was created, so the slack is one clock tick, for the two readings of it. An `at` in the
679
+ * future (a clock set back since) proves nothing.
680
+ */
681
+ export function lockHolderIsAlive(dataDir, startOf = processStartTime, createdAt = processCreatedAt) {
682
+ return isWriter(lockHolder(dataDir), startOf, createdAt) === true
683
+ }
684
+
685
+ /**
686
+ * Whether `{ pid, started, at }` names the live process that wrote it, by `lockHolderIsAlive`'s rule: true, false, or
687
+ * null when it lives and Windows cannot say when it was created (another logon's process); each caller decides what
688
+ * that counts as
689
+ */
690
+ export function isWriter(holder, startOf = processStartTime, createdAt = processCreatedAt) {
691
+ if (!holder || !isAlive(holder.pid)) return false
692
+ if (holder.started) return startOf(holder.pid) === holder.started
693
+ if (holder.at === undefined || holder.at > Date.now()) return false
694
+ const created = createdAt(holder.pid)
695
+ return created === null ? null : created <= holder.at + CLOCK_TICK_MS
696
+ }
697
+
698
+ /**
699
+ * `isWriter` with its third answer settled: a process that lives but whose creation Windows will not tell (another logon's,
700
+ * `null`) counts as the writer while its record is younger than `maxAgeMs`, by the `at` it wrote. Asking for more
701
+ * (an elevated read, a prompt) is not an option for a launcher; the cost is a stranger that took a dead writer's pid
702
+ * within that time counting as the writer for the rest of it.
703
+ */
704
+ export function isWriterWithin(holder, maxAgeMs, writer = isWriter) {
705
+ const w = writer(holder)
706
+ return w === null ? typeof holder?.at === 'number' && Date.now() - holder.at < maxAgeMs : w
707
+ }
708
+
709
+ /** One tick of the Windows clock */
710
+ const CLOCK_TICK_MS = 16
711
+
712
+ /**
713
+ * host.lock's `{ pid, started, by? }`. `by` (#1223, additive) is who started the host: `app`, `keeper` or `serve`
714
+ * (`instance-lock.ts`), absent when the host did not say
715
+ */
716
+ function parseLockHolder(text) {
717
+ try {
718
+ const v = JSON.parse(text)
719
+ if (!Number.isInteger(v?.pid) || v.pid <= 0) return null
720
+ const by = v.by === 'app' || v.by === 'keeper' || v.by === 'serve' ? v.by : null
721
+ return { pid: v.pid, started: typeof v.started === 'string' ? v.started : null, ...(Number.isFinite(v.at) ? { at: v.at } : {}), ...(by ? { by } : {}) }
722
+ } catch {
723
+ return null
724
+ }
725
+ }
726
+
727
+ /**
728
+ * A pid's start time, as `instance-lock.ts`'s `processStartTime` reads it: `ps -o lstart=` with the C locale, so the
729
+ * host that wrote the lock and this launcher read the same text. null without `ps` (Windows) or when it fails.
730
+ */
731
+ export function processStartTime(pid) {
732
+ if (process.platform === 'win32') return null
733
+ try {
734
+ return execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8', timeout: 2000, env: { ...process.env, LC_ALL: 'C' }, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null
735
+ } catch {
736
+ return null
737
+ }
738
+ }
739
+
740
+ /**
741
+ * When a pid's process was created, as milliseconds since the epoch, on Windows (PowerShell); null elsewhere, or when
742
+ * it cannot be told (a process of another account). Asked of .NET, not `Get-Process`: that one loads a module, which
743
+ * under PowerShell 7's module path (a CI runner's, a pwsh terminal's) fails, and every lock held on Windows read as a
744
+ * dead one's (#1906)
745
+ */
746
+ export function processCreatedAt(pid) {
747
+ if (process.platform !== 'win32') return null
748
+ try {
749
+ const out = execFileSync(windowsPowershell('wmi', process.env), ['-NoProfile', '-NonInteractive', '-Command', `([DateTimeOffset][Diagnostics.Process]::GetProcessById(${pid}).StartTime).ToUnixTimeMilliseconds()`], { encoding: 'utf8', timeout: 10_000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })
750
+ const ms = Number(out.trim())
751
+ return Number.isFinite(ms) && ms > 0 ? ms : null
752
+ } catch {
753
+ return null
754
+ }
755
+ }
756
+
757
+ /** Who `host.lock` names as the data folder's owner, `{ pid, started, by?, at? }`, or null */
758
+ export function lockHolder(dataDir) {
759
+ try {
760
+ return parseLockHolder(readFileSync(join(dataDir, 'host.lock'), 'utf8'))
761
+ } catch {
762
+ return null
763
+ }
764
+ }
765
+
766
+ /** Who `host.lock` names as the data folder's owner, or null */
767
+ export function lockHolderPid(dataDir) {
768
+ try {
769
+ return parseLockHolder(readFileSync(join(dataDir, 'host.lock'), 'utf8'))?.pid ?? null
770
+ } catch {
771
+ return null
772
+ }
773
+ }