#!/usr/bin/env python3
"""
Independently verify a GradiumOS Signal.

Checks the Ed25519 signature YOURSELF against the public key GradiumOS
publishes — you do not trust the server's verdict. If it prints
`signature valid : True`, the Signal was issued by the holder of the
GradiumOS signing key and has not been altered.

WHAT A SIGNATURE CANNOT TELL YOU: REVOCATION.

    A signature proves ISSUANCE and INTEGRITY. It cannot prove CURRENT
    VALIDITY. Revocation and expiry are SERVER-CHECKED properties, read
    from the proof wrapper's `state`.

17-08-2026: a revoked token checked here printed `signature valid : True`
beside a signed claim reading `"status": "active"`, with nothing saying the
two disagreed. The claim is not wrong — its `status` is the status at the
moment of issuance, and it must be, because those exact bytes are what the
signature covers. Revoking a Signal cannot rewrite them without destroying
the signature. So this script compares the two and warns loudly when they
differ; a signature check ALONE would pass a revoked credential.

Usage:
    python verify.py "GOS·SIOSA·BCAML·26·0012·STEKY"
    python verify.py "gs1.<signal-id>"

Requires: `cryptography` (pip install cryptography). Python >= 3.8.
"""
import base64
import json
import sys
import urllib.parse
import urllib.request

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.exceptions import InvalidSignature

API = "https://verify.veranox.in"


def get_json(url: str):
    with urllib.request.urlopen(url) as r:
        return json.loads(r.read().decode())


def b64url_decode(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def main() -> int:
    if len(sys.argv) < 2:
        print('usage: python verify.py "<GOS code or gs1.token>"')
        return 2
    token = sys.argv[1]

    jwks = get_json(f"{API}/.well-known/jwks.json")
    proof = get_json(
        f"{API}/api/v1/signal/proof?token={urllib.parse.quote(token)}"
    )["data"]

    if not proof or proof.get("state") in ("malformed", "not_found", "unsupported"):
        print("NOT A VALID SIGNAL:", proof.get("state") if proof else "unknown")
        return 1

    jwk = next((k for k in jwks["keys"] if k["kid"] == proof["kid"]), None)
    if jwk is None:
        print("No published key for kid=", proof["kid"])
        return 1

    public_key = Ed25519PublicKey.from_public_bytes(b64url_decode(jwk["x"]))
    try:
        public_key.verify(
            b64url_decode(proof["signature"]),
            proof["canonical"].encode("utf-8"),
        )
        signature_valid = True
    except InvalidSignature:
        signature_valid = False

    # Two statuses, two different questions. `state` is a live server lookup;
    # `claim["status"]` is frozen into the signed bytes at issuance.
    server_state = proof["state"]
    claim_status = (proof.get("claim") or {}).get("status", "(absent)")

    print("kid                    :", proof["kid"])
    print("signature valid        :", signature_valid)
    print("live status (server)   :", server_state)
    print(
        "status inside the claim:",
        f"{claim_status}  (as at issuance — the signature freezes it)",
    )
    print()
    print("WHAT THIS PROVES : the signature proves ISSUANCE and INTEGRITY —")
    print("                   these bytes were signed by the GradiumOS key and")
    print("                   have not been altered. It CANNOT prove current")
    print("                   validity. Revocation and expiry are server-checked")
    print('                   properties, read from "live status" above.')

    if claim_status == "active" and server_state != "valid":
        print()
        print("!!! ================================================================ !!!")
        print(f'!!! THE TWO STATUSES DISAGREE: server says "{server_state}", the signed')
        print('!!! claim says "active". THE SERVER IS RIGHT ABOUT CURRENT VALIDITY.')
        print("!!!")
        print("!!! DO NOT ACCEPT THIS CREDENTIAL. It was validly issued and has not")
        print(f"!!! been tampered with — and it is {server_state} now. The signature")
        print("!!! cannot say so: revoking a Signal cannot rewrite the bytes that")
        print("!!! were signed without destroying the signature itself. A check of")
        print("!!! the signature ALONE, with no server lookup, would have passed it.")
        print("!!! ================================================================ !!!")

    print()
    print("signed claim     :", json.dumps(proof["claim"], indent=2))
    # Two conditions because two questions. signature_valid alone is not a pass.
    return 0 if signature_valid and server_state == "valid" else 1


if __name__ == "__main__":
    sys.exit(main())
