bootstrap.js
"use strict";
// Locus for macOS: the plugin's bootstrap (docs/build/MAC_REPORT.md), the Linux plugin's code unchanged (only this
// header differs: tests/bootstrap_same.test.mjs). Plain CommonJS, Node's built-ins only, run with
// the node that runs the plugin (LM Studio's own), so nothing of the installer runs before its files are checked.
// node bootstrap.js detach --plan <file> --plan-sha256 <sha> --ppid <n> starts `run` detached, exits on spawn
// node bootstrap.js run --plan <file> --plan-sha256 <sha> --ppid <n> the install (below)
// node bootstrap.js status --state <state dir> the ticket, in words
// run: the plan file must have the given digest and pass checkPlan; the lock <state>/bootstrap.lock is taken (an
// exclusive create; exit 6 when held); the ticket <state>/bootstrap.json must be for this stage (exit 5 when it was
// forgotten); the attempt is recorded; then, each failure ending the attempt (ticket "failed", the step and a one-line
// reason, exit 4):
// 1. verify: this file's SHA-256, and EVERY installer file (FILE_RULES) against the plan's digests: none missing,
// changed or added;
// 2. install: /bin/sh <installer>/main/install.sh --from-plugin <the plan's install args>, with the plan's env;
// 3. release: settings.json is there and `python3 -I -B <secrets>/msi_verify.py --check` passes; the ticket says done;
// 4. start: the release's CLI `start --no-lmstudio --no-qr --wait 40` (a problem here stays a note).
// Everything goes to <run>/logs/bootstrap.log (names, steps, exit codes; anything shaped like a key is cut out).
const crypto = require("node:crypto");
const childProcess = require("node:child_process");
const fs = require("node:fs");
const path = require("node:path");
const EXIT = Object.freeze({ OK: 0, USAGE: 2, FAILED: 4, GONE: 5, HELD: 6 });
const TICKET_FILE = "bootstrap.json";
const LOCK_FILE = "bootstrap.lock";
const LOCK_MAX_AGE_MS = 45 * 60 * 1000;
const LOCK_UNREADABLE_MS = 60 * 1000;
const SELF_STOP_MS = 30 * 60 * 1000;
const FILE_RULES = Object.freeze([
{ dir: "main", match: (n) => /\.(py|sh)$/.test(n) },
{ dir: "server-python", match: (n) => /\.py$/.test(n) },
{ dir: "web", match: (n) => n === "page.html" },
]);
const REQUIRED_FILES = Object.freeze(["main/install.sh", "main/msi_linux.py", "main/msi_chat_cli.py", "main/msi_verify.py",
"main/msi_install.py", "server-python/gate_main.py", "server-python/gate_qr.py"]);
const HEX64 = /^[0-9a-f]{64}$/;
const STAGE_ID = /^[0-9a-f]{32}$/;
const REL_PATH = /^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.-]+)*$/;
const BARE_FLAGS = Object.freeze(["--real", "--yes"]);
const VALUE_FLAGS = Object.freeze(["--newt", "--engine-port", "--admin-port", "--lmstudio-api", "--python"]);
const ARG_VALUE = /^[A-Za-z0-9:/._-]{1,260}$/;
const SECRET_SHAPE = /[A-Za-z0-9_-]{32,}/g;
function isAbsPosix(p) {
return typeof p === "string" && p.startsWith("/") && p.length <= 4096 && !/[\u0000-\u001f]/.test(p) &&
!p.split("/").some((part) => part === "." || part === "..");
}
function isUnder(p, root) {
const a = p.replace(/\/+/g, "/").replace(/(.)\/$/, "$1");
const r = root.replace(/\/+/g, "/").replace(/(.)\/$/, "$1");
return a === r || a.startsWith(r === "/" ? "/" : r + "/");
}
function sha256File(file) {
return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
}
// Every installer file of FILE_RULES under `installer`, relative with "/", with its digest; links are a problem.
function collectFiles(installer) {
const files = {};
const problems = [];
for (const rule of FILE_RULES) {
let entries = [];
try {
entries = fs.readdirSync(path.posix.join(installer, rule.dir), { withFileTypes: true });
} catch (err) {
continue;
}
for (const entry of entries) {
if (!rule.match(entry.name)) continue;
const rel = rule.dir + "/" + entry.name;
if (entry.isSymbolicLink()) problems.push("a link: " + rel);
else if (entry.isFile()) files[rel] = sha256File(path.join(installer, rule.dir, entry.name));
}
}
for (const rel of REQUIRED_FILES) {
if (!(rel in files)) problems.push("missing: " + rel);
}
return { files, problems };
}
function installArgsProblem(args, real) {
if (!Array.isArray(args) || args.length > 40) return "install_args: not a list";
let sawReal = false;
for (let i = 0; i < args.length; i += 1) {
const arg = args[i];
if (BARE_FLAGS.includes(arg)) {
sawReal = sawReal || arg === "--real";
continue;
}
if (VALUE_FLAGS.includes(arg)) {
const value = args[i + 1];
if (typeof value !== "string" || !ARG_VALUE.test(value) || value.startsWith("-") || value.includes("..")) {
return "install_args: " + arg + " needs a plain value";
}
i += 1;
continue;
}
return "install_args: " + JSON.stringify(arg) + " is not accepted";
}
if (sawReal !== real) return real ? "install_args: a real plan needs --real" : "install_args: --real in a test plan";
return null;
}
// The plan's shape (src/linux.ts buildPlan): every place absolute; installer, run folder and settings under HOME; under
// MSI_CHAT_TEST (the plan's env) HOME under MSI_CHAT_TEST_ROOT and no --real. null = fine, else the reason.
function checkPlan(plan) {
if (typeof plan !== "object" || plan === null || plan.schema !== 1) return "not a plan";
if (!STAGE_ID.test(String(plan.stage_id))) return "a bad stage id";
for (const key of ["installer", "run_dir", "home", "python", "node", "settings"]) {
if (!isAbsPosix(plan[key])) return key + " is not an absolute path";
}
for (const key of ["installer", "run_dir", "settings"]) {
if (!isUnder(plan[key], plan.home) || plan[key] === plan.home) return key + " is not under HOME";
}
if (!/\/python3(\.[0-9]{1,2})?$/.test(plan.python)) return "python is not a python3";
if (typeof plan.bootstrap !== "object" || plan.bootstrap === null || !isAbsPosix(plan.bootstrap.path) || !HEX64.test(String(plan.bootstrap.sha256))) {
return "the bootstrap's path or digest";
}
if (typeof plan.files !== "object" || plan.files === null || Object.keys(plan.files).length === 0) return "no files";
for (const [rel, digest] of Object.entries(plan.files)) {
if (!REL_PATH.test(rel) || !HEX64.test(String(digest))) return "a bad file entry " + JSON.stringify(rel);
}
if (typeof plan.real !== "boolean") return "real is not true or false";
const problem = installArgsProblem(plan.install_args, plan.real);
if (problem !== null) return problem;
if (typeof plan.env !== "object" || plan.env === null) return "no env";
for (const [name, value] of Object.entries(plan.env)) {
if (typeof value !== "string" || /^LMS_/i.test(name)) return "the env holds " + name;
}
if (plan.env.HOME !== plan.home) return "the env's HOME is not the plan's";
if (plan.env.MSI_CHAT_TEST === "1" || process.env.MSI_CHAT_TEST === "1") {
const root = plan.env.MSI_CHAT_TEST_ROOT;
if (!isAbsPosix(root) || root === "/" || !isUnder(plan.home, root)) return "refused under MSI_CHAT_TEST: HOME is outside MSI_CHAT_TEST_ROOT";
if (plan.real) return "refused under MSI_CHAT_TEST: a real plan";
}
const max = plan.max_per_day;
if (!Number.isInteger(max) || max < 1 || max > 10) return "max_per_day is not 1-10";
return null;
}
function lockState(text, mtimeMs, nowMs, alive) {
if (text === null) return "none";
let raw = null;
try {
raw = JSON.parse(text);
} catch (err) {
raw = null;
}
if (raw === null || typeof raw !== "object" || typeof raw.pid !== "number" || typeof raw.started !== "string" || Number.isNaN(Date.parse(raw.started))) {
return mtimeMs !== null && nowMs - mtimeMs <= LOCK_UNREADABLE_MS ? "fresh" : "stale";
}
const started = Date.parse(raw.started);
if (started - nowMs > 60000 || nowMs - started > LOCK_MAX_AGE_MS) return "stale";
return alive(raw.pid) ? "fresh" : "stale";
}
function pidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (err) {
return err.code === "EPERM";
}
}
function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch (err) {
return null;
}
}
function clean(text) {
return String(text).replace(SECRET_SHAPE, "<cut>");
}
function parseArgs(argv) {
const opts = { _: [] };
for (let i = 0; i < argv.length; i += 1) {
const a = argv[i];
if (a.startsWith("--")) {
opts[a.slice(2)] = argv[i + 1];
i += 1;
} else {
opts._.push(a);
}
}
return opts;
}
function loadPlan(opts) {
if (!isAbsPosix(opts.plan) || !HEX64.test(String(opts["plan-sha256"]))) return { error: "usage: --plan <abs file> --plan-sha256 <hex>" };
const text = readText(opts.plan);
if (text === null) return { error: "the plan file cannot be read" };
if (crypto.createHash("sha256").update(text, "utf8").digest("hex") !== opts["plan-sha256"]) return { error: "the plan file is not the one main() wrote" };
let plan;
try {
plan = JSON.parse(text);
} catch (err) {
return { error: "the plan file is not JSON" };
}
const problem = checkPlan(plan);
return problem === null ? { plan } : { error: "the plan: " + problem };
}
function cmdDetach(opts) {
const loaded = loadPlan(opts);
if (loaded.error) {
process.stderr.write("bootstrap detach: " + loaded.error + "\n");
return Promise.resolve(EXIT.USAGE);
}
const logs = path.posix.join(loaded.plan.run_dir, "logs");
fs.mkdirSync(logs, { recursive: true });
const out = fs.openSync(path.posix.join(logs, "bootstrap_stdio.log"), "a");
return new Promise((resolve) => {
const child = childProcess.spawn(process.execPath, [__filename, "run", "--plan", opts.plan, "--plan-sha256", opts["plan-sha256"],
"--ppid", String(opts.ppid)], { detached: true, stdio: ["ignore", out, out], env: process.env, cwd: loaded.plan.home });
child.once("spawn", () => {
child.unref();
resolve(EXIT.OK);
});
child.once("error", () => resolve(EXIT.FAILED));
});
}
function writeTicket(file, ticket) {
const tmp = file + ".tmp-" + process.pid;
fs.writeFileSync(tmp, JSON.stringify(ticket, null, 1) + "\n");
fs.renameSync(tmp, file);
}
function run(plan, opts, log) {
const state = path.posix.join(plan.run_dir, "state");
fs.mkdirSync(state, { recursive: true });
const lockFile = path.posix.join(state, LOCK_FILE);
const ticketFile = path.posix.join(state, TICKET_FILE);
let lockMtime = null;
try {
lockMtime = fs.statSync(lockFile).mtimeMs;
} catch (err) {
lockMtime = null;
}
if (lockState(readText(lockFile), lockMtime, Date.now(), pidAlive) === "stale") fs.rmSync(lockFile, { force: true });
try {
fs.writeFileSync(lockFile, JSON.stringify({ pid: process.pid, started: new Date().toISOString(), stage_id: plan.stage_id,
ppid: Number(opts.ppid) || null }), { flag: "wx" });
} catch (err) {
log("the lock is held by another bootstrap: nothing done");
return EXIT.HELD;
}
try {
let ticket;
try {
ticket = JSON.parse(readText(ticketFile));
} catch (err) {
ticket = null;
}
if (ticket === null || ticket.stage_id !== plan.stage_id) {
log("no install ticket for this stage (forgotten by an uninstall): nothing done");
return EXIT.GONE;
}
ticket.attempts = Array.isArray(ticket.attempts) ? ticket.attempts : [];
ticket.attempts.push({ t: new Date().toISOString(), ppid: Number(opts.ppid) || null, pid: process.pid });
ticket.state = "running";
writeTicket(ticketFile, ticket);
const fail = (step, reason) => {
ticket.state = "failed";
ticket.failed = { step, reason: clean(reason).slice(0, 400), t: new Date().toISOString() };
writeTicket(ticketFile, ticket);
log("[fail] " + step + ": " + clean(reason));
return EXIT.FAILED;
};
// 1. verify
if (sha256File(__filename) !== plan.bootstrap.sha256) return fail("verify", "bootstrap.js is not the one the plugin baked");
const found = collectFiles(plan.installer);
const problems = found.problems.slice();
for (const [rel, digest] of Object.entries(plan.files)) {
if (!(rel in found.files)) problems.push("missing: " + rel);
else if (found.files[rel] !== digest) problems.push("changed: " + rel);
}
for (const rel of Object.keys(found.files)) {
if (!(rel in plan.files)) problems.push("added: " + rel);
}
if (problems.length > 0) return fail("verify", problems.length + " installer file(s) differ from the published digests: " + problems.slice(0, 5).join("; "));
log("verify: " + Object.keys(plan.files).length + " installer files match the published digests");
// 2. install
const env = Object.assign({}, plan.env, { MSI_CHAT_PYTHON: plan.python });
const args = [path.posix.join(plan.installer, "main", "install.sh"), "--from-plugin", ...plan.install_args];
log("install: /bin/sh main/install.sh --from-plugin " + plan.install_args.join(" "));
const inst = childProcess.spawnSync("/bin/sh", args, { env, cwd: plan.home, encoding: "utf8", timeout: 20 * 60 * 1000, maxBuffer: 8 << 20 });
for (const line of String(inst.stdout || "").concat(String(inst.stderr || "")).split("\n")) {
if (line.trim()) log(" " + clean(line));
}
if (inst.status !== 0) return fail("install", "install.sh ended with exit " + String(inst.status));
// 3. release
let settings;
try {
settings = JSON.parse(readText(plan.settings));
} catch (err) {
return fail("release", "no settings.json after the install");
}
const verifier = path.posix.join(String(settings.secrets_dir), "msi_verify.py");
const check = childProcess.spawnSync(plan.python, ["-I", "-B", verifier, "--check", "--settings", plan.settings], { env, cwd: plan.home, timeout: 60000 });
if (check.status !== 0) return fail("release", "the verifier refused the release (exit " + String(check.status) + ")");
ticket.state = "done";
ticket.done = new Date().toISOString();
delete ticket.failed;
writeTicket(ticketFile, ticket);
log("release: checked; the ticket says done");
// 4. start
const cli = path.posix.join(plan.run_dir, "releases", String(settings.version), "main", "msi_chat_cli.py");
const start = childProcess.spawnSync(plan.python, ["-I", "-B", "-X", "utf8", cli, "--settings", plan.settings, "start", "--no-lmstudio", "--no-qr", "--wait", "40"],
{ env, cwd: plan.home, encoding: "utf8", timeout: 120000 });
for (const line of String(start.stdout || "").concat(String(start.stderr || "")).split("\n")) {
if (line.trim()) log(" " + clean(line));
}
if (start.status !== 0) {
ticket.note = "Locus did not start (exit " + String(start.status) + "): locus start";
writeTicket(ticketFile, ticket);
}
log("done: Locus is installed" + (start.status === 0 ? " and running: run `locus pair` in a terminal to pair a phone" : ""));
return EXIT.OK;
} finally {
fs.rmSync(lockFile, { force: true });
}
}
function cmdRun(opts) {
const loaded = loadPlan(opts);
if (loaded.error) {
process.stderr.write("bootstrap run: " + loaded.error + "\n");
return EXIT.USAGE;
}
const plan = loaded.plan;
const logs = path.posix.join(plan.run_dir, "logs");
fs.mkdirSync(logs, { recursive: true });
const logFile = path.posix.join(logs, "bootstrap.log");
const log = (text) => fs.appendFileSync(logFile, new Date().toISOString() + " " + text + "\n");
const timer = setTimeout(() => {
log("[fail] the bootstrap stops itself after 30 min");
process.exit(EXIT.FAILED);
}, SELF_STOP_MS);
timer.unref();
log("bootstrap " + process.pid + " stage " + plan.stage_id.slice(0, 8) + " (env names: " + Object.keys(plan.env).sort().join(",") + ")");
return run(plan, opts, log);
}
function cmdStatus(opts) {
if (!isAbsPosix(opts.state)) {
process.stderr.write("usage: bootstrap.js status --state <state dir>\n");
return EXIT.USAGE;
}
const text = readText(path.posix.join(opts.state, TICKET_FILE));
if (text === null) {
process.stdout.write("no install ticket\n");
return 1;
}
const t = JSON.parse(text);
process.stdout.write("install " + t.state + (t.failed ? " at " + t.failed.step + ": " + t.failed.reason : "") + " (" + (t.attempts || []).length + " attempt(s))\n");
return t.state === "done" ? EXIT.OK : t.state === "failed" ? EXIT.FAILED : 1;
}
async function main(argv) {
const opts = parseArgs(argv);
const command = opts._[0];
if (command === "detach") return cmdDetach(opts);
if (command === "run") return cmdRun(opts);
if (command === "status") return cmdStatus(opts);
process.stderr.write("usage: bootstrap.js detach|run --plan <file> --plan-sha256 <hex> --ppid <n> | status --state <dir>\n");
return EXIT.USAGE;
}
module.exports = { FILE_RULES, REQUIRED_FILES, collectFiles, checkPlan, installArgsProblem, lockState, isAbsPosix, isUnder };
if (require.main === module) {
main(process.argv.slice(2)).then((code) => process.exit(code), () => process.exit(EXIT.FAILED));
}