#!/usr/bin/env node
// SPDX-License-Identifier: Apache-2.0
// Agent join CLI: the three calls from any machine, no page. Node >= 18, no dependencies.
//   node agent-join.mjs --base BASE_URL --name NAME --role ROLE --kind KIND --description TEXT \
//        --visibility public --key-out FILE --receipt-out FILE [--probe-replay] [--probe-email]
// BASE_URL is the production base URL.
// --receipt-out is required for a real join: the owner token has nowhere else to go. It must not exist yet (a dangling symlink
// counts as existing) and its folder must exist and be writable; both are checked before any network call.
// The moment the join is confirmed, before the readback, an INCOMPLETE recovery file (receipt_kind weio.participation.recovery/0,
// complete false, the owner token, the record as sent) is written to --receipt-out (mode 0600, never overwritten, a symlink is
// never followed). A completed receipt (receipt_kind weio.participation.receipt/0) replaces it only when the confirm answer
// says ok true and carries the activation metadata (status active, receipt event/id/at/method) AND the readback is the stored
// record for this id, with status present and exactly active and the fields the receipt is built from valid; anything else
// leaves the recovery file in place. This checks the fields the receipt projects, not every field of the Owner contract
// (created_at and updated_at, for example, are not checked).
// The completed receipt's record, verification label and founding number are the registry's stored readback, never the typed
// arguments.
// Every file is written in full: the write loops on the byte count fs.writeSync returns, syncs, and checks the size. The
// completed receipt is written to a new temporary file in the same folder and renamed into place, so a failed or short write
// never replaces or truncates a valid recovery file; the CLI then exits 1 and says so.
// The owner token is never printed, to stdout or stderr: every line printed passes through redact(), which replaces the exact
// token value, and any field named owner_token or token in an answer, with a placeholder. Registry error strings are shown
// redacted and cut to 200 characters; an answer too deep or too large to search for secrets is never echoed (a fixed
// message replaces its text and values). If --receipt-out cannot be written, the same recovery file goes to a new unique name
// next to it, else to the working directory, and only its path is printed; if that also fails, the message says no recovery
// file could be saved.
// stdout: the completed receipt JSON (owner_token shown as <redacted len N>).
// stderr: progress and probe results, one JSON object per line. Exit 0 when the join returned 200 and the readback matched
// (and every probe asked for met its expectation), 1 otherwise, 2 for bad usage. The private key is written only to --key-out
// (mode 0600), never printed.
import { generateKeyPairSync, sign as edSign, randomBytes } from "node:crypto";
import fs from "node:fs";
import path from "node:path";

const ROLES = ["operate_agents", "provide_capability", "seek_capability", "build_institutions"];
const KINDS = ["capability", "need"];
const VIS = ["private", "public"];
// The key-proof context is pinned here, as the registry fixes it. The remote manifest is never trusted to change it.
const PINNED_CONTEXT = "weio-participants-v1";
const RECEIPT_KIND = "weio.participation.receipt/0";
const RECOVERY_KIND = "weio.participation.recovery/0";
const FLAGS = new Set(["probe-replay", "probe-email", "help"]);
const VALUE = new Set(["base", "name", "role", "kind", "description", "visibility", "key-out", "receipt-out"]);

const USAGE = `usage: node agent-join.mjs --base URL --name NAME --role ROLE --kind KIND --description TEXT
         --receipt-out FILE [--visibility private|public] [--key-out FILE] [--probe-replay] [--probe-email]
  ROLE: ${ROLES.join(" | ")}
  KIND: ${KINDS.join(" | ")}
  --key-out      write the private key (JWK, mode 0600); without it the key is discarded, so this key-proof recovery path cannot replace a lost owner token
  --receipt-out  REQUIRED: save the owner token in a completed receipt after validated confirmation and readback, or in an incomplete recovery file when completion fails (mode 0600); the file must not exist yet
  --probe-replay after the join, re-send the used nonce and expect 410
  --probe-email  after the join, send a body with an email field and expect 403`;

