#!/bin/sh
# OffRouter post-quantum check (https://offrouter.org/pq). Read it before you run it: it only reads.
#   1. Does your connection to offrouter.org negotiate the hybrid X25519MLKEM768 key exchange?
#   2. Which end-to-end encryption keys do the model enclaves offer right now, and with which algorithm?
#   3. Does private web search offer a hybrid post-quantum key (X-Wing) for its end-to-end encryption?
# Needs OpenSSL 3.5+ (macOS: brew install openssl@3, then OPENSSL=$(brew --prefix openssl@3)/bin/openssl),
# curl, and jq for step 2.
set -u
HOST=${HOST:-offrouter.org}
OPENSSL=${OPENSSL:-openssl}

echo "1. TLS key exchange with $HOST"
version=$("$OPENSSL" version 2>/dev/null || true)
echo "   using: ${version:-no openssl found}"
case "$version" in
  "OpenSSL 3."[5-9]*|"OpenSSL 3."[1-9][0-9]*|"OpenSSL "[4-9]*) ;;
  *) echo "   needs OpenSSL 3.5 or newer for ML-KEM. Set OPENSSL=/path/to/openssl and run again."; exit 1 ;;
esac
out=$("$OPENSSL" s_client -connect "$HOST:443" -servername "$HOST" -groups X25519MLKEM768 -brief </dev/null 2>&1)
if printf '%s' "$out" | grep -qi 'X25519MLKEM768'; then
  echo "   hybrid post-quantum: X25519MLKEM768 negotiated"
else
  echo "   X25519MLKEM768 was NOT negotiated. Handshake output:"
  printf '%s\n' "$out" | sed 's/^/     /' | head -20
fi

echo
echo "2. End-to-end encryption keys the enclave offers"
if ! command -v jq >/dev/null 2>&1; then echo "   needs jq"; exit 1; fi
nonce=$("$OPENSSL" rand -hex 32)
curl -fsS "https://$HOST/v1/private/attestation?nonce=$nonce" \
  | jq -r '.attestation.workload_keyset.e2ee_public_keys[] | "   \(.key_id)  \(.algo)"'
echo "   x25519 / secp256k1 keys use a classical key exchange. A hybrid key appears here when it ships."
echo "   To check a key really lives in the enclave (quote, nonce, key set binding): https://$HOST/proof"

echo
echo "3. Private web search: end-to-end encryption keys"
curl -fsS "https://$HOST/v1/web" \
  | jq -r '"   v2  \(.e2ee.algo)", (if .e2ee_hybrid then "   v3  \(.e2ee_hybrid.algo)  key_id \(.e2ee_hybrid.key_id)  (hybrid post-quantum)" else "   no hybrid key offered yet" end)'
echo "   Each key is signed by the gateway enclave's signer, which its hardware quote names: https://$HOST/v1/web/attestation"
