mapsource-node 0.0.0-stage → 0.1.0
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/README.md +33 -2
- package/bin/mapsource-node.mjs +44 -0
- package/package.json +32 -4
- package/protocol/bootstrap/infra/mirror/runtime.json +28 -0
- package/protocol/bootstrap/scripts/artifact-lifecycle.mjs +531 -0
- package/protocol/bootstrap/scripts/mirror-mesh-agent.mjs +58 -0
- package/protocol/bootstrap/scripts/mirror-mesh-config.mjs +39 -0
- package/protocol/bootstrap/scripts/mirror-mesh-install.mjs +91 -0
- package/protocol/bootstrap/scripts/mirror-mesh-membership.mjs +71 -0
- package/protocol/bootstrap/scripts/mirror-peer-health.mjs +41 -0
- package/protocol/bootstrap/scripts/mirror-peer-path.mjs +98 -0
- package/protocol/bootstrap/scripts/mirror-transport-install.mjs +237 -0
- package/protocol/bootstrap/scripts/mirror-transport-reconcile.mjs +121 -0
- package/protocol/bootstrap/scripts/network-family-policy.mjs +13 -0
- package/protocol/bootstrap/scripts/release-ingress-router.mjs +212 -0
- package/protocol/bootstrap/scripts/release-policy.mjs +131 -0
- package/protocol/bootstrap/scripts/release-router.mjs +148 -0
- package/src/capability.mjs +101 -0
- package/src/commands.mjs +192 -0
- package/src/enrollment.mjs +153 -0
- package/src/index.ts +70 -0
- package/src/interface.ts +181 -0
- package/src/palette.ts +11 -0
- package/src/telemetry.ts +158 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Network-independent discovery. DNS carries signed public membership only;
|
|
3
|
+
// neither account credentials nor Cloudflare account API tokens live here.
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { readFile, mkdir, rename, open } from "node:fs/promises";
|
|
6
|
+
import { resolveTxt } from "node:dns/promises";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { parseArgs } from "node:util";
|
|
9
|
+
import { machineIdentityHash, verifiedMembership, readMembershipRecords, memberSshConfig } from "./mirror-mesh-membership.mjs";
|
|
10
|
+
|
|
11
|
+
const { values } = parseArgs({ options: { root: { type: "string" }, once: { type: "boolean" } } });
|
|
12
|
+
assert.ok(values.root); const root = path.resolve(values.root);
|
|
13
|
+
const identity = JSON.parse(await readFile(path.join(root, "enrollment.json"), "utf8"));
|
|
14
|
+
assert.equal((await readFile("/etc/machine-id", "utf8")).trim(), identity.machineId);
|
|
15
|
+
const publicKey = await readFile(path.join(root, "signing-public.pem"), "utf8");
|
|
16
|
+
const peerPublicKey = (await readFile(path.join(root, "peer-key.pub"), "utf8")).trim().split(/\s+/).slice(0, 2).join(" ");
|
|
17
|
+
let version = 0, envelope;
|
|
18
|
+
const atomicText = async (file, contents) => {
|
|
19
|
+
const pending = `${file}.pending`, handle = await open(pending, "w", 0o600);
|
|
20
|
+
try { await handle.writeFile(contents); await handle.sync(); } finally { await handle.close(); }
|
|
21
|
+
await rename(pending, file);
|
|
22
|
+
};
|
|
23
|
+
async function apply(next) {
|
|
24
|
+
const body = verifiedMembership(next, publicKey, { domain: identity.domain, minimumVersion: version });
|
|
25
|
+
if (body.version === version) { assert.equal(JSON.stringify(next), JSON.stringify(envelope), "Same membership version changed bytes."); return; }
|
|
26
|
+
const own = body.members.find(member => member.node === identity.node);
|
|
27
|
+
assert.ok(own && own.identityHash === machineIdentityHash(identity.machineId) && own.peerPublicKey === peerPublicKey
|
|
28
|
+
&& own.hostPublicKey === identity.hostPublicKey.split(/\s+/).slice(0, 2).join(" "), "Local node is not an enrolled mesh member.");
|
|
29
|
+
const peers = body.members.filter(member => member.node !== identity.node);
|
|
30
|
+
await mkdir(path.join(root, "ssh"), { recursive: true, mode: 0o700 });
|
|
31
|
+
for (const member of peers) await atomicText(path.join(root, "ssh", `${member.node}.conf`), memberSshConfig(member, root));
|
|
32
|
+
await atomicText(path.join(root, "ssh/known_hosts"), peers.map(member => `mapsource-mesh-node-${member.identityHash} ${member.hostPublicKey}`).join("\n") + "\n");
|
|
33
|
+
const restrictions = 'restrict,port-forwarding,permitopen="127.0.0.1:8989",permitopen="127.0.0.1:8990",permitopen="127.0.0.1:19390",command="/bin/false"';
|
|
34
|
+
await atomicText(path.join(root, "authorized-peers"), peers.map(member => `${restrictions} ${member.peerPublicKey}`).join("\n") + "\n");
|
|
35
|
+
await atomicText(path.join(root, "membership.json"), JSON.stringify(next) + "\n");
|
|
36
|
+
const directory = await open(root, "r"); try { await directory.sync(); } finally { await directory.close(); }
|
|
37
|
+
version = body.version; envelope = next;
|
|
38
|
+
console.log(JSON.stringify({ event: "mesh-membership-ready", node: identity.node, version, peers: peers.map(peer => peer.node), discovery: "signed-dns", accountAuthorityChanged: false }));
|
|
39
|
+
}
|
|
40
|
+
try { await apply(JSON.parse(await readFile(path.join(root, "membership.json"), "utf8"))); }
|
|
41
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
42
|
+
let stopped = false;
|
|
43
|
+
const poll = async () => {
|
|
44
|
+
try { await apply(readMembershipRecords(await resolveTxt(`_mapsource-mesh.${identity.domain}`))); }
|
|
45
|
+
catch { console.log(JSON.stringify({ event: "mesh-discovery-retry", node: identity.node, retainedVersion: version })); }
|
|
46
|
+
};
|
|
47
|
+
await poll();
|
|
48
|
+
if (values.once) assert.ok(version > 0, "No verified mesh membership is available.");
|
|
49
|
+
if (!values.once) {
|
|
50
|
+
while (!stopped) {
|
|
51
|
+
await new Promise(resolve => {
|
|
52
|
+
const finish = () => { clearTimeout(timer); process.off("SIGTERM", end); process.off("SIGINT", end); resolve(); };
|
|
53
|
+
const end = () => { stopped = true; finish(); };
|
|
54
|
+
const timer = setTimeout(finish, 60_000); process.once("SIGTERM", end); process.once("SIGINT", end);
|
|
55
|
+
});
|
|
56
|
+
if (!stopped) await poll();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
|
|
3
|
+
// Includes forwarded socket buffers and kernel/file cache charged to sshd,
|
|
4
|
+
// not just the daemon's RSS. Operator bulk jobs use separate supervised units.
|
|
5
|
+
export const meshSshBudget = Object.freeze({ highMiB: 384, maxMiB: 512 });
|
|
6
|
+
|
|
7
|
+
export function meshIdentity(input) {
|
|
8
|
+
const { node, machineId, domain = "mapsource.io", sshPort = 22991 } = input;
|
|
9
|
+
assert.match(node ?? "", /^[a-z][a-z0-9-]{0,31}$/);
|
|
10
|
+
assert.match(machineId ?? "", /^[a-f0-9]{32}$/);
|
|
11
|
+
assert.match(domain, /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/);
|
|
12
|
+
assert.ok(Number.isInteger(sshPort) && sshPort >= 1024 && sshPort <= 65535);
|
|
13
|
+
return { schema: "mapsource-portable-peer.v1", node, machineId, domain, sshPort,
|
|
14
|
+
hostname: `mapsource-peer-${node}.${domain}`, tunnelName: `mapsource-peer-${node}`,
|
|
15
|
+
hostKeyAlias: `mapsource-mesh-${machineId}`, alias: `mapsource-${node}` };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function meshSshServer(identity, { user, root, authorizedKeys }) {
|
|
19
|
+
meshIdentity(identity);
|
|
20
|
+
assert.match(user, /^[a-z_][a-z0-9_-]{0,31}$/);
|
|
21
|
+
for (const value of [root, authorizedKeys]) assert.match(value, /^\/[a-zA-Z0-9_./-]+$/);
|
|
22
|
+
return `ListenAddress 127.0.0.1\nPort ${identity.sshPort}\nHostKey ${root}/host-key\nAuthorizedKeysFile ${authorizedKeys} ${root}/authorized-peers\nPidFile ${root}/sshd.pid\nUsePAM no\nStrictModes yes\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nAuthenticationMethods publickey\nAllowUsers ${user}\nPermitRootLogin no\nSubsystem sftp internal-sftp\nAllowTcpForwarding local\nAllowAgentForwarding no\nX11Forwarding no\nPermitTunnel no\nPermitUserEnvironment no\nLogLevel ERROR\nMaxAuthTries 3\nLoginGraceTime 15\n`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function meshSshClient(identity, { user, key, knownHosts, cloudflared }) {
|
|
26
|
+
assert.deepEqual(meshIdentity(identity), Object.fromEntries(Object.keys(meshIdentity(identity)).map(key => [key, identity[key]])));
|
|
27
|
+
assert.match(user, /^[a-z_][a-z0-9_-]{0,31}$/);
|
|
28
|
+
assert.match(identity.hostPublicKey ?? "", /^ssh-ed25519 [A-Za-z0-9+/=]+(?: [^\r\n]*)?$/);
|
|
29
|
+
for (const value of [key, knownHosts, cloudflared]) assert.match(value, /^\/[a-zA-Z0-9_./-]+$/);
|
|
30
|
+
return `Host ${identity.alias}\n HostName ${identity.hostname}\n User ${user}\n IdentityFile ${key}\n IdentitiesOnly yes\n BatchMode yes\n StrictHostKeyChecking yes\n HostKeyAlias ${identity.hostKeyAlias}\n UserKnownHostsFile ${knownHosts}\n ProxyCommand ${cloudflared} access ssh --hostname %h\n ConnectTimeout 10\n ServerAliveInterval 5\n ServerAliveCountMax 3\n ExitOnForwardFailure yes\n`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function meshLinkUnit({ node, user, clientConfig, localPort, targetPort }) {
|
|
34
|
+
assert.match(node ?? "", /^[a-z][a-z0-9-]{0,31}$/);
|
|
35
|
+
assert.match(user ?? "", /^[a-z_][a-z0-9_-]{0,31}$/);
|
|
36
|
+
assert.match(clientConfig, /^\/[a-zA-Z0-9_./-]+$/);
|
|
37
|
+
for (const port of [localPort, targetPort]) assert.ok(Number.isInteger(port) && port >= 1024 && port <= 65535);
|
|
38
|
+
return `[Unit]\nDescription=Mapsource outbound private peer link to ${node}\nAfter=network-online.target mapsource-mesh-agent.service\nWants=network-online.target mapsource-mesh-agent.service\nStartLimitIntervalSec=0\n[Service]\nUser=${user}\nEnvironment=BROWSER=/bin/false\nExecStart=/usr/bin/ssh -F ${clientConfig} -N -T -L 127.0.0.1:${localPort}:127.0.0.1:${targetPort} mapsource-${node}\nRestart=always\nRestartSec=3\nMemoryMax=192M\nTasksMax=32\nNoNewPrivileges=true\nPrivateTmp=true\nProtectSystem=strict\nProtectHome=read-only\nLogNamespace=mapsource-mirror\n[Install]\nWantedBy=multi-user.target\n`;
|
|
39
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Run on an enrolled host, with the private enrollment payload on stdin.
|
|
3
|
+
// Separate services keep SSH/tunnel recovery independent of writer fencing.
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { readFile, writeFile, mkdir, access, cp, rename, open } from "node:fs/promises";
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { parseArgs } from "node:util";
|
|
11
|
+
import { meshIdentity, meshSshServer, meshSshBudget } from "./mirror-mesh-config.mjs";
|
|
12
|
+
import { freeSpacePreflight, withProjectTempDirectory } from "./artifact-lifecycle.mjs";
|
|
13
|
+
import { atomicJson } from "./release-router.mjs";
|
|
14
|
+
import { installTransport } from "./mirror-transport-install.mjs";
|
|
15
|
+
|
|
16
|
+
const { values } = parseArgs({ options: { execute: { type: "boolean" }, root: { type: "string" } } });
|
|
17
|
+
let input = ""; for await (const chunk of process.stdin) { input += chunk; assert.ok(Buffer.byteLength(input) <= 16 * 1024); }
|
|
18
|
+
const payload = JSON.parse(input), identity = meshIdentity(payload);
|
|
19
|
+
assert.equal((await readFile("/etc/machine-id", "utf8")).trim(), identity.machineId, "Wrong host.");
|
|
20
|
+
assert.ok(typeof payload.tunnelToken === "string" && payload.tunnelToken.length >= 32 && !/[\r\n]/.test(payload.tunnelToken));
|
|
21
|
+
const user = os.userInfo().username;
|
|
22
|
+
let root = values.root ? path.resolve(values.root) : path.join(os.homedir(), ".local/share/mapsource-mesh");
|
|
23
|
+
if (!values.root) {
|
|
24
|
+
// Preserve an enrolled first-version host key, including hosts whose older
|
|
25
|
+
// application parent directory is owned by root. Never move private state.
|
|
26
|
+
const legacy = path.join(os.homedir(), ".local/share/mapsource/mesh");
|
|
27
|
+
try {
|
|
28
|
+
const prior = JSON.parse(await readFile(path.join(legacy, "enrollment.json"), "utf8"));
|
|
29
|
+
if (prior.node === identity.node && prior.machineId === identity.machineId) root = legacy;
|
|
30
|
+
} catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
31
|
+
}
|
|
32
|
+
assert.match(root, /^\/[a-zA-Z0-9_./-]+$/);
|
|
33
|
+
assert.ok(root.startsWith(os.homedir() + "/"), "Mesh state must belong to the operating user.");
|
|
34
|
+
const authorizedKeys = path.join(os.homedir(), ".ssh/authorized_keys"); await access(authorizedKeys);
|
|
35
|
+
const runtime = JSON.parse(await readFile(new URL("../infra/mirror/runtime.json", import.meta.url), "utf8"));
|
|
36
|
+
assert.ok(["x64", "arm64"].includes(process.arch));
|
|
37
|
+
console.log(JSON.stringify({ operation: "install-portable-peer", node: identity.node, hostname: identity.hostname,
|
|
38
|
+
execute: Boolean(values.execute), accountControllerRestarted: false }));
|
|
39
|
+
if (values.execute) {
|
|
40
|
+
await freeSpacePreflight({ target: root, projectedBytes: 128 * 1024 ** 2 });
|
|
41
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
42
|
+
const configuration = path.join(root, "enrollment.json");
|
|
43
|
+
try { const prior = JSON.parse(await readFile(configuration, "utf8")); assert.equal(prior.machineId, identity.machineId); assert.equal(prior.node, identity.node); }
|
|
44
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
45
|
+
const binary = path.join(root, "cloudflared"), expected = runtime.cloudflaredSha256[process.arch];
|
|
46
|
+
const valid = async candidate => { try { return createHash("sha256").update(await readFile(candidate)).digest("hex") === expected; } catch { return false; } };
|
|
47
|
+
if (!await valid(binary)) {
|
|
48
|
+
await withProjectTempDirectory("mapsource-mesh-tool-", async scratch => {
|
|
49
|
+
const candidate = path.join(scratch, "cloudflared");
|
|
50
|
+
const installed = ["/srv/mapsource-mirror/toolchain/cloudflared", "/usr/local/bin/cloudflared"];
|
|
51
|
+
let source;
|
|
52
|
+
for (const file of installed) if (await valid(file)) { source = file; break; }
|
|
53
|
+
if (source) await cp(source, candidate);
|
|
54
|
+
else {
|
|
55
|
+
const arch = process.arch === "x64" ? "amd64" : "arm64";
|
|
56
|
+
const response = await fetch(`https://github.com/cloudflare/cloudflared/releases/download/${runtime.cloudflaredVersion}/cloudflared-linux-${arch}`, { signal: AbortSignal.timeout(60_000) });
|
|
57
|
+
assert.ok(response.ok); const file = await open(candidate, "wx", 0o700);
|
|
58
|
+
let bytes = 0;
|
|
59
|
+
try { for await (const chunk of response.body) { bytes += chunk.length; assert.ok(bytes <= 128 * 1024 ** 2); await file.writeFile(chunk); } await file.sync(); }
|
|
60
|
+
finally { await file.close(); }
|
|
61
|
+
}
|
|
62
|
+
assert.ok(await valid(candidate), "Cloudflared checksum mismatch.");
|
|
63
|
+
await cp(candidate, `${binary}.pending`); execFileSync("chmod", ["0700", `${binary}.pending`]); await rename(`${binary}.pending`, binary);
|
|
64
|
+
}, { projectedBytes: 256 * 1024 ** 2 });
|
|
65
|
+
}
|
|
66
|
+
const key = path.join(root, "host-key");
|
|
67
|
+
try { await access(key); } catch { execFileSync("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", `mapsource-mesh-${identity.machineId}`, "-f", key]); }
|
|
68
|
+
const hostPublicKey = (await readFile(`${key}.pub`, "utf8")).trim();
|
|
69
|
+
assert.match(hostPublicKey, /^ssh-ed25519 [A-Za-z0-9+/=]+(?: .*)?$/);
|
|
70
|
+
const peerKey = path.join(root, "peer-key");
|
|
71
|
+
try { await access(peerKey); } catch { execFileSync("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", `mapsource-peer-${identity.node}`, "-f", peerKey]); }
|
|
72
|
+
const peerPublicKey = (await readFile(`${peerKey}.pub`, "utf8")).trim();
|
|
73
|
+
await mkdir(path.join(root, "agent"), { recursive: true, mode: 0o700 });
|
|
74
|
+
for (const name of ["mirror-mesh-agent.mjs", "mirror-mesh-membership.mjs"]) await cp(new URL(name, import.meta.url), path.join(root, "agent", name));
|
|
75
|
+
await writeFile(path.join(root, "tunnel.token"), `${payload.tunnelToken}\n`, { mode: 0o600 });
|
|
76
|
+
await writeFile(path.join(root, "sshd.conf"), meshSshServer(identity, { user, root, authorizedKeys }), { mode: 0o600 });
|
|
77
|
+
execFileSync("/usr/sbin/sshd", ["-t", "-f", path.join(root, "sshd.conf")]);
|
|
78
|
+
const serverUnit = `[Unit]\nDescription=Mapsource key-only portable peer SSH (${identity.node})\nAfter=network.target\nStartLimitIntervalSec=0\n[Service]\nUser=${user}\nExecStart=/usr/sbin/sshd -D -e -f ${root}/sshd.conf\nExecReload=/bin/kill -HUP $MAINPID\nRestart=always\nRestartSec=3\nMemoryHigh=${meshSshBudget.highMiB}M\nMemoryMax=${meshSshBudget.maxMiB}M\nTasksMax=128\nUMask=0077\nLimitCORE=0\nLogNamespace=mapsource-mirror\n[Install]\nWantedBy=multi-user.target\n`;
|
|
79
|
+
const tunnelUnit = `[Unit]\nDescription=Mapsource outbound portable peer tunnel (${identity.node})\nAfter=network-online.target mapsource-mesh-sshd.service\nWants=network-online.target mapsource-mesh-sshd.service\nStartLimitIntervalSec=0\n[Service]\nUser=${user}\nExecStart=${binary} tunnel --no-autoupdate --metrics 127.0.0.1:20849 run --token-file ${root}/tunnel.token\nRestart=always\nRestartSec=3\nMemoryMax=256M\nTasksMax=64\nNoNewPrivileges=true\nProtectSystem=strict\nProtectHome=read-only\nPrivateTmp=true\nUMask=0077\nLimitCORE=0\nLogNamespace=mapsource-mirror\n[Install]\nWantedBy=multi-user.target\n`;
|
|
80
|
+
const agentUnit = `[Unit]\nDescription=Mapsource signed portable peer discovery (${identity.node})\nAfter=network-online.target\nWants=network-online.target\nConditionPathExists=${root}/signing-public.pem\nStartLimitIntervalSec=0\n[Service]\nUser=${user}\nExecStart=${process.execPath} ${root}/agent/mirror-mesh-agent.mjs --root ${root}\nRestart=always\nRestartSec=3\nMemoryMax=96M\nTasksMax=32\nNoNewPrivileges=true\nProtectSystem=strict\nProtectHome=read-only\nReadWritePaths=${root}\nPrivateTmp=true\nUMask=0077\nLimitCORE=0\nLogNamespace=mapsource-mirror\n[Install]\nWantedBy=multi-user.target\n`;
|
|
81
|
+
for (const [name, contents] of [["mapsource-mesh-sshd.service", serverUnit], ["mapsource-mesh-tunnel.service", tunnelUnit], ["mapsource-mesh-agent.service", agentUnit]]) {
|
|
82
|
+
const file = path.join(root, name); await writeFile(file, contents, { mode: 0o600 });
|
|
83
|
+
execFileSync("sudo", ["-n", "install", "-m", "0644", file, `/etc/systemd/system/${name}`]);
|
|
84
|
+
}
|
|
85
|
+
await atomicJson(configuration, { ...identity, hostPublicKey, peerPublicKey, user, root });
|
|
86
|
+
execFileSync("sudo", ["-n", "systemctl", "daemon-reload"]);
|
|
87
|
+
execFileSync("sudo", ["-n", "systemctl", "enable", "--now", "mapsource-mesh-sshd.service", "mapsource-mesh-tunnel.service", "mapsource-mesh-agent.service"], { stdio: ["ignore", "ignore", "pipe"] });
|
|
88
|
+
execFileSync("sudo", ["-n", "systemctl", "reload", "mapsource-mesh-sshd.service"]);
|
|
89
|
+
await installTransport(root, { execute: true });
|
|
90
|
+
console.log(JSON.stringify({ installed: true, ...identity, hostPublicKey, peerPublicKey, user, root, accountControllerRestarted: false }));
|
|
91
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { createHash, sign, verify } from "node:crypto";
|
|
3
|
+
import { deflateRawSync, inflateRawSync } from "node:zlib";
|
|
4
|
+
|
|
5
|
+
export const MESH_MEMBERSHIP_SCHEMA = "mapsource-mesh-membership.v1";
|
|
6
|
+
export const machineIdentityHash = value => createHash("sha256").update(`mapsource-mesh-v1:${value}`).digest("hex");
|
|
7
|
+
export function validateMembership(body) {
|
|
8
|
+
assert.equal(body?.schema, MESH_MEMBERSHIP_SCHEMA);
|
|
9
|
+
assert.ok(Number.isSafeInteger(body.version) && body.version > 0 && Number.isFinite(Date.parse(body.issuedAt)));
|
|
10
|
+
assert.match(body.domain ?? "", /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/);
|
|
11
|
+
assert.ok(Array.isArray(body.members) && body.members.length > 0 && body.members.length <= 16);
|
|
12
|
+
assert.deepEqual(Object.keys(body).sort(), ["schema", "version", "domain", "issuedAt", "members"].sort());
|
|
13
|
+
const names = new Set(), identities = new Set(), keys = new Set();
|
|
14
|
+
for (const member of body.members) {
|
|
15
|
+
assert.deepEqual(Object.keys(member).sort(), ["node", "user", "hostname", "identityHash", "hostPublicKey", "peerPublicKey"].sort());
|
|
16
|
+
assert.match(member.node ?? "", /^[a-z][a-z0-9-]{0,31}$/);
|
|
17
|
+
assert.match(member.user ?? "", /^[a-z_][a-z0-9_-]{0,31}$/);
|
|
18
|
+
assert.match(member.identityHash ?? "", /^[a-f0-9]{64}$/);
|
|
19
|
+
assert.equal(member.hostname, `mapsource-peer-${member.node}.${body.domain}`);
|
|
20
|
+
for (const key of [member.hostPublicKey, member.peerPublicKey]) assert.match(key ?? "", /^ssh-ed25519 [A-Za-z0-9+/=]{40,100}$/);
|
|
21
|
+
assert.ok(!names.has(member.node) && !identities.has(member.identityHash) && !keys.has(member.peerPublicKey), "Duplicate peer identity.");
|
|
22
|
+
names.add(member.node); identities.add(member.identityHash); keys.add(member.peerPublicKey);
|
|
23
|
+
}
|
|
24
|
+
assert.ok(Buffer.byteLength(JSON.stringify(body)) <= 32 * 1024);
|
|
25
|
+
return body;
|
|
26
|
+
}
|
|
27
|
+
export function signedMembership(body, privateKey) {
|
|
28
|
+
validateMembership(body);
|
|
29
|
+
return { body, signature: sign(null, Buffer.from(JSON.stringify(body)), privateKey).toString("base64") };
|
|
30
|
+
}
|
|
31
|
+
export function verifiedMembership(envelope, publicKey, { domain, minimumVersion = 0 } = {}) {
|
|
32
|
+
assert.ok(envelope && typeof envelope.signature === "string" && envelope.signature.length <= 100);
|
|
33
|
+
const body = validateMembership(envelope.body);
|
|
34
|
+
assert.ok(verify(null, Buffer.from(JSON.stringify(body)), publicKey, Buffer.from(envelope.signature, "base64")), "Mesh membership signature is invalid.");
|
|
35
|
+
assert.equal(body.domain, domain);
|
|
36
|
+
assert.ok(body.version >= minimumVersion, "Mesh membership rollback rejected.");
|
|
37
|
+
return body;
|
|
38
|
+
}
|
|
39
|
+
export function membershipRecords(envelope) {
|
|
40
|
+
const encoded = deflateRawSync(Buffer.from(JSON.stringify(envelope))).toString("base64");
|
|
41
|
+
assert.ok(encoded.length <= 16_000, "Mesh discovery exceeds its DNS byte budget.");
|
|
42
|
+
const count = Math.ceil(encoded.length / 1000);
|
|
43
|
+
return Array.from({ length: count }, (_, index) => `mapsource-mesh-v1:${envelope.body.version}:${index}:${count}:${encoded.slice(index * 1000, (index + 1) * 1000)}`);
|
|
44
|
+
}
|
|
45
|
+
export function readMembershipRecords(records) {
|
|
46
|
+
assert.ok(Array.isArray(records) && records.length <= 64);
|
|
47
|
+
const versions = new Map();
|
|
48
|
+
for (const chunks of records) {
|
|
49
|
+
assert.ok(Array.isArray(chunks) && chunks.length <= 32 && chunks.every(chunk => typeof chunk === "string" && chunk.length <= 2048));
|
|
50
|
+
const text = chunks.join(""); if (!text.startsWith("mapsource-mesh-v1:")) continue;
|
|
51
|
+
const match = /^mapsource-mesh-v1:([1-9][0-9]{0,14}):([0-9]{1,2}):([1-9][0-9]?):([A-Za-z0-9+/=]+)$/.exec(text);
|
|
52
|
+
assert.ok(match && text.length <= 1100, "Invalid mesh DNS record.");
|
|
53
|
+
const [, version, part, total, data] = match, index = Number(part), count = Number(total);
|
|
54
|
+
assert.ok(count <= 16 && index < count);
|
|
55
|
+
const group = versions.get(Number(version)) ?? { count, parts: new Map() };
|
|
56
|
+
assert.ok(group.count === count && (!group.parts.has(index) || group.parts.get(index) === data), "Conflicting mesh DNS records.");
|
|
57
|
+
group.parts.set(index, data); versions.set(Number(version), group);
|
|
58
|
+
}
|
|
59
|
+
for (const [version, group] of [...versions.entries()].sort((a, b) => b[0] - a[0])) {
|
|
60
|
+
if (group.parts.size !== group.count) continue;
|
|
61
|
+
const encoded = Array.from({ length: group.count }, (_, index) => group.parts.get(index)).join("");
|
|
62
|
+
const envelope = JSON.parse(inflateRawSync(Buffer.from(encoded, "base64"), { maxOutputLength: 40 * 1024 }).toString("utf8"));
|
|
63
|
+
assert.equal(envelope.body?.version, version); return envelope;
|
|
64
|
+
}
|
|
65
|
+
throw new Error("No complete mesh membership is published.");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function memberSshConfig(member, root) {
|
|
69
|
+
assert.match(root, /^\/[a-zA-Z0-9_./-]+$/);
|
|
70
|
+
return `Host mapsource-${member.node}\n HostName ${member.hostname}\n User ${member.user}\n IdentityFile ${root}/peer-key\n IdentitiesOnly yes\n BatchMode yes\n StrictHostKeyChecking yes\n HostKeyAlias mapsource-mesh-node-${member.identityHash}\n UserKnownHostsFile ${root}/ssh/known_hosts\n ProxyCommand ${root}/cloudflared access ssh --hostname %h\n ConnectTimeout 10\n ServerAliveInterval 5\n ServerAliveCountMax 3\n ExitOnForwardFailure yes\n`;
|
|
71
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import "./network-family-policy.mjs";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import net from "node:net";
|
|
4
|
+
|
|
5
|
+
export const PEER_HEALTH_TIMEOUT_MS = 4000;
|
|
6
|
+
|
|
7
|
+
// Connector readiness says nothing about its loopback SSH origin. Require a
|
|
8
|
+
// protocol banner, rather than merely a TCP accept, before calling it alive.
|
|
9
|
+
export function probePeerSsh({ port, timeoutMs = 1500 }) {
|
|
10
|
+
return new Promise(resolve => {
|
|
11
|
+
const socket = net.connect({ host: "127.0.0.1", port });
|
|
12
|
+
let settled = false, bytes = "";
|
|
13
|
+
const finish = healthy => { if (settled) return; settled = true; clearTimeout(timer); socket.destroy(); resolve(healthy); };
|
|
14
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
15
|
+
socket.on("data", chunk => {
|
|
16
|
+
bytes += chunk.toString("ascii");
|
|
17
|
+
if (bytes.length > 255) finish(false);
|
|
18
|
+
else if (bytes.includes("\n")) finish(/^SSH-2\.0-[\x21-\x7e]+(?: [\x20-\x7e]*)?\r?\n$/.test(bytes));
|
|
19
|
+
});
|
|
20
|
+
socket.once("error", () => finish(false)); socket.once("end", () => finish(false));
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// A local SSH listener can accept TCP while its remote channel is dead. An
|
|
25
|
+
// unauthenticated HEAD reaches the pinned remote HTTP origin without reading
|
|
26
|
+
// customer state or granting access. Its expected 401/404 is a live transport.
|
|
27
|
+
export function probePeerHttp({ host = "127.0.0.1", port, timeoutMs = PEER_HEALTH_TIMEOUT_MS }) {
|
|
28
|
+
return new Promise(resolve => {
|
|
29
|
+
let settled = false;
|
|
30
|
+
const finish = healthy => {
|
|
31
|
+
if (settled) return;
|
|
32
|
+
settled = true; clearTimeout(timer); request.destroy(); resolve(healthy);
|
|
33
|
+
};
|
|
34
|
+
const request = http.request({ host, port, method: "HEAD", path: "/health/live", agent: false,
|
|
35
|
+
headers: { connection: "close", "user-agent": "mapsource-peer-path/1" } }, response => {
|
|
36
|
+
finish(Number.isInteger(response.statusCode) && response.statusCode >= 200 && response.statusCode < 500);
|
|
37
|
+
});
|
|
38
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
39
|
+
request.once("error", () => finish(false)); request.end();
|
|
40
|
+
});
|
|
41
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// One stable loopback port per peer. Production installation admits only the
|
|
3
|
+
// registered Cloudflare path, independent of LAN addresses or host location.
|
|
4
|
+
// Bytes are piped unchanged; the peer origin still authenticates every request.
|
|
5
|
+
// node scripts/mirror-peer-path.mjs CONFIG_JSON
|
|
6
|
+
// { "listen": 18945, "upstreams": [{ "name": "edge", "port": 18941 }] }
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import net from "node:net";
|
|
9
|
+
import { readFileSync } from "node:fs";
|
|
10
|
+
import { probePeerHttp, PEER_HEALTH_TIMEOUT_MS } from "./mirror-peer-health.mjs";
|
|
11
|
+
|
|
12
|
+
export function startPeerPath({ listen, upstreams, connectTimeoutMs = 300, failureHoldMs = 5000, healthTimeoutMs = PEER_HEALTH_TIMEOUT_MS, healthCacheMs = 2000, host = "127.0.0.1" }) {
|
|
13
|
+
assert.ok(Number.isInteger(listen) && listen >= 0 && listen <= 65535);
|
|
14
|
+
assert.ok(Array.isArray(upstreams) && upstreams.length >= 1 && upstreams.length <= 4);
|
|
15
|
+
for (const upstream of upstreams) assert.ok(/^[a-z][a-z0-9-]{0,15}$/.test(upstream.name) && Number.isInteger(upstream.port) && upstream.port > 0);
|
|
16
|
+
assert.equal(new Set(upstreams.map(upstream => upstream.name)).size, upstreams.length);
|
|
17
|
+
for (const timeout of [connectTimeoutMs, failureHoldMs, healthTimeoutMs, healthCacheMs]) assert.ok(Number.isFinite(timeout) && timeout > 0 && timeout <= 60_000);
|
|
18
|
+
// A path that just failed is skipped briefly rather than adding its connect
|
|
19
|
+
// deadline to every incoming connection.
|
|
20
|
+
const failedUntil = new Map(), health = new Map(), probes = new Map(), active = new Map(), failedProbes = new Map(), receivedAt = new WeakMap(), progressAt = new Map();
|
|
21
|
+
const counts = Object.fromEntries(upstreams.map(upstream => [upstream.name, 0]));
|
|
22
|
+
let stopping = false;
|
|
23
|
+
const unhealthy = upstream => {
|
|
24
|
+
failedUntil.set(upstream.name, Date.now() + failureHoldMs);
|
|
25
|
+
health.delete(upstream.name);
|
|
26
|
+
};
|
|
27
|
+
const ready = async upstream => {
|
|
28
|
+
if (stopping) return false;
|
|
29
|
+
// Actual response bytes are fresher evidence than an independent HEAD
|
|
30
|
+
// delayed behind checkpoint traffic. Do not reject the next chunk merely
|
|
31
|
+
// because a busy-link probe timed out while other requests kept progressing.
|
|
32
|
+
if (Date.now() - (progressAt.get(upstream.name) ?? 0) < healthTimeoutMs) return true;
|
|
33
|
+
if ((failedUntil.get(upstream.name) ?? 0) > Date.now()) return false;
|
|
34
|
+
const cached = health.get(upstream.name);
|
|
35
|
+
if (cached && Date.now() - cached.at < healthCacheMs) return cached.ready;
|
|
36
|
+
if (probes.has(upstream.name)) return probes.get(upstream.name);
|
|
37
|
+
const probe = probePeerHttp({ host, port: upstream.port, timeoutMs: healthTimeoutMs }).then(ready => {
|
|
38
|
+
failedProbes.set(upstream.name, ready ? 0 : (failedProbes.get(upstream.name) ?? 0) + 1);
|
|
39
|
+
health.set(upstream.name, { ready, at: Date.now() });
|
|
40
|
+
if (!ready) unhealthy(upstream);
|
|
41
|
+
return ready;
|
|
42
|
+
}).finally(() => probes.delete(upstream.name));
|
|
43
|
+
probes.set(upstream.name, probe); return probe;
|
|
44
|
+
};
|
|
45
|
+
const connect = async (index, client) => {
|
|
46
|
+
let chosen = index;
|
|
47
|
+
for (; chosen < upstreams.length; chosen++) if (await ready(upstreams[chosen])) break;
|
|
48
|
+
if (client.destroyed) return;
|
|
49
|
+
if (chosen >= upstreams.length || stopping) { client.destroy(); return; }
|
|
50
|
+
const upstream = upstreams[chosen];
|
|
51
|
+
const socket = net.connect({ host, port: upstream.port });
|
|
52
|
+
const timer = setTimeout(() => socket.destroy(new Error("connect timeout")), connectTimeoutMs);
|
|
53
|
+
socket.once("close", () => clearTimeout(timer));
|
|
54
|
+
let connected = false;
|
|
55
|
+
client.once("close", () => socket.destroy());
|
|
56
|
+
socket.once("connect", () => {
|
|
57
|
+
connected = true; clearTimeout(timer); counts[upstream.name]++;
|
|
58
|
+
const sockets = active.get(upstream.name) ?? new Set(); active.set(upstream.name, sockets); sockets.add(socket);
|
|
59
|
+
receivedAt.set(socket, Date.now());
|
|
60
|
+
socket.on("data", () => { const at = Date.now(); receivedAt.set(socket, at); progressAt.set(upstream.name, at); });
|
|
61
|
+
client.pipe(socket); socket.pipe(client);
|
|
62
|
+
socket.once("error", () => client.destroy()); client.once("error", () => socket.destroy());
|
|
63
|
+
socket.once("close", () => { sockets.delete(socket); client.destroy(); });
|
|
64
|
+
client.resume();
|
|
65
|
+
});
|
|
66
|
+
socket.once("error", () => {
|
|
67
|
+
clearTimeout(timer); progressAt.delete(upstream.name); unhealthy(upstream);
|
|
68
|
+
// Only an unstarted connection may choose another transport. Never
|
|
69
|
+
// replay bytes after an account mutation might have reached the writer.
|
|
70
|
+
if (!connected && !client.destroyed) void connect(chosen + 1, client).catch(() => client.destroy());
|
|
71
|
+
});
|
|
72
|
+
};
|
|
73
|
+
const server = net.createServer({ pauseOnConnect: true }, client => { client.once("error", () => {}); void connect(0, client).catch(() => client.destroy()); });
|
|
74
|
+
// A busy but working link can delay a HEAD probe. Require independent
|
|
75
|
+
// failures and an idle stream before disconnecting it; never truncate a
|
|
76
|
+
// progressing checkpoint or replay an already-started account mutation.
|
|
77
|
+
const monitor = setInterval(() => {
|
|
78
|
+
for (const upstream of upstreams) if (active.get(upstream.name)?.size) {
|
|
79
|
+
void ready(upstream).then(healthy => {
|
|
80
|
+
if (!healthy && !stopping && (failedProbes.get(upstream.name) ?? 0) >= 2) for (const socket of active.get(upstream.name) ?? []) {
|
|
81
|
+
if (Date.now() - (receivedAt.get(socket) ?? 0) >= healthTimeoutMs + failureHoldMs) socket.destroy();
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}, healthCacheMs);
|
|
86
|
+
monitor.unref();
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
server.once("error", error => { clearInterval(monitor); reject(error); });
|
|
89
|
+
server.listen(listen, host, () => resolve({ port: server.address().port, counts,
|
|
90
|
+
close: () => { stopping = true; clearInterval(monitor); return new Promise(done => server.close(() => done())); } }));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (process.argv[1] === import.meta.filename) {
|
|
95
|
+
const path = await startPeerPath(JSON.parse(readFileSync(process.argv[2], "utf8")));
|
|
96
|
+
console.log(JSON.stringify({ status: "peer-path-ready", port: path.port }));
|
|
97
|
+
process.once("SIGTERM", () => { void path.close().then(() => process.exit(0)); });
|
|
98
|
+
}
|