#!/usr/bin/env node /** * DevEntitle Release Kit (Node) — signs release zips on your own machine. * * node deventitle-release.mjs keygen * node deventitle-release.mjs sign [--product=] [--version=] [--key-file=] [--output=] * node deventitle-release.mjs verify --public-key= [--manifest=] * * Same keys, manifests and signatures as the PHP kit and HUBCITY CRM's * `wise:release`: Ed25519 over "||", * a base64 32-byte public key and a base64 64-byte (seed + public) secret key. * * The secret key is read from DEVENTITLE_SIGNING_KEY or --key-file, never from * the command line. Nothing is sent anywhere. Needs Node 18+, no packages. * Licence: MIT. */ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign as edSign, verify as edVerify } from 'node:crypto'; import { closeSync, createReadStream, existsSync, openSync, readFileSync, readSync, statSync, writeFileSync } from 'node:fs'; import { basename } from 'node:path'; const KIT_VERSION = '1.0.0'; const VERSION_PATTERN = /^\d+(\.\d+){1,3}(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/; const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; const NAME_PATTERN = /^([a-z0-9]+(?:-[a-z0-9]+)*)-(\d+(?:\.\d+){1,3}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)\.zip$/; const out = (line = '') => process.stdout.write(line + '\n'); const fail = (message) => { process.stderr.write('Error: ' + message + '\n'); process.exit(1); }; const b64url = (buf) => buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); const fromB64url = (s) => Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/'), 'base64'); /** Strict base64 decode: null unless the text round-trips. */ function strictB64(text) { const value = String(text ?? '').trim(); if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return null; const buf = Buffer.from(value, 'base64'); return buf.toString('base64') === value ? buf : null; } const message = (product, version, sha) => Buffer.from(`${product}|${version}|${sha.toLowerCase()}`, 'utf8'); function publicKeyObject(raw32) { return createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: b64url(raw32) }, format: 'jwk' }); } /** libsodium secret key (32-byte seed + 32-byte public key) → Node key object. */ function privateKeyObject(secret64) { return createPrivateKey({ key: { kty: 'OKP', crv: 'Ed25519', d: b64url(secret64.subarray(0, 32)), x: b64url(secret64.subarray(32)) }, format: 'jwk' }); } function sha256File(path) { return new Promise((resolve, reject) => { const hash = createHash('sha256'); createReadStream(path).on('data', (chunk) => hash.update(chunk)).on('end', () => resolve(hash.digest('hex'))).on('error', reject); }); } function parseArguments(argv) { let command = null; const args = []; const options = {}; for (const arg of argv) { if (arg.startsWith('--')) { const [key, ...rest] = arg.slice(2).split('='); options[key] = rest.length ? rest.join('=') : true; } else if (command === null) { command = arg; } else { args.push(arg); } } return { command, args, options }; } function mustBeZip(path) { if (!path) fail('Which zip?'); if (!existsSync(path)) fail(`${path} does not exist.`); const head = Buffer.alloc(2); const fd = openSync(path, 'r'); readSync(fd, head, 0, 2, 0); closeSync(fd); if (head.toString('latin1') !== 'PK') fail(`${path} is not a zip archive.`); return path; } function productAndVersion(zip, options) { let product = options.product ?? null; let version = options.version ?? null; const match = basename(zip).match(NAME_PATTERN); if ((product === null || version === null) && match) { product ??= match[1]; version ??= match[2]; } if (product === null || !SLUG_PATTERN.test(product)) fail('Pass --product=, or name the zip -.zip.'); if (version === null || !VERSION_PATTERN.test(version)) fail('Pass --version=, or name the zip -.zip.'); return [product, version]; } function readSecret(options) { let value; if (options['key-file']) { try { value = readFileSync(options['key-file'], 'utf8'); } catch { fail(`Could not read ${options['key-file']}.`); } } else { value = process.env.DEVENTITLE_SIGNING_KEY; if (!value || !value.trim()) fail('Set DEVENTITLE_SIGNING_KEY to your secret key, or pass --key-file=. (Run "keygen" once to create a keypair.)'); } const secret = strictB64(value); if (!secret || secret.length !== 64) fail('That is not a secret key from "keygen" (base64 of 64 bytes).'); return secret; } function keygen() { const { publicKey, privateKey } = generateKeyPairSync('ed25519'); const pub = fromB64url(publicKey.export({ format: 'jwk' }).x); const seed = fromB64url(privateKey.export({ format: 'jwk' }).d); out(`DevEntitle Release Kit ${KIT_VERSION}: new Ed25519 signing keypair`); out(); out('PUBLIC key: paste it into the product on DevEntitle (Edit product -> Release signing)'); out('and ship it inside your product, so installed copies can check updates:'); out(' ' + pub.toString('base64')); out(); out('SECRET key: keep it offline (password manager, build machine only). Never commit it,'); out('never put it on a server, never upload it to DevEntitle. Anyone with it can sign releases.'); out(' ' + Buffer.concat([seed, pub]).toString('base64')); out(); out('Sign with: DEVENTITLE_SIGNING_KEY= node deventitle-release.mjs sign -.zip'); } async function sign(zip, options) { mustBeZip(zip); const [product, version] = productAndVersion(zip, options); const secret = readSecret(options); const privateKey = privateKeyObject(secret); const publicKey = publicKeyObject(secret.subarray(32)); const sha = await sha256File(zip); const signature = edSign(null, message(product, version, sha), privateKey); if (!edVerify(null, message(product, version, sha), publicKey, signature)) { fail("The signature did not verify with the key's own public half. The secret key is damaged."); } const manifest = { product, version, sha256: sha, size: statSync(zip).size, signature: signature.toString('base64'), built_at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'), }; const output = options.output ?? zip.replace(/\.zip$/i, '') + '.json'; writeFileSync(output, JSON.stringify(manifest, null, 4) + '\n'); out(`Signed ${product} ${version}`); out(' SHA-256: ' + sha); out(' Public key: ' + secret.subarray(32).toString('base64') + ' (must match the one on DevEntitle)'); out(' Manifest: ' + output); out('Upload the zip and the manifest to DevEntitle (Releases -> Upload release).'); } async function verify(zip, options) { mustBeZip(zip); const manifestPath = options.manifest ?? zip.replace(/\.zip$/i, '') + '.json'; let manifest; try { manifest = JSON.parse(readFileSync(manifestPath, 'utf8')); } catch { fail(`No readable manifest at ${manifestPath}. Pass --manifest=.`); } const pub = strictB64(options['public-key']); if (!pub || pub.length !== 32) fail("Pass the product's public key: --public-key=."); const [product, version] = productAndVersion(zip, { ...Object.fromEntries(Object.entries({ product: manifest.product, version: manifest.version }).filter(([, v]) => v)), ...options }); const sha = await sha256File(zip); const problems = []; if (String(manifest.sha256 ?? '').toLowerCase() !== sha) problems.push('the SHA-256 in the manifest does not match the zip'); if (manifest.size !== undefined && Number(manifest.size) !== statSync(zip).size) problems.push('the size in the manifest does not match the zip'); const signature = strictB64(manifest.signature); if (!signature || signature.length !== 64 || !edVerify(null, message(product, version, sha), publicKeyObject(pub), signature)) { problems.push(`the signature does not verify for "${product}|${version}|" with this public key`); } if (problems.length) fail('NOT valid: ' + problems.join('; ') + '.'); out(`Valid: ${product} ${version}, SHA-256 ${sha}, signature verified.`); } function usage() { out(`DevEntitle Release Kit ${KIT_VERSION}`); out(); out(' node deventitle-release.mjs keygen'); out(' node deventitle-release.mjs sign [--product=] [--version=] [--key-file=] [--output=]'); out(' node deventitle-release.mjs verify --public-key= [--manifest=]'); out(); out('The secret key comes from DEVENTITLE_SIGNING_KEY or --key-file. Nothing is sent anywhere.'); } const { command, args, options } = parseArguments(process.argv.slice(2)); switch (command) { case 'keygen': keygen(); break; case 'sign': await sign(args[0], options); break; case 'verify': await verify(args[0], options); break; default: usage(); process.exit(command === null || command === 'help' || command === '--help' ? 0 : 1); }