// ---- output: every line printed passes through redact() ------------------------------------------------------------
// SECRETS holds the owner token the moment any answer carries it (a field named owner_token or token). The search is bounded
// (MAX_DEPTH levels, MAX_NODES fields per answer). When an answer is deeper or larger than that, it cannot be checked for
// secrets, so UNCHECKED is set and stays set: from then on no registry-supplied text or value is printed, only WITHHELD.
const REDACTED = "<redacted>";
const SECRET_KEYS = new Set(["owner_token", "token"]);
const SHOWN_REDACTED = /^<redacted( len \d+)?>$/;
const SECRETS = new Set();
const MAX_DEPTH = 8;
const MAX_NODES = 10000;
const WITHHELD = "the registry error response could not be checked for secrets; details withheld";
let UNCHECKED = false;
// Returns true when every field of v was searched, false when a bound was reached (fail closed).
function collectSecrets(v, depth = 0, budget = { n: MAX_NODES }) {
  if (!v || typeof v !== "object") return true;
  if (depth > MAX_DEPTH) return false;
  let complete = true;
  for (const [k, x] of Object.entries(v)) {
    if (--budget.n < 0) return false;
    if (SECRET_KEYS.has(k.toLowerCase()) && typeof x === "string" && x !== "" && !SHOWN_REDACTED.test(x)) SECRETS.add(x);
    else if (!collectSecrets(x, depth + 1, budget)) complete = false;
  }
  return complete;
}
// The exact value, and its URL-encoded and JSON-escaped spellings, become the placeholder.
function redact(text) {
  let s = String(text);
  for (const t of SECRETS) {
    for (const form of new Set([t, encodeURIComponent(t), JSON.stringify(t).slice(1, -1)])) s = s.split(form).join(REDACTED);
  }
  return s;
}
// A value for a JSON log line: strings redacted, fields named owner_token / token replaced (the completed receipt's own
// "<redacted len N>" copy is kept as it is).
function scrub(v, depth = 0) {
  if (typeof v === "string") return redact(v);
  if (!v || typeof v !== "object") return v;
  if (depth > MAX_DEPTH) return REDACTED;
  if (Array.isArray(v)) return v.map((x) => scrub(x, depth + 1));
  return Object.fromEntries(
    Object.entries(v).map(([k, x]) => [k, SECRET_KEYS.has(k.toLowerCase()) && !(typeof x === "string" && SHOWN_REDACTED.test(x)) ? REDACTED : scrub(x, depth + 1)]),
  );
}
// A string the registry supplied: redacted, control characters dropped, at most 200 characters.
const safe = (text) => redact(String(text ?? "")).replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 200);
// A value from a registry answer (an id, a label): safe() while every answer could be checked, else a placeholder.
const regValue = (text) => (UNCHECKED ? "<withheld>" : safe(text));
// The registry's error string for a diagnostic: safe() while every answer could be checked, else the fixed WITHHELD text.
const regError = (r) => (UNCHECKED ? WITHHELD : safe(r && r.json && r.json.error));
const emitErr = (line) => console.error(redact(line));
const emitOut = (line) => console.log(redact(line));
const log = (obj) => emitErr(JSON.stringify(scrub(obj)));
process.on("uncaughtException", (e) => {
  emitErr("agent-join: unexpected error (" + safe(e && (e.code || e.name)) + ")");
  process.exit(1);
});

function usageError(msg) {
  emitErr("agent-join: " + msg + "\n" + USAGE);
  process.exit(2);
}

function parse(argv) {
  const o = {};
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    if (!a.startsWith("--")) usageError("unexpected argument: " + a);
    const k = a.slice(2);
    if (FLAGS.has(k)) {
      o[k] = true;
    } else if (VALUE.has(k)) {
      const v = argv[++i];
      if (v === undefined) usageError("missing value for --" + k);
      o[k] = v;
    } else usageError("unknown option --" + k);
  }
  return o;
}

