1import base64
2import hashlib
3import hmac
4import os
5import time
6
7from cryptography.hazmat.primitives.ciphers.aead import AESGCM
8
9_NONCE_BYTES = 12
10
11# Domain separator — the verifier (a Cloudflare Worker, not Python) must
12# prepend the exact same tag before HMAC. Lets the same secret sign other
13# message kinds later without confusion. If you change this string, update
14# the Worker side in lockstep.
15_RENDER_TOKEN_TAG = "render-token:"
16
17
18def _derive_key(secret: str) -> bytes:
19 # Plain SHA-256 (no salt/HKDF) because `secret` is a high-entropy
20 # server-generated value, not a user password.
21 return hashlib.sha256(secret.encode()).digest()
22
23
24def encrypt_identity(user_id: int | str, secret: str) -> str:
25 """AES-256-GCM-encrypt a user id. Returns base64url(nonce + ciphertext + tag)."""
26 key = _derive_key(secret)
27 nonce = os.urandom(_NONCE_BYTES)
28 ciphertext = AESGCM(key).encrypt(nonce, str(user_id).encode(), None)
29 return base64.urlsafe_b64encode(nonce + ciphertext).decode()
30
31
32def sign_render_token(secret: str, *, now: int | None = None) -> str:
33 """Sign a fresh render timestamp. Returns `<unix_seconds>.<hex_hmac_sha256>`, or `""` when no secret."""
34 if not secret:
35 return ""
36 ts = int(now if now is not None else time.time())
37 message = (_RENDER_TOKEN_TAG + str(ts)).encode()
38 mac = hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()
39 return f"{ts}.{mac}"