"""Short-reference registry for interactive buttons. QQ caps a button's action.data at 100 bytes and Telegram caps callback_data at 64, so the real callback payload can never travel inside the button itself. The gateway hands out an opaque short reference instead and keeps the payload here. A reference is single-use by default and pinned to one user, mirroring the guarantees the QQ protocol already offers (click_limit / specify_user_ids) so behaviour stays consistent on platforms that do not enforce them. References live in memory only: after a restart every outstanding button reports "已失效", which is the safe direction — a stale approval must never silently succeed. """ from __future__ import annotations import re import secrets import time from dataclasses import dataclass, field from typing import Any # g1.<12 chars>.<24 hex> -> 39 bytes. With the "bg::" prefix the worst case stays # under Telegram's 64-byte callback_data limit, which is the tighter of the two platforms. REF_RE = re.compile(r"^g1\.[A-Za-z0-9_-]{12}\.[0-9a-f]{24}$") ACTION_RE = re.compile(r"^[a-z][a-z0-9_-]{0,15}$") DEFAULT_TTL_SECONDS = 600 MAX_ENTRIES = 512 @dataclass class Entry: ref: str owner: str handler: str payload: dict[str, Any] allowed_user_id: str | None expires_at: float single_use: bool = True consumed: bool = False actions: tuple[str, ...] = field(default_factory=tuple) class ButtonRegistry: def __init__(self, *, clock=time.monotonic) -> None: self._entries: dict[str, Entry] = {} self._clock = clock @staticmethod def new_ref() -> str: return f"g1.{secrets.token_urlsafe(9)[:12]}.{secrets.token_hex(12)}" def issue( self, *, owner: str, handler: str, payload: dict[str, Any], actions: tuple[str, ...], allowed_user_id: str | None = None, ttl_seconds: int = DEFAULT_TTL_SECONDS, single_use: bool = True, ) -> str: if not owner or not handler: raise ValueError("owner 与 handler 不能为空") if not actions: raise ValueError("至少要有一个 action") for action in actions: if not ACTION_RE.fullmatch(action): raise ValueError(f"非法 action: {action!r}") ttl = max(30, min(int(ttl_seconds), 24 * 3600)) self.purge() if len(self._entries) >= MAX_ENTRIES: # Drop the entry closest to expiry rather than refusing service. oldest = min(self._entries.values(), key=lambda e: e.expires_at) self._entries.pop(oldest.ref, None) ref = self.new_ref() self._entries[ref] = Entry( ref=ref, owner=owner, handler=handler, payload=dict(payload or {}), allowed_user_id=str(allowed_user_id) if allowed_user_id else None, expires_at=self._clock() + ttl, single_use=bool(single_use), actions=tuple(actions), ) return ref def purge(self) -> int: now = self._clock() stale = [ref for ref, e in self._entries.items() if e.expires_at <= now] for ref in stale: self._entries.pop(ref, None) return len(stale) def peek(self, ref: str) -> Entry | None: entry = self._entries.get(ref) if entry is None: return None if entry.expires_at <= self._clock(): self._entries.pop(ref, None) return None return entry def claim(self, ref: str, action: str, user_id: str | None) -> tuple[Entry | None, str]: """Validate a click. Returns (entry, reason); entry is None when the click is rejected.""" if not REF_RE.fullmatch(str(ref or "")): return None, "invalid_ref" entry = self.peek(ref) if entry is None: return None, "expired" if action not in entry.actions: return None, "unknown_action" if entry.allowed_user_id and str(user_id or "") != entry.allowed_user_id: return None, "forbidden" if entry.consumed: return entry, "already_consumed" if entry.single_use: entry.consumed = True self._entries.pop(ref, None) return entry, "ok" def revoke(self, ref: str) -> bool: return self._entries.pop(ref, None) is not None def __len__(self) -> int: return len(self._entries)