#!/usr/bin/env node "use strict"; // Vendor-side tooling for the template store supply-chain anchor. The // ADTemplates repo CI runs `sign` on every publish; panel operators pin the // matching public key (see TEMPLATE-STORE-SIGNING.md). All crypto lives in // utils/template-store-trust.js so this tool and the panel verify with // byte-identical logic. // // node scripts/sign-template-store.js keygen // Generate an Ed25519 keypair. Prints the private key once (store it in // the CI secret TEMPLATE_STORE_SIGNING_KEY) and the public key (pin it // on panels / publish it for verification). // // node scripts/sign-template-store.js sign // Compute the canonical digest over the committed template files and // write store-signature.json at the repo root. // // node scripts/sign-template-store.js verify // Re-verify a checkout against TEMPLATE_STORE_SIGNING_PUBKEY (or the // public key embedded in the freshly written signature file's key pin). const fs = require("fs"); const path = require("path"); const crypto = require("crypto"); const { computeStoreDigestFromRaw, canonicalStoreSigningPayload, parseEd25519PublicKey, verifyStoreSignature, } = require("../utils/template-store-trust"); // Keep in sync with index.js TEMPLATE_STORE_CATEGORIES / safeTemplateStoreFileName. const STORE_CATEGORIES = ["games", "communication", "development", "hosting", "media"]; const FILE_NAME_RE = /^[a-z0-9][a-z0-9._-]*\.json$/i; function storeRepo() { return String(process.env.ADPANEL_TEMPLATE_STORE_REPO || "antonndev/ADTemplates").trim(); } function listStoreFiles(repoDir) { const files = []; for (const category of STORE_CATEGORIES) { const dir = path.join(repoDir, category); let names = []; try { names = fs.readdirSync(dir); } catch { continue; } for (const name of names) { if (!FILE_NAME_RE.test(name)) continue; files.push({ relPath: `${category}/${name}`, absolutePath: path.join(dir, name) }); } } files.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0)); return files; } function readPrivateKeyPem() { const raw = String(process.env.TEMPLATE_STORE_SIGNING_KEY || "").trim(); if (!raw) { console.error("TEMPLATE_STORE_SIGNING_KEY is not set (PKCS8 PEM or base64 of the raw 32-byte seed)."); process.exit(1); } if (raw.includes("PRIVATE KEY")) return raw.replace(/\\n/g, "\n"); // Base64 of the raw 32-byte seed: wrap it in PKCS8 v1 fixed prefix. const seed = Buffer.from(raw, "base64"); if (seed.length !== 32) { console.error("TEMPLATE_STORE_SIGNING_KEY is neither a PEM nor a base64 32-byte Ed25519 seed."); process.exit(1); } const pkcs8Prefix = Buffer.from("302e020100300506032b657004220420", "hex"); const der = Buffer.concat([pkcs8Prefix, seed]); return crypto.createPrivateKey({ key: der, format: "der", type: "pkcs8" }).export({ type: "pkcs8", format: "pem" }).toString(); } function cmdKeygen() { const { privateKey, publicKey } = crypto.generateKeyPairSync("ed25519"); const pkcs8 = privateKey.export({ type: "pkcs8", format: "der" }); const seed = pkcs8.subarray(pkcs8.length - 32); const jwk = publicKey.export({ format: "jwk" }); const pubRaw = Buffer.from(jwk.x, "base64"); console.log("Private key (store in the CI secret TEMPLATE_STORE_SIGNING_KEY — shown once):"); console.log(privateKey.export({ type: "pkcs8", format: "pem" }).trim()); console.log("\nPrivate key seed (base64, alternative to the PEM):"); console.log(seed.toString("base64")); console.log("\nPublic key (raw base64 — pin this on panels as ADPANEL_TEMPLATE_STORE_SIGNING_PUBKEY):"); console.log(pubRaw.toString("base64")); const parsed = parseEd25519PublicKey(pubRaw.toString("base64")); if (parsed) { console.log("\nPublic key fingerprint (sha256 of the raw key bytes):"); console.log(parsed.fingerprint); } } function collectRawFiles(repoDir) { const files = listStoreFiles(repoDir); if (!files.length) { console.error(`No store template files found under ${repoDir} — expected e.g. games/paper.json.`); process.exit(1); } return files.map((file) => ({ relPath: file.relPath, raw: fs.readFileSync(file.absolutePath, "utf8"), })); } function cmdSign(repoDir) { repoDir = path.resolve(repoDir); const repo = storeRepo(); const privateKeyPem = readPrivateKeyPem(); const privateKey = crypto.createPrivateKey(privateKeyPem); const publicKey = crypto.createPublicKey(privateKey); const jwk = publicKey.export({ format: "jwk" }); const pubRaw = Buffer.from(jwk.x, "base64"); const parsedPub = parseEd25519PublicKey(pubRaw.toString("base64")); if (!parsedPub) { console.error("Internal error: could not parse the generated public key."); process.exit(1); } const files = collectRawFiles(repoDir); const { digest } = computeStoreDigestFromRaw(repo, files); const generatedAt = new Date().toISOString(); const payload = canonicalStoreSigningPayload(repo, digest, generatedAt); const signature = crypto.sign(null, Buffer.from(payload, "utf8"), privateKey).toString("base64"); const signatureFile = { version: 2, repo, digest, generatedAt, publicKeyFingerprint: parsedPub.fingerprint, signature, }; const target = path.join(repoDir, "store-signature.json"); fs.writeFileSync(target, `${JSON.stringify(signatureFile, null, 2)}\n`); console.log(`Signed ${files.length} template files for ${repo}.`); console.log(`Wrote ${target} (digest ${digest}).`); console.log("Commit and push this file with the templates it covers."); } function cmdVerify(repoDir) { repoDir = path.resolve(repoDir); const repo = storeRepo(); const signatureFile = JSON.parse(fs.readFileSync(path.join(repoDir, "store-signature.json"), "utf8")); // Verification without a trusted key proves nothing, so a pinned key is // required even here on the vendor side. const pinned = parseEd25519PublicKey(process.env.TEMPLATE_STORE_SIGNING_PUBKEY || ""); if (!pinned) { console.error("TEMPLATE_STORE_SIGNING_PUBKEY is not set — refusing to verify without a trusted key."); process.exit(1); } const files = collectRawFiles(repoDir); const result = verifyStoreSignature({ signatureFile, repo, files, pinnedKey: pinned }); if (!result.verified) { console.error(`VERIFICATION FAILED: ${result.reason}`); process.exit(1); } console.log(`VERIFIED: ${files.length} template files match the signed digest ${result.digest}.`); } function main() { const [command, ...rest] = process.argv.slice(2); switch (command) { case "keygen": cmdKeygen(); break; case "sign": cmdSign(rest[0] || "."); break; case "verify": cmdVerify(rest[0] || "."); break; default: console.log("Usage:"); console.log(" node scripts/sign-template-store.js keygen"); console.log(" node scripts/sign-template-store.js sign "); console.log(" node scripts/sign-template-store.js verify "); process.exit(command ? 1 : 0); } } main();