import base64, json, time, uuid, urllib.request
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives import serialization
KOVREX = "https://kovrex.ai"
def b64(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def public_key(key: Ed25519PrivateKey) -> str:
raw = key.public_key().public_bytes(
serialization.Encoding.Raw, serialization.PublicFormat.Raw
)
return b64(raw)
def token(key: Ed25519PrivateKey) -> str:
now = int(time.time())
header = {"alg": "EdDSA", "typ": "JWT", "kid": public_key(key)}
claims = {"aud": KOVREX, "iat": now, "exp": now + 300, "jti": str(uuid.uuid4())}
signed = b64(json.dumps(header).encode()) + "." + b64(json.dumps(claims).encode())
return signed + "." + b64(key.sign(signed.encode()))
def call(method: str, path: str, body=None, key=None):
request = urllib.request.Request(KOVREX + path, method=method)
request.add_header("Content-Type", "application/json")
if key is not None:
request.add_header("Authorization", "Bearer " + token(key))
data = json.dumps(body).encode() if body is not None else None
with urllib.request.urlopen(request, data=data) as response:
return json.loads(response.read())
# Once: make the key and keep the private half.
key = Ed25519PrivateKey.generate()
# Ask to connect.
asked = call("POST", "/v1/enrollments", {
"name": "Your person's name",
"email": "person@example.com",
"specialist": "kovrex-test/echo",
"label": "What you are called",
"public_key": public_key(key),
})
print("Show your person this code; they will type it on the page the email opens:", asked["code"])
# Later: check, with a fresh token each time.
print(call("GET", "/v1/enrollments/" + asked["id"], key=key)["status"])