proof-cli 1.0.0

Command-line interface for creating, verifying, and evaluating Proof Engine proofs
Documentation
// Copyright 2026 Proof Engine Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! proof-cli: command-line front end over the library crates (Phase 7).
//! Adds no trust logic of its own: every artifact is re-verified on load,
//! every time input is an explicit flag, keys are supplied per invocation.

pub mod artifact;
pub mod check;
pub mod demo;
pub mod make;

use std::collections::{HashMap, HashSet};

/// Exit codes: 0 PASS, 1 FAIL/INDETERMINATE verdict, 2 usage or engine error.
pub const EXIT_OK: i32 = 0;
pub const EXIT_FAIL: i32 = 1;
pub const EXIT_ERR: i32 = 2;

/// Parsed command line: subcommand + positional args + `--flag value` flags.
/// Deliberately hand-rolled (no new dependencies in V0.1).
#[derive(Debug, Default)]
pub struct Cli {
    pub command: String,
    pub positional: Vec<String>,
    values: HashMap<String, String>,
    multi: HashMap<String, Vec<String>>,
    flags: HashSet<String>,
}

impl Cli {
    pub fn parse(args: &[String]) -> Result<Cli, String> {
        let mut it = args.iter().peekable();
        let command = it
            .next()
            .ok_or_else(|| "missing command (try `help`)".to_string())?
            .clone();
        let mut cli = Cli {
            command,
            ..Cli::default()
        };
        while let Some(a) = it.next() {
            let Some(name) = a.strip_prefix("--") else {
                cli.positional.push(a.clone());
                continue;
            };
            let (name, inline) = match name.split_once('=') {
                Some((n, v)) => (n.to_string(), Some(v.to_string())),
                None => (name.to_string(), None),
            };
            // A `--flag` with no inline value takes the next token as its
            // value only when that token does not look like another flag.
            // Peek first: a boolean flag must never swallow `--other` tokens.
            let value = match inline {
                Some(v) => v,
                None => match it.peek() {
                    Some(v) if !v.starts_with("--") => it.next().unwrap().clone(),
                    _ => {
                        // Boolean flag (no value).
                        cli.flags.insert(name);
                        continue;
                    }
                },
            };
            cli.multi
                .entry(name.clone())
                .or_default()
                .push(value.clone());
            cli.values.insert(name, value);
        }
        Ok(cli)
    }
    /// Value of a required flag.
    pub fn req(&self, name: &str) -> Result<String, String> {
        self.values
            .get(name)
            .cloned()
            .ok_or_else(|| format!("missing required flag --{name}"))
    }

    /// Value of an optional flag.
    pub fn opt(&self, name: &str) -> Option<String> {
        self.values.get(name).cloned()
    }

    /// All values of a repeatable flag, in order.
    pub fn many(&self, name: &str) -> Vec<String> {
        self.multi.get(name).cloned().unwrap_or_default()
    }

    /// True when a boolean flag was present.
    pub fn has(&self, name: &str) -> bool {
        self.flags.contains(name)
    }

    /// True when --quiet is set (suppress progress output).
    pub fn quiet(&self) -> bool {
        self.has("quiet")
    }

    /// Required u64 flag.
    pub fn req_u64(&self, name: &str) -> Result<u64, String> {
        self.req(name)?
            .parse()
            .map_err(|_| format!("--{name} must be a u64"))
    }

    /// Optional u64 flag.
    pub fn opt_u64(&self, name: &str) -> Result<Option<u64>, String> {
        match self.opt(name) {
            None => Ok(None),
            Some(v) => v
                .parse()
                .map(Some)
                .map_err(|_| format!("--{name} must be a u64")),
        }
    }
}

/// Parse `k=v[,k=v…]` into flat metadata / claim fields. Values are text,
/// `true`/`false`, or unsigned integers (matching the closed MetaValue set).
pub fn parse_fields(
    spec: Option<String>,
) -> Result<Vec<(String, proof_core::model::MetaValue)>, String> {
    let Some(spec) = spec else {
        return Ok(vec![]);
    };
    let mut out = vec![];
    for pair in spec.split(',') {
        let Some((k, v)) = pair.split_once('=') else {
            return Err(format!("bad field `{pair}` (expected k=v)"));
        };
        if k.is_empty() || v.is_empty() {
            return Err(format!("bad field `{pair}` (empty key or value)"));
        }
        let mv = if v == "true" {
            proof_core::model::MetaValue::Bool(true)
        } else if v == "false" {
            proof_core::model::MetaValue::Bool(false)
        } else if let Ok(n) = v.parse::<u64>() {
            proof_core::model::MetaValue::Uint(n)
        } else {
            proof_core::model::MetaValue::Text(v.to_string())
        };
        out.push((k.to_string(), mv));
    }
    Ok(out)
}

/// Load an Ed25519 key from `--seed`: `test` selects the fixed test key
/// (fixtures/demos ONLY); otherwise 64 hex chars = 32 seed bytes.
pub fn load_key(seed: &str) -> Result<proof_crypto::Ed25519Key, String> {
    load_key_material(seed, "--seed")
}

