// mandate-demo.mjs: runnable proof for Emissar Mandate v0.1 (https://emissar.ai/specs/mandate/v0.1).
//
// Node 20+ (tested on Node 24). No dependencies: WebCrypto (crypto.subtle), CompressionStream,
// and node:fs only when --write is given.
//
//   node mandate-demo.mjs              run the scenarios and print the report
//   node mandate-demo.mjs --write DIR  also write the example JSON files into DIR
//
// It issues a mandate (SD-JWT, RFC 9901) bound to an agent key by RFC 7638 thumbprint (cnf.jkt),
// presents it inside a real A2A v1.0 SendMessage body, verifies it with the numbered steps of the
// spec's section 9, checks revocation against a local Token Status List, and shows the failures.
// Not implemented here: duplicate JSON member detection (JSON.parse keeps the last one).

import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";

const { subtle } = globalThis.crypto;
const EXT_URI = "https://emissar.ai/ext/mandate/v1";
const MANDATE_TYP = "vnd.emissar.mandate+sd-jwt";
const TERMINAL = new Set(["TASK_STATE_COMPLETED", "TASK_STATE_FAILED", "TASK_STATE_CANCELED", "TASK_STATE_REJECTED"]);

// ---------- encoding and JOSE helpers ----------
const enc = new TextEncoder();
const dec = new TextDecoder("utf-8", { fatal: true });
const B64U = /^[A-Za-z0-9_-]+$/;
const b64u = (bytes) => Buffer.from(bytes).toString("base64url");
const fromB64u = (s) => {
  if (typeof s !== "string" || !B64U.test(s)) throw new Error("not base64url");
  return new Uint8Array(Buffer.from(s, "base64url"));
};
const b64uJson = (obj) => b64u(enc.encode(JSON.stringify(obj)));
const parseB64uJson = (s) => JSON.parse(dec.decode(fromB64u(s)));
const sha256 = async (bytes) => new Uint8Array(await subtle.digest("SHA-256", bytes));
const randomB64u = (n) => b64u(crypto.getRandomValues(new Uint8Array(n)));
const iso = (t) => new Date(t * 1000).toISOString();
const ES256 = { name: "ECDSA", hash: "SHA-256" };
const P256 = { name: "ECDSA", namedCurve: "P-256" };

async function newKeyPair() {
  const kp = await subtle.generateKey(P256, true, ["sign", "verify"]);
  const { kty, crv, x, y } = await subtle.exportKey("jwk", kp.publicKey);
  return { privateKey: kp.privateKey, publicJwk: { kty, crv, x, y } };
}

async function signJwt(header, payload, privateKey) {
  const input = `${b64uJson(header)}.${b64uJson(payload)}`;
  const sig = await subtle.sign(ES256, privateKey, enc.encode(input)); // raw R||S, as JWS requires
  return `${input}.${b64u(sig)}`;
}

function decodeJwt(jwt) {
  const parts = typeof jwt === "string" ? jwt.split(".") : [];
  if (parts.length !== 3 || !parts.every((p) => B64U.test(p))) throw new Error("not a compact JWS");
  return {
    header: parseB64uJson(parts[0]),
    payload: parseB64uJson(parts[1]),
    signingInput: `${parts[0]}.${parts[1]}`,
    signature: fromB64u(parts[2]),
  };
}

async function verifyJws(decoded, jwk) {
  if (decoded.signature.length !== 64) return false;
  const key = await subtle.importKey("jwk", { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y }, P256, false, ["verify"]);
  return subtle.verify(ES256, key, decoded.signature, enc.encode(decoded.signingInput));
}

// RFC 7638: required EC members in lexicographic order, no whitespace, SHA-256, base64url.
async function jwkThumbprint(jwk) {
  if (jwk?.kty !== "EC" || typeof jwk.crv !== "string" || typeof jwk.x !== "string" || typeof jwk.y !== "string") {
    throw new Error("not an EC public JWK");
  }
  const canonical = `{"crv":${JSON.stringify(jwk.crv)},"kty":"EC","x":${JSON.stringify(jwk.x)},"y":${JSON.stringify(jwk.y)}}`;
  return b64u(await sha256(enc.encode(canonical)));
}

// ---------- Token Status List (draft-ietf-oauth-status-list-21) ----------
async function pipe(bytes, stream) {
  return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer());
}
const zlibDeflate = (bytes) => pipe(bytes, new CompressionStream("deflate")); // "deflate" = ZLIB (RFC 1950) wrapping DEFLATE
const zlibInflate = (bytes) => pipe(bytes, new DecompressionStream("deflate"));

function readStatus(bytes, idx, bits) {
  const perByte = 8 / bits;
  const byte = bytes[Math.floor(idx / perByte)];
  if (byte === undefined) return undefined; // out of bounds
  return (byte >> ((idx % perByte) * bits)) & ((1 << bits) - 1); // packed from the least significant bit
}

class StatusIssuer {
  constructor({ uri, size, bits = 1 }) {
    Object.assign(this, { uri, size, bits, bytes: new Uint8Array(Math.ceil((size * bits) / 8)) });
  }
  set(idx, value) {
    const perByte = 8 / this.bits, i = Math.floor(idx / perByte), shift = (idx % perByte) * this.bits;
    const mask = ((1 << this.bits) - 1) << shift;
    this.bytes[i] = (this.bytes[i] & ~mask) | ((value << shift) & mask);
  }
  async token(signer, now) {
    const payload = {
      sub: this.uri, iat: now, exp: now + 86400, ttl: 300,
      status_list: { bits: this.bits, lst: b64u(await zlibDeflate(this.bytes)) },
    };
    const header = { alg: "ES256", kid: signer.kid, typ: "statuslist+jwt" };
    return { header, payload, compact: await signJwt(header, payload, signer.privateKey) };
  }
}

