"""Opaque keyset cursors: HMAC-protected (created_at, id) plus a resource scope.""" from __future__ import annotations import base64 import binascii import datetime as dt import hashlib import hmac import json import uuid VERSION = 1 MAC_BYTES = 16 class InvalidCursor(ValueError): """Cursor is malformed, forged, expired or belongs to another resource.""" def _key(secret): return hashlib.sha256(b'mtusi-messenger-cursor-v1' + secret).digest() def encode(scope, created_at, object_id, secret): """Serialize a keyset position bound to one resource scope.""" payload = json.dumps( {'v': VERSION, 'scope': scope, 'created_at': created_at, 'id': str(object_id)}, separators=(',', ':'), sort_keys=True).encode('utf-8') mac = hmac.new(_key(secret), payload, hashlib.sha256).digest()[:MAC_BYTES] return base64.urlsafe_b64encode(payload + mac).decode('ascii').rstrip('=') def decode(token, scope, secret): """Return (created_at datetime, uuid) or raise InvalidCursor.""" if not isinstance(token, str) or not token: raise InvalidCursor('empty cursor') padding = '=' * (-len(token) % 4) try: raw = base64.urlsafe_b64decode(token + padding) except (binascii.Error, ValueError): raise InvalidCursor('cursor is not base64url') from None if len(raw) <= MAC_BYTES: raise InvalidCursor('cursor is too short') payload, mac = raw[:-MAC_BYTES], raw[-MAC_BYTES:] if not hmac.compare_digest(mac, hmac.new(_key(secret), payload, hashlib.sha256).digest()[:MAC_BYTES]): raise InvalidCursor('cursor signature mismatch') try: data = json.loads(payload.decode('utf-8')) except (ValueError, UnicodeError): raise InvalidCursor('cursor payload is not JSON') from None if not isinstance(data, dict) or data.get('v') != VERSION: raise InvalidCursor('unsupported cursor version') if data.get('scope') != scope: raise InvalidCursor('cursor belongs to another resource') created_at = data.get('created_at') object_id = data.get('id') if not isinstance(created_at, str) or not isinstance(object_id, str): raise InvalidCursor('cursor payload types') try: stamp = dt.datetime.fromisoformat(created_at.replace('Z', '+00:00')) identifier = uuid.UUID(object_id) except ValueError: raise InvalidCursor('cursor payload values') from None if stamp.tzinfo is None: raise InvalidCursor('cursor timestamp has no timezone') return stamp.astimezone(dt.timezone.utc), identifier