#!/usr/bin/env node import { createHash, createPrivateKey, createPublicKey, sign } from "node:crypto"; import { constants } from "node:fs"; import { lstat, open, writeFile } from "node:fs/promises"; import { resolve } from "node:path"; import { pathToFileURL } from "node:url"; import { parseArgs } from "node:util"; const NETWORK = "rla-mainnet-1"; const SIGN_DOMAIN = "rla-tx:"; const MAX_NONCE = 18_446_744_073_709_551_615n; const RECORD_KEY = /^app\.[a-z0-9]+(?:-[a-z0-9]+)*$/; const RESOURCE_NAME = /^[\p{L}\p{N} ._()/-]{2,60}$/u; const SOURCE = /^https:\/\/github\.com\/([A-Za-z0-9-]{1,39})\/([A-Za-z0-9._-]{1,100})\/(?:tree|commit)\/([a-f0-9]{40})$/; const GRAVAR = ["tipo", "chave", "dados", "dias"]; const REGISTRAR = [ "tipo", "nome", "descricao", "perfil", "dias", "unidade", "visibilidade", "modo_preco", ]; const MANIFEST = ["schema_version", "id", "name", "version", "homepage", "source_url", "category", "description", "download"]; const DOWNLOAD = ["repository", "asset", "size_bytes", "sha256"]; const PEM = Buffer.from("-----BEGIN PRIVATE KEY-----"); const HELP = `Go4pp offline RLA app publisher node rla-publish.mjs address --key PUBLISHER_PKCS8 node rla-publish.mjs sign --key PUBLISHER_PKCS8 --payload PUBLICACAO_JSON --step 1 --nonce N --ate UNIX --out SIGNED_JSON node rla-publish.mjs sign --key PUBLISHER_PKCS8 --payload PUBLICACAO_JSON --step 2 --confirmed-record RECORD_JSON --nonce N --ate UNIX --out SIGNED_JSON`; function requireCondition(ok, explanation) { if (!ok) throw new Error(explanation); } function object(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function exactFields(value, fields) { return object(value) && Object.keys(value).length === fields.length && fields.every((field) => Object.hasOwn(value, field)); } function validDays(value, max) { return Number.isSafeInteger(value) && value >= 1 && value <= max; } function recordKey(value) { return typeof value === "string" && value.length <= 64 && RECORD_KEY.test(value); } function appRecord(dados, chave) { requireCondition(recordKey(chave), "Use a record key of the form app.."); requireCondition(typeof dados === "string" && Buffer.byteLength(dados, "utf8") <= 4_096, "The app record must be a JSON string of at most 4096 UTF-8 bytes."); let manifest; try { manifest = JSON.parse(dados); } catch { throw new Error("The app record is not valid JSON."); } requireCondition(object(manifest) && JSON.stringify(manifest) === dados && Object.keys(manifest).every((field) => MANIFEST.includes(field)) && manifest.schema_version === 1 && typeof manifest.id === "string" && "app." + manifest.id === chave && typeof manifest.name === "string" && typeof manifest.version === "string" && typeof manifest.homepage === "string", "The manifest must be compact, match the app key, and use the Shop schema."); const [, owner, repository, commit] = typeof manifest.source_url === "string" ? SOURCE.exec(manifest.source_url) ?? [] : []; requireCondition(commit && !/^0{40}$/.test(commit) && !owner.startsWith("-") && !owner.endsWith("-") && !owner.includes("--") && repository !== "." && repository !== "..", "Use a GitHub source link pinned to a commit."); requireCondition((manifest.category === undefined || typeof manifest.category === "string") && (manifest.description === undefined || typeof manifest.description === "string"), "The description and category must contain plain text."); requireCondition(!Object.hasOwn(manifest, "download") || (exactFields(manifest.download, DOWNLOAD) && typeof manifest.download.repository === "string" && manifest.download.repository.toLowerCase() === (owner + "/" + repository).toLowerCase() && typeof manifest.download.asset === "string" && typeof manifest.download.sha256 === "string" && Number.isSafeInteger(manifest.download.size_bytes)), "The download object contains unsupported fields."); requireCondition(!/-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(dados), "The public manifest contains private key material."); } function validateRecordOperation(value) { requireCondition(exactFields(value, GRAVAR) && value.tipo === "gravar" && validDays(value.dias, 3_650), "Step 1 needs the unsigned gravar object produced by the Shop."); appRecord(value.dados, value.chave); } function validateResourceOperation(value) { const { preco_unidade = 0, ...resource } = value ?? {}; requireCondition(exactFields(resource, REGISTRAR) && resource.tipo === "registrar_recurso" && resource.perfil === "apps/1" && resource.unidade === "consulta" && resource.visibilidade === "publico" && resource.modo_preco === "gratis" && preco_unidade === 0 && typeof resource.nome === "string" && RESOURCE_NAME.test(resource.nome) && recordKey(resource.descricao) && validDays(resource.dias, 365), "Step 2 needs the unsigned registrar_recurso object for a free public apps/1 resource."); } export function publisherAddress(key) { requireCondition(key?.type === "private" && key.asymmetricKeyType === "ed25519", "An Ed25519 private key is required."); const keyBytes = Buffer.from(createPublicKey(key).export({ format: "jwk" }).x, "base64url"); return "rla1" + createHash("sha256").update(keyBytes).digest("hex").slice(0, 40); } export function signPublisherPayload(payload, { key, step, nonce, ate, confirmedRecord, now = Math.floor(Date.now() / 1_000) }) { const de = publisherAddress(key); requireCondition(typeof nonce === "string" && /^[1-9][0-9]{0,19}$/.test(nonce) && BigInt(nonce) <= MAX_NONCE, "Provide a positive decimal nonce supported by RLA."); requireCondition(typeof ate === "string" && /^[1-9][0-9]{0,15}$/.test(ate) && Number.isSafeInteger(now) && now > 0 && Number.isSafeInteger(Number(ate)) && Number(ate) > now && Number(ate) <= now + 3_600, "Provide an expiration in Unix seconds within the next hour."); let operation = payload; let first; if (Array.isArray(payload)) { requireCondition(payload.length === 2 && (step === "1" || step === "2"), "Select step 1 or 2 for the Shop's transaction pair."); [first] = payload; validateRecordOperation(first); validateResourceOperation(payload[1]); requireCondition(first.chave === payload[1].descricao, "Both steps must refer to the same app record."); operation = payload[Number(step) - 1]; } const index = operation?.tipo === "gravar" ? "1" : "2"; requireCondition(step === undefined || step === index, "The selected step does not match the transaction type."); if (index === "1") { validateRecordOperation(operation); } else { validateResourceOperation(operation); requireCondition(confirmedRecord?.dono === de && confirmedRecord?.chave === operation.descricao && Number.isSafeInteger(confirmedRecord?.criado) && confirmedRecord.criado > 0 && confirmedRecord.criado <= now && Number.isSafeInteger(confirmedRecord?.expira) && (confirmedRecord.expira === 0 || confirmedRecord.expira > Number(ate)) && (!first || first.dados === confirmedRecord.dados), "Before step 2, supply the confirmed app record read from the official chain for this wallet."); appRecord(confirmedRecord.dados, operation.descricao); } // Nonces are native uint64 JSON numbers, including values beyond JS's safe integer range. const unsigned = index === "1" ? operation : { ...operation, preco_unidade: 0 }; const base = JSON.stringify({ ...unsigned, rede: NETWORK, de }); const corpo = base.slice(0, -1) + `,"nonce":${nonce},"ate":${ate}}`; const chave = Buffer.from(createPublicKey(key).export({ format: "jwk" }).x, "base64url").toString("hex"); const assinatura = sign(null, Buffer.from(SIGN_DOMAIN + corpo, "utf8"), key).toString("hex"); const envelope = { corpo, chave, assinatura }; requireCondition(Buffer.byteLength(corpo, "utf8") <= 15_000 && Buffer.byteLength(JSON.stringify(envelope), "utf8") <= 16 * 1024, "The signed transaction exceeds the official gateway's size limit."); return envelope; } async function localFile(file, maximum, error) { try { const stat = await lstat(file); requireCondition(stat.isFile() && stat.size > 0 && stat.size <= maximum, error); const flags = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0); const handle = await open(file, flags); try { const current = await handle.stat(); requireCondition(current.isFile() && current.dev === stat.dev && current.ino === stat.ino, error); const bytes = Buffer.alloc(maximum + 1); let count = 0; while (count < bytes.length) { const { bytesRead } = await handle.read(bytes, count, bytes.length - count, count); if (!bytesRead) break; count += bytesRead; } requireCondition(count === stat.size, error); return bytes.subarray(0, count); } finally { await handle.close(); } } catch { throw new Error(error); } } async function readLocalKey(path) { const error = "Could not read a local, unencrypted PKCS#8 Ed25519 key in PEM or DER format."; const raw = await localFile(path, 8_192, error); try { const key = raw.subarray(0, PEM.length).equals(PEM) ? createPrivateKey({ key: raw, format: "pem" }) : createPrivateKey({ key: raw, format: "der", type: "pkcs8" }); publisherAddress(key); return key; } catch { throw new Error(error); } finally { raw.fill(0); } } async function readLocalJson(path, message) { try { const raw = await localFile(path, 32_768, message); return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw)); } catch { throw new Error(message); } } async function main(args) { const { values, positionals: [command, ...extra] } = parseArgs({ args, allowPositionals: true, options: { help: { type: "boolean" }, key: { type: "string" }, payload: { type: "string" }, step: { type: "string" }, nonce: { type: "string" }, ate: { type: "string" }, out: { type: "string" }, "confirmed-record": { type: "string" }, }, }); if (values.help || !command) { process.stdout.write(HELP + "\n"); return; } requireCondition(!extra.length && ["address", "sign"].includes(command) && values.key, "Supply an address or sign command with --key. See --help."); if (command === "address") { requireCondition(Object.keys(values).length === 1, "The address command accepts only --key."); process.stdout.write(publisherAddress(await readLocalKey(values.key)) + "\n"); return; } requireCondition(values.payload && values.out && values.nonce && values.ate, "The sign command needs --payload, --out, --nonce and --ate."); const payload = await readLocalJson(values.payload, "Could not read the unsigned Shop transaction JSON."); const confirmedRecord = values["confirmed-record"] === undefined ? undefined : await readLocalJson(values["confirmed-record"], "Could not read the confirmed app record JSON."); const key = await readLocalKey(values.key); const envelope = signPublisherPayload(payload, { key, step: values.step, nonce: values.nonce, ate: values.ate, confirmedRecord }); try { await writeFile(values.out, JSON.stringify(envelope), { encoding: "utf8", flag: "wx", mode: 0o600 }); } catch { throw new Error("Could not create the new signed envelope file. Existing files were left untouched."); } process.stdout.write("Signed offline for " + publisherAddress(key) + ". Saved the new envelope.\n"); } if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { main(process.argv.slice(2)).catch((error) => { // Argument parsing may include supplied input in errors. Keep diagnostics local and bounded. process.stderr.write(error.code?.startsWith("ERR_PARSE_ARGS") ? "Invalid arguments. See --help.\n" : error.message + "\n"); process.exitCode = 1; }); }