// ---------- SD-JWT issuance and presentation (RFC 9901) ----------
async function makeDisclosure(array) {
  const disclosure = b64u(enc.encode(JSON.stringify(array)));
  return { disclosure, digest: b64u(await sha256(enc.encode(disclosure))), decoded: array };
}

async function issueMandate(issuer, m) {
  const disclosures = [];
  const principal = { type: m.principal.type };
  const principalDigests = [];
  for (const [name, value] of Object.entries(m.principal.selectivelyDisclosed)) {
    const d = await makeDisclosure([randomB64u(16), name, value]);
    d.label = `principal.${name}`;
    disclosures.push(d);
    principalDigests.push(d.digest);
  }
  if (principalDigests.length) principal._sd = principalDigests.sort();
  const details = [];
  for (const [i, detail] of m.details.entries()) {
    const d = await makeDisclosure([randomB64u(16), detail]);
    d.label = `authorization_details[${i}]`;
    disclosures.push(d);
    details.push({ "...": d.digest });
  }
  const payload = {
    iss: issuer.iss, sub: m.sub, aud: m.aud, iat: m.iat, exp: m.exp, jti: randomB64u(16),
    cnf: { jkt: m.agentJkt }, act: { sub: m.agentId },
    status: { status_list: { idx: m.statusIdx, uri: m.statusUri } },
    principal, authorization_details: details, _sd_alg: "sha-256",
  };
  const header = { alg: "ES256", typ: MANDATE_TYP, kid: issuer.kid };
  const jwt = await signJwt(header, payload, issuer.privateKey);
  return { jwt, header, payload, disclosures, sdJwt: [jwt, ...disclosures.map((d) => d.disclosure)].join("~") + "~" };
}

// The holder (agent) chooses disclosures, then signs a KB-JWT with its own key over the result.
async function present({ mandate, labels, agent, audience, nonce, op, now }) {
  const chosen = mandate.disclosures.filter((d) => labels.includes(d.label));
  const sd = [mandate.jwt, ...chosen.map((d) => d.disclosure)].join("~") + "~";
  const kbHeader = { typ: "kb+jwt", alg: "ES256", jwk: agent.publicJwk };
  const kbPayload = { iat: now, aud: audience, nonce, sd_hash: b64u(await sha256(enc.encode(sd))), op };
  const kbJwt = await signJwt(kbHeader, kbPayload, agent.privateKey);
  return { presentation: sd + kbJwt, chosen, kbHeader, kbPayload };
}

// ---------- Verifier: section 9 of the spec, step by step ----------
class Fail extends Error {
  constructor(step, error, description) { super(description); Object.assign(this, { step, error }); }
}
const DETAIL_MEMBERS = new Set(["type", "actions", "identifier", "limits"]);
const LIMIT_MEMBERS = new Set(["max_amount", "total_amount", "max_uses", "rate"]);
const OP_MEMBERS = new Set(["type", "action", "identifier", "amount"]);
const isAmount = (a) => a && typeof a === "object" && Number.isInteger(a.amount) && a.amount >= 0 &&
  typeof a.currency === "string" && /^[A-Z]{3}$/.test(a.currency) && Object.keys(a).length === 2;
const money = (a) => `${(a.amount / 100).toFixed(2)} ${a.currency}`;

class MandateVerifier {
  constructor(cfg) {
    Object.assign(this, { skew: 60, kbMaxAge: 300, maxLifetime: 30 * 86400, challengeLife: 600, statusMaxAge: 300, ...cfg });
    this.challenges = new Map(); // nonce -> { taskId, exp }
    this.usage = new Map();      // "iss|jti|index" -> { uses, spent, times[] }
    this.statusCache = new Map();
  }

  newChallenge(taskId, now) {
    for (const [nonce, c] of this.challenges) if (c.taskId === taskId) this.challenges.delete(nonce); // one live challenge per task
    const nonce = randomB64u(16);
    this.challenges.set(nonce, { taskId, exp: now + this.challengeLife });
    return { nonce, audience: this.audience, expiresAt: iso(now + this.challengeLife) };
  }