const o = parse(process.argv.slice(2));
if (o.help) {
  emitOut(USAGE);
  process.exit(0);
}
for (const k of ["base", "name", "role", "kind", "description", "receipt-out"]) if (!o[k]) usageError("--" + k + " is required");
o.visibility = o.visibility || "private";
if (!ROLES.includes(o.role)) usageError("bad --role");
if (!KINDS.includes(o.kind)) usageError("bad --kind");
if (!VIS.includes(o.visibility)) usageError("bad --visibility");
let BASE;
try {
  BASE = new URL(o.base);
  if (!["http:", "https:"].includes(BASE.protocol)) throw new Error("scheme");
} catch {
  usageError("bad --base");
}
// The owner token travels in the Authorization header: plain http is allowed only to this machine.
if (BASE.protocol === "http:" && !["127.0.0.1", "localhost", "[::1]"].includes(BASE.hostname)) usageError("--base must be https (http only for 127.0.0.1, localhost or ::1)");
const origin = BASE.origin;

const b64u = (buf) => Buffer.from(buf).toString("base64url");

async function call(method, p, body, token) {
  const headers = { Accept: "application/json" };
  if (body !== undefined) headers["Content-Type"] = "application/json";
  if (token) headers.Authorization = "Bearer " + token;
  let res;
  try {
    res = await fetch(origin + p, {
      method,
      headers,
      body: body === undefined ? undefined : JSON.stringify(body),
      redirect: "error",
      signal: AbortSignal.timeout(20000),
    });
  } catch (e) {
    return { status: 0, json: { ok: false, error: "network: " + safe(e.cause?.code || e.name) } };
  }
  const text = await res.text();
  let json;
  try {
    json = JSON.parse(text);
  } catch {
    json = { ok: false, error: "non-JSON answer" };
  }
  if (!collectSecrets(json)) UNCHECKED = true;
  return { status: res.status, json };
}

// Write every byte of buf. fs.writeSync may write fewer bytes than asked and says how many it wrote, so this loops on that
// count; three calls in a row with no progress, an impossible count or a file that is not buf.length bytes afterwards is an
// error (code EIO), never a silent short file. The data is synced before it returns.
function writeAll(fd, buf) {
  let off = 0;
  let stalls = 0;
  while (off < buf.length) {
    const n = fs.writeSync(fd, buf, off, buf.length - off);
    if (!Number.isInteger(n) || n < 0 || n > buf.length - off) throw Object.assign(new Error("impossible write count"), { code: "EIO" });
    if (n === 0) {
      if (++stalls >= 3) throw Object.assign(new Error("write made no progress"), { code: "EIO" });
      continue;
    }
    stalls = 0;
    off += n;
  }
  fs.fsyncSync(fd);
  if (fs.fstatSync(fd).size !== buf.length) throw Object.assign(new Error("short file"), { code: "EIO" });
}

// Create a new file, mode 0600, never overwriting and never following a symlink (O_EXCL | O_NOFOLLOW), written in full. A file
// this call created but could not fill is removed again, so a failed write leaves no half-written secret file behind.
function writeNew(file, text) {
  const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
  try {
    writeAll(fd, Buffer.from(text, "utf8"));
    fs.fchmodSync(fd, 0o600);
  } catch (e) {
    fs.closeSync(fd);
    try {
      fs.unlinkSync(file);
    } catch {}
    throw e;
  }
  fs.closeSync(fd);
}

// The recovery copy when --receipt-out cannot be written: a new unique name next to it, else in the working directory.
// Returns the path written, or null when no place took it. Never overwrites, never follows a symlink.
function writeRecovery(requested, text) {
  const spots = [
    [path.dirname(path.resolve(requested)), path.basename(requested) + ".recovery-"],
    [process.cwd(), "agent-join-recovery-"],
  ];
  for (const [dir, stem] of spots) {
    for (let i = 0; i < 3; i++) {
      const f = path.join(dir, stem + b64u(randomBytes(9)) + ".json");
      try {
        writeNew(f, text);
        return f;
      } catch (e) {
        if (!e || e.code !== "EEXIST") break;
      }
    }
  }
  return null;
}

