install / plugin_payload.js

"use strict";
// The buyer payload's publish side (docs\build\PC_INSTALL_REPORT.md; design 6a point 2), plain CommonJS, Node built-ins
// only, used by install\plugin_publish.js (`publish-stage --buyer-pins <pins file>`) and by the tests:
// - writeZip: a deterministic zip (sorted names, one fixed time stamp, no extra fields, deflate or store);
// - the PC program as one zip, payload\program-<first 16 hex of its SHA-256>.zip: the installer files bootstrap.js's
//   FILE_RULES hash WITHOUT the owner's own (OWNER_ONLY), their digests baked as payload.program.files (the bootstrap's
//   verify step checks the unpacked program file by file), plus lmstudio-plugin\manifest.json (plugin_tool.js reads it);
// - the pins file (lmstudio-plugin\payload-pins.json, not shipped): Python and newt, each {version, url, sha256, size},
//   checked with payload.js's own rules; the newt pin must be install.cmd's;
// - the payload object baked into HUB_FILES: {schema 1, module_sha256 (the copy's payload.js), python, newt, program};
// - the program zip's own scan: its file list is exactly the buyer's (no owner-only file: OWNER_ONLY, review H2), and no
//   entry holds a private key, a secret literal or any of the owner's private details (payload-private.json, not shipped).
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const zlib = require("node:zlib");

