mapsource-node 0.0.0-stage → 0.1.1
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 +41 -0
- package/package.json +51 -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,148 @@
|
|
|
1
|
+
// Independent of the fenced database controller. Switching this web pointer
|
|
2
|
+
// never kills an application process or interrupts an in-flight response.
|
|
3
|
+
import "./network-family-policy.mjs";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { createIngressPlane, streamingRequest } from "./release-ingress-router.mjs";
|
|
6
|
+
import http from "node:http";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { createReadStream } from "node:fs";
|
|
9
|
+
import { readFile, open, rename, stat, realpath } from "node:fs/promises";
|
|
10
|
+
import { timingSafeEqual,createHash } from "node:crypto";
|
|
11
|
+
import { RELEASE_SCHEMA } from "./release-policy.mjs";
|
|
12
|
+
|
|
13
|
+
export async function atomicJson(file, value) {
|
|
14
|
+
const pending = `${file}.pending`;
|
|
15
|
+
const handle = await open(pending, "w", 0o600);
|
|
16
|
+
try { await handle.writeFile(JSON.stringify(value) + "\n"); await handle.sync(); } finally { await handle.close(); }
|
|
17
|
+
await rename(pending, file);
|
|
18
|
+
const directory = await open(path.dirname(file), "r"); try { await directory.sync(); } finally { await directory.close(); }
|
|
19
|
+
}
|
|
20
|
+
const json = (response, code, value) => response.writeHead(code, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(value));
|
|
21
|
+
const safeHost = value => ["mapsource.io", "api.mapsource.io", "app.mapsource.io", "127.0.0.1", "localhost"].includes(String(value).split(":")[0]);
|
|
22
|
+
const mime = name => ({ ".js":"application/javascript", ".css":"text/css", ".woff2":"font/woff2", ".woff":"font/woff", ".png":"image/png", ".svg":"image/svg+xml", ".json":"application/json", ".map":"application/json" })[path.extname(name)] || "application/octet-stream";
|
|
23
|
+
export async function probeWeb(origin, { paths = [["/",200],["/account?intent=sign_in",200],["/status",200],["/authentication-station",200],["/admin",404],["/mediakit",200]] } = {}) {
|
|
24
|
+
let assetChecked = false;
|
|
25
|
+
for (const [route, expected] of paths) {
|
|
26
|
+
const started = performance.now();
|
|
27
|
+
const response = await fetch(origin + route, { redirect:"manual", headers:{host:"mapsource.io"}, signal:AbortSignal.timeout(10_000) });
|
|
28
|
+
assert.equal(response.status, expected, `Candidate ${route}: HTTP ${response.status}, expected ${expected}`);
|
|
29
|
+
const body = await response.text();
|
|
30
|
+
assert.ok(body.length > 100 && !body.includes("Application error: a server-side exception"), `Candidate ${route} did not render.`);
|
|
31
|
+
assert.ok(performance.now() - started < 5000, `Candidate ${route} exceeded the 5s readiness limit.`);
|
|
32
|
+
if (route === "/") {
|
|
33
|
+
const assets = [...new Set([...body.matchAll(/(?:src|href)="([^"?]*\/_next\/static\/[^"?]+)"/g)].map(match=>match[1]))];
|
|
34
|
+
assert.ok(assets.length > 0, "Candidate page has no JavaScript/style assets.");
|
|
35
|
+
for (const asset of assets) { const reply = await fetch(new URL(asset,origin), {signal:AbortSignal.timeout(10_000)}); assert.ok(reply.ok, `Missing candidate asset ${asset}`); await reply.body?.cancel(); }
|
|
36
|
+
assetChecked = true;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return { passed:true, assetChecked, routes:paths.length };
|
|
40
|
+
}
|
|
41
|
+
export async function probeWebBuild(root,origin) {
|
|
42
|
+
const buildId=(await readFile(path.join(root,"apps/web/.next/BUILD_ID"),"utf8")).trim();assert.match(buildId,/^[A-Za-z0-9_-]{1,100}$/);
|
|
43
|
+
const relative=`/_next/static/${buildId}/_buildManifest.js`,expected=await readFile(path.join(root,"apps/web/.next/static",buildId,"_buildManifest.js"));
|
|
44
|
+
const response=await fetch(origin+relative,{signal:AbortSignal.timeout(5000)});assert.equal(response.status,200,"Candidate is not serving its staged build ID.");
|
|
45
|
+
assert.equal(createHash("sha256").update(Buffer.from(await response.arrayBuffer())).digest("hex"),createHash("sha256").update(expected).digest("hex"),"Candidate's served build differs from the immutable CI artifact.");
|
|
46
|
+
}
|
|
47
|
+
function forward(request, response, origin, fallback, release, streaming = false) {
|
|
48
|
+
const address = new URL(origin);
|
|
49
|
+
const headers = { ...request.headers, host:request.headers.host || "mapsource.io" };
|
|
50
|
+
for (const name of ["connection", "keep-alive", "x-mapsource-origin-token", "x-mapsource-ha-target", "x-mapsource-public-host"]) delete headers[name];
|
|
51
|
+
const upstream = http.request({ hostname:address.hostname, port:address.port, path:request.url, method:request.method, headers }, result => {
|
|
52
|
+
if (streaming) upstream.setTimeout(0);
|
|
53
|
+
if (fallback && result.statusCode >= 500) { result.resume(); forward(request,response,fallback,null,"legacy"); return; }
|
|
54
|
+
const outgoing = { ...result.headers, "x-mapsource-web-release":release }; delete outgoing.connection;
|
|
55
|
+
// Keep-alive lifetime belongs to this socket. Forwarding Fastify's 72s
|
|
56
|
+
// hint through this 5s server makes clients reuse a socket we have closed.
|
|
57
|
+
delete outgoing["keep-alive"];
|
|
58
|
+
response.writeHead(result.statusCode,outgoing); result.pipe(response);
|
|
59
|
+
});
|
|
60
|
+
upstream.once("error",()=>{if(!response.headersSent && fallback)forward(request,response,fallback,null,"legacy");else if(!response.headersSent)json(response,502,{error:"Web origin unavailable"});else response.destroy();});
|
|
61
|
+
upstream.setTimeout(185_000,()=>upstream.destroy(new Error("Web origin timeout")));
|
|
62
|
+
request.once("aborted",()=>upstream.destroy());
|
|
63
|
+
response.once("close",()=>{if(!response.writableFinished)upstream.destroy();});
|
|
64
|
+
// Retry is restricted to bodyless document reads. Mutations and API reads
|
|
65
|
+
// are streamed once to the existing authority, never replayed here.
|
|
66
|
+
if (fallback) upstream.end(); else request.pipe(upstream);
|
|
67
|
+
}
|
|
68
|
+
export async function startReleaseRouter(config) {
|
|
69
|
+
const ingress = await createIngressPlane(config);
|
|
70
|
+
assert.ok(config.stateFile && config.releaseRoot && config.controlTokenFile);
|
|
71
|
+
const token = Buffer.from((await readFile(config.controlTokenFile,"utf8")).trim()); assert.ok(token.length >= 32);
|
|
72
|
+
const legacy = config.legacyOrigin || "http://127.0.0.1:3210", gateway = config.gatewayOrigin || "http://127.0.0.1:8787";
|
|
73
|
+
for (const origin of [legacy,gateway]) { const url=new URL(origin); assert.equal(url.protocol,"http:"); assert.equal(url.hostname,"127.0.0.1"); }
|
|
74
|
+
let state; try { state=JSON.parse(await readFile(config.stateFile,"utf8")); } catch(error) { if(error.code!=="ENOENT")throw error; state={active:null,previous:null,slots:[]}; }
|
|
75
|
+
let mutation = false, stopped = false;
|
|
76
|
+
const slot = commit => state.slots.find(s=>s.commit===commit);
|
|
77
|
+
const persist = async next => { await atomicJson(config.stateFile,next); state=next; };
|
|
78
|
+
const rollback = async () => {const previous=slot(state.previous);await persist({...state,active:previous?.commit??null,previous:null,activatedAt:Date.now()});};
|
|
79
|
+
const serve = async (request,response) => {
|
|
80
|
+
if (!safeHost(request.headers.host)) return json(response,400,{error:"Invalid host"});
|
|
81
|
+
const url = new URL(request.url,"http://localhost");
|
|
82
|
+
if (String(request.headers.host).split(":")[0] === "app.mapsource.io") return forward(request,response,config.appOrigin ?? "http://127.0.0.1:3220",null,"application");
|
|
83
|
+
if (String(request.headers.host).split(":")[0] === "api.mapsource.io") return forward(request,response,gateway,null,"authority",streamingRequest(request,config.ingress?.streamingResponses));
|
|
84
|
+
// The authority and its existing relay continue handling every API,
|
|
85
|
+
// metering and account mutation throughout the web rollout.
|
|
86
|
+
if (/^\/(?:api(?:\/|$)|health\/|mcp(?:\.json|\/|$)|llms?(?:-full)?\.txt$|\.well-known\/mcp\/)/.test(url.pathname)
|
|
87
|
+
|| ["/docs/quickstart.md","/docs/agents.md","/docs/compatibility.md"].includes(url.pathname)) return forward(request,response,gateway,null,"authority",streamingRequest(request,config.ingress?.streamingResponses));
|
|
88
|
+
if (["GET","HEAD"].includes(request.method) && url.pathname.startsWith("/_next/static/")) {
|
|
89
|
+
let relative; try { relative=decodeURIComponent(url.pathname.slice("/_next/static/".length)); } catch { return json(response,400,{error:"Invalid asset path"}); }
|
|
90
|
+
if (!relative || relative.split(/[\\/]/).some(p=>p===".."||p==="."||!p)) return json(response,404,{error:"Unknown asset"});
|
|
91
|
+
// Stage on ALL hosts before the first pointer switch. New HTML can then
|
|
92
|
+
// retrieve its chunks from any host during the staggered rollout.
|
|
93
|
+
for (const candidate of [...state.slots].reverse()) {
|
|
94
|
+
const root=path.join(candidate.root,"apps/web/.next/static"), file=path.join(root,relative);
|
|
95
|
+
try { const canonical=await realpath(file); if(!canonical.startsWith(root+path.sep))continue; const info=await stat(canonical); if(!info.isFile())continue;
|
|
96
|
+
response.writeHead(200,{"content-type":mime(file),"content-length":info.size,"cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff","x-mapsource-web-release":candidate.commit});
|
|
97
|
+
if(request.method==="HEAD")response.end();else {const stream=createReadStream(canonical);stream.once("error",()=>response.destroy());response.once("close",()=>stream.destroy());stream.pipe(response);} return;
|
|
98
|
+
} catch(error) { if(!["ENOENT","ENOTDIR"].includes(error.code))throw error; }
|
|
99
|
+
}
|
|
100
|
+
return forward(request,response,legacy,null,"legacy");
|
|
101
|
+
}
|
|
102
|
+
const active=slot(state.active);
|
|
103
|
+
const documentRead=["GET","HEAD"].includes(request.method) && !url.searchParams.has("_rsc") && !request.headers.rsc;
|
|
104
|
+
forward(request,response,active?.origin??legacy,active&&documentRead?slot(state.previous)?.origin??legacy:null,active?.commit??"legacy");
|
|
105
|
+
};
|
|
106
|
+
const web=http.createServer((req,res)=>{void (ingress ? ingress.serve(req,res,serve,state.active) : serve(req,res)).catch(()=>{if(!res.headersSent)json(res,502,{error:"Web router unavailable"});else res.destroy();});});
|
|
107
|
+
const control=http.createServer((req,res)=>{void (async()=>{
|
|
108
|
+
const received=Buffer.from(req.headers.authorization??""), expected=Buffer.concat([Buffer.from("Bearer "),token]);
|
|
109
|
+
if(received.length!==expected.length||!timingSafeEqual(received,expected))return json(res,404,{});
|
|
110
|
+
if(req.method==="GET"&&req.url==="/status")return json(res,200,{...state,node:config.node,routerRevision:config.routerRevision,ingress:ingress?.state()});
|
|
111
|
+
if(req.method!=="POST"||!["/stage","/activate","/rollback","/retire","/forget",...(ingress?["/maintenance/drain","/maintenance/hold","/maintenance/resume","/maintenance/quiesce"]:[])].includes(req.url))return json(res,404,{});
|
|
112
|
+
if(mutation)return json(res,409,{error:"Another deployment operation is running"}); mutation=true;
|
|
113
|
+
try {
|
|
114
|
+
let text="";for await(const chunk of req){text+=chunk;assert.ok(Buffer.byteLength(text)<=4096);}const body=JSON.parse(text||"{}");
|
|
115
|
+
if(req.url==="/maintenance/quiesce") { assert.equal(config.socketActivation,true,"A retained systemd socket is required for ingress restart"); assert.equal(ingress.state().commit,body.commit); ingress.quiesce(); web.close(()=>{}); web.closeIdleConnections(); return json(res,200,ingress.state()); }
|
|
116
|
+
if(req.url.startsWith("/maintenance/"))return json(res,200,ingress.maintenanceControl(req.url,body));
|
|
117
|
+
if(req.url==="/stage") {
|
|
118
|
+
assert.match(body.commit??"",/^[a-f0-9]{40}$/);assert.ok((config.slotPorts??[3310,3311]).includes(body.port),"Use a reserved web slot.");
|
|
119
|
+
const root=await realpath(path.join(config.releaseRoot,body.commit));assert.equal(root,path.join(await realpath(config.releaseRoot),body.commit));
|
|
120
|
+
const manifest=JSON.parse(await readFile(path.join(root,"release.json"),"utf8"));assert.equal(manifest.schema,RELEASE_SCHEMA);assert.equal(manifest.commit,body.commit);
|
|
121
|
+
const buildId=(await readFile(path.join(root,"apps/web/.next/BUILD_ID"),"utf8")).trim();assert.equal((await readFile(path.join(root,"apps/web/.next/MAPSOURCE_BUILD_COMPLETE"),"utf8")).trim(),buildId);assert.equal(manifest.buildId,buildId);
|
|
122
|
+
assert.ok(!state.slots.some(s=>s.commit!==body.commit&&s.port===body.port),"Forget and drain the old slot before reuse.");
|
|
123
|
+
const candidate={commit:body.commit,root,port:body.port,origin:`http://127.0.0.1:${body.port}`,buildId};await probeWebBuild(candidate.root,candidate.origin);await probeWeb(candidate.origin);
|
|
124
|
+
await persist({...state,slots:[...state.slots.filter(s=>s.commit!==body.commit),candidate]});
|
|
125
|
+
} else if(req.url==="/activate") {
|
|
126
|
+
const candidate=slot(body.commit);assert.ok(candidate,"Candidate was not staged.");await probeWebBuild(candidate.root,candidate.origin);await probeWeb(candidate.origin);
|
|
127
|
+
if(state.active!==candidate.commit)await persist({...state,previous:state.active,active:candidate.commit,activatedAt:Date.now()});
|
|
128
|
+
} else if(req.url==="/rollback") {if(!body.commit||state.active===body.commit)await rollback();}
|
|
129
|
+
else if(req.url==="/retire") {
|
|
130
|
+
assert.ok(Date.now()-(state.activatedAt??0)>=185_000,"The former web process has not drained.");
|
|
131
|
+
await persist({...state,previous:null,slots:state.slots.map(s=>s.commit!==state.active?{...s,origin:null,port:null}:s)});
|
|
132
|
+
}
|
|
133
|
+
else {assert.ok(body.commit!==state.active&&body.commit!==state.previous,"Cannot forget serving or rollback releases.");await persist({...state,slots:state.slots.filter(s=>s.commit!==body.commit)});}
|
|
134
|
+
json(res,200,{active:state.active,previous:state.previous});
|
|
135
|
+
} finally {mutation=false;}
|
|
136
|
+
})().catch(error=>{if(!res.headersSent)json(res,422,{error:error.message});else res.destroy();});});
|
|
137
|
+
for(const server of [web,control]){server.headersTimeout=15_000;server.requestTimeout=185_000;}
|
|
138
|
+
await Promise.all([new Promise((resolve,reject)=>{web.once("error",reject);if(config.socketActivation){assert.equal(Number(process.env.LISTEN_PID),process.pid);assert.equal(Number(process.env.LISTEN_FDS),1);web.listen({fd:3},resolve);}else web.listen(config.port??18992,"127.0.0.1",resolve);}),new Promise((resolve,reject)=>{control.once("error",reject);control.listen(config.controlPort??18993,"127.0.0.1",resolve);})]);
|
|
139
|
+
// A single failing route is enough to withdraw the candidate. Keep every
|
|
140
|
+
// former process alive until fleet-wide soak AND the drain interval finish.
|
|
141
|
+
const monitor=setInterval(()=>{if(stopped||mutation||!state.active)return;mutation=true;const active=slot(state.active);void probeWebBuild(active.root,active.origin).then(()=>probeWeb(active.origin)).catch(async error=>{await rollback();console.error(JSON.stringify({event:"automatic-web-rollback",commit:active.commit,error:error.message}));}).finally(()=>{mutation=false;});},config.monitorMs??15_000); monitor.unref();
|
|
142
|
+
return {web,control,close:async()=>{stopped=true;clearInterval(monitor);await Promise.all([web,control].map(server=>new Promise(resolve=>{server.close(resolve);server.closeIdleConnections();})));}};
|
|
143
|
+
}
|
|
144
|
+
if(process.argv[1]===import.meta.filename){
|
|
145
|
+
const config=JSON.parse(await readFile(process.argv[2],"utf8"));assert.equal((await readFile("/etc/machine-id","utf8")).trim(),config.machineId);
|
|
146
|
+
const router=await startReleaseRouter(config);const stop=()=>void router.close().then(()=>process.exit(0));process.once("SIGTERM",stop);process.once("SIGINT",stop);
|
|
147
|
+
console.log(JSON.stringify({event:"web-router-ready",node:config.node,port:config.port??18992}));
|
|
148
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { access, readFile, realpath, stat, statfs } from "node:fs/promises";
|
|
2
|
+
import { availableParallelism, totalmem } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const GiB = 1024 ** 3;
|
|
6
|
+
const idPattern = /^[a-z][a-z0-9-]{0,31}$/;
|
|
7
|
+
const bytes = value => Number.isSafeInteger(value) && value >= 0;
|
|
8
|
+
const requireValue = (condition, message) => { if (!condition) throw new Error(message); };
|
|
9
|
+
const indexed = (rows, kind, validate) => {
|
|
10
|
+
requireValue(Array.isArray(rows) && rows.length <= 128, `Invalid ${kind} list.`);
|
|
11
|
+
const result = new Map();
|
|
12
|
+
for (const row of rows) {
|
|
13
|
+
requireValue(row && idPattern.test(row.id) && !result.has(row.id) && validate(row), `Invalid or duplicate ${kind}.`);
|
|
14
|
+
result.set(row.id, row);
|
|
15
|
+
}
|
|
16
|
+
return result;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function validateCatalog(catalog) {
|
|
20
|
+
requireValue(catalog?.schema === "mapsource-node-catalog.v1" && /^[a-f0-9]{40}$/.test(catalog.commit), "This service catalog requires a compatible Mapsource Node release.");
|
|
21
|
+
const volumes = indexed(catalog.volumes, "volume", volume => bytes(volume.reserveBytes));
|
|
22
|
+
const resources = indexed(catalog.resources, "resource", resource => volumes.has(resource.volume)
|
|
23
|
+
&& bytes(resource.peakBytes) && bytes(resource.finalBytes) && resource.peakBytes >= resource.finalBytes
|
|
24
|
+
&& Number.isSafeInteger(resource.inodes) && resource.inodes >= 0);
|
|
25
|
+
const services = indexed(catalog.services, "service", service =>
|
|
26
|
+
typeof service.label === "string" && service.label.length > 0 && service.label.length <= 80
|
|
27
|
+
&& Array.isArray(service.resources) && service.resources.every(id => resources.has(id))
|
|
28
|
+
&& Array.isArray(service.architectures) && service.architectures.every(arch => ["x64", "arm64"].includes(arch))
|
|
29
|
+
&& Array.isArray(service.tools) && service.tools.every(tool => idPattern.test(tool))
|
|
30
|
+
&& bytes(service.memoryBytes) && Number.isSafeInteger(service.cpu) && service.cpu > 0);
|
|
31
|
+
return { volumes, resources, services };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function nearestMount(target) {
|
|
35
|
+
requireValue(path.isAbsolute(target), "Deployment volumes must be absolute paths.");
|
|
36
|
+
return realpath(target).catch(error => {
|
|
37
|
+
if (error.code !== "ENOENT" || target === "/") throw error;
|
|
38
|
+
return nearestMount(path.dirname(target));
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function measureHost(targets) {
|
|
43
|
+
const tools = [];
|
|
44
|
+
await Promise.all(["docker", "ssh", "sshd", "rsync", "systemctl", "sudo", "python3", "java"].map(async tool => {
|
|
45
|
+
for (const directory of [...(process.env.PATH ?? "").split(":").filter(path.isAbsolute), "/usr/sbin", "/usr/bin"]) {
|
|
46
|
+
try { await access(path.join(directory, tool), 1); tools.push(tool); break; }
|
|
47
|
+
catch { /* Check the remaining executable paths. */ }
|
|
48
|
+
}
|
|
49
|
+
}));
|
|
50
|
+
const mounts = {};
|
|
51
|
+
for (const [id, target] of Object.entries(targets)) {
|
|
52
|
+
const directory = await nearestMount(target);
|
|
53
|
+
const [volume, metadata] = await Promise.all([statfs(directory), stat(directory)]);
|
|
54
|
+
mounts[id] = { path: target, device: metadata.dev, bytes: volume.bavail * volume.bsize, inodes: volume.ffree };
|
|
55
|
+
}
|
|
56
|
+
const memory = /^MemAvailable:\s+(\d+) kB$/m.exec(await readFile("/proc/meminfo", "utf8").catch(() => ""));
|
|
57
|
+
const os = /^ID="?([a-z0-9-]+)"?$/m.exec(await readFile("/etc/os-release", "utf8").catch(() => ""))?.[1] ?? "unknown";
|
|
58
|
+
const cuda = await access("/dev/nvidiactl").then(() => true, () => access("/dev/nvhost-gpu").then(() => true, () => false));
|
|
59
|
+
return { platform: process.platform, os, architecture: process.arch, cpu: availableParallelism(), memoryBytes: memory ? Number(memory[1]) * 1024 : totalmem(), cuda, tools: tools.sort(), mounts };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function planServices(catalog, host, selections) {
|
|
63
|
+
const { volumes, resources, services } = validateCatalog(catalog);
|
|
64
|
+
requireValue(Array.isArray(selections) && selections.length > 0 && selections.length <= services.size, "Select at least one service.");
|
|
65
|
+
const requested = [...new Set(selections)].map(id => {
|
|
66
|
+
requireValue(services.has(id), `Unknown service: ${id}`);
|
|
67
|
+
return services.get(id);
|
|
68
|
+
});
|
|
69
|
+
const errors = [];
|
|
70
|
+
if (host.platform !== "linux" || !["ubuntu", "debian"].includes(host.os)) errors.push("Select a supported Ubuntu or Debian host.");
|
|
71
|
+
for (const service of requested) {
|
|
72
|
+
if (!service.architectures.includes(host.architecture)) errors.push(`${service.label} does not support this architecture.`);
|
|
73
|
+
const missing = service.tools.filter(tool => !host.tools.includes(tool));
|
|
74
|
+
if (missing.length) errors.push(`${service.label} requires ${missing.join(", ")}.`);
|
|
75
|
+
}
|
|
76
|
+
const requiredCpu = requested.reduce((sum, service) => sum + service.cpu, 0);
|
|
77
|
+
const requiredMemory = requested.reduce((sum, service) => sum + service.memoryBytes, GiB);
|
|
78
|
+
if (requiredCpu > host.cpu) errors.push(`Selected services require ${requiredCpu} available CPU threads.`);
|
|
79
|
+
if (requiredMemory > host.memoryBytes) errors.push(`Selected services require ${(requiredMemory / GiB).toFixed(1)} GiB of available memory including reserve.`);
|
|
80
|
+
const disks = new Map();
|
|
81
|
+
for (const id of new Set(requested.flatMap(service => service.resources))) {
|
|
82
|
+
const resource = resources.get(id);
|
|
83
|
+
const policy = volumes.get(resource.volume);
|
|
84
|
+
const mount = host.mounts[resource.volume];
|
|
85
|
+
if (!mount) { errors.push(`Choose a filesystem for ${resource.volume}.`); continue; }
|
|
86
|
+
const disk = disks.get(mount.device) ?? { paths: [], peakBytes: 0, finalBytes: 0, reserveBytes: 0, inodes: 0, availableBytes: mount.bytes, availableInodes: mount.inodes };
|
|
87
|
+
if (!disk.paths.includes(mount.path)) disk.paths.push(mount.path);
|
|
88
|
+
disk.peakBytes += resource.peakBytes;
|
|
89
|
+
disk.finalBytes += resource.finalBytes;
|
|
90
|
+
disk.reserveBytes = Math.max(disk.reserveBytes, policy.reserveBytes);
|
|
91
|
+
disk.inodes += resource.inodes;
|
|
92
|
+
disk.availableBytes = Math.min(disk.availableBytes, mount.bytes);
|
|
93
|
+
disk.availableInodes = Math.min(disk.availableInodes, mount.inodes);
|
|
94
|
+
disks.set(mount.device, disk);
|
|
95
|
+
}
|
|
96
|
+
for (const disk of disks.values()) {
|
|
97
|
+
if (disk.peakBytes + disk.reserveBytes > disk.availableBytes) errors.push(`Insufficient staging and reserve space on ${disk.paths.join(", ")}.`);
|
|
98
|
+
if (disk.inodes > disk.availableInodes) errors.push(`Insufficient free inodes on ${disk.paths.join(", ")}.`);
|
|
99
|
+
}
|
|
100
|
+
return { eligible: errors.length === 0, services: requested.map(({ id, label }) => ({ id, label })), requiredCpu, requiredMemory, disks: [...disks.values()], errors };
|
|
101
|
+
}
|
package/src/commands.mjs
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { access, mkdir, open, rm } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { measureHost, planServices, validateCatalog } from "./capability.mjs";
|
|
9
|
+
import { catalogDigest, enrollmentRequest, localIdentity, operatorRequest, readEnrollment, readInvitation, saveEnrollment, secretInput } from "./enrollment.mjs";
|
|
10
|
+
|
|
11
|
+
const mirrorRoot = "/srv/mapsource-mirror";
|
|
12
|
+
const bootstrap = fileURLToPath(new URL("../protocol/bootstrap/scripts/mirror-mesh-install.mjs", import.meta.url));
|
|
13
|
+
const targets = { system: "/usr/local", data: mirrorRoot };
|
|
14
|
+
const sshKey = /^ssh-ed25519 [A-Za-z0-9+/=]+(?: [a-zA-Z0-9-]+)?$/;
|
|
15
|
+
const printable = value => String(value).replace(/[\p{Cc}\p{Cf}]/gu, "");
|
|
16
|
+
const gib = value => (value / 1024 ** 3).toFixed(1) + " GiB";
|
|
17
|
+
const show = value => console.log(JSON.stringify(value, null, 2));
|
|
18
|
+
const servicesOption = { services: { type: "string" } };
|
|
19
|
+
const flags = (args, options) => parseArgs({ args, options }).values;
|
|
20
|
+
const ids = value => value.split(",").map(item => item.trim()).filter(Boolean);
|
|
21
|
+
const usage = `Mapsource Node
|
|
22
|
+
|
|
23
|
+
mapsource-node Open the terminal dashboard
|
|
24
|
+
mapsource-node --json Read current fleet telemetry
|
|
25
|
+
mapsource-node services List profiles offered by the local authority
|
|
26
|
+
mapsource-node invite --node NAME --services ID[,ID] [--out FILE]
|
|
27
|
+
mapsource-node revoke --node NAME Revoke an unused sync key
|
|
28
|
+
mapsource-node setup [--key-file FILE | --key-stdin] [--services ID[,ID]] [--apply]
|
|
29
|
+
mapsource-node resume Resume an authorized enrollment and deploy
|
|
30
|
+
mapsource-node status Read enrollment and service progress
|
|
31
|
+
mapsource-node disable [--services ID[,ID]] [--apply]
|
|
32
|
+
mapsource-node retire [--services ID[,ID]] [--apply]
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
async function input(prompt) {
|
|
36
|
+
if (!process.stdin.isTTY) throw new Error("This choice requires a terminal or an explicit option.");
|
|
37
|
+
const reader = createInterface({ input: process.stdin, output: process.stderr });
|
|
38
|
+
try { return (await reader.question(prompt)).trim(); }
|
|
39
|
+
finally { reader.close(); }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function showPlan(plan) {
|
|
43
|
+
console.log(plan.services.map(service => printable(service.label)).join(", "));
|
|
44
|
+
console.log(`Needs ${plan.requiredCpu} CPU threads and ${gib(plan.requiredMemory)} of available memory.`);
|
|
45
|
+
for (const disk of plan.disks) {
|
|
46
|
+
console.log(`${disk.paths.join(", ")} · ${gib(disk.peakBytes)} peak · ${gib(disk.reserveBytes)} reserve · ${gib(disk.availableBytes)} free · ${disk.inodes.toLocaleString()} inodes`);
|
|
47
|
+
}
|
|
48
|
+
for (const issue of plan.errors) console.log(printable(issue));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function localMesh(configuration) {
|
|
52
|
+
const { operatorPublicKey, ...payload } = configuration;
|
|
53
|
+
if (!sshKey.test(operatorPublicKey ?? "")) throw new Error("Invalid scoped peer operator key.");
|
|
54
|
+
const sshDirectory = path.join(homedir(), ".ssh");
|
|
55
|
+
const authorized = path.join(sshDirectory, "authorized_keys");
|
|
56
|
+
await mkdir(sshDirectory, { recursive: true, mode: 0o700 });
|
|
57
|
+
const file = await open(authorized, "a+", 0o600);
|
|
58
|
+
try {
|
|
59
|
+
const info = await file.stat();
|
|
60
|
+
if (!info.isFile() || info.uid !== process.getuid() || info.mode & 0o022) throw new Error("Use a private authorized_keys file.");
|
|
61
|
+
const before = await file.readFile("utf8");
|
|
62
|
+
const line = `restrict ${operatorPublicKey}`;
|
|
63
|
+
if (!before.split("\n").includes(line)) await file.appendFile("\n" + line + "\n");
|
|
64
|
+
await file.sync();
|
|
65
|
+
} finally { await file.close(); }
|
|
66
|
+
// Only the reviewed, npm-pinned bootstrap code is executable. The authority
|
|
67
|
+
// supplies the scoped connector credential and node identity as data.
|
|
68
|
+
const text = execFileSync(process.execPath, [bootstrap, "--execute"], {
|
|
69
|
+
input: JSON.stringify(payload), encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], timeout: 180_000,
|
|
70
|
+
});
|
|
71
|
+
const installed = JSON.parse(text.trim().split("\n").at(-1));
|
|
72
|
+
if (installed.installed !== true || installed.node !== payload.node || installed.machineId !== payload.machineId) {
|
|
73
|
+
throw new Error("The local peer transport did not return the expected identity.");
|
|
74
|
+
}
|
|
75
|
+
return { publicKeys: { host: installed.hostPublicKey, peer: installed.peerPublicKey }, root: installed.root };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function localPrivileges(services, catalog) {
|
|
79
|
+
execFileSync("/usr/bin/sudo", ["-n", "true"], { stdio: "ignore", timeout: 5000 });
|
|
80
|
+
if (catalog.services.some(service => services.includes(service.id) && service.tools.includes("docker"))) {
|
|
81
|
+
execFileSync("docker", ["info", "--format", "{{.ServerVersion}}"], { stdio: "ignore", timeout: 8000 });
|
|
82
|
+
execFileSync("docker", ["compose", "version", "--short"], { stdio: "ignore", timeout: 8000 });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function resume() {
|
|
87
|
+
const saved = await readEnrollment();
|
|
88
|
+
if (saved.pendingClaim) throw new Error("Re-enter the same sync key with setup to resume the authorized selection.");
|
|
89
|
+
const identity = await localIdentity();
|
|
90
|
+
const call = (operation, value = {}) => enrollmentRequest(saved.endpoint, operation, { node: saved.node, ...value }, { identity });
|
|
91
|
+
let result = await call("status");
|
|
92
|
+
if (["authorized", "tunnel-issued"].includes(result.phase)) {
|
|
93
|
+
const peer = await call("bootstrap");
|
|
94
|
+
const identityProof = await localMesh(peer);
|
|
95
|
+
result = await call("register", identityProof);
|
|
96
|
+
}
|
|
97
|
+
if (["registered", "failed"].includes(result.phase)) {
|
|
98
|
+
const host = await measureHost(targets);
|
|
99
|
+
const plan = planServices(saved.catalog, host, saved.services);
|
|
100
|
+
if (!plan.eligible) { showPlan(plan); throw new Error("This host no longer meets the selected service requirements."); }
|
|
101
|
+
await localPrivileges(saved.services, saved.catalog);
|
|
102
|
+
result = await call("deploy");
|
|
103
|
+
}
|
|
104
|
+
return result;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function setup(args) {
|
|
108
|
+
const options = flags(args, { ...servicesOption, "key-file": { type: "string" }, "key-stdin": { type: "boolean" }, apply: { type: "boolean" } });
|
|
109
|
+
if (options["key-file"] && options["key-stdin"]) throw new Error("Choose one sync key input.");
|
|
110
|
+
let saved = await readEnrollment().catch(error => { if (error.code !== "ENOENT") throw error; });
|
|
111
|
+
if (saved && !saved.pendingClaim) { show(await resume()); return; }
|
|
112
|
+
const invitation = readInvitation(await secretInput({ fromFile: options["key-file"], fromStdin: options["key-stdin"] }));
|
|
113
|
+
if (saved && saved.endpoint !== invitation.endpoint) throw new Error("Resume with the original sync key.");
|
|
114
|
+
if (!saved) {
|
|
115
|
+
const grant = await enrollmentRequest(invitation.endpoint, "catalog", {}, { invitation });
|
|
116
|
+
const catalog = grant.catalog;
|
|
117
|
+
validateCatalog(catalog);
|
|
118
|
+
const host = await measureHost(targets);
|
|
119
|
+
console.log(`${host.os} ${host.architecture} · ${host.cpu} threads · ${gib(host.memoryBytes)} available · CUDA device ${host.cuda ? "detected" : "absent"}`);
|
|
120
|
+
for (const service of catalog.services.filter(item => grant.allowed.includes(item.id))) {
|
|
121
|
+
const { errors, eligible } = planServices(catalog, host, [service.id]);
|
|
122
|
+
console.log(` ${service.id} ${printable(service.label)} · ${eligible ? "compatible" : printable(errors[0])}`);
|
|
123
|
+
}
|
|
124
|
+
const selection = ids(options.services ?? await input("Select service IDs separated by commas: "));
|
|
125
|
+
if (!selection.every(id => grant.allowed.includes(id))) throw new Error("The sync key does not permit one or more selected services.");
|
|
126
|
+
const plan = planServices(catalog, host, selection);
|
|
127
|
+
showPlan(plan);
|
|
128
|
+
if (!plan.eligible) throw new Error("The selection exceeds this host’s capacity.");
|
|
129
|
+
if (!options.apply && (!process.stdin.isTTY || (await input("Apply this plan? [y/N] ")).toLowerCase() !== "y")) return;
|
|
130
|
+
await localPrivileges(selection, catalog);
|
|
131
|
+
saved = { node: grant.node, endpoint: invitation.endpoint, services: [...new Set(selection)].sort(), catalog, pendingClaim: true };
|
|
132
|
+
await saveEnrollment(saved);
|
|
133
|
+
}
|
|
134
|
+
const identity = await localIdentity();
|
|
135
|
+
const receipt = await enrollmentRequest(saved.endpoint, "claim", {
|
|
136
|
+
machineId: identity.machineId, username: identity.username, services: saved.services, catalogDigest: catalogDigest(saved.catalog),
|
|
137
|
+
}, { invitation, identity });
|
|
138
|
+
if (receipt.node !== saved.node) throw new Error("The claimed identity does not match the enrollment.");
|
|
139
|
+
await saveEnrollment({ ...saved, pendingClaim: false });
|
|
140
|
+
show(await resume());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function main(command, args) {
|
|
144
|
+
if (command === "--help" && !args.length) { process.stdout.write(usage); return; }
|
|
145
|
+
if (command === "setup") { await setup(args); return; }
|
|
146
|
+
if (command === "resume" && !args.length) { show(await resume()); return; }
|
|
147
|
+
if (command === "services" && !args.length) { show((await operatorRequest("catalog", {})).catalog.services); return; }
|
|
148
|
+
if (command === "invite" || command === "revoke") {
|
|
149
|
+
const options = flags(args, command === "invite" ? { node: { type: "string" }, out: { type: "string" }, ...servicesOption } : { node: { type: "string" } });
|
|
150
|
+
if (!options.node) throw new Error("Pass --node NAME.");
|
|
151
|
+
if (command === "revoke") { show(await operatorRequest(command, { node: options.node })); return; }
|
|
152
|
+
if (!options.services) throw new Error("Pass --services with at least one service ID.");
|
|
153
|
+
if (options.out) {
|
|
154
|
+
const fd = await open(options.out, "wx", 0o600);
|
|
155
|
+
let complete = false;
|
|
156
|
+
try {
|
|
157
|
+
const result = await operatorRequest(command, { node: options.node, services: ids(options.services) });
|
|
158
|
+
await fd.writeFile(result.key + "\n"); await fd.sync();
|
|
159
|
+
complete = true;
|
|
160
|
+
show({ node: result.node, expiresAt: result.expiresAt, keyFile: options.out });
|
|
161
|
+
} finally { await fd.close(); if (!complete) await rm(options.out); }
|
|
162
|
+
} else {
|
|
163
|
+
if (!process.stdout.isTTY) throw new Error("Use --out FILE to avoid printing a key into logs or a pipeline.");
|
|
164
|
+
const result = await operatorRequest(command, { node: options.node, services: ids(options.services) });
|
|
165
|
+
console.log(result.key);
|
|
166
|
+
console.log("Expires " + new Date(result.expiresAt).toISOString());
|
|
167
|
+
}
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (["status", "disable", "retire"].includes(command)) {
|
|
171
|
+
const options = flags(args, command === "status" ? {} : { ...servicesOption, apply: { type: "boolean" } });
|
|
172
|
+
const saved = await readEnrollment();
|
|
173
|
+
if (saved.pendingClaim) throw new Error("Waiting for sync key confirmation. Run mapsource-node setup.");
|
|
174
|
+
show(await enrollmentRequest(saved.endpoint, command, { node: saved.node, preview: !options.apply,
|
|
175
|
+
...(options.services && { services: ids(options.services) }) }, { identity: await localIdentity() }));
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
throw new Error("Unknown command. Run mapsource-node --help.");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function firstRun() {
|
|
182
|
+
const enrolled = await Promise.all(["/etc/mapsource-cd/node-v5.json", "/etc/systemd/system/mapsource-mesh-tunnel.service"]
|
|
183
|
+
.map(file => access(file).then(() => true, () => false)));
|
|
184
|
+
if (enrolled.some(Boolean)) return false;
|
|
185
|
+
const state = await readEnrollment().catch(error => { if (error.code !== "ENOENT") throw error; });
|
|
186
|
+
if (state && !state.pendingClaim) return false;
|
|
187
|
+
if (!process.stdin.isTTY) return false;
|
|
188
|
+
console.log("Mapsource Node · First-time setup");
|
|
189
|
+
console.log("Create a sync key on an enrolled host with mapsource-node invite.");
|
|
190
|
+
await setup([]);
|
|
191
|
+
return true;
|
|
192
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { createHash, createPrivateKey, generateKeyPairSync, randomUUID, sign } from "node:crypto";
|
|
2
|
+
import { mkdir, open, readFile, realpath, rename, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { homedir, userInfo } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { Writable } from "node:stream";
|
|
7
|
+
import { request } from "node:http";
|
|
8
|
+
|
|
9
|
+
const enrollmentHost = /^mapsource-enroll-[a-z][a-z0-9-]{0,31}\.mapsource\.io$/;
|
|
10
|
+
const stateRoot = () => path.join(process.env.XDG_STATE_HOME || path.join(homedir(), ".local/state"), "mapsource-node");
|
|
11
|
+
const maximumReply = 1024 ** 2;
|
|
12
|
+
|
|
13
|
+
export function readInvitation(input, { allowLoopback = false } = {}) {
|
|
14
|
+
const match = /^mps-sync1:([a-z0-9.-]+(?::[0-9]+)?):([a-f0-9]{32}):([A-Za-z0-9_-]{43})$/.exec(input.trim());
|
|
15
|
+
if (!match) throw new Error("Enter a valid Mapsource sync key.");
|
|
16
|
+
const [, host, id, secret] = match;
|
|
17
|
+
const loopback = allowLoopback && /^127\.0\.0\.1:[1-9][0-9]{1,4}$/.test(host);
|
|
18
|
+
if (!loopback && !enrollmentHost.test(host)) throw new Error("The sync key must use a registered Mapsource enrollment host.");
|
|
19
|
+
return { endpoint: `${loopback ? "http" : "https"}://${host}`, id, secret };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function privateRead(file) {
|
|
23
|
+
const resolved = await realpath(file);
|
|
24
|
+
const info = await stat(resolved);
|
|
25
|
+
if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077)) throw new Error("Enrollment credentials must belong to you and have mode 0600.");
|
|
26
|
+
if (info.size > 256 * 1024) throw new Error("Enrollment state exceeds its size budget.");
|
|
27
|
+
return readFile(resolved, "utf8");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function privateWrite(name, data, { exclusive = false } = {}) {
|
|
31
|
+
const root = stateRoot();
|
|
32
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
33
|
+
const directory = await stat(root);
|
|
34
|
+
if (!directory.isDirectory() || directory.uid !== process.getuid() || (directory.mode & 0o077)) throw new Error("Enrollment state must be a private directory.");
|
|
35
|
+
const destination = path.join(root, name);
|
|
36
|
+
const pending = exclusive ? destination : path.join(root, ".pending-" + randomUUID());
|
|
37
|
+
const file = await open(pending, "wx", 0o600);
|
|
38
|
+
try {
|
|
39
|
+
try { await file.writeFile(JSON.stringify(data) + "\n"); await file.sync(); }
|
|
40
|
+
finally { await file.close(); }
|
|
41
|
+
if (!exclusive) await rename(pending, destination);
|
|
42
|
+
const directoryFD = await open(root, "r");
|
|
43
|
+
try { await directoryFD.sync(); } finally { await directoryFD.close(); }
|
|
44
|
+
} finally {
|
|
45
|
+
if (!exclusive) await rm(pending, { force: true });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function localIdentity() {
|
|
50
|
+
const file = path.join(stateRoot(), "identity.json");
|
|
51
|
+
try { return JSON.parse(await privateRead(file)); }
|
|
52
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
53
|
+
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
|
|
54
|
+
const machineId = (await readFile("/etc/machine-id", "utf8")).trim();
|
|
55
|
+
if (!/^[a-f0-9]{32}$/.test(machineId)) throw new Error("The machine needs a valid Linux machine ID.");
|
|
56
|
+
const username = userInfo().username;
|
|
57
|
+
if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(username) || username === "root") throw new Error("Run setup as the local Mapsource service user with sudo access.");
|
|
58
|
+
const identity = {
|
|
59
|
+
machineId, username,
|
|
60
|
+
publicKey: publicKey.export({ type: "spki", format: "der" }).toString("base64url"),
|
|
61
|
+
privateKey: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
|
|
62
|
+
};
|
|
63
|
+
try { await privateWrite("identity.json", identity, { exclusive: true }); }
|
|
64
|
+
catch (error) { if (error.code === "EEXIST") return JSON.parse(await privateRead(file)); throw error; }
|
|
65
|
+
return identity;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const readEnrollment = () => privateRead(path.join(stateRoot(), "enrollment.json")).then(JSON.parse);
|
|
69
|
+
export const saveEnrollment = data => privateWrite("enrollment.json", data);
|
|
70
|
+
|
|
71
|
+
export async function secretInput({ fromStdin, fromFile } = {}) {
|
|
72
|
+
if (fromFile) return (await privateRead(fromFile)).trim();
|
|
73
|
+
if (fromStdin) {
|
|
74
|
+
let data = "";
|
|
75
|
+
for await (const chunk of process.stdin) {
|
|
76
|
+
data += chunk;
|
|
77
|
+
if (data.length > 4096) throw new Error("Sync key input is too long.");
|
|
78
|
+
}
|
|
79
|
+
return data.trim();
|
|
80
|
+
}
|
|
81
|
+
if (!process.stdin.isTTY) throw new Error("Use --key-stdin or --key-file for a noninteractive enrollment.");
|
|
82
|
+
const discard = new Writable({ write(_chunk, _encoding, callback) { callback(); } });
|
|
83
|
+
const reader = createInterface({ input: process.stdin, output: discard, terminal: true });
|
|
84
|
+
try {
|
|
85
|
+
process.stderr.write("Paste the sync key, then press Enter: ");
|
|
86
|
+
return (await new Promise((resolve, reject) => {
|
|
87
|
+
reader.once("close", () => reject(new Error("Input canceled.")));
|
|
88
|
+
reader.once("SIGINT", () => reader.close());
|
|
89
|
+
reader.question("").then(resolve, reject);
|
|
90
|
+
})).trim();
|
|
91
|
+
} finally { reader.close(); process.stderr.write("\n"); }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function signOperation(identity, operation, payload, timestamp = Date.now(), requestId = randomUUID()) {
|
|
95
|
+
const body = { ...payload, publicKey: identity.publicKey, timestamp, requestId };
|
|
96
|
+
const encoded = Buffer.from(JSON.stringify([operation, body]));
|
|
97
|
+
return { body, proof: sign(null, encoded, createPrivateKey(identity.privateKey)).toString("base64url") };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function enrollmentRequest(endpoint, operation, payload, { invitation, identity, fetcher = fetch } = {}) {
|
|
101
|
+
const value = identity ? signOperation(identity, operation, payload) : { body: payload };
|
|
102
|
+
const response = await fetcher(new URL("/v1/" + operation, endpoint), {
|
|
103
|
+
method: "POST", redirect: "error", signal: AbortSignal.timeout(25_000),
|
|
104
|
+
headers: { "content-type": "application/json", ...(invitation && { authorization: `Bearer ${invitation.id}.${invitation.secret}` }) },
|
|
105
|
+
body: JSON.stringify(value),
|
|
106
|
+
});
|
|
107
|
+
const reader = response.body?.getReader();
|
|
108
|
+
if (!reader) throw new Error("Enrollment authority did not return a response.");
|
|
109
|
+
const chunks = [];
|
|
110
|
+
let bytes = 0;
|
|
111
|
+
try {
|
|
112
|
+
for (;;) {
|
|
113
|
+
const { done, value } = await reader.read();
|
|
114
|
+
if (done) break;
|
|
115
|
+
bytes += value.length;
|
|
116
|
+
if (bytes > maximumReply) throw new Error("Enrollment response exceeded its size budget.");
|
|
117
|
+
chunks.push(value);
|
|
118
|
+
}
|
|
119
|
+
} finally { await reader.cancel().catch(() => {}); }
|
|
120
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
121
|
+
if (!response.ok) {
|
|
122
|
+
const reason = /^[a-z][a-z0-9-]{0,60}$/.test(body.error ?? "") ? ` (${body.error})` : "";
|
|
123
|
+
throw new Error(`Enrollment request failed with HTTP ${response.status}${reason}.`);
|
|
124
|
+
}
|
|
125
|
+
return body;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function catalogDigest(catalog) {
|
|
129
|
+
return createHash("sha256").update(JSON.stringify(catalog)).digest("hex");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function operatorRequest(operation, input, socketPath = path.join(homedir(), ".local/share/mapsource/node-enrollment/operator.sock")) {
|
|
133
|
+
return new Promise((resolve, reject) => {
|
|
134
|
+
const body = JSON.stringify(input);
|
|
135
|
+
const req = request({ socketPath, path: "/v1/" + operation, method: "POST",
|
|
136
|
+
headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) } }, async response => {
|
|
137
|
+
try {
|
|
138
|
+
let reply = "";
|
|
139
|
+
for await (const chunk of response) {
|
|
140
|
+
reply += chunk;
|
|
141
|
+
if (Buffer.byteLength(reply) > maximumReply) throw new Error("Operator response exceeds its budget.");
|
|
142
|
+
}
|
|
143
|
+
const value = JSON.parse(reply);
|
|
144
|
+
if (response.statusCode !== 200) throw new Error("Operator request failed (" + (value.error ?? response.statusCode) + ").");
|
|
145
|
+
resolve(value);
|
|
146
|
+
} catch (error) { reject(error); }
|
|
147
|
+
});
|
|
148
|
+
req.setTimeout(15_000, () => req.destroy(new Error("Enrollment authority did not respond.")));
|
|
149
|
+
req.on("error", cause => reject(cause.code === "ENOENT" || cause.code === "ECONNREFUSED"
|
|
150
|
+
? new Error("This host does not have an active Mapsource enrollment authority.") : cause));
|
|
151
|
+
req.end(body);
|
|
152
|
+
});
|
|
153
|
+
}
|