"use strict"; // Trust anchor primitives for the template store supply chain. // // The store syncs template JSON from a third-party git repo (and a CDN // fallback) and those templates compile directly into container launch // configuration: installer scripts, container images and managed startup // scripts that panel nodes execute. TLS to github.com/jsDelivr only proves // who you talked to, not that the repo owner published the content — a // compromised repo account, a hijacked CDN cache or a rogue maintainer would // otherwise silently push code to every panel on the next hourly sync. // // This module provides the transport-independent anchor: // * a canonical content digest over the raw fetched bytes (git guarantees // both sides see identical content, so normalization never participates), // * Ed25519 detached-signature verification against a pinned vendor key, // * git blob SHA-1 cross-checks of listing hashes against fetched bytes, // * a docker image registry allowlist shared conceptually with main.go's // sink-side mirror (keep both behaviorally equivalent), // * resolution of the operator's trust configuration (env > file > default). // // Everything here is pure: no filesystem, no network, no clock. Callers own // I/O so the panel boundary stays testable. const crypto = require("crypto"); // --- Canonical content digest ---------------------------------------------- const STORE_DIGEST_VERSION = "ADPanel-TemplateStore-v1"; // Digest input covers the exact bytes fetched from upstream, keyed by // repo-relative path and sorted so both sides derive the same value from the // same tree regardless of API listing order. Entries are {relPath, sha256} // with sha256 being the hex digest of the RAW (pre-normalization) bytes. function canonicalStoreDigestInput(repo, entries) { const cleanRepo = String(repo || "").trim(); const sorted = (Array.isArray(entries) ? entries : []) .filter((entry) => entry && typeof entry.relPath === "string" && /^[0-9a-f]{64}$/.test(String(entry.sha256 || ""))) .map((entry) => ({ relPath: entry.relPath, sha256: String(entry.sha256).toLowerCase() })) .sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0)); const lines = sorted.map((entry) => `${entry.sha256} ${entry.relPath}`); return `${STORE_DIGEST_VERSION}\nrepo:${cleanRepo}\n${lines.join("\n")}\n`; } // The string the vendor's private key signs: the payload version tag, the // repo the digest was computed for (binds a signature to one store, preventing // signature replay across repos), the digest itself, and the snapshot's // generatedAt timestamp — binding the timestamp into the signature is what // makes the panel's rollback/replay refusal cryptographic instead of advisory: // old signed content cannot be re-dated by whoever controls the transport. // v2 (bumped from v1) added generatedAt; v1 signatures are rejected. const SIGNATURE_PAYLOAD_VERSION = "ADPanel-TemplateStore-Signature-v2"; function canonicalStoreSigningPayload(repo, digest, generatedAt) { const cleanRepo = String(repo || "").trim(); const cleanDigest = String(digest || "").toLowerCase(); const cleanGeneratedAt = String(generatedAt || "").trim(); return `${SIGNATURE_PAYLOAD_VERSION}\nrepo:${cleanRepo}\ndigest:${cleanDigest}\ngeneratedAt:${cleanGeneratedAt}\n`; } function sha256Hex(data) { return crypto.createHash("sha256").update(data).digest("hex"); } // files: [{relPath, raw}] with raw as string or Buffer — raw upstream bytes. // Returns {digest, entries} for the fetched content set. function computeStoreDigestFromRaw(repo, files) { const entries = (Array.isArray(files) ? files : []) .filter((file) => file && typeof file.relPath === "string" && file.relPath && file.raw != null) .map((file) => ({ relPath: file.relPath, sha256: sha256Hex(Buffer.from(file.raw, "utf8")) })); return { entries, digest: sha256Hex(canonicalStoreDigestInput(repo, entries)), }; } // --- Ed25519 key handling ----------------------------------------------------- // Accepts a base64 raw 32-byte Ed25519 public key (what the setup script // writes) or a base64 SPKI DER blob (crypto's default export shape) and // normalizes it to a KeyObject plus fingerprint (sha256 of the raw key bytes) // so signatures can be bound to the exact pinned key. function parseEd25519PublicKey(input) { const raw = String(input || "").trim(); if (!raw) return null; let der; try { der = Buffer.from(raw, "base64"); } catch { return null; } if (!der.length || der.length > 512) return null; let keyObject = null; let rawKeyBytes = null; if (der.length === 32) { rawKeyBytes = der; // Node has no direct raw-public-key import; wrap it in the fixed // 44-byte Ed25519 SPKI prefix (RFC 8410). const spki = Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), der]); try { keyObject = crypto.createPublicKey({ key: spki, format: "der", type: "spki" }); } catch { return null; } } else { try { keyObject = crypto.createPublicKey({ key: der, format: "der", type: "spki" }); const jwk = keyObject.export({ format: "jwk" }); if (!jwk || jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.x !== "string") return null; rawKeyBytes = Buffer.from(jwk.x, "base64"); } catch { return null; } } if (!keyObject || !rawKeyBytes || rawKeyBytes.length !== 32) return null; return { key: keyObject, raw: rawKeyBytes, fingerprint: sha256Hex(rawKeyBytes), }; } // --- Signature verification --------------------------------------------------- // signatureFile: parsed JSON of the repo's store-signature.json // files: [{relPath, raw}] raw fetched upstream bytes // pinnedKey: parsed public key from parseEd25519PublicKey // Returns { verified, reason, digest, generatedAt } — verified is true only // when every check passes; never throws. function verifyStoreSignature({ signatureFile, repo, files, pinnedKey }) { const result = { verified: false, reason: "", digest: "", generatedAt: "" }; if (!pinnedKey || !pinnedKey.key) { result.reason = "no signing public key is pinned on this panel"; return result; } if (!signatureFile || typeof signatureFile !== "object" || Array.isArray(signatureFile)) { result.reason = "store signature file missing or malformed"; return result; } if (Number(signatureFile.version) !== 2) { result.reason = `unsupported store signature version ${JSON.stringify(signatureFile.version)} (expected 2)`; return result; } const declaredRepo = String(signatureFile.repo || "").trim(); if (declaredRepo && repo && declaredRepo.toLowerCase() !== String(repo).trim().toLowerCase()) { result.reason = `signature was produced for repo "${declaredRepo}", not "${repo}"`; return result; } const declaredFingerprint = String(signatureFile.publicKeyFingerprint || "").trim().toLowerCase(); if (declaredFingerprint && declaredFingerprint !== pinnedKey.fingerprint) { result.reason = "signature names a different public key than the one pinned on this panel"; return result; } const signature = String(signatureFile.signature || "").trim(); if (!signature) { result.reason = "store signature file carries no signature"; return result; } // generatedAt is part of the signed payload, so it must be present and is // bound to exactly what was signed — re-dating a snapshot breaks the // signature, which is what makes rollback refusal enforceable. const declaredGeneratedAt = String(signatureFile.generatedAt || "").trim(); if (!declaredGeneratedAt) { result.reason = "store signature file carries no generatedAt timestamp — freshness cannot be bound to the signature"; return result; } const computed = computeStoreDigestFromRaw(repo, files); result.digest = computed.digest; if (String(signatureFile.digest || "").toLowerCase() !== computed.digest) { result.reason = "content digest does not match the signed digest — fetched store content differs from what the vendor signed"; return result; } let sigBytes; try { sigBytes = Buffer.from(signature, "base64"); } catch { result.reason = "signature is not valid base64"; return result; } const payload = Buffer.from(canonicalStoreSigningPayload(repo, computed.digest, declaredGeneratedAt), "utf8"); let valid = false; try { valid = crypto.verify(null, payload, pinnedKey.key, sigBytes); } catch { valid = false; } if (!valid) { result.reason = "signature verification failed against the pinned public key"; return result; } result.verified = true; result.generatedAt = declaredGeneratedAt; return result; } // --- Listing hash cross-check --------------------------------------------------- // The two upstream listings report file content differently: GitHub's tree // API names each blob's git SHA-1 (hex), jsDelivr's flat listing names the // base64-encoded SHA-256 of the exact file bytes. Verifying either against // the fetched bytes closes the gap between "what the listing promised" and // "what the raw fetch returned" — a mismatched CDN cache or truncated fetch // can never pose as listed content. A declared hash in neither format is // reported as unverifiable so the caller can surface it instead of silently // treating the file as verified. // SHA-1 is deliberately not a chosen primitive here: this reproduces git's own // blob object hash ("blob \0" + content) so a GitHub tree listing — which // can only report the repo's git object hashes — can be cross-checked against // the fetched bytes. It is a transport-consistency check, not the trust anchor: // authenticity rests on the Ed25519 signature over the SHA-256 canonical digest // (verifyStoreSignature), so even a chosen-prefix SHA-1 collision between the // listing and the fetch could never promote content the vendor did not sign: // enforce mode (the default) refuses it outright, warn mode serves it loudly // flagged. When a listing declares SHA-256 instead (jsDelivr), // verifyListedContentHash verifies that format, in constant time. function expectedGitBlobSha1(raw) { const buf = Buffer.from(raw, "utf8"); const header = Buffer.from(`blob ${buf.length}\0`, "utf8"); return crypto.createHash("sha1").update(Buffer.concat([header, buf])).digest("hex"); } // Boolean convenience form — NOT used by the sync path, and not suitable for a // security decision: a boolean cannot express "unverifiable", so this wrapper // fail-opens (returns true) when the declared hash is not 40-hex SHA-1. The // sync path uses the tri-state verifyListedContentHash below, which fails // closed instead. function verifyGitBlobSha1(raw, declaredHash) { const declared = String(declaredHash || "").trim().toLowerCase(); if (!/^[0-9a-f]{40}$/.test(declared)) return true; // nothing verifiable declared return expectedGitBlobSha1(raw) === declared; } // Dual-format verifier over both listing styles. A 40-hex declared hash is // treated as a git blob SHA-1 (case-insensitive); anything that base64/ // base64url-decodes to exactly 32 bytes is treated as a raw SHA-256 and // compared in constant time — base64 is case-sensitive, so the declared value // is never case-folded. Hashes that decode to any other length (64-hex git // sha256 blob hashes, for instance) are not guessed at: they come back // unverifiable rather than matched against the wrong digest. function verifyListedContentHash(raw, declaredHash) { const declared = String(declaredHash || "").trim(); if (!declared) { return { verified: false, unverifiable: true, reason: "listing declared no content hash" }; } if (/^[0-9a-f]{40}$/i.test(declared)) { const sha1 = declared.toLowerCase(); // Constant-time compare, mirroring the SHA-256 branch below (defense in // depth; both sides are fixed-length digests within one sync flow). const expected = Buffer.from(expectedGitBlobSha1(raw), "hex"); const declaredBytes = Buffer.from(sha1, "hex"); if (expected.length === declaredBytes.length && crypto.timingSafeEqual(expected, declaredBytes)) { return { verified: true }; } return { verified: false, reason: `fetched bytes do not match the listing's git blob SHA-1 ${sha1}` }; } if (/^[a-z0-9+/=_-]+$/i.test(declared)) { const decoded = Buffer.from(declared.replace(/-/g, "+").replace(/_/g, "/"), "base64"); if (decoded.length === 32) { const actual = crypto.createHash("sha256").update(Buffer.from(raw, "utf8")).digest(); if (crypto.timingSafeEqual(actual, decoded)) return { verified: true }; return { verified: false, reason: `fetched bytes do not match the listing's SHA-256 ${declared}` }; } } return { verified: false, unverifiable: true, reason: `listing hash format not recognizable (${declared.slice(0, 12)}…)` }; } // --- Docker image registry allowlist -------------------------------------------- // Default allowlist: the major public registries. Operators with private // registries replace or extend it via ADPANEL_TEMPLATE_ALLOWED_REGISTRIES // (panel) / ADPANEL_ALLOWED_TEMPLATE_IMAGE_REGISTRIES (node agent). Mirrored // in main.go's templateImageRegistryAllowed — keep both equivalent. const DEFAULT_TEMPLATE_IMAGE_REGISTRIES = [ "docker.io", "ghcr.io", "gcr.io", "quay.io", "registry.k8s.io", "public.ecr.aws", ]; function normalizeRegistryList(value) { return String(value || "") .split(",") .map((entry) => entry.trim().toLowerCase()) .filter(Boolean); } function resolveAllowedTemplateRegistries(envValue) { const configured = normalizeRegistryList(envValue); return configured.length ? configured : DEFAULT_TEMPLATE_IMAGE_REGISTRIES.slice(); } // First path component is the registry only when it looks like a host // (contains "." or ":" or is "localhost"); otherwise the ref is a Docker Hub // name ("ubuntu" → docker.io/library/ubuntu). Mirrors main.go. function imageRegistryForRef(ref) { const clean = String(ref || "").trim(); if (!clean) return ""; const firstSlash = clean.indexOf("/"); const first = firstSlash > 0 ? clean.slice(0, firstSlash) : ""; if (first && (first.includes(".") || first.includes(":") || first.toLowerCase() === "localhost")) { return first.toLowerCase(); } return "docker.io"; } function validateTemplateImageRefInput(ref, allowlist) { const clean = String(ref || "").trim(); if (!clean) return "missing docker image"; if (/[\s\x00-\x1f]/.test(clean)) return "docker image reference contains whitespace or control characters"; const registry = imageRegistryForRef(clean); const allowed = Array.isArray(allowlist) && allowlist.length ? allowlist : DEFAULT_TEMPLATE_IMAGE_REGISTRIES; if (!allowed.some((entry) => entry.toLowerCase() === registry)) { return `docker image registry "${registry || "unknown"}" is not allowed (allowed: ${allowed.join(", ")})`; } return null; } // Docker tag grammar: first character letter/digit/underscore, then // letters/digits/underscore/dot/dash, 128 characters max (the part after ":" // in a full reference — template payloads carry it separately, and the node // agent rejects the combined image:tag at server-create time, so a malformed // tag must fail closed here instead of being persisted). Empty is INVALID: // callers default an empty tag to "latest" BEFORE calling, so a refusal // always names garbage the sender actually wrote. const DOCKER_TAG_INPUT_RE = /^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$/; function validateDockerTagInput(value) { const clean = String(value || "").trim(); if (!DOCKER_TAG_INPUT_RE.test(clean)) { const shown = clean.length > 120 ? `${clean.slice(0, 120)}…` : clean; return `invalid docker tag "${shown}" — tags must start with a letter, digit or underscore, may only contain letters, digits, ".", "_" and "-" and are limited to 128 characters`; } return null; } // --- Trust configuration resolution ----------------------------------------------- const TRUST_MODES = new Set(["enforce", "warn"]); // The vendor's Ed25519 public key, pinned in the panel distribution itself. // This is the same trust anchor as the panel code — whoever can rewrite this // constant can already rewrite every other line of the panel — so shipping it // costs nothing and lets every stock panel verify store content out of the // box, with zero operator configuration. env and data/template-store-trust.json // still win, for key rotation and for operators who sign their own store fork. const BUILTIN_VENDOR_PUBLIC_KEY = "0wFARAyPX5NxLP7ZeqGw8cwrqnL3RvedSZhiH6A6lVk="; // env > trustFile > built-in vendor key. Default mode is ALWAYS "enforce" — // unsigned store content compiles into what nodes execute. With the built-in // vendor key a stock panel refuses to promote anything the vendor did not // sign; an operator who overrides the key takes over that role. An invalid // mode string also lands on enforce: the permissive mode must be spelled out, // never fallen into. function resolveTemplateStoreTrustConfig({ env = {}, trustFile = null } = {}) { const file = trustFile && typeof trustFile === "object" && !Array.isArray(trustFile) ? trustFile : {}; // Trim each source before falling through, so a whitespace-only override // counts as "not configured" and lands on the built-in vendor key instead // of silently un-pinning the anchor with a confusing error. const envKey = String(env.ADPANEL_TEMPLATE_STORE_SIGNING_PUBKEY ?? "").trim(); const fileKey = file.publicKey == null ? "" : String(file.publicKey).trim(); const publicKey = envKey || fileKey || BUILTIN_VENDOR_PUBLIC_KEY; let mode = String(env.ADPANEL_TEMPLATE_STORE_SIGNATURE_MODE || file.mode || "").trim().toLowerCase(); if (!TRUST_MODES.has(mode)) mode = "enforce"; const autoUpdateRaw = String(env.ADPANEL_TEMPLATE_STORE_AUTO_UPDATE != null ? env.ADPANEL_TEMPLATE_STORE_AUTO_UPDATE : (file.autoUpdate != null ? file.autoUpdate : ""), "").trim().toLowerCase(); const autoUpdate = autoUpdateRaw === "" ? true : !["0", "false", "no", "off"].includes(autoUpdateRaw); const pinnedRef = String(env.ADPANEL_TEMPLATE_STORE_PINNED_REF || file.pinnedRef || "").trim(); return { publicKey, mode, autoUpdate, pinnedRef }; } // --- Sync diff (review-gate visibility) ---------------------------------------------- // Diff of the store content between two syncs, computed from manifest file // entries ({name, sha256} per category). Pure, so the sync path can record it // and the UI can render exactly what an auto-update changed. function buildStoreSyncDiff(previousCategories, nextCategories) { const collect = (categories) => { const map = new Map(); for (const [categoryId, category] of Object.entries(categories || {})) { for (const file of (category && Array.isArray(category.files)) ? category.files : []) { if (file && file.name) map.set(`${categoryId}/${file.name}`, String(file.sha256 || "")); } } return map; }; const before = collect(previousCategories); const after = collect(nextCategories); const diff = { added: [], removed: [], changed: [] }; for (const [key, sha] of after) { if (!before.has(key)) diff.added.push(key); else if (before.get(key) !== sha) diff.changed.push(key); } for (const key of before.keys()) { if (!after.has(key)) diff.removed.push(key); } for (const list of [diff.added, diff.removed, diff.changed]) list.sort(); return diff; } module.exports = { STORE_DIGEST_VERSION, DEFAULT_TEMPLATE_IMAGE_REGISTRIES, BUILTIN_VENDOR_PUBLIC_KEY, canonicalStoreDigestInput, canonicalStoreSigningPayload, computeStoreDigestFromRaw, parseEd25519PublicKey, verifyStoreSignature, expectedGitBlobSha1, verifyGitBlobSha1, verifyListedContentHash, imageRegistryForRef, resolveAllowedTemplateRegistries, validateTemplateImageRefInput, validateDockerTagInput, resolveTemplateStoreTrustConfig, buildStoreSyncDiff, sha256Hex, };