  async verify({ presentation, taskId, now }) {
    const trace = [];
    const ok = (step, note) => trace.push({ step, note });
    try {
      // Step 2: split SD-JWT+KB.
      if (presentation.length > 16384) throw new Fail(2, "mandate_invalid", "presentation larger than 16384 characters");
      const parts = presentation.split("~");
      const kbJwt = parts.pop();
      const [issuerJwt, ...disclosures] = parts;
      if (!issuerJwt || !kbJwt || disclosures.some((d) => !d)) throw new Fail(2, "mandate_invalid", "not an SD-JWT+KB");
      ok(2, `issuer JWT, ${disclosures.length} disclosure(s), KB-JWT`);

      // Step 3: issuer JWT header.
      let ij;
      try { ij = decodeJwt(issuerJwt); } catch { throw new Fail(3, "mandate_invalid", "issuer JWT is not a compact JWS"); }
      const h = ij.header;
      if (h.typ !== MANDATE_TYP) throw new Fail(3, "mandate_invalid", `typ must be ${MANDATE_TYP}`);
      if (h.alg !== "ES256") throw new Fail(3, "mandate_invalid", "alg not accepted");
      if (typeof h.kid !== "string") throw new Fail(3, "mandate_invalid", "kid missing");
      if ("jku" in h || "jwk" in h || "x5u" in h || "crit" in h) throw new Fail(3, "mandate_invalid", "header parameter not allowed");
      ok(3, `typ ${h.typ}, alg ${h.alg}, kid ${h.kid}`);

      // Step 4: trusted issuer and key, from local trust configuration only.
      const iss = ij.payload.iss;
      const key = this.issuers.get(iss)?.keys[h.kid];
      if (!key) throw new Fail(4, "mandate_invalid", "issuer or key not trusted");
      ok(4, `trusted issuer ${iss}`);

      // Step 5: issuer signature.
      if (!(await verifyJws(ij, key))) throw new Fail(5, "mandate_invalid", "issuer signature invalid");
      ok(5, "issuer signature valid");

      // Step 6: disclosures (RFC 9901 section 7.1), allowed only in principal members and detail elements.
      const { processed, detailIndex } = await this.applyDisclosures(ij.payload, disclosures);
      ok(6, `${disclosures.length} disclosure(s) applied, ${processed.authorization_details.length} detail(s) visible`);

      // Step 7: required claims and lifetime.
      const p = processed;
      const req = typeof p.iss === "string" && typeof p.sub === "string" && p.sub && Number.isInteger(p.iat) &&
        Number.isInteger(p.exp) && typeof p.jti === "string" && p.jti.length >= 16 &&
        (typeof p.aud === "string" || (Array.isArray(p.aud) && p.aud.length && p.aud.every((a) => typeof a === "string"))) &&
        typeof p.cnf?.jkt === "string" && Number.isInteger(p.status?.status_list?.idx) && p.status.status_list.idx >= 0 &&
        typeof p.status.status_list.uri === "string" && Array.isArray(ij.payload.authorization_details) &&
        ij.payload.authorization_details.length > 0 && (p.nbf === undefined || Number.isInteger(p.nbf));
      if (!req) throw new Fail(7, "mandate_invalid", "required claim missing or malformed");
      if (p.exp <= p.iat || p.exp - p.iat > this.maxLifetime) throw new Fail(7, "mandate_invalid", "lifetime outside policy");
      ok(7, `jti ${p.jti}, lifetime ${p.exp - p.iat} s`);

      // Step 8: validity window.
      if (p.iat > now + this.skew) throw new Fail(8, "mandate_invalid", "iat in the future");
      if (p.nbf !== undefined && now < p.nbf - this.skew) throw new Fail(8, "mandate_not_yet_valid", `not valid before ${iso(p.nbf)}`);
      if (now >= p.exp + this.skew) throw new Fail(8, "mandate_expired", `expired at ${iso(p.exp)}`);
      ok(8, `valid until ${iso(p.exp)}`);

      // Step 9: audience.
      if (!(p.aud === this.audience || (Array.isArray(p.aud) && p.aud.includes(this.audience)))) {
        throw new Fail(9, "mandate_invalid", "aud does not name this verifier");
      }
      ok(9, `aud ${this.audience}`);

      // Step 10: key binding: KB-JWT header key must hash to cnf.jkt, and must verify the KB-JWT.
      let kb;
      try { kb = decodeJwt(kbJwt); } catch { throw new Fail(10, "proof_invalid", "KB-JWT is not a compact JWS"); }
      const jwk = kb.header.jwk;
      if (kb.header.typ !== "kb+jwt" || kb.header.alg !== "ES256" || jwk?.kty !== "EC" || jwk.crv !== "P-256" || "d" in jwk) {
        throw new Fail(10, "proof_invalid", "KB-JWT header invalid");
      }
      const jkt = await jwkThumbprint(jwk);
      if (jkt !== p.cnf.jkt) throw new Fail(10, "proof_invalid", `presenting key ${jkt} is not the bound agent key ${p.cnf.jkt}`);
      if (!(await verifyJws(kb, jwk))) throw new Fail(10, "proof_invalid", "KB-JWT signature invalid");
      ok(10, `agent key thumbprint matches cnf.jkt ${jkt}`);

      // Step 11: KB-JWT claims.
      const k = kb.payload;
      const sdHash = b64u(await sha256(enc.encode([issuerJwt, ...disclosures].join("~") + "~")));
      if (k.sd_hash !== sdHash) throw new Fail(11, "proof_invalid", "sd_hash mismatch");
      if (k.aud !== this.audience) throw new Fail(11, "proof_invalid", "KB-JWT aud mismatch");
      if (!Number.isInteger(k.iat) || k.iat > now + this.skew || k.iat < now - this.kbMaxAge) throw new Fail(11, "proof_invalid", "KB-JWT iat outside window");
      if (typeof k.nonce !== "string" || !k.op || typeof k.op !== "object") throw new Fail(11, "proof_invalid", "nonce or op missing");
      ok(11, "sd_hash, aud and iat valid");

      // Step 12: nonce is a live challenge for this task; consume it whatever happens next.
      const c = this.challenges.get(k.nonce);
      this.challenges.delete(k.nonce);
      if (!c || c.taskId !== taskId || now > c.exp) throw new Fail(12, "proof_invalid", "nonce is not a live challenge for this task");
      ok(12, "challenge nonce consumed");

      // Step 13: status (Token Status List section 8.3).
      const st = await this.status(p.status.status_list.uri, p.iss, now);
      const v = readStatus(st.bytes, p.status.status_list.idx, st.bits);
      if (v === undefined) throw new Fail(13, "mandate_invalid", "status index out of bounds");
      if (v === 1) throw new Fail(13, "mandate_revoked", "status list says INVALID (revoked)");
      if (v === 2) throw new Fail(13, "mandate_suspended", "status list says SUSPENDED");
      if (v !== 0) throw new Fail(13, "mandate_invalid", `unknown status value ${v}`);
      ok(13, `status VALID at index ${p.status.status_list.idx}`);

      // Step 14: operation coverage.
      const op = k.op;
      const opOk = Object.keys(op).every((m) => OP_MEMBERS.has(m)) && typeof op.type === "string" &&
        typeof op.action === "string" && (op.identifier === undefined || typeof op.identifier === "string") &&
        (op.amount === undefined || isAmount(op.amount));
      if (!opOk) throw new Fail(14, "proof_invalid", "op malformed");
      const candidates = [];
      let unsupported = false;
      const multiAudience = Array.isArray(p.aud) && p.aud.length > 1; // cumulative limits need a single audience
      p.authorization_details.forEach((d, i) => {
        const L = d?.limits ?? {};
        const wellFormed = d && typeof d === "object" && Object.keys(d).every((m) => DETAIL_MEMBERS.has(m)) &&
          !(multiAudience && (L.total_amount || L.max_uses || L.rate)) &&
          typeof d.type === "string" && Array.isArray(d.actions) && d.actions.length > 0 &&
          d.actions.every((a) => typeof a === "string") && (d.identifier === undefined || typeof d.identifier === "string") &&
          typeof L === "object" && Object.keys(L).every((m) => LIMIT_MEMBERS.has(m)) &&
          (L.max_amount === undefined || isAmount(L.max_amount)) && (L.total_amount === undefined || isAmount(L.total_amount)) &&
          (!L.max_amount || !L.total_amount || L.max_amount.currency === L.total_amount.currency) &&
          (L.max_uses === undefined || (Number.isInteger(L.max_uses) && L.max_uses >= 1)) &&
          (L.rate === undefined || (Number.isInteger(L.rate.count) && L.rate.count >= 1 && Number.isInteger(L.rate.window) && L.rate.window >= 1));
        if (!wellFormed || !this.acceptedTypes.has(d.type)) { if (d?.type === op.type) unsupported = true; return; }
        if (d.type !== op.type || !d.actions.includes(op.action)) return;
        if (d.identifier !== undefined && d.identifier !== op.identifier) return;
        if (op.amount && (L.max_amount ?? L.total_amount)?.currency !== op.amount.currency) return;
        candidates.push({ d, index: detailIndex[i] });
      });
      if (!candidates.length) {
        throw new Fail(14, unsupported ? "unsupported_detail" : "insufficient_scope",
          `no disclosed authorization detail covers ${op.action} ${op.identifier ?? ""}`.trim());
      }
      ok(14, `covered by authorization_details[${candidates[0].index}]`);

      // Step 15: limits, counted per (iss, jti, issued index).
      let chosen, reasons = [];
      for (const cnd of candidates) {
        const L = cnd.d.limits ?? {};
        const key = `${p.iss}|${p.jti}|${cnd.index}`;
        const u = this.usage.get(key) ?? { uses: 0, spent: 0, times: [] };
        const amt = op.amount?.amount ?? 0;
        reasons = [];
        if (L.max_amount && amt > L.max_amount.amount) reasons.push(`${money(op.amount)} exceeds max_amount ${money(L.max_amount)}`);
        if (L.total_amount && u.spent + amt > L.total_amount.amount) reasons.push(`total would exceed ${money(L.total_amount)}`);
        if (L.max_uses && u.uses + 1 > L.max_uses) reasons.push(`max_uses ${L.max_uses} reached`);
        if (L.rate && u.times.filter((t) => t > now - L.rate.window).length + 1 > L.rate.count) reasons.push("rate limit reached");
        if (!reasons.length) { chosen = { ...cnd, key, u, amt }; break; }
      }
      if (!chosen) throw new Fail(15, "limit_exceeded", reasons.join("; "));
      ok(15, `within limits (use ${chosen.u.uses + 1}${chosen.d.limits?.max_uses ? ` of ${chosen.d.limits.max_uses}` : ""})`);

      // Step 16: commit usage atomically with the decision (single-threaded here).
      this.usage.set(chosen.key, { uses: chosen.u.uses + 1, spent: chosen.u.spent + chosen.amt, times: [...chosen.u.times, now] });
      ok(16, "usage recorded");
      return { ok: true, trace, op, iss: p.iss, jti: p.jti, sdHash, jkt, detailIndex: chosen.index, processed };
    } catch (e) {
      if (!(e instanceof Fail)) throw e;
      return { ok: false, trace, step: e.step, error: e.error, description: e.message };
    }
  }

