payload.js

"use strict";
// Locus buyer payload (design-product.md 6a point 2; docs\build\PC_INSTALL_REPORT.md). Plain CommonJS, Node built-ins
// only. bootstrap.js ("run") loads this file only after its SHA-256 matched the digest baked into the plugin
// (HUB_FILES payload.module_sha256), from the very bytes it hashed. On a stranger's PC it lays down, under the buyer's
// Locus folder <profile>\AppData\Local\Locus (the plan's buyer.root):
//   python\         the python.org embeddable runtime: the zip pinned by SHA-256 and size, extracted;
//   newt\newt.exe   newt_windows_amd64.exe from the newt GitHub release, pinned by SHA-256 and size;
//   program\<id>\   the Locus PC program, carried in the plugin as payload\program-<id>.zip (pinned the same way).
// Every byte is checked before it is used. A download goes to <name>.part while it is hashed; a wrong size or digest,
// an early end or a refused redirect deletes it and stops the install with a reason a person can read. The URLs are
// python.org's and the newt GitHub release's (GitHub's redirect to its release file host is followed, https only);
// under MSI_CHAT_TEST only plain http to 127.0.0.1 (the test's own server). The zip reader refuses links, absolute or
// parent paths, Windows device names, duplicates, encryption, zip64 and anything past its size caps. This file names
// no place of any PC and holds no secret.
const crypto = require("node:crypto");
const fs = require("node:fs");
const http = require("node:http");
const https = require("node:https");
const path = require("node:path");
const zlib = require("node:zlib");

const MiB = 1024 * 1024;
const CAPS = Object.freeze({ python: 64 * MiB, newt: 128 * MiB, program: 32 * MiB });
const ZIP_MAX_ENTRIES = 4000;
const ZIP_MAX_TOTAL = 512 * MiB;
const IDLE_MS = 60000;
const PART_MS = 20 * 60000;
const MAX_REDIRECTS = 5;
const HEX64 = /^[0-9a-f]{64}$/;
const VERSION = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;
const PROGRAM_FILE = /^program-([0-9a-f]{16})\.zip$/;
const REL_PATH = /^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.-]+)*$/;
const BUYER_REL = "\\AppData\\Local\\Locus";
// the official places (written as patterns: the shipped code holds no link)
const OFFICIAL = Object.freeze({
  python: /^https:\/\/www\.python\.org\/ftp\/python\/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/python-\1-embed-amd64\.zip$/,
  newt: /^https:\/\/github\.com\/fosrl\/newt\/releases\/download\/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/newt_windows_amd64\.exe$/,
});
const REDIRECT_HOSTS = Object.freeze({ python: /^www\.python\.org$/i, newt: /^(github\.com|[a-z0-9-]+\.githubusercontent\.com)$/i });
const LOOPBACK_URL = /^http:\/\/127\.0\.0\.1:([0-9]{1,5})\/[A-Za-z0-9._~/-]{1,200}$/;
const WHAT = Object.freeze({ python: "the Python runtime", newt: "newt (the tunnel program)", program: "the Locus program" });
const RUNTIME_MARKER = "locus-runtime.json";
const INSTALLED_FILE = "installed-payload.json";
const PART_NAME = /^[A-Za-z0-9_][A-Za-z0-9._+-]{0,127}$/;
const DEVICE_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;

// The buyer's folders, all from the root; the upload area (the files phones send) is <profile>\Locus-uploads: the
// engine refuses an upload folder in app data, and the person finds his files there. A Windows user folder with a space
// (the owner's pick, review round): Python lives in the space-free root (spaceFreeRoot) instead, as does the copy of the
// pin script newt's --updown runs (msi_newt; newt splits that command at spaces). One table with src\hub.ts buyerLayout.
function layoutOf(root, payload, testMode, spaceFree) {
  const programId = PROGRAM_FILE.exec(payload.program.file)[1];
  const newtName = testMode && payload.newt.name === "newt.py" ? "newt.py" : "newt.exe";
  const pyBase = spaceFree || root;
  return Object.freeze({
    root, runDir: root + "\\run", python: pyBase + "\\python\\python.exe", pythonDir: pyBase + "\\python", newtDir: root + "\\newt",
    newt: root + "\\newt\\" + newtName, programDir: root + "\\program", program: root + "\\program\\" + programId,
    downloads: root + "\\downloads", data: root + "\\data",
    uploads: root.slice(0, -BUYER_REL.length) + "\\Locus-uploads", secrets: root + "\\secrets",
    uninstaller: root + "\\uninstall.cmd", spaceFree: spaceFree || null,
  });
}

// The space-free root of a user folder with a space: <ProgramData>\Locus\u<16 hex of the profile's path>, one per
// Windows account, made private by the bootstrap before anything is written in it (privateFolder).
function spaceFreeRoot(profile, programData) {
  const id = crypto.createHash("sha256").update(String(profile).replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase(), "utf8").digest("hex");
  return String(programData).replace(/[\\/]+$/, "") + "\\Locus\\u" + id.slice(0, 16);
}

function isPlainObject(v) {
  return typeof v === "object" && v !== null && !Array.isArray(v);
}

