mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 06:35:24 +00:00
feat: add plugin packing, signing, pinned trust and tmxplug bundling
This commit is contained in:
1 parent
c6a44b7ff3
commit
2ee9b3592c
25 files changed
+1764
-56
No files matched your search
@@ -1,19 +1,23 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { create } from "tar";
|
||||
import { readManifest } from "../lib/plugin-dir.mjs";
|
||||
import { collectFiles, createTmxplug } from "../lib/tmxplug.mjs";
|
||||
import { sha256 } from "../lib/signing.mjs";
|
||||
import { validate } from "./validate.mjs";
|
||||
|
||||
/** Everything a server needs to run the plugin, and nothing else. D3 signs it. */
|
||||
const CONTENTS = [
|
||||
"manifest.json",
|
||||
"dist",
|
||||
"locales",
|
||||
"migrations",
|
||||
"README.md",
|
||||
"CHANGELOG.md",
|
||||
];
|
||||
function readOption(args, name) {
|
||||
const index = args.indexOf(name);
|
||||
if (index === -1) return null;
|
||||
const value = args[index + 1];
|
||||
if (!value) throw new Error(`${name} needs a value`);
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function pack({ cwd }) {
|
||||
/**
|
||||
* Writes <id>-<version>.tmxplug. Validates first and refuses on any error,
|
||||
* so a broken manifest never becomes a release.
|
||||
*/
|
||||
export async function pack({ cwd, args = [] }) {
|
||||
const manifest = readManifest(cwd);
|
||||
const pluginId = manifest.id ?? path.basename(cwd);
|
||||
const version = manifest.version ?? "0.0.0";
|
||||
@@ -22,12 +26,17 @@ export async function pack({ cwd }) {
|
||||
throw new Error(`${pluginId}: nothing built. Run termix-plugin build.`);
|
||||
}
|
||||
|
||||
const files = CONTENTS.filter((entry) =>
|
||||
fs.existsSync(path.join(cwd, entry)),
|
||||
);
|
||||
const outfile = path.join(cwd, `${pluginId}-${version}.tgz`);
|
||||
await validate({ cwd });
|
||||
|
||||
await create({ gzip: true, cwd, file: outfile }, files);
|
||||
const outDir = path.resolve(cwd, readOption(args, "--out") ?? ".");
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
const outfile = path.join(outDir, `${pluginId}-${version}.tmxplug`);
|
||||
|
||||
const archive = createTmxplug(cwd, collectFiles(cwd));
|
||||
fs.writeFileSync(outfile, archive);
|
||||
|
||||
console.log(`packed ${path.basename(outfile)}`);
|
||||
console.log(` size ${archive.length}`);
|
||||
console.log(` sha256 ${sha256(archive).toString("hex")}`);
|
||||
return outfile;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import {
|
||||
SIGNING_KEY_ENV,
|
||||
generateKeyPair,
|
||||
loadPrivateKey,
|
||||
sha256,
|
||||
signArtifact,
|
||||
verifyArtifact,
|
||||
} from "../lib/signing.mjs";
|
||||
|
||||
function readOption(args, name) {
|
||||
const index = args.indexOf(name);
|
||||
if (index === -1) return null;
|
||||
const value = args[index + 1];
|
||||
if (!value) throw new Error(`${name} needs a value`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function artifactArg(cwd, args) {
|
||||
const file = args.find((arg) => arg.endsWith(".tmxplug"));
|
||||
if (!file) throw new Error("Pass the .tmxplug file to use");
|
||||
const full = path.resolve(cwd, file);
|
||||
if (!fs.existsSync(full)) throw new Error(`${file} does not exist`);
|
||||
return full;
|
||||
}
|
||||
|
||||
/** Writes <file>.sig: base64 Ed25519 over the sha256 of the .tmxplug. */
|
||||
export async function sign({ cwd, args = [], env = process.env }) {
|
||||
const file = artifactArg(cwd, args);
|
||||
const key = loadPrivateKey(env[SIGNING_KEY_ENV]);
|
||||
const buffer = fs.readFileSync(file);
|
||||
const signature = signArtifact(buffer, key);
|
||||
fs.writeFileSync(`${file}.sig`, `${signature}\n`);
|
||||
console.log(`signed ${path.basename(file)}`);
|
||||
console.log(` sha256 ${sha256(buffer).toString("hex")}`);
|
||||
console.log(` signature ${signature}`);
|
||||
return signature;
|
||||
}
|
||||
|
||||
/** Checks a .tmxplug against its .sig and one or more public keys. */
|
||||
export async function verify({ cwd, args = [] }) {
|
||||
const file = artifactArg(cwd, args);
|
||||
const keys = (readOption(args, "--key") ?? "")
|
||||
.split(",")
|
||||
.map((key) => key.trim())
|
||||
.filter(Boolean);
|
||||
if (keys.length === 0) throw new Error("Pass --key <base64 public key>");
|
||||
const sigFile = readOption(args, "--sig") ?? `${file}.sig`;
|
||||
if (!fs.existsSync(sigFile)) throw new Error(`${sigFile} does not exist`);
|
||||
|
||||
const matched = verifyArtifact(
|
||||
fs.readFileSync(file),
|
||||
fs.readFileSync(sigFile, "utf8"),
|
||||
keys,
|
||||
);
|
||||
if (!matched)
|
||||
throw new Error(`${path.basename(file)}: signature is not valid`);
|
||||
console.log(`ok ${path.basename(file)} signed by key ${matched}`);
|
||||
return matched;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a new private key to a file and prints the public half. The
|
||||
* private key never goes to stdout, so it does not end up in a CI log.
|
||||
*/
|
||||
export async function keygen({ cwd, args = [] }) {
|
||||
const outDir = path.resolve(cwd, readOption(args, "--out") ?? ".");
|
||||
const keyFile = path.join(outDir, "termix-plugin-signing.key");
|
||||
if (fs.existsSync(keyFile)) {
|
||||
throw new Error(`${keyFile} already exists; move it first`);
|
||||
}
|
||||
const pair = generateKeyPair();
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
fs.writeFileSync(keyFile, `${pair.privateKey}\n`, { mode: 0o600 });
|
||||
console.log(`private key ${keyFile}`);
|
||||
console.log(`public key ${pair.publicKey}`);
|
||||
console.log(`key id ${pair.keyId}`);
|
||||
console.log(
|
||||
`Store the private key as ${SIGNING_KEY_ENV}, then delete the file.`,
|
||||
);
|
||||
return { keyFile, publicKey: pair.publicKey, keyId: pair.keyId };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* termix-plugin: build, validate, test and pack a Termix plugin.
|
||||
* termix-plugin: build, validate, test, pack and sign a Termix plugin.
|
||||
*
|
||||
* Run from a plugin directory (npm run build inside plugins/<id>/ does).
|
||||
*/
|
||||
@@ -10,9 +10,19 @@ import { build } from "./commands/build.mjs";
|
||||
import { validate } from "./commands/validate.mjs";
|
||||
import { test } from "./commands/test.mjs";
|
||||
import { pack } from "./commands/pack.mjs";
|
||||
import { sign, verify, keygen } from "./commands/sign.mjs";
|
||||
import { migrations } from "./commands/migrations.mjs";
|
||||
|
||||
const COMMANDS = { build, validate, test, pack, migrations };
|
||||
const COMMANDS = {
|
||||
build,
|
||||
validate,
|
||||
test,
|
||||
pack,
|
||||
sign,
|
||||
verify,
|
||||
keygen,
|
||||
migrations,
|
||||
};
|
||||
|
||||
const [command, ...args] = process.argv.slice(2);
|
||||
|
||||
@@ -24,7 +34,10 @@ if (!command || command === "--help" || command === "-h") {
|
||||
" build Bundle the plugin into dist/",
|
||||
" validate Check manifest.json and the files it names",
|
||||
" test Run the plugin's vitest suite",
|
||||
" pack Write a .tgz of the built plugin",
|
||||
" pack Write <id>-<version>.tmxplug of the built plugin [--out dir]",
|
||||
" sign Sign a .tmxplug with TERMIX_PLUGIN_SIGNING_KEY <file>",
|
||||
" verify Check a .tmxplug's .sig <file> --key <base64>[,...]",
|
||||
" keygen Write a new signing key pair [--out dir]",
|
||||
" migrations Generate migrations from the plugin's table definitions",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import crypto from "node:crypto";
|
||||
|
||||
/** The env var that holds the base64 PKCS8 private key. Never commit it. */
|
||||
export const SIGNING_KEY_ENV = "TERMIX_PLUGIN_SIGNING_KEY";
|
||||
|
||||
// DER prefix of an Ed25519 SubjectPublicKeyInfo; the raw 32-byte key follows.
|
||||
const SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
|
||||
|
||||
export function sha256(buffer) {
|
||||
return crypto.createHash("sha256").update(buffer).digest();
|
||||
}
|
||||
|
||||
export function publicKeyFromRaw(base64) {
|
||||
const raw = Buffer.from(base64.trim(), "base64");
|
||||
if (raw.length !== 32) throw new Error("A public key is 32 bytes, base64");
|
||||
return crypto.createPublicKey({
|
||||
key: Buffer.concat([SPKI_PREFIX, raw]),
|
||||
format: "der",
|
||||
type: "spki",
|
||||
});
|
||||
}
|
||||
|
||||
export function rawPublicKey(keyObject) {
|
||||
const der = keyObject.export({ format: "der", type: "spki" });
|
||||
return der.subarray(SPKI_PREFIX.length).toString("base64");
|
||||
}
|
||||
|
||||
/** First 16 hex chars of the sha256 of the raw public key. */
|
||||
export function keyId(publicKeyBase64) {
|
||||
return sha256(Buffer.from(publicKeyBase64, "base64"))
|
||||
.toString("hex")
|
||||
.slice(0, 16);
|
||||
}
|
||||
|
||||
export function generateKeyPair() {
|
||||
const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
|
||||
const publicBase64 = rawPublicKey(publicKey);
|
||||
return {
|
||||
publicKey: publicBase64,
|
||||
privateKey: privateKey
|
||||
.export({ format: "der", type: "pkcs8" })
|
||||
.toString("base64"),
|
||||
keyId: keyId(publicBase64),
|
||||
};
|
||||
}
|
||||
|
||||
/** Accepts base64 PKCS8 DER (what keygen writes) or a PEM block. */
|
||||
export function loadPrivateKey(value) {
|
||||
if (!value || !value.trim()) {
|
||||
throw new Error(`${SIGNING_KEY_ENV} is not set`);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
const key = trimmed.startsWith("-----BEGIN")
|
||||
? crypto.createPrivateKey(trimmed)
|
||||
: crypto.createPrivateKey({
|
||||
key: Buffer.from(trimmed, "base64"),
|
||||
format: "der",
|
||||
type: "pkcs8",
|
||||
});
|
||||
if (key.asymmetricKeyType !== "ed25519") {
|
||||
throw new Error("The signing key must be an Ed25519 key");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/** Ed25519 over the raw 32-byte sha256 of the artifact, base64. */
|
||||
export function signArtifact(buffer, privateKey) {
|
||||
return crypto.sign(null, sha256(buffer), privateKey).toString("base64");
|
||||
}
|
||||
|
||||
/** The id of the first key that verifies the signature, or null. */
|
||||
export function verifyArtifact(buffer, signatureBase64, publicKeys) {
|
||||
const digest = sha256(buffer);
|
||||
const signature = Buffer.from(signatureBase64.trim(), "base64");
|
||||
if (signature.length !== 64) return null;
|
||||
for (const key of publicKeys) {
|
||||
try {
|
||||
if (crypto.verify(null, digest, publicKeyFromRaw(key), signature)) {
|
||||
return keyId(key);
|
||||
}
|
||||
} catch {
|
||||
// A malformed key is just a key that does not match.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import zlib from "node:zlib";
|
||||
|
||||
/** What a .tmxplug holds, in the order the spec lists it. */
|
||||
export const TMXPLUG_CONTENTS = [
|
||||
"manifest.json",
|
||||
"dist",
|
||||
"locales",
|
||||
"migrations",
|
||||
"README.md",
|
||||
"CHANGELOG.md",
|
||||
"icon.svg",
|
||||
];
|
||||
|
||||
const BLOCK = 512;
|
||||
|
||||
/**
|
||||
* Every file under the given top-level entries, as sorted posix paths.
|
||||
* Directories are implied by their files, so none get their own entry.
|
||||
*/
|
||||
export function collectFiles(cwd, entries = TMXPLUG_CONTENTS) {
|
||||
const files = [];
|
||||
const walk = (rel) => {
|
||||
const full = path.join(cwd, rel);
|
||||
const stat = fs.lstatSync(full);
|
||||
if (stat.isSymbolicLink()) {
|
||||
throw new Error(`${rel} is a symlink; a .tmxplug holds plain files only`);
|
||||
}
|
||||
if (stat.isDirectory()) {
|
||||
for (const child of fs.readdirSync(full)) {
|
||||
walk(path.posix.join(rel, child));
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
files.push(rel);
|
||||
}
|
||||
};
|
||||
for (const entry of entries) {
|
||||
if (fs.existsSync(path.join(cwd, entry))) walk(entry);
|
||||
}
|
||||
return files.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
}
|
||||
|
||||
function writeString(buf, offset, length, value) {
|
||||
const bytes = Buffer.from(value, "utf8");
|
||||
if (bytes.length > length) throw new Error(`"${value}" is too long`);
|
||||
bytes.copy(buf, offset);
|
||||
}
|
||||
|
||||
function writeOctal(buf, offset, length, value) {
|
||||
writeString(buf, offset, length, value.toString(8).padStart(length - 1, "0"));
|
||||
}
|
||||
|
||||
function splitName(name) {
|
||||
if (Buffer.byteLength(name) <= 100) return { name, prefix: "" };
|
||||
for (let i = name.length - 1; i > 0; i--) {
|
||||
if (name[i] !== "/") continue;
|
||||
const prefix = name.slice(0, i);
|
||||
const rest = name.slice(i + 1);
|
||||
if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(rest) <= 100) {
|
||||
return { name: rest, prefix };
|
||||
}
|
||||
}
|
||||
throw new Error(`${name} is too long for a .tmxplug entry`);
|
||||
}
|
||||
|
||||
function header(name, size) {
|
||||
const buf = Buffer.alloc(BLOCK);
|
||||
const split = splitName(name);
|
||||
writeString(buf, 0, 100, split.name);
|
||||
writeOctal(buf, 100, 8, 0o644);
|
||||
writeOctal(buf, 108, 8, 0);
|
||||
writeOctal(buf, 116, 8, 0);
|
||||
writeOctal(buf, 124, 12, size);
|
||||
writeOctal(buf, 136, 12, 0);
|
||||
buf.fill(0x20, 148, 156);
|
||||
buf[156] = 0x30;
|
||||
writeString(buf, 257, 6, "ustar");
|
||||
writeString(buf, 263, 2, "00");
|
||||
writeString(buf, 345, 155, split.prefix);
|
||||
let sum = 0;
|
||||
for (const byte of buf) sum += byte;
|
||||
writeString(buf, 148, 8, sum.toString(8).padStart(6, "0") + "\0 ");
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* A gzipped ustar archive that depends only on file names and contents:
|
||||
* fixed mode, owner and mtime, sorted entries, and a gzip header with no
|
||||
* timestamp and a fixed OS byte (Node on Windows writes a different one).
|
||||
* Rebuilding from the same tag gives the same sha256 on any machine.
|
||||
*/
|
||||
export function createTmxplug(cwd, files) {
|
||||
const parts = [];
|
||||
for (const rel of files) {
|
||||
const data = fs.readFileSync(path.join(cwd, rel));
|
||||
parts.push(header(rel, data.length), data);
|
||||
const pad = (BLOCK - (data.length % BLOCK)) % BLOCK;
|
||||
if (pad) parts.push(Buffer.alloc(pad));
|
||||
}
|
||||
parts.push(Buffer.alloc(BLOCK * 2));
|
||||
const gz = zlib.gzipSync(Buffer.concat(parts), { level: 9 });
|
||||
gz.writeUInt32LE(0, 4);
|
||||
gz[9] = 0x03;
|
||||
return gz;
|
||||
}
|
||||
Reference in new issue
Block a user