// Replace our own file atomically: the whole text goes to a new temp file in the same folder (wx, 0600, synced), and only a
// complete temp file is renamed over it. A failure at any step leaves the existing file exactly as it was.
function replaceOwn(file, text) {
  const tmp = path.join(path.dirname(file), "." + path.basename(file) + "." + process.pid + "." + b64u(randomBytes(6)) + ".tmp");
  writeNew(tmp, text);
  try {
    fs.renameSync(tmp, file);
  } catch (e) {
    try {
      fs.unlinkSync(tmp);
    } catch {}
    throw e;
  }
}

// Before any network call: the path must not exist (lstat, so a dangling symlink counts) and its folder must be a writable directory.
function precheckOut(flag, f) {
  if (!f) return;
  let exists = true;
  try {
    fs.lstatSync(f);
  } catch (e) {
    if (e && e.code === "ENOENT") exists = false;
    else usageError(flag + " cannot be checked (" + (e && e.code) + ")");
  }
  if (exists) usageError(flag + " exists; refusing to overwrite or follow it");
  const dir = path.dirname(path.resolve(f));
  try {
    if (!fs.statSync(dir).isDirectory()) throw new Error("not a directory");
    fs.accessSync(dir, fs.constants.W_OK | fs.constants.X_OK);
  } catch {
    usageError(flag + ": the folder does not exist or is not writable");
  }
}

function fail(step, r) {
  log({ step, status: r.status, error: regError(r) });
  process.exit(1);
}

// ---- the registry contract, as far as a completed receipt needs it ----------------------------------------------------
const ID_RE = /^p_[A-Za-z0-9_-]{16}$/;
const KEY_RE = /^[A-Za-z0-9_-]{43}$/;
const VERIFICATION = "self-described, unverified";
const TS_RE = /^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d+)?(Z|[+-]([01]\d|2[0-3]):[0-5]\d)$/;
const isTime = (s) => {
  const m = typeof s === "string" && TS_RE.exec(s);
  if (!m) return false;
  const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
  const dt = new Date(Date.UTC(y, mo - 1, d));
  return dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d;
};
const textOk = (s, max) => typeof s === "string" && [...s].length >= 1 && [...s].length <= max;

// The confirm-key answer: ok true, id, status active, and receipt {event activated, id, at, method ed25519}. Returns field
// names only.
function confirmProblems(j, id) {
  const p = [];
  if (j.ok !== true) p.push("ok");
  if (j.id !== id) p.push("id");
  if (j.status !== "active") p.push("status");
  const r = j.receipt;
  if (!r || typeof r !== "object" || Array.isArray(r)) p.push("receipt");
  else {
    if (r.event !== "activated") p.push("receipt.event");
    if (r.id !== id) p.push("receipt.id");
    if (!isTime(r.at)) p.push("receipt.at");
    if (r.method !== "ed25519") p.push("receipt.method");
  }
  return p;
}

// The readback: the stored record for this id, with status present and exactly active and the fields the completed receipt is
// built from (the receipt schema's values). Not every Owner field: created_at and updated_at are not checked. Returns field
// names only.
function readbackProblems(view, id, pub) {
  const p = [];
  if (!view) return ["participant"];
  if (view.id !== id) p.push("id");
  if (!ROLES.includes(view.role)) p.push("role");
  if (!KINDS.includes(view.record_kind)) p.push("record_kind");
  if (!VIS.includes(view.visibility)) p.push("visibility");
  if (!["human", "agent"].includes(view.participant_type)) p.push("participant_type");
  if (!textOk(view.name, 80)) p.push("name");
  if (!textOk(view.description, 700)) p.push("description");
  if (view.verification !== VERIFICATION) p.push("verification");
  if (typeof view.public_key !== "string" || !KEY_RE.test(view.public_key) || view.public_key !== pub) p.push("public_key");
  const fs_ = view.founding_seq;
  if (fs_ !== undefined && fs_ !== null && !(Number.isInteger(fs_) && fs_ >= 1 && fs_ <= 100)) p.push("founding_seq");
  if (view.status !== "active") p.push("status");
  return p;
}

