# agent_proof.sh: builds the Agent-Proof header for one request.
# Source it in bash, then call:
#   prove <signing key.pem> <METHOD> <path> <access token> [key file whose public part is sent]
# The header value is base64url JSON: pub (public key PEM, base64), sig (ECDSA signature
# over "METHOD, path, ts, jti, ath" joined by newlines, DER, base64), ts, jti, htm, htu, ath.
# Needs openssl, jq and tr. Generic demo, not AAuth.

b64url() { openssl base64 -A | tr '+/' '-_' | tr -d '='; }

prove() {
  local signkey="$1" htm="$2" htu="$3" token="$4" pubkey="${5:-$1}"
  local ts jti ath msg sig pub
  ts=$(date +%s)
  jti=$(openssl rand -hex 8)
  ath=$(printf '%s' "$token" | openssl dgst -sha256 -binary | b64url)
  msg=$(printf '%s\n%s\n%s\n%s\n%s' "$htm" "$htu" "$ts" "$jti" "$ath")
  sig=$(printf '%s' "$msg" | openssl dgst -sha256 -sign "$signkey" | openssl base64 -A)
  pub=$(openssl ec -in "$pubkey" -pubout 2>/dev/null | openssl base64 -A)
  jq -cn --arg pub "$pub" --arg sig "$sig" --arg jti "$jti" --arg htm "$htm" \
    --arg htu "$htu" --arg ath "$ath" --argjson ts "$ts" \
    '{pub: $pub, sig: $sig, ts: $ts, jti: $jti, htm: $htm, htu: $htu, ath: $ath}' | b64url
}

# Decode one part (header or payload) of a JWT, for reading the claims.
decode_part() {
  local s
  s=$(printf '%s' "$1" | tr '_-' '/+')
  while [ $(( ${#s} % 4 )) -ne 0 ]; do s="$s="; done
  printf '%s' "$s" | openssl base64 -d -A
}