  async applyDisclosures(payload, strings) {
    if ((payload._sd_alg ?? "sha-256") !== "sha-256") throw new Fail(6, "mandate_invalid", "_sd_alg must be sha-256");
    const byDigest = new Map();
    for (const s of strings) {
      let arr;
      try { arr = JSON.parse(dec.decode(fromB64u(s))); } catch { throw new Fail(6, "mandate_invalid", "disclosure is not base64url JSON"); }
      const digest = b64u(await sha256(enc.encode(s)));
      if (byDigest.has(digest)) throw new Fail(6, "mandate_invalid", "disclosure sent twice");
      if (!Array.isArray(arr) || (arr.length !== 2 && arr.length !== 3) || typeof arr[0] !== "string") {
        throw new Fail(6, "mandate_invalid", "disclosure is not a salted array");
      }
      byDigest.set(digest, { arr, used: false });
    }
    const take = (digest, len, where) => {
      const d = byDigest.get(digest);
      if (!d) return undefined; // not disclosed by the holder
      if (d.used) throw new Fail(6, "mandate_invalid", "digest referenced twice");
      if (d.arr.length !== len) throw new Fail(6, "mandate_invalid", `wrong disclosure form at ${where}`);
      d.used = true;
      return d.arr;
    };
    const principalIn = payload.principal;
    const principal = principalIn === undefined ? undefined : { ...principalIn };
    if (principal) {
      delete principal._sd;
      for (const digest of principalIn._sd ?? []) {
        const arr = take(digest, 3, "principal");
        if (!arr) continue;
        const [, name, value] = arr;
        if (typeof name !== "string" || name === "_sd" || name === "..." || name in principal) {
          throw new Fail(6, "mandate_invalid", "bad disclosed claim name");
        }
        principal[name] = value;
      }
    }
    const details = [], detailIndex = [];
    (payload.authorization_details ?? []).forEach((el, i) => {
      if (el && typeof el === "object" && !Array.isArray(el) && Object.keys(el).length === 1 && "..." in el) {
        const arr = take(el["..."], 2, `authorization_details[${i}]`);
        if (!arr) return; // undisclosed element: absent, so it grants nothing
        details.push(arr[1]); detailIndex.push(i);
      } else { details.push(el); detailIndex.push(i); }
    });
    for (const d of byDigest.values()) if (!d.used) throw new Fail(6, "mandate_invalid", "disclosure not referenced where disclosures are allowed");
    const processed = { ...payload, authorization_details: details };
    delete processed._sd_alg;
    if ("_sd" in processed) throw new Fail(6, "mandate_invalid", "selective disclosure used outside principal and authorization_details");
    if (principal) processed.principal = principal;
    return { processed, detailIndex };
  }