// program.files: the buyer's installer files and their digests (the bootstrap's verify list; review H2).
function programFilesProblem(files) {
  if (!isPlainObject(files) || Object.keys(files).length === 0 || Object.keys(files).length > 2000) return "program.files is not a list of digests";
  for (const [rel, digest] of Object.entries(files)) {
    if (!REL_PATH.test(rel) || rel.split("/").some((p) => p === "." || p === "..")) return "program.files: a bad path";
    if (typeof digest !== "string" || !HEX64.test(digest)) return "program.files: a bad digest";
  }
  return null;
}

function pinProblem(part, pin, testMode) {
  if (!isPlainObject(pin)) return part + ": not an object";
  if (typeof pin.sha256 !== "string" || !HEX64.test(pin.sha256)) return part + ".sha256 is not 64 hex characters";
  if (!Number.isInteger(pin.size) || pin.size < 1 || pin.size > CAPS[part]) return part + ".size is not 1-" + CAPS[part];
  if (part === "program") {
    const m = typeof pin.file === "string" ? PROGRAM_FILE.exec(pin.file) : null;
    if (m === null || m[1] !== pin.sha256.slice(0, 16)) return "program.file is not program-<the first 16 hex of its digest>.zip";
    if (pin.url !== undefined) return "program.url: the program is carried in the plugin, never downloaded";
    return programFilesProblem(pin.files);
  }
  if (typeof pin.version !== "string" || !VERSION.test(pin.version)) return part + ".version is not x.y.z";
  const official = typeof pin.url === "string" ? OFFICIAL[part].exec(pin.url) : null;
  const loopback = testMode && typeof pin.url === "string" && LOOPBACK_URL.test(pin.url);
  if (!loopback && (official === null || official[1] !== pin.version)) return part + ".url is not the official download of " + pin.version;
  if (pin.name !== undefined && !(part === "newt" && testMode && pin.name === "newt.py")) return part + ".name is only for the test's newt stand-in";
  return null;
}

// null when the baked payload is acceptable (main() checks the same in src\hub.ts parsePayload).
function payloadProblem(payload, testMode) {
  if (!isPlainObject(payload) || payload.schema !== 1) return "payload: schema is not 1";
  if (typeof payload.module_sha256 !== "string" || !HEX64.test(payload.module_sha256)) return "payload: module_sha256 is not 64 hex characters";
  for (const part of ["python", "newt", "program"]) {
    const problem = pinProblem(part, payload[part], testMode);
    if (problem !== null) return "payload: " + problem;
  }
  return null;
}

// --- files ----------------------------------------------------------------------------------------------------------

function sha256OfFile(file, fsApi = fs) {
  const hash = crypto.createHash("sha256");
  const fd = fsApi.openSync(file, "r");
  try {
    const buf = Buffer.alloc(1 << 20);
    let n;
    while ((n = fsApi.readSync(fd, buf, 0, buf.length, null)) > 0) hash.update(buf.subarray(0, n));
  } finally {
    fsApi.closeSync(fd);
  }
  return hash.digest("hex");
}

// True when `file` is a plain file of exactly the pinned size and digest.
function matches(file, pin, fsApi = fs) {
  try {
    const st = fsApi.lstatSync(file);
    return st.isFile() && !st.isSymbolicLink() && st.size === pin.size && sha256OfFile(file, fsApi) === pin.sha256;
  } catch (err) {
    return false;
  }
}

function removeQuietly(target, fsApi = fs) {
  try {
    fsApi.rmSync(target, { recursive: true, force: true, maxRetries: 3 });
  } catch (err) {
    // left for the next attempt
  }
}

function renameRetry(from, to, fsApi = fs) {
  for (let i = 0; ; i += 1) {
    try {
      fsApi.renameSync(from, to);
      return;
    } catch (err) {
      if (i >= 10 || !["EPERM", "EBUSY", "EACCES"].includes(err.code)) throw err;
      Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);
    }
  }
}

// --- the download ---------------------------------------------------------------------------------------------------

function hostOf(url) {
  try {
    return new URL(url).host;
  } catch (err) {
    return "?";
  }
}

function failure(part, kind, text) {
  return { ok: false, step: "download", kind, reason: text };
}

// The next place a redirect may send this part to: https on its official hosts (http on the loopback under the test).
function redirectProblem(part, next, testMode) {
  if (testMode && LOOPBACK_URL.test(next)) return null;
  let u;
  try {
    u = new URL(next);
  } catch (err) {
    return "a redirect to an unreadable address";
  }
  if (u.protocol !== "https:") return "a redirect to a plain-http address";
  if (u.username || u.password || u.port) return "a redirect to an address with a port or a login";
  if (!REDIRECT_HOSTS[part] || !REDIRECT_HOSTS[part].test(u.hostname)) return "a redirect to another site (" + u.hostname + ")";
  return null;
}

function offlineText(part, host, code) {
  return "Locus could not download " + WHAT[part] + ": " + host + " cannot be reached (" + code + "). Is this PC online? " +
    "Nothing was installed; it tries again at the next LM Studio start";
}