// Refuse bad output paths before doing anything on the network.
if (o["key-out"] && path.resolve(o["key-out"]) === path.resolve(o["receipt-out"])) usageError("invalid --key-out / --receipt-out");
precheckOut("--key-out", o["key-out"]);
precheckOut("--receipt-out", o["receipt-out"]);

// Call 1: the manifest. Its join context must equal the pinned one; a missing manifest is noted, not fatal (the registry may be addressed directly).
const context = PINNED_CONTEXT;
const mf = await call("GET", "/.well-known/weio-gateway.json");
if (mf.status === 200 && mf.json && (mf.json.schema === "weio.gateway/0" || mf.json.schema === "weio.gateway/1")) {
  const mctx = mf.json.join && mf.json.join.context;
  if (mctx !== undefined && mctx !== context) {
    log({ step: "manifest", error: "the manifest join context differs from the pinned context " + JSON.stringify(context) + "; refusing to join" });
    process.exit(1);
  }
  log({ step: "manifest", status: 200, publication_state: typeof mf.json.publication_state === "string" ? regValue(mf.json.publication_state) : null });
} else {
  log({ step: "manifest", status: mf.status });
}

// Key pair. The raw public key is the JWK "x" (base64url, 32 bytes).
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
const jwk = privateKey.export({ format: "jwk" });
const pub = jwk.x;
if (o["key-out"]) writeNew(o["key-out"], JSON.stringify({ kty: "OKP", crv: "Ed25519", x: jwk.x, d: jwk.d }, null, 2) + "\n");

const record = { participant_type: "agent", role: o.role, name: o.name, record_kind: o.kind, description: o.description, visibility: o.visibility };

// Call 2: create with the public key.
const c1 = await call("POST", "/api/participants", { ...record, public_key: pub });
if (c1.status !== 202) fail("create", c1);
const { id, nonce, sign } = c1.json;
if (typeof id !== "string" || typeof nonce !== "string" || sign !== `${context}|${id}|${nonce}`) {
  log({ step: "challenge", error: "the message to sign is not " + context + "|<id>|<nonce>; refusing to sign" });
  process.exit(1);
}

// Call 3: sign the UTF-8 bytes of `sign` and confirm.
const signature = b64u(edSign(null, Buffer.from(sign, "utf8"), privateKey));
const confirmBody = { id, nonce, signature };
const c2 = await call("POST", "/api/participants/confirm-key", confirmBody);
if (c2.status !== 200) fail("confirm-key", c2);
const token = c2.json.owner_token;
const reg = c2.json.receipt && typeof c2.json.receipt === "object" ? c2.json.receipt : {};
const str = (v) => (typeof v === "string" ? v : null);
if (typeof token !== "string" || token === "") {
  log({ step: "confirm-key", status: 200, error: "no owner token in the answer" });
  process.exit(1);
}

// The record is active now. Save the owner token FIRST, in an INCOMPLETE recovery file (not a receipt: the readback has not
// happened and the record is what was sent), so nothing later can lose it. The token is never printed.
const outFile = o["receipt-out"];
const recovery = {
  receipt_kind: RECOVERY_KIND,
  complete: false,
  incomplete_note: "INCOMPLETE: not a completed receipt. The readback of the stored record has not succeeded, and record_as_sent is what was sent, not what the registry stored.",
  registry: origin,
  gateway: "agent-join.mjs",
  id,
  status: str(c2.json.status),
  method: str(reg.method),
  activated_at: str(reg.at),
  public_key: pub,
  record_as_sent: record,
  owner_token: token,
};
const recoveryText = JSON.stringify(recovery, null, 2) + "\n";
try {
  writeNew(outFile, recoveryText);
} catch (e) {
  // The record is active and the token exists only in this process. Never print it: save a recovery file and print only its path.
  const alt = writeRecovery(outFile, recoveryText);
  if (alt) {
    emitErr("agent-join: the record " + regValue(id) + " may be active, but " + outFile + " could not be written (" + safe(e && e.code) + "). An incomplete recovery file with the owner token is saved in " + alt + " (mode 0600).");
  } else {
    emitErr("The record may be active, but no recovery file could be saved. The token is not included in this message.");
    log({ step: "receipt", id: regValue(id), error: "could not write " + outFile + " (" + safe(e && e.code) + ") or a recovery copy" });
  }
  process.exit(1);
}
// The note text is the accepted wording; "kind" names what the file is.
log({ step: "receipt", note: "interim receipt with the owner token saved (mode 0600); rewritten after a successful readback", kind: RECOVERY_KIND + " (incomplete recovery file, not a completed receipt)", file: outFile });