  async status(uri, iss, now) {
    const cached = this.statusCache.get(uri);
    if (cached && now - cached.fetchedAt < Math.min(cached.ttl ?? 0, this.statusMaxAge) && (cached.exp === undefined || now < cached.exp)) return cached;
    let t;
    try { t = decodeJwt(await this.fetchStatusList(uri)); } catch { throw new Fail(13, "status_unavailable", "status list could not be fetched"); }
    const key = this.issuers.get(iss)?.keys[t.header.kid];
    if (t.header.typ !== "statuslist+jwt" || t.header.alg !== "ES256" || !key || !(await verifyJws(t, key))) {
      throw new Fail(13, "status_unavailable", "status list token not valid for this issuer");
    }
    const sl = t.payload.status_list;
    if (t.payload.sub !== uri || !Number.isInteger(t.payload.iat) || ![1, 2, 4, 8].includes(sl?.bits) || typeof sl.lst !== "string") {
      throw new Fail(13, "status_unavailable", "status list token malformed");
    }
    if (t.payload.exp !== undefined && now >= t.payload.exp) throw new Fail(13, "status_unavailable", "status list token expired");
    const entry = { bits: sl.bits, bytes: await zlibInflate(fromB64u(sl.lst)), ttl: t.payload.ttl, exp: t.payload.exp, fetchedAt: now };
    this.statusCache.set(uri, entry);
    return entry;
  }
}

// ---------- A2A v1.0 verifier agent (JSON-RPC binding), just enough for the scenarios ----------
const ERROR_TEXT = {
  mandate_required: "No mandate was presented.",
  mandate_invalid: "The mandate could not be verified.",
  proof_invalid: "The presentation could not be verified.",
  mandate_expired: "The mandate has expired.",
  mandate_not_yet_valid: "The mandate is not valid yet.",
  mandate_revoked: "The mandate was revoked.",
  mandate_suspended: "The mandate is suspended.",
  insufficient_scope: "The mandate does not cover this action.",
  unsupported_detail: "The mandate uses an authorization detail this agent does not support.",
  limit_exceeded: "This action exceeds a limit in the mandate.",
  status_unavailable: "The mandate's revocation status could not be checked. Try again later.",
};
class ProviderAgent {
  constructor(verifier) { Object.assign(this, { verifier, tasks: new Map(), log: [] }); }

  async handle(headers, body, now) {
    const reply = (payload) => ({ headers: { "Content-Type": "application/json", "A2A-Extensions": EXT_URI }, body: { jsonrpc: "2.0", id: body.id, ...payload } });
    const rpcError = (code, message, data) => reply({ error: { code, message, data } });
    const msg = body.params?.message;
    const activated = String(headers["A2A-Extensions"] ?? "").split(",").map((s) => s.trim()).includes(EXT_URI);
    const entry = activated ? msg.metadata?.[EXT_URI] : undefined; // not activated: ignore the metadata
    if (entry !== undefined && (typeof entry !== "object" || entry === null || Array.isArray(entry) ||
        typeof entry.presentation !== "string" || Object.keys(entry).length !== 1)) {
      return rpcError(-32602, "Invalid parameters", [{ "@type": "type.googleapis.com/google.rpc.BadRequest",
        fieldViolations: [{ field: `message.metadata["${EXT_URI}"]`, description: "must be an object with one string member, presentation" }] }]);
    }
    let task;
    if (msg.taskId) {
      task = this.tasks.get(msg.taskId);
      if (!task) return rpcError(-32001, "Task not found", [{ "@type": "type.googleapis.com/google.rpc.ErrorInfo", reason: "TASK_NOT_FOUND", domain: "a2a-protocol.org" }]);
      if (TERMINAL.has(task.status.state)) {
        return rpcError(-32004, "This task has already ended.", [{ "@type": "type.googleapis.com/google.rpc.ErrorInfo", reason: "UNSUPPORTED_OPERATION", domain: "a2a-protocol.org" }]);
      }
    } else {
      task = { id: crypto.randomUUID(), contextId: msg.contextId ?? crypto.randomUUID(), status: { state: "TASK_STATE_SUBMITTED", timestamp: iso(now) } };
      this.tasks.set(task.id, task);
    }
    if (!entry) return reply({ result: { task: this.authRequired(task, "mandate_required", now) } });
    const r = await this.verifier.verify({ presentation: entry.presentation, taskId: task.id, now });
    // The detailed reason (r.description) stays in the verifier's log; the client gets the code and a generic description.
    this.log.push({ taskId: task.id, messageId: msg.messageId, ...r, trace: undefined });
    if (!r.ok) return reply({ result: { task: this.authRequired(task, r.error, now) }, _verification: r });
    // Perform exactly the verified op, never an operation read from message text.
    task.status = { state: "TASK_STATE_COMPLETED", timestamp: iso(now) };
    task.artifacts = [{
      artifactId: crypto.randomUUID(), name: "Refund",
      parts: [
        { text: `Refund of ${money(r.op.amount)} on order ${r.op.identifier} approved.` },
        { data: { orderId: r.op.identifier, refunded: r.op.amount, status: "approved" }, mediaType: "application/json" },
      ],
      extensions: [EXT_URI],
      metadata: { [EXT_URI]: { result: "accepted", iss: r.iss, jti: r.jti, sdHash: r.sdHash, jkt: r.jkt } },
    }];
    return reply({ result: { task }, _verification: r });
  }