fn load_key_material(seed: &str, what: &str) -> Result<proof_crypto::Ed25519Key, String> {
    if seed == "test" {
        return Ok(proof_crypto::build::fixtures::test_key());
    }
    let bytes = hex::decode(seed).map_err(|e| format!("{what} bad hex: {e}"))?;
    let arr: [u8; 32] = bytes
        .try_into()
        .map_err(|_| format!("{what} must be `test` or 64 hex chars (32 bytes)"))?;
    Ok(proof_crypto::Ed25519Key::from_seed(&arr))
}

/// Load a key for commands taking `--seed`/`--seed-file`. `--seed-file`
/// reads the seed from a file (capped by MAX_INPUT_FILE_BYTES) so raw key
/// material never lands in argv, shell history, or process listings;
/// `--seed` keeps working for demos/tests. The two flags must not combine.
pub fn load_key_opt(cli: &Cli) -> Result<proof_crypto::Ed25519Key, String> {
    match (cli.opt("seed"), cli.opt("seed-file")) {
        (Some(_), Some(_)) => Err("--seed and --seed-file are mutually exclusive".into()),
        (None, Some(path)) => {
            let seed = read_input_file(&path)?;
            load_key_material(seed.trim(), "--seed-file")
        }
        (Some(seed), None) => load_key(&seed),
        (None, None) => Err("missing required flag --seed (or --seed-file)".into()),
    }
}

pub fn limits() -> proof_core::Limits {
    proof_core::Limits::default()
}

/// Print progress to stderr unless --quiet is set.
pub fn progress(quiet: bool, msg: &str) {
    if !quiet {
        eprintln!("{msg}");
    }
}

/// Cap for any file the CLI reads (artifacts, proofs, policies). Well above
/// the largest legitimate input (1 MiB proof → ~2 MiB hex JSON): oversized
/// files are refused with a clean error instead of being buffered without
/// bound (Phase 7 hostile review H1).
pub const MAX_INPUT_FILE_BYTES: u64 = 8 << 20;

/// Read a CLI input file with the size cap enforced during buffering (no
/// TOCTOU window: at most one byte over the cap is ever read).
// PE-SEC-002: 8 MiB cap enforced during buffering.
pub fn read_input_file(path: &str) -> Result<String, String> {
    use std::io::Read;
    let mut f = std::fs::File::open(path).map_err(|e| format!("read {path}: {e}"))?;
    let mut buf = Vec::new();
    f.by_ref()
        .take(MAX_INPUT_FILE_BYTES + 1)
        .read_to_end(&mut buf)
        .map_err(|e| format!("read {path}: {e}"))?;
    if buf.len() as u64 > MAX_INPUT_FILE_BYTES {
        return Err(format!(
            "{path}: file too large (>{MAX_INPUT_FILE_BYTES} bytes)"
        ));
    }
    String::from_utf8(buf).map_err(|_| format!("{path}: invalid UTF-8"))
}

pub const USAGE: &str = "\
proof-cli — Proof Engine command line (V1.0)

Exit codes: 0 = PASS/valid, 1 = FAIL/INDETERMINATE verdict, 2 = usage or engine error.
All commands accept --quiet to suppress progress output on stderr.

Creation commands (write JSON artifact files wrapping canonical CBOR bytes):
  create-event --type <event.type> --subject <id> --effective-at <u64>
               --payload-hex <64 hex> [--meta k=v,...] --out <file>
  attest       --seed <test|64hex> --subject <id> --claim-type <t> [--claim k=v,...]
               --issued-at <u64> [--expires-at <u64>] [--evidence-ref <id>] --out <file>
  add-evidence --kind <kind> --digest-hex <64 hex> [--attestation-ref <id>] [--hint <t>]
               --out <file>
  relate       --from <id> --type <TYPE> --to <id> [--evidence-ref <id>]
               [--attestation-ref <id>] --out <file>
  build        --kind <t> --subject <s> --predicate <p> [--object <o>] [--at-time <u64>]
               [--context k=v,...] --created-at <u64> --events <f[,f…]>
               --attestations <f[,f…]> --evidence <f[,f…]> --relationships <f[,f…]>
               --out <file>
  revoke       --seed <test|64hex> --target <id> [--reason <t>] --at <u64> --out <file>
  supersede    --seed <test|64hex> --old <id> --new <id> --at <u64> --out <file>

Verification commands:
  verify       --proof <file> --clock <u64> [--skew <u64=300>]
               [--revocations-known-at <u64>] [--status <file>]… [--authority <keyref>]…
  evaluate     --proof <file> --policy <file> --clock <u64> [--skew <u64=300>]
               [--trusted <keyref>]… [--revoked <id,id,…>] [--revocations-known-at <u64>]
                [--json] — machine-readable policy_outcome + report JSON on stdout
  explain      (same flags as evaluate; prints the full explanation)

  demo         [--out <dir>=demo/out] — deterministic end-to-end killer use-case
  help         — this text

Artifacts are JSON wrappers around canonical CBOR bytes (hex); bytes are
re-verified on every load — ids recomputed, signatures checked. Seeds are for
demos/tests only; production key handling is out of scope for V1.0.
Prefer --seed-file <path> over --seed <hex>: raw key material in argv is
visible to ps(1) and shell history; the two flags never combine.";