#!/usr/bin/env bash set -euo pipefail usage(){ echo "Usage: $0 INPUT [--evidence-root DIR]" >&2; exit 2; }; fail(){ echo "error: $*" >&2; exit 1; } sha256_file(){ if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1"|awk '{print $1}'; elif command -v sha256 >/dev/null 2>&1; then sha256 -q "$1"; else openssl dgst -sha256 "$1"|awk '{print $NF}'; fi; } json_string(){ local value=$1; [[ "$value" == \"*\" ]]||fail "Typst returned a non-string value"; value=${value:1:${#value}-2}; [[ "$value" != *\\* && "$value" != *\"* ]]||fail "unsupported escaped path"; printf '%s' "$value"; } input=${1:-}; [[ -n "$input" ]]||usage; shift; evidence_root= while (($#)); do case $1 in --evidence-root) (($#>=2))||usage; evidence_root=$2;shift 2;;*) usage;;esac; done root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P); input=$(realpath "$input") stage=$(mktemp -d "${TMPDIR:-/tmp}/diagnostic-validate.XXXXXXXX"); trap 'rm -rf "$stage"' EXIT cp "$input" "$stage/diagnostic.json"; cp "$root/tools/validate.typ" "$stage/validate.typ" typst query --root "$stage" --input diagnostic=diagnostic.json "$stage/validate.typ" '' --one >/dev/null 2>&1||fail "invalid diagnostic v1: $input" if [[ -n "$evidence_root" ]]; then artifact=$(json_string "$(typst query --root "$stage" --input diagnostic=diagnostic.json "$stage/validate.typ" '' --field value --one 2>/dev/null)") expected=$(json_string "$(typst query --root "$stage" --input diagnostic=diagnostic.json "$stage/validate.typ" '' --field value --one 2>/dev/null)") [[ "$artifact" != /* && "$artifact" != *..* ]]||fail "source artifact escapes evidence root" source=$(realpath "$evidence_root/$artifact"); evidence_base=$(realpath "$evidence_root") [[ "$source" == "$evidence_base"/* && -f "$source" ]]||fail "source artifact escapes evidence root" [[ $(sha256_file "$source") == "$expected" ]]||fail "evidence checksum differs" cp "$source" "$stage/raw.json"; cp "$root/tools/verify-evidence.typ" "$stage/verify-evidence.typ" typst query --root "$stage" --input diagnostic=diagnostic.json --input raw=raw.json "$stage/verify-evidence.typ" '' --one >/dev/null 2>&1||fail "observation differs from referenced raw evidence" fi echo "Valid diagnostic v1: $input"