  authRequired(task, error, now) {
    const description = ERROR_TEXT[error];
    task.status = {
      state: "TASK_STATE_AUTH_REQUIRED", timestamp: iso(now),
      message: {
        messageId: crypto.randomUUID(), contextId: task.contextId, taskId: task.id, role: "ROLE_AGENT",
        parts: [{ text: `${description} This refund needs a mandate from the account holder for order ORD-1042, up to 200.00 CAD.` }],
        extensions: [EXT_URI],
        metadata: { [EXT_URI]: {
          error, errorDescription: description,
          challenge: this.verifier.newChallenge(task.id, now),
          authorizationDetails: [{ type: T_ORDER, actions: ["refund"], identifier: "ORD-1042", limits: { max_amount: { amount: 20000, currency: "CAD" } } }],
          acceptedIssuers: [...this.verifier.issuers.keys()],
        } },
      },
    };
    return task;
  }
}

function sendMessage({ id, text, taskId, contextId, presentation }) {
  const message = { messageId: crypto.randomUUID(), role: "ROLE_USER", parts: [{ text }] };
  if (taskId) message.taskId = taskId;
  if (contextId) message.contextId = contextId;
  if (presentation) {
    message.extensions = [EXT_URI];
    message.metadata = { [EXT_URI]: { presentation } };
  }
  return {
    headers: { "Content-Type": "application/json", "A2A-Version": "1.0", "A2A-Extensions": EXT_URI },
    body: { jsonrpc: "2.0", id, method: "SendMessage", params: { message, configuration: { historyLength: 0 } } },
  };
}

// ---------- scenario data (illustrative parties, reserved .example names) ----------
const T_ORDER = "https://provider.example/mandate-types/order";
const T_SUB = "https://provider.example/mandate-types/subscription";
const AUDIENCE = "https://agents.provider.example";
const ISS = "https://mandates.assistant.example";
const STATUS_URI = `${ISS}/status/3`;
const AGENT_ID = "https://agents.assistant.example/billing";

const short = (s, n = 60) => (typeof s === "string" && s.length > n ? `${s.slice(0, n)}…[${s.length} chars]` : s);
const shorten = (v) => JSON.parse(JSON.stringify(v, (k, x) => (typeof x === "string" ? short(x) : x)));
const show = (label, v) => console.log(`${label}\n${JSON.stringify(shorten(v), null, 2)}\n`);

