#!/usr/bin/env node
// drwho.me Domain Audit Report verifier — self-contained, zero project imports.
//
//   curl -O https://drwho.me/scripts/verify-pack.mjs
//   curl -O https://drwho.me/.well-known/evidence-pack-pubkey.pem
//   node verify-pack.mjs --dir <dir containing pack.pdf, pack.json, manifest.json, manifest.sig>
//
// Exit codes: 0 verified · 1 verification failed · 2 usage/IO error.
//
// Canonical-JSON spec: RFC 8785 stable stringify — keys sorted alphabetically
// recursively, minimal whitespace, no trailing newline. The implementation
// below matches lib/evidence-pack/canonical-json.ts (safe-stable-stringify)
// for the value shapes the manifest uses (number/string/boolean/null/array/
// object — no Date, no Map, no BigInt, no circular refs).

import { createHash, createPublicKey, verify as cryptoVerify } from "node:crypto";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";

function canonicalJSON(value) {
  if (value === null || typeof value !== "object") return JSON.stringify(value);
  if (Array.isArray(value)) return `[${value.map((v) => canonicalJSON(v)).join(",")}]`;
  const keys = Object.keys(value).sort();
  const parts = [];
  for (const k of keys) {
    const v = value[k];
    if (v === undefined) continue;
    parts.push(`${JSON.stringify(k)}:${canonicalJSON(v)}`);
  }
  return `{${parts.join(",")}}`;
}

function sha256Hex(buf) {
  return createHash("sha256").update(buf).digest("hex");
}

function verifyPack({ packPdf, packJson, manifestJson, manifestSig, publicKeyPem }) {
  let manifest;
  try {
    manifest = JSON.parse(manifestJson.toString("utf8"));
  } catch (e) {
    return { ok: false, reason: `manifest is not valid JSON: ${e.message}` };
  }
  if (manifest.version !== 1) {
    return { ok: false, reason: `unsupported manifest version ${manifest.version}` };
  }
  const pubKey = createPublicKey(publicKeyPem);
  const canonicalBytes = Buffer.from(canonicalJSON(manifest), "utf8");
  const sigBuf = Buffer.from(manifestSig.trim(), "base64");
  if (!cryptoVerify(null, canonicalBytes, pubKey, sigBuf)) {
    return { ok: false, reason: "Ed25519 signature does not verify against the public key" };
  }
  const pdfHash = sha256Hex(packPdf);
  if (pdfHash !== manifest.artifacts.pdf.sha256) {
    return {
      ok: false,
      reason: `pack.pdf sha256 mismatch — expected ${manifest.artifacts.pdf.sha256}, got ${pdfHash}`,
    };
  }
  if (packPdf.length !== manifest.artifacts.pdf.bytes) {
    return {
      ok: false,
      reason: `pack.pdf byte-count mismatch — expected ${manifest.artifacts.pdf.bytes}, got ${packPdf.length}`,
    };
  }
  const jsonHash = sha256Hex(packJson);
  if (jsonHash !== manifest.artifacts.json.sha256) {
    return {
      ok: false,
      reason: `pack.json sha256 mismatch — expected ${manifest.artifacts.json.sha256}, got ${jsonHash}`,
    };
  }
  if (packJson.length !== manifest.artifacts.json.bytes) {
    return {
      ok: false,
      reason: `pack.json byte-count mismatch — expected ${manifest.artifacts.json.bytes}, got ${packJson.length}`,
    };
  }
  return { ok: true, manifest };
}

function parseArgs(argv) {
  let dir = process.cwd();
  let pubkey = null;
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    if (a === "--dir") dir = resolve(argv[++i]);
    else if (a === "--pubkey") pubkey = resolve(argv[++i]);
    else if (a === "--help" || a === "-h") {
      console.log("usage: node verify-pack.mjs [--dir <path>] [--pubkey <path>]");
      process.exit(0);
    }
  }
  return { dir, pubkey: pubkey ?? resolve(dir, "evidence-pack-pubkey.pem") };
}

const { dir, pubkey } = parseArgs(process.argv.slice(2));
let packPdf;
let packJson;
let manifestJson;
let manifestSig;
let publicKeyPem;
try {
  [packPdf, packJson, manifestJson, manifestSig, publicKeyPem] = await Promise.all([
    readFile(resolve(dir, "pack.pdf")),
    readFile(resolve(dir, "pack.json")),
    readFile(resolve(dir, "manifest.json")),
    readFile(resolve(dir, "manifest.sig"), "utf8"),
    readFile(pubkey, "utf8"),
  ]);
} catch (e) {
  console.error(`I/O error: ${e.message}`);
  process.exit(2);
}

const result = verifyPack({ packPdf, packJson, manifestJson, manifestSig, publicKeyPem });
if (!result.ok) {
  console.error(`FAIL: ${result.reason}`);
  process.exit(1);
}
const m = result.manifest;
console.log(`verified — pack for ${m.domain} signed ${m.scannedAt} by ${m.signingKeyId}`);
console.log(`  pack.pdf  ${m.artifacts.pdf.bytes} bytes  sha256=${m.artifacts.pdf.sha256}`);
console.log(`  pack.json ${m.artifacts.json.bytes} bytes  sha256=${m.artifacts.json.sha256}`);