const DOS_TIME = 0;               // 00:00:00
const DOS_DATE = (0 << 9) | (1 << 5) | 1;   // 1980-01-01
const MANIFEST_REL = "lmstudio-plugin/manifest.json";
// a key block (the armor line followed by its base64 body, not code that names the armor) and a key-shaped literal
// assigned to a secret's name (20+ characters of a key's alphabet in quotes: the program's own texts never match)
const PEM_KEY = /-----BEGIN [A-Z ]*PRIVATE KEY-----\s*\r?\n\s*[A-Za-z0-9+/=]{40,}/;
const SECRET_WORD = /\b(?:token|secret|password|passwd|api[ _-]?key)\b["']?\s*[:=]\s*["'`]([A-Za-z0-9+/_=-]{20,})["'`]/gi;

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

// [{name, data}] -> a zip Buffer. The same files always give the same bytes (sorted by name, fixed time, no extras).
function writeZip(files, { method = 8 } = {}) {
  const sorted = [...files].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
  const locals = [];
  const centrals = [];
  let offset = 0;
  for (const f of sorted) {
    const name = Buffer.from(f.name, "utf8");
    const data = Buffer.isBuffer(f.data) ? f.data : Buffer.from(f.data);
    const packed = method === 8 ? zlib.deflateRawSync(data, { level: 9 }) : data;
    const crc = crc32(data);
    const local = Buffer.alloc(30);
    local.writeUInt32LE(0x04034b50, 0);
    local.writeUInt16LE(20, 4);
    local.writeUInt16LE(0x0800, 6);
    local.writeUInt16LE(method, 8);
    local.writeUInt16LE(DOS_TIME, 10);
    local.writeUInt16LE(DOS_DATE, 12);
    local.writeUInt32LE(crc, 14);
    local.writeUInt32LE(packed.length, 18);
    local.writeUInt32LE(data.length, 22);
    local.writeUInt16LE(name.length, 26);
    local.writeUInt16LE(0, 28);
    const central = Buffer.alloc(46);
    central.writeUInt32LE(0x02014b50, 0);
    central.writeUInt16LE(20, 4);
    central.writeUInt16LE(20, 6);
    central.writeUInt16LE(0x0800, 8);
    central.writeUInt16LE(method, 10);
    central.writeUInt16LE(DOS_TIME, 12);
    central.writeUInt16LE(DOS_DATE, 14);
    central.writeUInt32LE(crc, 16);
    central.writeUInt32LE(packed.length, 20);
    central.writeUInt32LE(data.length, 24);
    central.writeUInt16LE(name.length, 28);
    central.writeUInt32LE(offset, 42);
    locals.push(local, name, packed);
    centrals.push(central, name);
    offset += local.length + name.length + packed.length;
  }
  const cd = Buffer.concat(centrals);
  const end = Buffer.alloc(22);
  end.writeUInt32LE(0x06054b50, 0);
  end.writeUInt16LE(sorted.length, 8);
  end.writeUInt16LE(sorted.length, 10);
  end.writeUInt32LE(cd.length, 12);
  end.writeUInt32LE(offset, 16);
  return Buffer.concat([...locals, cd, end]);
}

const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex");

// Review H2: the owner's own files, never in a buyer's program (his defaults and details, his scripts, his phone gate,
// his sealed-file readers, the Linux CLI). A trailing "*" names a folder.
const OWNER_ONLY = Object.freeze(["main/msi_owner.py", "main/owner_defaults.cmd", "main/uninstall.cmd", "main/msi-chat.cmd",
  "main/find_mac.ps1", "main/msi_linux.py", "server-python/gate_owner.py", "server-python/phone_gate.py",
  "server-python/phone_gate_v2.py", "tools/*"]);

function isOwnerOnly(rel) {
  return OWNER_ONLY.some((o) => (o.endsWith("/*") ? rel.startsWith(o.slice(0, -1)) : rel === o));
}

// The buyer's program: bootstrap.js's installer files of `repo` (collectFiles) without the owner's, and the plugin
// manifest. {rels (zip names), digests (the buyer's files: the verify step's list)}. Throws.
function programFiles(repo, boot) {
  const collected = boot.collectFiles(repo);
  if (collected.problems.length > 0) throw new Error("the repository is not complete: " + collected.problems.join("; "));
  const digests = Object.fromEntries(Object.entries(collected.files).filter(([rel]) => !isOwnerOnly(rel)).sort());
  if (!fs.existsSync(path.join(repo, ...MANIFEST_REL.split("/")))) throw new Error("the repository has no " + MANIFEST_REL);
  return { rels: [...Object.keys(digests), MANIFEST_REL].sort(), digests };
}

// {buffer, sha256, size, file, count, files}: payload\program-<16 hex>.zip and the digests of its installer files.
// Each file is read once: its zip entry and its digest come from the same bytes.
function buildProgramZip(repo, boot) {
  const { rels } = programFiles(repo, boot);
  const entries = rels.map((rel) => ({ name: rel, data: fs.readFileSync(path.join(repo, ...rel.split("/"))) }));
  const files = Object.fromEntries(entries.filter((e) => e.name !== MANIFEST_REL).map((e) => [e.name, sha256(e.data)]));
  const buffer = writeZip(entries);
  const digest = sha256(buffer);
  return { buffer, sha256: digest, size: buffer.length, file: "program-" + digest.slice(0, 16) + ".zip", count: rels.length, files };
}

// The private details a buyer's program must not name (lmstudio-plugin\payload-private.json, not shipped):
// [[what, RegExp]]. Throws when the file is missing or holds no rule: no build without it.
function loadPrivateRules(file) {
  let raw;
  try {
    raw = JSON.parse(fs.readFileSync(file, "utf8"));
  } catch (err) {
    throw new Error("the private details file cannot be read: " + file);
  }
  const rules = (Array.isArray(raw.patterns) ? raw.patterns : []).filter((r) => Array.isArray(r) && r.length === 3)
    .map(([what, source, flags]) => [String(what), new RegExp(String(source), String(flags))]);
  if (rules.length === 0) throw new Error("the private details file holds no rule: " + file);
  return rules;
}

// install.cmd's newt pin (the one every newt.exe is checked against at install).
function installCmdNewtPin(text) {
  const m = /^set "NEWT_SHA256_PINNED=([0-9a-f]{64})"\r?$/m.exec(String(text));
  return m === null ? null : m[1];
}

// The pins file: {python: {version, url, sha256, size}, newt: {...}}, checked by payload.js's rules (the test's loopback
// only under MSI_CHAT_TEST). Official newt pins must equal install.cmd's. Throws an Error with the reason.
function readPins(file, payloadModule, { testMode = false, installCmdText = null } = {}) {
  let raw;
  try {
    raw = JSON.parse(fs.readFileSync(file, "utf8"));
  } catch (err) {
    throw new Error("the pins file cannot be read: " + file);
  }
  const pins = {};
  for (const part of ["python", "newt"]) {
    const pin = raw && raw[part];
    const problem = payloadModule.pinProblem(part, pin, testMode);
    if (problem !== null) throw new Error("the pins file: " + problem);
    pins[part] = { version: pin.version, url: pin.url, sha256: pin.sha256, size: pin.size, ...(pin.name === undefined ? {} : { name: pin.name }) };
  }
  if (payloadModule.OFFICIAL.newt.test(pins.newt.url)) {
    const pinned = installCmdNewtPin(installCmdText);
    if (pinned === null || pinned !== pins.newt.sha256) throw new Error("the pins file: newt's SHA-256 is not install.cmd's pin");
  }
  return pins;
}

// The payload object of HUB_FILES: program.files are the buyer's installer files' digests (the bootstrap's verify list).
function payloadObject(pins, program, moduleSha256) {
  return { schema: 1, module_sha256: moduleSha256, python: pins.python, newt: pins.newt,
    program: { file: program.file, sha256: program.sha256, size: program.size, files: program.files } };
}

// The program zip's own scan: {secrets: [...], private: [...]} ([] = fine). Its file list must be the expected one; no
// entry may hold a key block or a key-shaped secret literal, nor any of the owner's private details (rules).
function scanProgramZip(buffer, payloadModule, expectedRels, rules) {
  const secrets = [];
  const privates = [];
  let entries;
  try {
    entries = payloadModule.readZip(buffer);
  } catch (err) {
    return { secrets: ["the program zip does not read: " + err.message], private: privates };
  }
  const names = entries.map((e) => e.name).sort();
  if (JSON.stringify(names) !== JSON.stringify([...expectedRels].sort())) secrets.push("the program zip's files are not the buyer's files");
  for (const e of entries) {
    if (isOwnerOnly(e.name)) privates.push("an owner-only file: " + e.name);
    const raw = buffer.subarray(e.start, e.start + e.csize);
    const text = (e.method === 0 ? raw : zlib.inflateRawSync(raw)).toString("utf8");
    if (PEM_KEY.test(text)) secrets.push("a private key in " + e.name);
    if ((text.match(SECRET_WORD) || []).length > 0) secrets.push("a secret literal in " + e.name);
    for (const [what, re] of rules) if (re.test(text)) privates.push(what + " in " + e.name);
  }
  return { secrets, private: privates };
}

module.exports = { writeZip, crc32, programFiles, buildProgramZip, installCmdNewtPin, readPins, payloadObject, scanProgramZip, loadPrivateRules,
  isOwnerOnly, OWNER_ONLY, MANIFEST_REL };