async function main() {
  const writeDir = process.argv.includes("--write") ? process.argv[process.argv.indexOf("--write") + 1] : null;
  const now = Math.floor(Date.now() / 1000);
  console.log(`Emissar Mandate v0.1 demo. node ${process.version}, clock ${iso(now)}\n`);

  // Self-tests against published vectors.
  const rfc9449Key = { kty: "EC", crv: "P-256", x: "l8tFrhx-34tV3hRICRDY9zCkDlpBhF42UQUfWVAWBFs", y: "9VE4jf_Ok_o64zbTTlcuNJajHmt6v9TDVrU0CdvGRDA" };
  const tp = await jwkThumbprint(rfc9449Key);
  const tsl = Buffer.from(await zlibInflate(fromB64u("eNrbuRgAAhcBXQ"))).toString("hex");
  const selfOk = tp === "0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I" && tsl === "b9a3";
  console.log("Self-tests");
  console.log(`  RFC 7638 thumbprint of the RFC 9449 example key: ${tp} ${tp === "0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I" ? "(matches RFC 9449 section 6.1)" : "(MISMATCH)"}`);
  console.log(`  Token Status List example "eNrbuRgAAhcBXQ" inflates to ${tsl} ${tsl === "b9a3" ? "(matches draft section 4.2)" : "(MISMATCH)"}\n`);

  // Parties.
  const issuer = { iss: ISS, kid: "mandate-key-2026-09", ...(await newKeyPair()) };
  const agent = await newKeyPair();
  const attacker = await newKeyPair();
  const agentJkt = await jwkThumbprint(agent.publicJwk);
  const statusList = new StatusIssuer({ uri: STATUS_URI, size: 131072, bits: 1 });
  let published = await statusList.token(issuer, now);
  const verifier = new MandateVerifier({
    audience: AUDIENCE,
    issuers: new Map([[ISS, { keys: { [issuer.kid]: issuer.publicJwk } }]]),
    acceptedTypes: new Set([T_ORDER, T_SUB]),
    // Trust configuration: only this issuer's status URI may be fetched; anything else counts as unobtainable.
    fetchStatusList: async (uri) => { if (uri !== STATUS_URI) throw new Error("status URI not permitted"); return published.compact; },
    statusMaxAge: 0, // demo: refetch every time so revocation shows at once; production caches up to ttl
  });
  const provider = new ProviderAgent(verifier);
  console.log("Setup");
  console.log(`  issuer ${ISS} (kid ${issuer.kid}); verifier audience ${AUDIENCE}`);
  console.log(`  agent key jkt    ${agentJkt}`);
  console.log(`  attacker key jkt ${await jwkThumbprint(attacker.publicJwk)}`);
  console.log(`  status list ${STATUS_URI}: ${statusList.size} entries, bits 1, lst ${published.payload.status_list.lst.length} chars\n`);

  // Issue M1: refund up to CAD 200.00 on ORD-1042 (max 2 uses), cancel SUB-3310. Principal details and each detail are selectively disclosable.
  const idx1 = crypto.getRandomValues(new Uint32Array(1))[0] % statusList.size;
  const details = [
    { type: T_ORDER, actions: ["refund"], identifier: "ORD-1042",
      limits: { max_amount: { amount: 20000, currency: "CAD" }, total_amount: { amount: 20000, currency: "CAD" }, max_uses: 2 } },
    { type: T_SUB, actions: ["cancel"], identifier: "SUB-3310" },
  ];
  const m1 = await issueMandate(issuer, {
    sub: "psub-6f1c2a9e", aud: AUDIENCE, iat: now, exp: now + 3600, agentJkt, agentId: AGENT_ID,
    statusIdx: idx1, statusUri: STATUS_URI, details,
    principal: { type: "person", selectivelyDisclosed: { name: "Alex Example", account: "CUST-88121" } },
  });
  show("Issued mandate M1: issuer JWT header", m1.header);
  show("Issued mandate M1: issuer JWT payload (as signed; _sd and ... hold digests)", m1.payload);
  console.log("Issued mandate M1: disclosures");
  for (const d of m1.disclosures) console.log(`  ${d.label.padEnd(26)} digest ${d.digest}  ${JSON.stringify(d.decoded).slice(0, 90)}`);
  console.log(`  compact SD-JWT as issued: ${m1.sdJwt.length} chars\n`);

  const results = [];
  const record = (id, name, expected, res) => {
    const task = res.body.result?.task;
    const outcome = res.body.error ? `JSON-RPC ${res.body.error.code}` : task.status.state;
    const detail = res.body.error ? res.body.error.data?.[0]?.reason ?? "" : task.status.message?.metadata?.[EXT_URI]?.error ?? task.artifacts?.[0]?.metadata?.[EXT_URI]?.result;
    const v = res.body._verification;
    const got = `${outcome} ${detail ?? ""}`.trim();
    results.push({ id, name, expected, got, pass: got === expected, step: v && !v.ok ? v.step : undefined, why: v && !v.ok ? v.description : undefined });
    return task;
  };
  let rpc = 1;
  const call = async (req, t = now) => { const res = await provider.handle(req.headers, req.body, t); return res; };
  const challengeOf = (task) => task.status.message.metadata[EXT_URI].challenge.nonce;
  const refund = (amount) => ({ type: T_ORDER, action: "refund", identifier: "ORD-1042", amount: { amount, currency: "CAD" } });
  const orderOnly = ["authorization_details[0]", "principal.account"];

  // A: first contact, no mandate.
  const reqA = sendMessage({ id: rpc++, text: "Please refund 42.00 CAD on order ORD-1042 for my user." });
  const resA = await call(reqA);
  const taskA = record("A", "no mandate presented", "TASK_STATE_AUTH_REQUIRED mandate_required", resA);

  // B: valid presentation on the same task, answering the challenge.
  const pB = await present({ mandate: m1, labels: orderOnly, agent, audience: AUDIENCE, nonce: challengeOf(taskA), op: refund(4200), now });
  const reqB = sendMessage({ id: rpc++, text: "Refund 42.00 CAD on ORD-1042. Mandate attached.", taskId: taskA.id, presentation: pB.presentation });
  const resB = await call(reqB);
  record("B", "valid mandate, refund 42.00 CAD", "TASK_STATE_COMPLETED accepted", resB);

  // C1: the same request again: A2A itself refuses (task is terminal).
  record("C1", "replay of B on its finished task", "JSON-RPC -32004 UNSUPPORTED_OPERATION", await call({ headers: reqB.headers, body: { ...reqB.body, id: rpc++ } }));
  // C2: B's presentation copied into a new task: its nonce was consumed and belongs to another task.
  const reqC2 = sendMessage({ id: rpc++, text: "Refund 42.00 CAD on ORD-1042.", presentation: pB.presentation });
  record("C2", "replay of B's presentation in a new task", "TASK_STATE_AUTH_REQUIRED proof_invalid", await call(reqC2));

  // Helper: open a task, take its challenge, then present.
  const attempt = async ({ mandate, labels, key, op, t = now }) => {
    const first = await call(sendMessage({ id: rpc++, text: "Please refund an order for my user." }), t);
    const task = first.body.result.task;
    const p = await present({ mandate, labels, agent: key, audience: AUDIENCE, nonce: challengeOf(task), op, now: t });
    return call(sendMessage({ id: rpc++, text: "Mandate attached.", taskId: task.id, presentation: p.presentation }), t);
  };

  // D: wrong agent key. The attacker holds M1's issuer JWT and disclosures (seen in B) but not the agent's private key.
  record("D", "stolen mandate, attacker's own key", "TASK_STATE_AUTH_REQUIRED proof_invalid", await attempt({ mandate: m1, labels: orderOnly, key: attacker, op: refund(4200) }));

  // E: over the per-operation limit.
  record("E", "refund 250.00 CAD, max_amount 200.00", "TASK_STATE_AUTH_REQUIRED limit_exceeded", await attempt({ mandate: m1, labels: orderOnly, key: agent, op: refund(25000) }));

  // F: action not in scope: the disclosed detail covers SUB-3310, the op names SUB-9999.
  record("F", "cancel SUB-9999, mandate covers SUB-3310", "TASK_STATE_AUTH_REQUIRED insufficient_scope",
    await attempt({ mandate: m1, labels: ["authorization_details[1]"], key: agent, op: { type: T_SUB, action: "cancel", identifier: "SUB-9999" } }));

  // G: expired mandate M2 (valid from now-7200 to now-3600).
  const idx2 = (idx1 + 1) % statusList.size;
  const m2 = await issueMandate(issuer, {
    sub: "psub-6f1c2a9e", aud: AUDIENCE, iat: now - 7200, exp: now - 3600, agentJkt, agentId: AGENT_ID,
    statusIdx: idx2, statusUri: STATUS_URI, details, principal: { type: "person", selectivelyDisclosed: {} },
  });
  record("G", "expired mandate", "TASK_STATE_AUTH_REQUIRED mandate_expired", await attempt({ mandate: m2, labels: ["authorization_details[0]"], key: agent, op: refund(1000) }));

  // H: the principal revokes M1; the issuer flips its status bit and republishes the Status List Token.
  statusList.set(idx1, 1);
  published = await statusList.token(issuer, now);
  const resH = await attempt({ mandate: m1, labels: orderOnly, key: agent, op: refund(1000) });
  record("H", "revoked mandate, refund 10.00 CAD", "TASK_STATE_AUTH_REQUIRED mandate_revoked", resH);

  // Report.
  show("B: SendMessage request body (A2A v1.0 JSON-RPC)", reqB.body);
  console.log("B: verification trace");
  for (const s of resB.body._verification.trace) console.log(`  step ${String(s.step).padStart(2)}  ok  ${s.note}`);
  console.log();
  const { _verification: _vb, ...bodyB } = resB.body;
  show("B: response (task completed; artifact metadata carries the result)", bodyB);
  const { _verification: _vh, ...bodyH } = resH.body;
  show("H: response (revoked; task back in AUTH_REQUIRED with a fresh challenge)", bodyH);

  console.log("Scenarios");
  console.log("  id  scenario                                     result                                          step  pass");
  for (const r of results) {
    console.log(`  ${r.id.padEnd(3)} ${r.name.padEnd(44)} ${r.got.padEnd(47)} ${String(r.step ?? "-").padStart(4)}  ${r.pass ? "yes" : "NO"}`);
    if (r.why) console.log(`      reason: ${r.why}`);
  }
  const passed = results.filter((r) => r.pass).length;
  console.log(`\n${passed}/${results.length} scenarios matched the expected outcome; self-tests ${selfOk ? "passed" : "FAILED"}.`);

  if (writeDir) {
    mkdirSync(writeDir, { recursive: true });
    const w = (name, obj) => writeFileSync(join(writeDir, name), JSON.stringify(obj, null, 2) + "\n");
    const processedB = resB.body._verification.processed;
    w("mandate.json", {
      description: "Mandate M1 from one run of mandate-demo.mjs. Illustrative parties; keys were generated for the run.",
      compact: m1.sdJwt, header: m1.header, payloadAsIssued: m1.payload,
      disclosures: m1.disclosures.map(({ label, digest, disclosure, decoded }) => ({ label, digest, disclosure, decoded })),
      processedPayloadAsPresentedInB: processedB,
    });
    w("presentation.json", {
      description: "The SD-JWT+KB the agent sent in scenario B: the issuer JWT, two chosen disclosures, and the KB-JWT.",
      presentation: pB.presentation, disclosuresPresented: pB.chosen.map((d) => d.label),
      kbJwtHeader: pB.kbHeader, kbJwtPayload: pB.kbPayload,
    });
    w("send-message-request.json", reqB.body);
    w("send-message-response-completed.json", bodyB);
    w("auth-required-response.json", bodyH);
    w("status-list-token.json", { compact: published.compact, header: published.header, payload: published.payload, revokedIndex: idx1 });
    w("agent-card.json", {
      name: "Example Outfitters Support",
      description: "Answers order, refund and membership requests for Example Outfitters customers. Illustrative.",
      supportedInterfaces: [{ url: `${AUDIENCE}/a2a/v1`, protocolBinding: "JSONRPC", protocolVersion: "1.0" }],
      provider: { organization: "Example Outfitters", url: "https://provider.example" },
      version: "1.0.0",
      capabilities: {
        streaming: false, pushNotifications: false,
        extensions: [{
          uri: EXT_URI,
          description: "Refunds and membership cancellations need an Emissar Mandate from the account holder.",
          required: false,
          params: { audience: AUDIENCE, algorithms: ["ES256"], types: [T_ORDER, T_SUB], acceptedIssuers: [ISS] },
        }],
      },
      defaultInputModes: ["text/plain", "application/json"],
      defaultOutputModes: ["text/plain", "application/json"],
      skills: [{ id: "refund", name: "Order refund", description: "Refunds an order within the limits of the customer's mandate.", tags: ["refund", "orders"] }],
    });
    console.log(`\nWrote example files to ${writeDir}`);
  }
  if (!selfOk || passed !== results.length) process.exitCode = 1;
}

await main();