// The activation metadata must be complete (status active; receipt event, id, at, method) before anything is called complete.
const cp = ID_RE.test(id) ? confirmProblems(c2.json, id) : ["id"];
if (cp.length) {
  log({ step: "confirm-key", status: 200, error: "the confirm answer is not a complete ACTIVE activation (fields: " + cp.join(",") + ")" });
  emitErr("agent-join: the record " + regValue(id) + " may be active; the confirm answer was incomplete. An incomplete recovery file with the owner token (not a completed receipt) is saved in " + outFile + " (mode 0600).");
  process.exit(1);
}

// Readback with the owner token (works for private records too).
const rb = await call("GET", "/api/participants/" + encodeURIComponent(id), undefined, token);
const view = rb.status === 200 && rb.json && rb.json.participant && typeof rb.json.participant === "object" ? rb.json.participant : null;
const RECORD_KEYS = ["participant_type", "role", "name", "record_kind", "description", "visibility"];
const rbp = readbackProblems(view, id, pub);
// An answer that could not be checked for secrets never becomes a completed receipt on stdout.
if (rbp.length || UNCHECKED) {
  log({ step: "readback", status: rb.status, error: UNCHECKED ? WITHHELD : view ? "the readback is incomplete or invalid (fields: " + rbp.join(",") + ")" : regError(rb) });
  emitErr("agent-join: the record " + regValue(id) + ": activation was confirmed, but the readback failed. An incomplete recovery file with the owner token (not a completed receipt) is saved in " + outFile + " (mode 0600).");
  process.exit(1);
}

// The completed receipt takes everything about the record from the registry's stored readback (NFC, trimmed), never from the
// typed arguments. It is written only now, after a successful readback.
const receipt = {
  receipt_kind: RECEIPT_KIND,
  registry: origin,
  gateway: "agent-join.mjs",
  id: view.id,
  status: c2.json.status,
  method: reg.method,
  activated_at: reg.at,
  founding_seq: view.founding_seq === undefined ? null : view.founding_seq,
  verification: view.verification,
  public_key: view.public_key,
  record: Object.fromEntries(RECORD_KEYS.map((k) => [k, view[k]])),
  readback: { public: "/api/participants/" + view.id, profile: "/participants/" + view.id },
};
const shown = { ...receipt, owner_token: `<redacted len ${String(token).length}>` };
try {
  replaceOwn(outFile, JSON.stringify({ ...receipt, owner_token: token }, null, 2) + "\n");
} catch (e) {
  log({ step: "receipt", error: "could not write the completed receipt (" + safe(e && e.code) + "); " + outFile + " still holds the incomplete recovery file with the owner token" });
  process.exit(1);
}
emitOut(JSON.stringify(shown, null, 2));

let ok = true;
if (o["probe-replay"]) {
  const r = await call("POST", "/api/participants/confirm-key", confirmBody);
  const pass = r.status === 410;
  ok = ok && pass;
  log({ probe: "replay", status: r.status, expected: 410, pass });
}
if (o["probe-email"]) {
  const r = await call("POST", "/api/participants", { ...record, participant_type: "human", email: "probe@example.invalid" });
  const pass = r.status === 403;
  ok = ok && pass;
  log({ probe: "email", status: r.status, expected: 403, pass });
}
process.exit(ok ? 0 : 1);
