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.
- package/bin/centralu.mjs +434 -61
- package/bin/node-floor.mjs +42 -0
- package/bin/platform.mjs +380 -0
- package/bin/semver.mjs +34 -1
- package/bin/serve-args.mjs +181 -0
- package/bin/serve-autostart.mjs +490 -0
- package/bin/serve-detach.mjs +377 -0
- package/bin/serve-files.mjs +773 -0
- package/bin/serve-handover.mjs +192 -0
- package/bin/serve-host.mjs +467 -0
- package/bin/serve-install.mjs +218 -0
- package/bin/serve-keys.mjs +126 -0
- package/bin/serve-port.mjs +79 -0
- package/bin/serve-run.mjs +290 -0
- package/bin/serve-switch.mjs +635 -0
- package/bin/serve-util.mjs +144 -0
- package/bin/serve-window.mjs +147 -0
- package/bin/serve-windows.mjs +181 -0
- package/bin/serve.mjs +39 -0
- package/bin/swap.mjs +48 -0
- package/package.json +10 -6
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two launchers and the install they reach: `<data>/bin/centralu` that `serve` keeps for an npm
|
|
3
|
+
* install, and the managed install the hub writes over ssh (`<data>/remote/`, docs/plans/remote-hub.md
|
|
4
|
+
* §10.1), with the launcher that never changes and the pointers it reads.
|
|
5
|
+
*/
|
|
6
|
+
import { chmodSync, mkdirSync, readFileSync, statSync } from 'node:fs'
|
|
7
|
+
import { dirname, join } from 'node:path'
|
|
8
|
+
import { replaceFile, say } from './serve-util.mjs'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The launcher `serve` keeps at `<data folder>/bin/centralu` (`centralu.cmd` on Windows).
|
|
12
|
+
*
|
|
13
|
+
* The client runs `ssh -T -o BatchMode=yes <target> centralu …`, and a non-interactive SSH shell
|
|
14
|
+
* reads no profile: npm's global bin under nvm, fnm, volta or `~/.npm-global` is not on its PATH,
|
|
15
|
+
* and often neither is `node`. So the plain name fails with exit 127, and the person, who just ran
|
|
16
|
+
* `centralu serve` in their own shell, sees no reason why. This file names both by absolute path,
|
|
17
|
+
* so `~/.centralu/bin/centralu` works from any shell. It is rewritten whenever it differs from
|
|
18
|
+
* what this run would write, which follows a Node upgrade or a moved npm prefix on the next start.
|
|
19
|
+
*/
|
|
20
|
+
export function launcherScript(platform, execPath, cliPath) {
|
|
21
|
+
if (platform === 'win32') {
|
|
22
|
+
// A batch file reads every % as the start of a variable (`100% cli.mjs" %*` came out as `100*`); %% is a literal one
|
|
23
|
+
const lit = (v) => String(v).replaceAll('%', '%%')
|
|
24
|
+
/*
|
|
25
|
+
* The file is UTF-8, and cmd.exe reads each line of a batch file in the console's code page as it reaches it: 949
|
|
26
|
+
* on a Korean Windows, where a profile folder named in Korean came out as other characters and node found no
|
|
27
|
+
* centralu.mjs there (#849). So the lines before the paths, all ASCII, switch the console to UTF-8 (65001), and the
|
|
28
|
+
* code page it had is put back on the line with the paths, ahead of node: cmd.exe reads and decodes a whole line
|
|
29
|
+
* before it runs any of it, so the paths are already read as UTF-8 by then. The console is the shell's that ran
|
|
30
|
+
* this, and node runs on the page it had; a Ctrl+C answered at "Terminate batch job (Y/N)?" ends this file
|
|
31
|
+
* before any later line, and a restore there was skipped. chcp is named by its full path: the shell's PATH may
|
|
32
|
+
* not have System32 on it.
|
|
33
|
+
*/
|
|
34
|
+
return [
|
|
35
|
+
'@echo off',
|
|
36
|
+
"rem Written by `centralu serve`: reaches this install without npm's folder on PATH.",
|
|
37
|
+
'setlocal',
|
|
38
|
+
'set "CENTRALU_CP="',
|
|
39
|
+
`for /f "tokens=2 delims=:." %%c in ('%SystemRoot%\\System32\\chcp.com') do set /a "CENTRALU_CP=%%c" >nul 2>&1`,
|
|
40
|
+
'%SystemRoot%\\System32\\chcp.com 65001 >nul 2>&1',
|
|
41
|
+
`(if defined CENTRALU_CP %SystemRoot%\\System32\\chcp.com %CENTRALU_CP% >nul 2>&1) & "${lit(execPath)}" "${lit(cliPath)}" %*`,
|
|
42
|
+
'exit /b %ERRORLEVEL%',
|
|
43
|
+
'',
|
|
44
|
+
].join('\r\n')
|
|
45
|
+
}
|
|
46
|
+
const q = (v) => `'${String(v).replaceAll("'", "'\\''")}'`
|
|
47
|
+
return (
|
|
48
|
+
'#!/bin/sh\n' +
|
|
49
|
+
"# Written by `centralu serve`: reaches this install from a shell whose PATH has neither npm's global\n" +
|
|
50
|
+
'# folder nor node (a non-interactive SSH session). Rewritten when node or the package moves.\n' +
|
|
51
|
+
`exec ${q(execPath)} ${q(cliPath)} "$@"\n`
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Writes the launcher if it is missing or out of date. Returns its path. Never fatal to the caller */
|
|
56
|
+
export function ensureLauncher(dataDir, { platform = process.platform, execPath = process.execPath, cliPath }) {
|
|
57
|
+
const file = join(dataDir, 'bin', platform === 'win32' ? 'centralu.cmd' : 'centralu')
|
|
58
|
+
const want = launcherScript(platform, execPath, cliPath)
|
|
59
|
+
let have = null
|
|
60
|
+
try {
|
|
61
|
+
have = readFileSync(file, 'utf8')
|
|
62
|
+
} catch {
|
|
63
|
+
// not there yet
|
|
64
|
+
}
|
|
65
|
+
if (have !== want) {
|
|
66
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
67
|
+
replaceFile(file, want, { mode: 0o755 })
|
|
68
|
+
}
|
|
69
|
+
if (platform !== 'win32' && (statSync(file).mode & 0o777) !== 0o755) chmodSync(file, 0o755)
|
|
70
|
+
return file
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* ensureLauncher, with a failure said on stderr instead of thrown: the launcher is a convenience.
|
|
75
|
+
*
|
|
76
|
+
* Not under the managed launcher (`CENTRALU_MANAGED=1`, docs/plans/remote-hub.md §10.1): an install
|
|
77
|
+
* the hub made over ssh has its own launcher in `<data>/remote/bin/`, which reads `current`. Writing
|
|
78
|
+
* `<data>/bin/centralu` from there would point an npm install's launcher at one managed version, and
|
|
79
|
+
* the two would rewrite each other's file on every start.
|
|
80
|
+
*/
|
|
81
|
+
export function keepLauncher(dataDir, cliPath, env) {
|
|
82
|
+
if (!cliPath || env?.CENTRALU_MANAGED === '1') return
|
|
83
|
+
try {
|
|
84
|
+
ensureLauncher(dataDir, { cliPath })
|
|
85
|
+
} catch (e) {
|
|
86
|
+
say(`could not write the launcher in ${join(dataDir, 'bin')}: ${e.message}`)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The install the hub manages on this machine (docs/plans/remote-hub.md §10.1): side-by-side
|
|
92
|
+
* versions, the pinned Node they run on, and two pointer files naming what runs and what to roll
|
|
93
|
+
* back to. The hub's installer writes it; `serve` only reads it.
|
|
94
|
+
*/
|
|
95
|
+
export function remoteLayout(dataDir) {
|
|
96
|
+
const root = join(dataDir, 'remote')
|
|
97
|
+
return {
|
|
98
|
+
root,
|
|
99
|
+
current: join(root, 'current'),
|
|
100
|
+
previous: join(root, 'previous'),
|
|
101
|
+
versions: join(root, 'versions'),
|
|
102
|
+
node: join(root, 'node'),
|
|
103
|
+
bin: join(root, 'bin'),
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A word a pointer file may hold: a folder name, nothing a path could escape with */
|
|
108
|
+
export const POINTER_WORD = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$/
|
|
109
|
+
|
|
110
|
+
/** `current` / `previous`: one line, "<centralu version> <node version>". null for anything else */
|
|
111
|
+
export function parsePointer(text) {
|
|
112
|
+
const m = /^\s*(\S+)[ \t]+(\S+)\s*$/.exec(String(text ?? ''))
|
|
113
|
+
if (!m || !POINTER_WORD.test(m[1]) || !POINTER_WORD.test(m[2])) return null
|
|
114
|
+
return { version: m[1], node: m[2] }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Where a managed version came from, from its `install.json`: `{ kind: 'dev', commit, dirty }` for a dev build put
|
|
119
|
+
* there from a git commit (`pnpm remote-dev`, #1036), null for a release (or anything unreadable). The hub shows it
|
|
120
|
+
* on the machine's row, so a build no release produced is never mistaken for one.
|
|
121
|
+
*/
|
|
122
|
+
export function installSource(versionDir) {
|
|
123
|
+
try {
|
|
124
|
+
const s = JSON.parse(readFileSync(join(versionDir, 'install.json'), 'utf8')).source
|
|
125
|
+
if (s?.kind === 'dev' && typeof s.commit === 'string' && /^[0-9a-f]{7,64}$/.test(s.commit)) return { kind: 'dev', commit: s.commit, dirty: s.dirty === true }
|
|
126
|
+
} catch {
|
|
127
|
+
// no install.json, or not one this reads
|
|
128
|
+
}
|
|
129
|
+
return null
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The connection line's `install` field (docs/plans/remote-hub.md §10.5): whether this command was
|
|
134
|
+
* started by the managed launcher, the managed install's `current` and `previous`, and the Node
|
|
135
|
+
* running this command. Read from the machine at every ask, never kept by the hub (S12).
|
|
136
|
+
*/
|
|
137
|
+
export function installInfo(dataDir, env, nodeVersion = process.versions.node) {
|
|
138
|
+
const l = remoteLayout(dataDir)
|
|
139
|
+
const read = (file) => {
|
|
140
|
+
let p
|
|
141
|
+
try {
|
|
142
|
+
p = parsePointer(readFileSync(file, 'utf8'))
|
|
143
|
+
} catch {
|
|
144
|
+
return null
|
|
145
|
+
}
|
|
146
|
+
const source = p && installSource(join(l.versions, p.version))
|
|
147
|
+
return p && source ? { ...p, source } : p
|
|
148
|
+
}
|
|
149
|
+
return { managed: env.CENTRALU_MANAGED === '1', current: read(l.current), previous: read(l.previous), node: nodeVersion, lastSwitch: lastSwitchOf(l.root) }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The last switch there (`switch.json`, serve-switch.mjs), as much as a hub needs to know whether to read it: its id,
|
|
154
|
+
* whether it ended, and whether its outcome was reported (`--seen`). A hub that was away for the whole of it, or
|
|
155
|
+
* restarted since, learns from this at its next open that there is an outcome to say (#1907). Null when none ran
|
|
156
|
+
*/
|
|
157
|
+
function lastSwitchOf(root) {
|
|
158
|
+
try {
|
|
159
|
+
const s = JSON.parse(readFileSync(join(root, 'switch.json'), 'utf8'))
|
|
160
|
+
return typeof s?.id === 'string' ? { id: s.id, ended: typeof s.outcome === 'string', seen: s.seen === true } : null
|
|
161
|
+
} catch {
|
|
162
|
+
return null
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The managed launcher, `<data>/remote/bin/centralu` (`centralu.cmd` on Windows), as the installer
|
|
168
|
+
* writes it (docs/plans/remote-hub.md §10.1, S8).
|
|
169
|
+
*
|
|
170
|
+
* **Its text never changes.** It reads `current` at every start and runs that version's
|
|
171
|
+
* `centralu.mjs` on that version's Node, so switching versions is one file replaced by a rename,
|
|
172
|
+
* atomic on both systems. A launcher rewritten per version would be replaced while it may be
|
|
173
|
+
* running, and cmd.exe reads a batch file by offset as it runs. It sets `CENTRALU_MANAGED=1`, so
|
|
174
|
+
* the `serve` it starts leaves `<data>/bin/` to an npm install on the same machine.
|
|
175
|
+
*
|
|
176
|
+
* Both refuse a pointer that holds anything but plain version words, so an edited `current` cannot
|
|
177
|
+
* point it outside the install.
|
|
178
|
+
*/
|
|
179
|
+
export function managedLauncherScript(platform) {
|
|
180
|
+
if (platform === 'win32') {
|
|
181
|
+
return (
|
|
182
|
+
[
|
|
183
|
+
'@echo off',
|
|
184
|
+
'rem The Centralu launcher for the install the app manages over SSH. It never changes: it reads',
|
|
185
|
+
'rem "current" at every start, so switching versions replaces that file and never this one.',
|
|
186
|
+
'setlocal',
|
|
187
|
+
'set "CENTRALU_REMOTE=%~dp0.."',
|
|
188
|
+
'set "CENTRALU_LINE="',
|
|
189
|
+
'set "CENTRALU_V="',
|
|
190
|
+
'set "CENTRALU_N="',
|
|
191
|
+
'set /p CENTRALU_LINE=<"%CENTRALU_REMOTE%\\current"',
|
|
192
|
+
'for /f "tokens=1,2" %%a in ("%CENTRALU_LINE%") do (set "CENTRALU_V=%%a" & set "CENTRALU_N=%%b")',
|
|
193
|
+
'if not defined CENTRALU_N goto none',
|
|
194
|
+
'echo %CENTRALU_V% %CENTRALU_N%| findstr /r /c:"^[0-9A-Za-z][0-9A-Za-z.+-]* [0-9A-Za-z][0-9A-Za-z.+-]*$" >nul || goto none',
|
|
195
|
+
'set CENTRALU_MANAGED=1',
|
|
196
|
+
'"%CENTRALU_REMOTE%\\node\\v%CENTRALU_N%\\node.exe" "%CENTRALU_REMOTE%\\versions\\%CENTRALU_V%\\node_modules\\centralu\\bin\\centralu.mjs" %*',
|
|
197
|
+
'exit /b %ERRORLEVEL%',
|
|
198
|
+
':none',
|
|
199
|
+
'echo Centralu: no version is installed in %CENTRALU_REMOTE% 1>&2',
|
|
200
|
+
'exit /b 1',
|
|
201
|
+
].join('\r\n') + '\r\n'
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
return [
|
|
205
|
+
'#!/bin/sh',
|
|
206
|
+
'# The Centralu launcher for the install the app manages over SSH. It never changes: it reads',
|
|
207
|
+
'# `current` at every start, so switching versions replaces that file and never this one.',
|
|
208
|
+
'remote=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P) || exit 1',
|
|
209
|
+
'v= n=',
|
|
210
|
+
'read -r v n < "$remote/current" 2>/dev/null',
|
|
211
|
+
'case "$v" in ""|[!0-9A-Za-z]*|*[!0-9A-Za-z.+-]*) echo "Centralu: no version is installed in $remote" >&2; exit 1 ;; esac',
|
|
212
|
+
'case "$n" in ""|[!0-9A-Za-z]*|*[!0-9A-Za-z.+-]*) echo "Centralu: no version is installed in $remote" >&2; exit 1 ;; esac',
|
|
213
|
+
'CENTRALU_MANAGED=1',
|
|
214
|
+
'export CENTRALU_MANAGED',
|
|
215
|
+
'exec "$remote/node/v$n/bin/node" "$remote/versions/$v/node_modules/centralu/bin/centralu.mjs" "$@"',
|
|
216
|
+
'',
|
|
217
|
+
].join('\n')
|
|
218
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The launcher's side of a hub's key pairing (#1711, docs/plans/key-pairing.md §4.1 to §4.3): the check of a hub's
|
|
3
|
+
* public key at `--pair-key`, the public key of the host's signing key derived from serve.json's `key`, and the check of
|
|
4
|
+
* the running host's signed proof. The same rules as the host's `transport/link-keys.ts`, which this standalone launcher
|
|
5
|
+
* cannot import; `tooling/launcher-keys.test.ts` holds the two to the same answers and to the pinned vector.
|
|
6
|
+
*/
|
|
7
|
+
import { createHmac, createPrivateKey, createPublicKey, verify } from 'node:crypto'
|
|
8
|
+
|
|
9
|
+
/** Bytes of a nonce, a public key and a signature (`@cc/protocol` `link-wire.ts`) */
|
|
10
|
+
export const LINK_NONCE_BYTES = 24
|
|
11
|
+
export const LINK_PUBLIC_KEY_BYTES = 32
|
|
12
|
+
export const LINK_SIGNATURE_BYTES = 64
|
|
13
|
+
|
|
14
|
+
const CONTEXT_LABEL = 'centralu link v1'
|
|
15
|
+
const HOST_ROLE_LABEL = 'centralu link host v1'
|
|
16
|
+
const HOST_KEY_LABEL = 'centralu host key v1'
|
|
17
|
+
const SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex')
|
|
18
|
+
const PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex')
|
|
19
|
+
const P = 2n ** 255n - 19n
|
|
20
|
+
|
|
21
|
+
/** The bytes of `text` when it is exactly the base64url (no padding) of `bytes` bytes: encoding them again gives the same string */
|
|
22
|
+
export function decodeBase64url(text, bytes) {
|
|
23
|
+
if (typeof text !== 'string') return null
|
|
24
|
+
const raw = Buffer.from(text, 'base64url')
|
|
25
|
+
if (raw.length !== bytes || raw.toString('base64url') !== text) return null
|
|
26
|
+
return raw
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The 32 bytes as a little-endian number with the top bit (the sign of x) cleared */
|
|
30
|
+
function yOf(raw) {
|
|
31
|
+
let y = 0n
|
|
32
|
+
for (let i = raw.length - 1; i >= 0; i--) y = (y << 8n) | BigInt(i === raw.length - 1 ? raw[i] & 0x7f : raw[i])
|
|
33
|
+
return y
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The y of the eight small-order points: 0, 1, p − 1 and the two of order 8 (libsodium's `ge25519_has_small_order`) */
|
|
37
|
+
const SMALL_ORDER_Y = [
|
|
38
|
+
0n,
|
|
39
|
+
1n,
|
|
40
|
+
P - 1n,
|
|
41
|
+
yOf(Buffer.from('26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', 'hex')),
|
|
42
|
+
yOf(Buffer.from('c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', 'hex')),
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* `{ text, raw, key }` for a public key the host takes (§4.1), or null: exactly 43 canonical base64url characters, a y
|
|
47
|
+
* below p, not the y of a small-order point (either sign bit), and an Ed25519 key `node:crypto` imports. Unchecked, on
|
|
48
|
+
* Node 22 a small-order key verifies a forged signature over every message.
|
|
49
|
+
*/
|
|
50
|
+
export function parseLinkPublicKey(text) {
|
|
51
|
+
const raw = decodeBase64url(text, LINK_PUBLIC_KEY_BYTES)
|
|
52
|
+
if (!raw) return null
|
|
53
|
+
const y = yOf(raw)
|
|
54
|
+
if (y >= P || SMALL_ORDER_Y.includes(y)) return null
|
|
55
|
+
let key
|
|
56
|
+
try {
|
|
57
|
+
key = createPublicKey({ key: Buffer.concat([SPKI_PREFIX, raw]), format: 'der', type: 'spki' })
|
|
58
|
+
} catch {
|
|
59
|
+
return null
|
|
60
|
+
}
|
|
61
|
+
return key.asymmetricKeyType === 'ed25519' ? { text, raw, key } : null
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The public key a host started with `key` signs with (§4.1): `seed = HMAC-SHA256(key, "centralu host key v1")`, as
|
|
66
|
+
* PKCS#8. What `--pair-key` reports when no host runs and none of a keeper's may run with another key (§4.2).
|
|
67
|
+
*/
|
|
68
|
+
export function hostLinkPublicKey(key) {
|
|
69
|
+
if (typeof key !== 'string' || key.length === 0) throw new Error('The host key is empty')
|
|
70
|
+
const seed = createHmac('sha256', key).update(HOST_KEY_LABEL).digest()
|
|
71
|
+
const priv = createPrivateKey({ key: Buffer.concat([PKCS8_PREFIX, seed]), format: 'der', type: 'pkcs8' })
|
|
72
|
+
const der = createPublicKey(priv).export({ format: 'der', type: 'spki' })
|
|
73
|
+
const text = der.subarray(SPKI_PREFIX.length).toString('base64url')
|
|
74
|
+
if (!parseLinkPublicKey(text)) throw new Error('The derived host key was refused')
|
|
75
|
+
return text
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** `u32be(len) ‖ bytes` for each part; a string as ASCII, and one with another character throws */
|
|
79
|
+
export function encodeFields(parts) {
|
|
80
|
+
const out = []
|
|
81
|
+
for (const part of parts) {
|
|
82
|
+
if (typeof part === 'string' && Array.from(part).some((c) => c.codePointAt(0) > 0x7f)) throw new Error('A field string is ASCII')
|
|
83
|
+
const b = typeof part === 'string' ? Buffer.from(part, 'ascii') : Buffer.from(part)
|
|
84
|
+
const len = Buffer.alloc(4)
|
|
85
|
+
len.writeUInt32BE(b.length)
|
|
86
|
+
out.push(len, b)
|
|
87
|
+
}
|
|
88
|
+
return Buffer.concat(out)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** `127.0.0.1:<port>` for a port 1 to 65535, null otherwise (the host's `linkAddress`) */
|
|
92
|
+
export function linkAddress(port) {
|
|
93
|
+
return Number.isInteger(port) && port >= 1 && port <= 65535 ? `127.0.0.1:${port}` : null
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The transcript `T` (§4.3), or null when a value is refused */
|
|
97
|
+
export function linkTranscript({ hubNonce, hostNonce, hostKey, hubKey, keyId, address }) {
|
|
98
|
+
const nh = decodeBase64url(hubNonce, LINK_NONCE_BYTES)
|
|
99
|
+
const ns = decodeBase64url(hostNonce, LINK_NONCE_BYTES)
|
|
100
|
+
const pm = parseLinkPublicKey(hostKey)
|
|
101
|
+
const ph = parseLinkPublicKey(hubKey)
|
|
102
|
+
if (!nh || !ns || !pm || !ph) return null
|
|
103
|
+
if (typeof keyId !== 'string' || !/^[0-9a-f]{8}$/.test(keyId)) return null
|
|
104
|
+
if (typeof address !== 'string' || !/^127\.0\.0\.1:[1-9][0-9]{0,4}$/.test(address) || linkAddress(Number(address.slice(10))) !== address) return null
|
|
105
|
+
return encodeFields([CONTEXT_LABEL, nh, ns, pm.raw, ph.raw, keyId, address])
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The key a running host signs with, when `proof` is its signed answer to a key `prove` of `hubNonce` (§4.2 step 3):
|
|
110
|
+
* `hostNonce`, `hostKey` and `sig` all present, strict, and the host's signature verifying over the transcript built
|
|
111
|
+
* here from the hub's key, the entry's id and the address the hub forwards to. Null for anything else: an answer
|
|
112
|
+
* without a signature (a host from before key pairing), or one that does not verify.
|
|
113
|
+
*/
|
|
114
|
+
export function signedHostKey(proof, { hubNonce, hubKey, keyId, port }) {
|
|
115
|
+
if (proof?.kind !== 'proof' || proof.nonce !== hubNonce) return null
|
|
116
|
+
const pm = parseLinkPublicKey(proof.hostKey)
|
|
117
|
+
const sig = decodeBase64url(proof.sig, LINK_SIGNATURE_BYTES)
|
|
118
|
+
if (!pm || !sig) return null
|
|
119
|
+
const t = linkTranscript({ hubNonce, hostNonce: proof.hostNonce, hostKey: proof.hostKey, hubKey, keyId, address: linkAddress(port) })
|
|
120
|
+
if (!t) return null
|
|
121
|
+
try {
|
|
122
|
+
return verify(null, Buffer.concat([encodeFields([HOST_ROLE_LABEL]), t]), pm.key, sig) ? pm.text : null
|
|
123
|
+
} catch {
|
|
124
|
+
return null
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** The port `centralu serve` listens on: the default, the recorded one, and the next free one (#482) */
|
|
2
|
+
import { createServer } from 'node:net'
|
|
3
|
+
import { runCaptured } from './serve-util.mjs'
|
|
4
|
+
import { detachHow, windowsTool } from './serve-windows.mjs'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The port `serve` listens on unless told otherwise, and keeps across restarts.
|
|
8
|
+
*
|
|
9
|
+
* Stable, because the client is told it once per connection and the person may write it into an
|
|
10
|
+
* SSH config or a systemd unit. Below 20000 on purpose: every OS lends ports from its ephemeral
|
|
11
|
+
* range to outgoing connections (Linux 32768–60999, macOS and Windows 49152–65535), and the host
|
|
12
|
+
* itself hands out per-app view origins from 20000–32767 (views/origin-ports.ts). A default inside
|
|
13
|
+
* either range could be taken by something transient the day the host restarts.
|
|
14
|
+
*/
|
|
15
|
+
export const DEFAULT_SERVE_PORT = 17175
|
|
16
|
+
|
|
17
|
+
/** How many ports from the recorded one `serve` tries when it is taken (#482); none at or above 20000 */
|
|
18
|
+
export const SERVE_PORT_TRIES = 20
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The port `serve` starts the host on (#482): `{ port, from }`, `from` being the port it moved away
|
|
22
|
+
* from (null when it did not), or null when every candidate is taken.
|
|
23
|
+
*
|
|
24
|
+
* A port the person gave (`--port`) is used as given: they asked for that one. Otherwise the recorded
|
|
25
|
+
* port (else the default) when it is free, and when another program listens there, the next free
|
|
26
|
+
* one above it, below 20000 (the ranges `DEFAULT_SERVE_PORT` keeps out of). The host's ready line
|
|
27
|
+
* then records the port it got, so `--connection` reports it and the hub forwards to it.
|
|
28
|
+
*
|
|
29
|
+
* The usual other program is the other half of one Windows laptop: WSL2 relays a distro's
|
|
30
|
+
* 127.0.0.1 ports to Windows (`wslrelay.exe`), so a Windows install and a WSL install linked as two
|
|
31
|
+
* machines both wanted 17175, and whichever started second could not start at all.
|
|
32
|
+
* `taken(port)` answers whether something listens there.
|
|
33
|
+
*/
|
|
34
|
+
export async function chooseServePort({ asked, recorded, taken }) {
|
|
35
|
+
if (asked !== null && asked !== undefined) return { port: asked, from: null }
|
|
36
|
+
const first = recorded ?? DEFAULT_SERVE_PORT
|
|
37
|
+
for (let p = first; p < first + SERVE_PORT_TRIES && p <= 65535; p++) {
|
|
38
|
+
if (p !== first && p >= 20000) break
|
|
39
|
+
if (!(await taken(p))) return { port: p, from: p === first ? null : first }
|
|
40
|
+
}
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Whether something listens on 127.0.0.1:`port` here: a listen that fails with EADDRINUSE (or EACCES) */
|
|
45
|
+
export function listensHere(port) {
|
|
46
|
+
return new Promise((resolve) => {
|
|
47
|
+
const srv = createServer()
|
|
48
|
+
srv.once('error', (e) => resolve(e?.code === 'EADDRINUSE' || e?.code === 'EACCES'))
|
|
49
|
+
srv.listen({ host: '127.0.0.1', port, exclusive: true }, () => srv.close(() => resolve(false)))
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The TCP ports Windows listens on, from `netstat.exe -an -p TCP` output: a listening socket is the
|
|
55
|
+
* row whose foreign address is `0.0.0.0:0` (or `[::]:0`). Read that way rather than by the state
|
|
56
|
+
* column, which Windows translates (a Korean Windows does not print LISTENING everywhere).
|
|
57
|
+
*/
|
|
58
|
+
export function parseNetstatListening(text) {
|
|
59
|
+
const ports = new Set()
|
|
60
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
61
|
+
const m = /^\s*TCP\s+(?:127\.0\.0\.1|0\.0\.0\.0|\[::1?\]):(\d+)\s+(?:0\.0\.0\.0:0|\[::\]:0)\s/i.exec(line)
|
|
62
|
+
if (m) ports.add(Number(m[1]))
|
|
63
|
+
}
|
|
64
|
+
return ports
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The ports the Windows side listens on, seen from inside a WSL distro (empty elsewhere, or when
|
|
69
|
+
* Windows cannot be asked). Inside the distro a port Windows holds looks free, yet a host there
|
|
70
|
+
* would be unreachable from the hub: the hub's forward ends on Windows' 127.0.0.1, where the
|
|
71
|
+
* Windows program answers instead (#482).
|
|
72
|
+
*/
|
|
73
|
+
export async function windowsListening(env, platform) {
|
|
74
|
+
if (detachHow(platform, env) !== 'wsl') return new Set()
|
|
75
|
+
const netstat = windowsTool('wsl', env, ['System32', 'netstat.exe'])
|
|
76
|
+
if (!netstat) return new Set()
|
|
77
|
+
const r = await runCaptured(netstat, ['-an', '-p', 'TCP'], env)
|
|
78
|
+
return r.code === 0 ? parseNetstatListening(r.stdout) : new Set()
|
|
79
|
+
}
|