// GET url into <dest>.part, hashed on the way, then renamed to dest when the size and the digest are the pinned ones.
// Resolves {ok: true} or a failure {ok: false, step: "download", kind, reason}; the .part file never survives a failure.
function download(part, url, dest, pin, options = {}) {
  const testMode = options.testMode === true;
  const fsApi = options.fs || fs;
  const idleMs = options.idleMs || IDLE_MS;
  const partMs = options.partMs || PART_MS;
  const tmp = dest + ".part";
  const firstHost = hostOf(url);
  return new Promise((resolve) => {
    let fd = null;
    let done = false;
    let deadline = null;
    const finish = (result) => {
      if (done) return;
      done = true;
      clearTimeout(deadline);
      if (fd !== null) {
        try { fsApi.closeSync(fd); } catch (err) { /* closed */ }
        fd = null;
      }
      if (!result.ok) removeQuietly(tmp, fsApi);
      resolve(result);
    };
    deadline = setTimeout(() => finish(failure(part, "timeout", "the download of " + WHAT[part] + " from " + firstHost +
      " took longer than " + Math.round(partMs / 60000) + " minutes: nothing was installed; it tries again at the next LM Studio start")), partMs);
    const get = (address, hops) => {
      const mod = address.startsWith("https:") ? https : http;
      let req;
      try {
        req = mod.get(address, { headers: { "User-Agent": "Locus-installer", Accept: "*/*", "Accept-Encoding": "identity" }, timeout: idleMs, agent: false });
      } catch (err) {
        finish(failure(part, "offline", offlineText(part, hostOf(address), (err && err.code) || "a bad address")));
        return;
      }
      req.on("timeout", () => {
        req.destroy();
        finish(failure(part, "offline", offlineText(part, hostOf(address), "no answer for " + Math.round(idleMs / 1000) + " s")));
      });
      req.on("error", (err) => {
        if (fd === null) finish(failure(part, "offline", offlineText(part, hostOf(address), (err && err.code) || "a network error")));
      });
      req.on("response", (res) => onResponse(address, hops, req, res));
    };
    const onResponse = (address, hops, req, res) => {
      const status = res.statusCode || 0;
      if ([301, 302, 303, 307, 308].includes(status)) {
        res.resume();
        const location = res.headers.location;
        let next = null;
        try {
          next = typeof location === "string" ? new URL(location, address).toString() : null;
        } catch (err) {
          next = null;
        }
        const problem = next === null ? "a redirect without an address" : hops >= MAX_REDIRECTS ? "too many redirects" : redirectProblem(part, next, testMode);
        if (problem !== null) {
          finish(failure(part, "redirect", "the download of " + WHAT[part] + " from " + firstHost + " was refused: " + problem + "; nothing was installed"));
          return;
        }
        get(next, hops + 1);
        return;
      }
      if (status !== 200) {
        res.resume();
        finish(failure(part, "http", "the download of " + WHAT[part] + " failed: " + hostOf(address) + " answered HTTP " + status +
          "; nothing was installed; it tries again at the next LM Studio start"));
        return;
      }
      const length = res.headers["content-length"];
      if (length !== undefined && Number(length) !== pin.size) {
        finish(failure(part, "size", WHAT[part] + " on " + hostOf(address) + " is " + length + " bytes, not the pinned " + pin.size +
          ": refused, nothing was installed"));
        res.destroy();
        return;
      }
      const hash = crypto.createHash("sha256");
      let bytes = 0;
      try {
        fsApi.mkdirSync(path.win32.dirname(tmp), { recursive: true });
        fd = fsApi.openSync(tmp, "w");
      } catch (err) {
        finish(failure(part, "disk", WHAT[part] + " could not be written (" + (err && err.code) + "): is the disk full?"));
        res.destroy();
        return;
      }
      res.setTimeout(idleMs, () => res.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
      res.on("data", (chunk) => {
        if (done) return;
        bytes += chunk.length;
        if (bytes > pin.size) {
          finish(failure(part, "size", WHAT[part] + " from " + hostOf(address) + " is larger than the pinned " + pin.size +
            " bytes: refused, nothing was installed"));
          res.destroy();
          return;
        }
        hash.update(chunk);
        try {
          fsApi.writeSync(fd, chunk);
        } catch (err) {
          finish(failure(part, "disk", WHAT[part] + " could not be written (" + (err && err.code) + "): is the disk full?"));
          res.destroy();
        }
      });
      const ended = (complete) => {
        if (done) return;
        if (!complete || bytes !== pin.size) {
          finish(failure(part, "partial", "the download of " + WHAT[part] + " from " + hostOf(address) + " stopped at " + bytes + " of " +
            pin.size + " bytes: nothing was installed; it tries again at the next LM Studio start"));
          return;
        }
        if (hash.digest("hex") !== pin.sha256) {
          finish(failure(part, "mismatch", WHAT[part] + " downloaded from " + hostOf(address) + " is not the pinned file (its SHA-256 differs): " +
            "it was deleted and nothing was installed"));
          return;
        }
        try {
          fsApi.closeSync(fd);
          fd = null;
          removeQuietly(dest, fsApi);
          renameRetry(tmp, dest, fsApi);
        } catch (err) {
          finish(failure(part, "disk", WHAT[part] + " could not be put in place (" + (err && err.code) + ")"));
          return;
        }
        finish({ ok: true, bytes });
      };
      res.on("end", () => ended(res.complete));
      res.on("aborted", () => ended(false));
      res.on("error", () => ended(false));
      res.on("close", () => ended(res.complete));
    };
    get(url, 0);
  });
}

// --- the zip reader -------------------------------------------------------------------------------------------------

let crcTable = null;
function crc32(buf) {
  if (typeof zlib.crc32 === "function") return zlib.crc32(buf) >>> 0;
  if (crcTable === null) {
    crcTable = new Int32Array(256);
    for (let n = 0; n < 256; n += 1) {
      let c = n;
      for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
      crcTable[n] = c;
    }
  }
  let crc = -1;
  for (let i = 0; i < buf.length; i += 1) crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
  return (crc ^ -1) >>> 0;
}

class ZipError extends Error {}

function entryNameProblem(name) {
  if (name.length === 0 || name.length > 400) return "an empty or overlong name";
  if (name.includes("\\") || name.includes(":") || name.startsWith("/")) return "an absolute or Windows-style name";
  const parts = name.replace(/\/$/, "").split("/");
  if (parts.length > 8) return "a name too deep";
  for (const p of parts) {
    if (!PART_NAME.test(p) || /\.$/.test(p) || DEVICE_NAME.test(p)) return "a name Locus does not write (" + JSON.stringify(name.slice(0, 80)) + ")";
  }
  return null;
}

// The entries of a zip held in `buf`: [{name, method, crc, csize, usize, data offset}]. Throws ZipError.
function readZip(buf) {
  const min = Math.max(0, buf.length - 22 - 65535);
  let eocd = -1;
  for (let i = buf.length - 22; i >= min; i -= 1) {
    if (buf.readUInt32LE(i) === 0x06054b50) {
      eocd = i;
      break;
    }
  }
  if (eocd < 0) throw new ZipError("not a zip file");
  const count = buf.readUInt16LE(eocd + 10);
  const cdSize = buf.readUInt32LE(eocd + 12);
  const cdOff = buf.readUInt32LE(eocd + 16);
  if (count === 0xffff || cdOff === 0xffffffff || cdSize === 0xffffffff) throw new ZipError("a zip64 file");
  if (count === 0 || count > ZIP_MAX_ENTRIES) throw new ZipError("no entries or too many entries");
  if (cdOff + cdSize > eocd) throw new ZipError("a broken directory");
  const entries = [];
  const seen = new Set();
  let total = 0;
  let p = cdOff;
  for (let i = 0; i < count; i += 1) {
    if (p + 46 > eocd || buf.readUInt32LE(p) !== 0x02014b50) throw new ZipError("a broken directory entry");
    const flags = buf.readUInt16LE(p + 8);
    const method = buf.readUInt16LE(p + 10);
    const crc = buf.readUInt32LE(p + 16);
    const csize = buf.readUInt32LE(p + 20);
    const usize = buf.readUInt32LE(p + 24);
    const nlen = buf.readUInt16LE(p + 28);
    const elen = buf.readUInt16LE(p + 30);
    const clen = buf.readUInt16LE(p + 32);
    const attrs = buf.readUInt32LE(p + 38);
    const local = buf.readUInt32LE(p + 42);
    const name = buf.toString("utf8", p + 46, p + 46 + nlen);
    p += 46 + nlen + elen + clen;
    if (flags & 0x0001) throw new ZipError("an encrypted entry");
    if (method !== 0 && method !== 8) throw new ZipError("an entry packed another way (method " + method + ")");
    if (csize === 0xffffffff || usize === 0xffffffff) throw new ZipError("a zip64 entry");
    if (((attrs >>> 16) & 0o170000) === 0o120000) throw new ZipError("a link entry");
    const problem = entryNameProblem(name);
    if (problem !== null) throw new ZipError(problem);
    const key = name.toLowerCase().replace(/\/$/, "");
    if (seen.has(key)) throw new ZipError("a name twice (" + JSON.stringify(name.slice(0, 80)) + ")");
    seen.add(key);
    if (name.endsWith("/")) continue;                      // a folder: made when a file needs it
    total += usize;
    if (total > ZIP_MAX_TOTAL) throw new ZipError("more than " + ZIP_MAX_TOTAL / MiB + " MiB unpacked");
    if (local + 30 > cdOff || buf.readUInt32LE(local) !== 0x04034b50) throw new ZipError("a broken local header");
    const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
    if (start + csize > cdOff) throw new ZipError("an entry past the end");
    entries.push(Object.freeze({ name, method, crc, csize, usize, start }));
  }
  const files = new Set(entries.map((e) => e.name.toLowerCase()));
  for (const name of files) {
    const parts = name.split("/");
    for (let i = 1; i < parts.length; i += 1) {
      if (files.has(parts.slice(0, i).join("/"))) throw new ZipError("a file and a folder of one name");
    }
  }
  return entries;
}

// Unpacks a zip held in memory (the very bytes whose digest was checked: review L5) into the NEW folder `dest` (it must
// not exist). Returns {count, files: {name: sha256}}. Throws ZipError.
function extractZipBuffer(buf, dest, fsApi = fs) {
  const entries = readZip(buf);
  fsApi.mkdirSync(dest, { recursive: false });
  const files = {};
  for (const e of entries) {
    const raw = buf.subarray(e.start, e.start + e.csize);
    let data;
    try {
      data = e.method === 0 ? raw : zlib.inflateRawSync(raw, { maxOutputLength: Math.max(1, e.usize) });
    } catch (err) {
      throw new ZipError("an entry that does not unpack (" + JSON.stringify(e.name.slice(0, 80)) + ")");
    }
    if (data.length !== e.usize || crc32(data) !== e.crc) throw new ZipError("an entry whose check sum differs (" + JSON.stringify(e.name.slice(0, 80)) + ")");
    const target = path.win32.join(dest, ...e.name.split("/"));
    fsApi.mkdirSync(path.win32.dirname(target), { recursive: true });
    fsApi.writeFileSync(target, data, { flag: "wx" });
    files[e.name] = crypto.createHash("sha256").update(data).digest("hex");
  }
  return { count: entries.length, files };
}

// Unpacks the zip file into the NEW folder `dest`. Returns the number of files. Throws ZipError.
function extractZip(zipFile, dest, fsApi = fs) {
  return extractZipBuffer(fsApi.readFileSync(zipFile), dest, fsApi).count;
}

// --- laying it down -------------------------------------------------------------------------------------------------

function readJson(file, fsApi = fs) {
  try {
    const value = JSON.parse(fsApi.readFileSync(file, "utf8"));
    return isPlainObject(value) ? value : null;
  } catch (err) {
    return null;
  }
}

// A pinned file read ONCE into memory and checked there: the bytes returned are the bytes that matched (review L5).
function readPinned(file, pin, fsApi = fs) {
  try {
    const st = fsApi.lstatSync(file);
    if (!st.isFile() || st.isSymbolicLink() || st.size !== pin.size) return null;
    const buf = fsApi.readFileSync(file);
    return buf.length === pin.size && crypto.createHash("sha256").update(buf).digest("hex") === pin.sha256 ? buf : null;
  } catch (err) {
    return null;
  }
}

// The pinned file of a part at `dest`: kept when it is already there and right, else downloaded (to dest).
async function obtain(part, pin, dest, ctx) {
  if (matches(dest, pin, ctx.fs)) {
    ctx.log("payload: " + WHAT[part] + " is already here and matches its pin");
    return { ok: true, fresh: false };
  }
  removeQuietly(dest, ctx.fs);
  ctx.log("payload: downloading " + WHAT[part] + " (" + pin.version + ", " + pin.size + " bytes) from " + hostOf(pin.url));
  const got = await ctx.download(part, pin.url, dest, pin, { testMode: ctx.testMode, fs: ctx.fs });
  if (got.ok) ctx.log("payload: " + WHAT[part] + " downloaded and its SHA-256 matches the pin");
  return Object.assign({ fresh: true }, got);
}

// Unpacks verified zip bytes into <dir> through <dir>.new; the old folder goes only once the new one is complete.
function replaceWithZip(buf, dir, marker, ctx) {
  const fresh = dir + ".new";
  const old = dir + ".old";
  removeQuietly(fresh, ctx.fs);
  removeQuietly(old, ctx.fs);
  let out;
  try {
    out = extractZipBuffer(buf, fresh, ctx.fs);
    if (marker) ctx.fs.writeFileSync(path.win32.join(fresh, RUNTIME_MARKER), JSON.stringify(Object.assign({}, marker, { files: out.files })) + "\n", "utf8");
    if (ctx.fs.existsSync(dir)) renameRetry(dir, old, ctx.fs);
    renameRetry(fresh, dir, ctx.fs);
  } catch (err) {
    removeQuietly(fresh, ctx.fs);
    if (!ctx.fs.existsSync(dir) && ctx.fs.existsSync(old)) {
      try { renameRetry(old, dir, ctx.fs); } catch (e) { /* the next attempt lays it down again */ }
    }
    throw err;
  }
  removeQuietly(old, ctx.fs);
  return out.count;
}

// The laid-down Python is the pinned one: its marker names the zip's digest AND every file it unpacked is still the
// same (review L5: the folder is not trusted from its marker alone).
function pythonIsCurrent(pin, layout, fsApi) {
  const marker = readJson(path.win32.join(layout.pythonDir, RUNTIME_MARKER), fsApi);
  if (marker === null || marker.sha256 !== pin.sha256 || !isPlainObject(marker.files) || Object.keys(marker.files).length === 0) return false;
  for (const [name, digest] of Object.entries(marker.files)) {
    try {
      if (sha256OfFile(path.win32.join(layout.pythonDir, ...name.split("/")), fsApi) !== digest) return false;
    } catch (err) {
      return false;
    }
  }
  return fsApi.existsSync(layout.python);
}

// Phase 1 (nothing in use is touched): the Python zip downloaded and checked, held in memory; null when current.
async function preparePython(pin, layout, ctx) {
  if (pythonIsCurrent(pin, layout, ctx.fs)) {
    ctx.log("payload: " + WHAT.python + " " + pin.version + " is already laid down (every file checked)");
    return { ok: true, zip: null };
  }
  const zipFile = path.win32.join(layout.downloads, "python-" + pin.version + "-embed-amd64.zip");
  const got = await obtain("python", pin, zipFile, ctx);
  if (!got.ok) return got;
  const zip = readPinned(zipFile, pin, ctx.fs);
  if (zip === null) return { ok: false, step: "download", reason: WHAT.python + " changed after its download: refused, nothing was installed" };
  return { ok: true, zip, zipFile };
}

function commitPython(pin, layout, prepared, ctx) {
  if (prepared.zip === null) return { ok: true };
  try {
    const count = replaceWithZip(prepared.zip, layout.pythonDir, { schema: 1, sha256: pin.sha256, version: pin.version }, ctx);
    if (!ctx.fs.existsSync(layout.python)) return { ok: false, step: "lay-down", reason: "the Python runtime holds no python.exe" };
    ctx.log("payload: " + WHAT.python + " laid down (" + count + " files)");
  } catch (err) {
    return { ok: false, step: "lay-down", reason: WHAT.python + " could not be unpacked: " + (err instanceof ZipError ? err.message : (err && err.code) || "an error") };
  }
  removeQuietly(prepared.zipFile, ctx.fs);
  return { ok: true };
}

// Phase 1 for newt: a new newt is downloaded beside the downloads, not over the one a running Locus may use.
async function prepareNewt(pin, layout, ctx) {
  if (matches(layout.newt, pin, ctx.fs)) {
    ctx.log("payload: " + WHAT.newt + " is already here and matches its pin");
    return { ok: true, staged: null };
  }
  const staged = path.win32.join(layout.downloads, path.win32.basename(layout.newt));
  const got = await obtain("newt", pin, staged, ctx);
  return got.ok ? { ok: true, staged } : got;
}

function commitNewt(pin, layout, prepared, ctx) {
  if (prepared.staged === null) return { ok: true };
  try {
    ctx.fs.mkdirSync(layout.newtDir, { recursive: true });
    removeQuietly(layout.newt, ctx.fs);
    renameRetry(prepared.staged, layout.newt, ctx.fs);
  } catch (err) {
    return { ok: false, step: "lay-down", reason: WHAT.newt + " could not be put in place (" + ((err && err.code) || "an error") + ")" };
  }
  return matches(layout.newt, pin, ctx.fs) ? { ok: true } :
    { ok: false, step: "lay-down", reason: WHAT.newt + " changed while it was put in place: refused" };
}

// The carried program: read once, checked in memory, unpacked from those bytes (review L5) into program\<id>, a folder
// no running Locus uses (it runs its release copy).
function layProgram(pin, layout, pluginDir, ctx) {
  const carried = path.win32.join(pluginDir, "payload", pin.file);
  const zip = readPinned(carried, pin, ctx.fs);
  if (zip === null) {
    return { ok: false, step: "verify", reason: "the Locus program carried in the plugin (payload\\" + pin.file + ") is missing or is not the " +
      "pinned file: install the plugin again from LM Studio" };
  }
  try {
    ctx.fs.mkdirSync(layout.programDir, { recursive: true });
    const count = replaceWithZip(zip, layout.program, null, ctx);
    ctx.log("payload: " + WHAT.program + " laid down (" + count + " files)");
  } catch (err) {
    return { ok: false, step: "lay-down", reason: WHAT.program + " could not be unpacked: " + (err instanceof ZipError ? err.message : (err && err.code) || "an error") };
  }
  return { ok: true };
}

// The space-free root (a Windows user folder with a space): made for this user only BEFORE anything is written in it
// (other accounts may create files in ProgramData's folders). icacls: no inherited entry; this user, SYSTEM and the
// Administrators only. A folder another account holds is refused (its owner cannot be changed by this user).
function privateFolder(dir, ctx) {
  const root = ctx.systemRoot;
  if (typeof root !== "string" || !/^[A-Za-z]:[\\/]/.test(root)) return { ok: false, step: "lay-down", reason: "SystemRoot is not known: refused" };
  const run = ctx.spawnSync || require("node:child_process").spawnSync;
  try {
    const st = ctx.fs.lstatSync(dir);
    if (!st.isDirectory() || st.isSymbolicLink()) return { ok: false, step: "lay-down", reason: dir + " is not a plain folder: refused" };
  } catch (err) {
    ctx.fs.mkdirSync(dir, { recursive: true });
  }
  const who = run(path.win32.join(root, "System32", "whoami.exe"), ["/user", "/fo", "csv", "/nh"], { encoding: "utf8", windowsHide: true, timeout: 15000 });
  const sid = /"(S-1-5-[0-9-]+)"\s*$/m.exec(String(who.stdout || ""));
  if (who.status !== 0 || sid === null) return { ok: false, step: "lay-down", reason: "this Windows account's id could not be read (whoami)" };
  const icacls = path.win32.join(root, "System32", "icacls.exe");
  const set = run(icacls, [dir, "/setowner", "*" + sid[1]], { windowsHide: true, timeout: 30000 });
  const grant = set.status === 0 ? run(icacls, [dir, "/inheritance:r", "/grant:r", "*" + sid[1] + ":(OI)(CI)F", "*S-1-5-18:(OI)(CI)F",
    "*S-1-5-32-544:(OI)(CI)F"], { windowsHide: true, timeout: 30000 }) : set;
  if (grant.status !== 0) return { ok: false, step: "lay-down", reason: dir + " is held by another Windows account or its rights cannot be set: refused" };
  const shown = run(icacls, [dir], { encoding: "utf8", windowsHide: true, timeout: 30000 });
  const others = String(shown.stdout || "").split(/\r?\n/).filter((l) => /:\(/.test(l) && !/NT AUTHORITY\\SYSTEM|BUILTIN\\Administrators/i.test(l));
  if (shown.status !== 0 || others.length !== 1) return { ok: false, step: "lay-down", reason: dir + "'s rights are not this account's alone: refused" };
  return { ok: true };
}

// The whole payload for the plan: {ok: true, layout} or {ok: false, step, reason}. Never throws. Phase 1 gets and checks
// everything without touching what a running Locus uses; then ctx.stopLocus (an update: Locus stops); then phase 2 puts
// Python and newt in place (review M4: an update lays the new pins down over an installed Locus).
async function layDown(ctx) {
  const plan = ctx.plan;
  const env = isPlainObject(plan.env) ? plan.env : {};
  const systemRoot = env[Object.keys(env).find((k) => k.toLowerCase() === "systemroot")] || process.env.SystemRoot;
  const deps = { fs: ctx.deps.fs || fs, log: ctx.log, testMode: plan.testMode === true, download: ctx.deps.download || download,
    spawnSync: ctx.deps.spawnSync, systemRoot };
  try {
    const problem = payloadProblem(plan.payload, deps.testMode);
    if (problem !== null) return { ok: false, step: "verify", reason: problem };
    const layout = layoutOf(plan.buyer.root, plan.payload, deps.testMode, plan.buyer.space_free);
    for (const dir of [layout.root, layout.downloads]) deps.fs.mkdirSync(dir, { recursive: true });
    if (layout.spaceFree) {
      const made = privateFolder(layout.spaceFree, deps);
      if (!made.ok) return made;
    }
    const program = layProgram(plan.payload.program, layout, path.win32.dirname(plan.bootstrap.path), deps);
    if (!program.ok) return program;
    const python = await preparePython(plan.payload.python, layout, deps);
    if (!python.ok) return python;
    const newt = await prepareNewt(plan.payload.newt, layout, deps);
    if (!newt.ok) return newt;
    if ((python.zip !== null || newt.staged !== null) && typeof ctx.stopLocus === "function") {
      const stopped = await ctx.stopLocus();
      if (!stopped.ok) return stopped;
    }
    for (const done of [commitPython(plan.payload.python, layout, python, deps), commitNewt(plan.payload.newt, layout, newt, deps)]) {
      if (!done.ok) return done;
    }
    return { ok: true, layout };
  } catch (err) {
    return { ok: false, step: "lay-down", reason: "unexpected " + ((err && (err.code || err.name)) || "error") };
  }
}

// What an installed Locus was laid down from (<root>\installed-payload.json), written after a successful install: the
// next main() compares it with the plugin's own payload (review M4: a different one is an update).
function payloadIdentity(payload) {
  return { python: payload.python.sha256, newt: payload.newt.sha256, program: payload.program.sha256 };
}

function writeInstalledPayload(ctx) {
  const layout = layoutOf(ctx.plan.buyer.root, ctx.plan.payload, ctx.plan.testMode === true, ctx.plan.buyer.space_free);
  const file = path.win32.join(layout.root, INSTALLED_FILE);
  (ctx.deps.fs || fs).writeFileSync(file, JSON.stringify(Object.assign({ schema: 1, stage_id: ctx.plan.stage_id },
    payloadIdentity(ctx.plan.payload))) + "\n", "utf8");
  return file;
}

// --- the buyer's uninstaller ----------------------------------------------------------------------------------------

function cmdPath(p) {
  if (typeof p !== "string" || /["%!^&|<>\r\n]/.test(p)) throw new Error("a path the uninstaller cannot hold");
  return p;
}

// <root>\uninstall.cmd, written after a successful install. It frees the licence first (msi-chat uninstall deactivates;
// a failure changes nothing: review M3), tells the plugin to install nothing by itself again, and removes the program
// files. The chats (<root>\data) and the files phones sent (the upload area) stay unless /purge (the owner's pick).
function uninstallerText(layout, cli, settingsPath, node, pluginDir) {
  const lines = [
    "@echo off",
    "rem Locus: removes Locus from this PC (written by the Locus plugin's installer). It frees this PC's activation",
    "rem (another PC can be activated), signs out its phones and removes the program. The chats and the files your",
    "rem phones sent stay unless /purge.",
    "rem   uninstall.cmd [/purge] [/yes]     /yes: without the question",
    "setlocal EnableExtensions DisableDelayedExpansion",
    "set \"ROOT=" + cmdPath(layout.root) + "\"",
    "set \"PY=" + cmdPath(layout.python) + "\"",
    "set \"CLI=" + cmdPath(cli) + "\"",
    "set \"SETTINGS=" + cmdPath(settingsPath) + "\"",
    "set \"NODE=" + cmdPath(node) + "\"",
    "set \"TOOL=" + cmdPath(layout.program + "\\lmstudio-plugin\\install\\plugin_tool.js") + "\"",
    "set \"PLUGIN_DIR=" + cmdPath(pluginDir) + "\"",
    "set \"UPLOADS=" + cmdPath(layout.uploads) + "\"",
    "set \"SPACEFREE=" + cmdPath(layout.spaceFree || "") + "\"",
    "rem review L4: the system's own ping (never one found in the current folder)",
    "set \"PING=%SystemRoot%\\System32\\PING.EXE\"",
    "rem this file's own path, read before shift moves %0",
    "set \"SELF=%~f0\"",
    "set \"PURGE=\"",
    "set \"YES=\"",
    ":args",
    "if \"%~1\"==\"\" goto argsdone",
    "if /I \"%~1\"==\"/purge\" (set \"PURGE= --purge\" & shift & goto args)",
    "if /I \"%~1\"==\"/yes\" (set \"YES=1\" & shift & goto args)",
    "echo uninstall.cmd: %1 is not accepted. Allowed: /purge /yes. Nothing was changed.",
    "exit /b 2",
    ":argsdone",
    "echo Locus uninstall: this frees this PC's activation, signs out its phones and removes Locus (\"%ROOT%\").",
    "if defined PURGE goto say_purge",
    "echo Your Locus chats and the files your phones sent (\"%UPLOADS%\") are kept: uninstall.cmd /purge deletes them too.",
    "goto ask",
    ":say_purge",
    "echo /purge: your Locus chats and the files your phones sent (\"%UPLOADS%\") are deleted too.",
    ":ask",
    "if defined YES goto go",
    "set \"ANSWER=\"",
    "set /p \"ANSWER=Uninstall Locus? Type yes: \"",
    "if not defined ANSWER goto no",
    "setlocal EnableDelayedExpansion",
    "if /I not \"!ANSWER!\"==\"yes\" (endlocal & goto no)",
    "endlocal",
    ":go",
    "if not exist \"%SETTINGS%\" (echo [fail] Locus is not installed here: \"%SETTINGS%\" & exit /b 3)",
    "cd /d \"%ROOT%\\..\"",
    "\"%PY%\" -I -B -X utf8 \"%CLI%\" --settings \"%SETTINGS%\" uninstall --yes%PURGE%",
    "set \"RC=%errorlevel%\"",
    "if not \"%RC%\"==\"0\" (echo [fail] locus uninstall ended with exit code %RC%: nothing of Locus was removed, see above. & exit /b %RC%)",
    "if exist \"%TOOL%\" if exist \"%NODE%\" \"%NODE%\" --disable-warning=MODULE_TYPELESS_PACKAGE_JSON \"%TOOL%\" bootstrap-forget --run-dir \"%ROOT%\\run\" --plugin-dir \"%PLUGIN_DIR%\" --yes-really >nul",
    "echo Removing the program files of Locus: \"%ROOT%\"",
    "for %%D in (python newt program downloads run secrets) do call :gone \"%ROOT%\\%%D\"",
    "if defined SPACEFREE call :gone \"%SPACEFREE%\"",
    "del /q \"%ROOT%\\installed-payload.json\" 2>nul",
    "if defined PURGE goto last_purge",
    "rem the chats stay: this file goes last ((goto) ends the script first, so cmd never reads past it)",
    "(goto) 2>nul & del /q \"%SELF%\"",
    ":last_purge",
    "call :gone \"%ROOT%\\data\"",
    "(goto) 2>nul & rmdir /s /q \"%ROOT%\"",
    ":gone",
    "rem a folder still held for a moment (a process that has just exited): up to 20 tries, a second apart",
    "for /l %%i in (1,1,20) do if exist \"%~1\" (rmdir /s /q \"%~1\" 2>nul & if exist \"%~1\" \"%PING%\" -n 2 127.0.0.1 >nul)",
    "exit /b 0",
    ":no",
    "echo Nothing was changed.",
    "exit /b 2",
    "",
  ];
  return lines.join("\r\n");
}

function writeUninstaller(ctx, done) {
  const layout = layoutOf(ctx.plan.buyer.root, ctx.plan.payload, ctx.plan.testMode === true, ctx.plan.buyer.space_free);
  // the CLI of the unpacked program (the buyer's "repository", checked file by file at install), not the release's: the
  // purge refuses to delete the folder its own code runs from, and the release lies in the run folder it purges
  void done.release;
  const cli = path.win32.join(layout.program, "main", "msi_chat_cli.py");
  const text = uninstallerText(layout, cli, done.settingsPath, ctx.plan.node, path.win32.dirname(ctx.plan.bootstrap.path));
  (ctx.deps.fs || fs).writeFileSync(layout.uninstaller, text, "ascii");
  return layout.uninstaller;
}

module.exports = {
  CAPS, OFFICIAL, LOOPBACK_URL, RUNTIME_MARKER, INSTALLED_FILE, WHAT, ZipError, layoutOf, spaceFreeRoot, payloadProblem, pinProblem,
  redirectProblem, download, matches, sha256OfFile, crc32, readZip, extractZip, extractZipBuffer, layDown, payloadIdentity,
  writeInstalledPayload, uninstallerText, writeUninstaller,
};