#!/usr/bin/env node
// verify.mjs — standalone Ed25519 receipt verifier.
//
// REUSE-CHECKED: deliberately standalone — a published third-party verifier
// must not depend on this repo. Mirrors the frozen v1 canonicalization spec
// (aryah-shared src/audit-trail/README.md).
//
// Usage:
//   node verify.mjs <artifact-url-or-file> [jwks-url]
//
//   <artifact-url-or-file>  An https:// URL or local path to a *.signed.json
//                           receipt artifact ({ payload, sig, verify }).
//   [jwks-url]              https:// URL or local path to a JWKS document.
//                           Defaults to the production AnswerShare JWKS.
//
// Prints `PASS <kid> <created_at>` and exits 0 when the signature verifies.
// Prints `FAIL <reason>` and exits 1 otherwise. No dependencies beyond the
// Node >=18 standard library (fetch, fs, WebCrypto).
//
// Deliberately never calls process.exit() directly: with an in-flight
// fetch() keep-alive connection still open, a forced exit races Node's
// libuv teardown on some platforms. process.exitCode is set instead and the
// process is left to end naturally once the event loop drains.

const DEFAULT_JWKS_URL = "https://answershare.com/.well-known/jwks.json";

// Node >=19 exposes WebCrypto as a global; older Node 18.x needs the
// node:crypto fallback. Either way we never touch node:crypto's non-Web API.
const webcrypto = globalThis.crypto ?? (await import("node:crypto")).webcrypto;

function fail(reason) {
  console.log(`FAIL ${reason}`);
  process.exitCode = 1;
}

// Canonical JSON serialization — RFC-8785 (JCS)-style profile, mirroring the
// frozen v1 spec these artifacts are signed under:
//   - Object keys sorted ascending by UTF-16 code unit.
//   - `undefined` values omitted (moot for parsed JSON; kept for parity).
//   - `null` preserved; arrays keep order.
//   - Standard JSON.stringify token form for strings/numbers/booleans/null.
//   - No insignificant whitespace (compact `{"k":v,...}` / `[v,...]`).
//   - Non-finite numbers throw rather than silently becoming `null`.
function canonicalJSONStringify(value) {
  return encode(value);
}

function encode(value) {
  if (value === null) return "null";
  const t = typeof value;
  if (t === "number") {
    if (!Number.isFinite(value)) {
      throw new TypeError("canonicalJSONStringify: non-finite number");
    }
    return JSON.stringify(value);
  }
  if (t === "string" || t === "boolean") return JSON.stringify(value);
  if (t === "bigint") {
    throw new TypeError("canonicalJSONStringify: BigInt is not JSON-serializable");
  }
  if (Array.isArray(value)) {
    const items = value.map((el) => (el === undefined ? "null" : encode(el)));
    return "[" + items.join(",") + "]";
  }
  if (t === "object") {
    const obj = value;
    const keys = Object.keys(obj)
      .filter((k) => obj[k] !== undefined)
      .sort();
    const parts = keys.map((k) => JSON.stringify(k) + ":" + encode(obj[k]));
    return "{" + parts.join(",") + "}";
  }
  throw new TypeError(`canonicalJSONStringify: unsupported value of type ${t}`);
}

async function readJSON(source) {
  if (/^https?:\/\//i.test(source)) {
    const res = await fetch(source);
    if (!res.ok) throw new Error(`fetch ${source} -> HTTP ${res.status}`);
    return res.json();
  }
  const { readFile } = await import("node:fs/promises");
  const text = await readFile(source, "utf8");
  return JSON.parse(text);
}

async function main() {
  const [artifactSource, jwksSource = DEFAULT_JWKS_URL] = process.argv.slice(2);
  if (!artifactSource) {
    console.error("usage: node verify.mjs <artifact-url-or-file> [jwks-url]");
    process.exitCode = 2;
    return;
  }

  let artifact;
  try {
    artifact = await readJSON(artifactSource);
  } catch (err) {
    return fail(`could not read artifact: ${err.message}`);
  }

  const { payload, sig } = artifact ?? {};
  if (!payload || typeof payload !== "object") return fail("artifact missing 'payload'");
  if (typeof sig !== "string" || sig.length === 0) return fail("artifact missing 'sig'");

  const kid = payload.sig_key_id;
  if (typeof kid !== "string" || kid.length === 0) {
    return fail("payload missing 'sig_key_id'");
  }

  let jwks;
  try {
    jwks = await readJSON(jwksSource);
  } catch (err) {
    return fail(`could not read jwks: ${err.message}`);
  }

  const jwk = Array.isArray(jwks?.keys) ? jwks.keys.find((k) => k.kid === kid) : undefined;
  if (!jwk) return fail(`no key with kid "${kid}" in jwks (${jwksSource})`);

  let canonicalBytes;
  try {
    canonicalBytes = new TextEncoder().encode(canonicalJSONStringify(payload));
  } catch (err) {
    return fail(`canonicalization error: ${err.message}`);
  }

  let publicKey;
  try {
    publicKey = await webcrypto.subtle.importKey("jwk", jwk, { name: "Ed25519" }, true, ["verify"]);
  } catch (err) {
    return fail(`could not import public key: ${err.message}`);
  }

  let sigBytes;
  try {
    sigBytes = Buffer.from(sig, "base64");
  } catch (err) {
    return fail(`could not decode signature: ${err.message}`);
  }

  let ok;
  try {
    ok = await webcrypto.subtle.verify({ name: "Ed25519" }, publicKey, sigBytes, canonicalBytes);
  } catch (err) {
    return fail(`verify threw: ${err.message}`);
  }

  if (!ok) return fail("signature does not match");

  console.log(`PASS ${kid} ${payload.created_at ?? ""}`.trimEnd());
  process.exitCode = 0;
}

main().catch((err) => fail(`unexpected error: ${err?.message ?? err}`));
