|
| 1 | +"""Callback URL handling for buttons and modals. |
| 2 | +
|
| 3 | +Python port of callback-url.ts (vercel/chat#454). |
| 4 | +
|
| 5 | +When a button (or modal) carries a ``callback_url``, the SDK stores the URL |
| 6 | +in the state adapter under a short random token at post time and rewrites |
| 7 | +the button's ``value`` to an encoded token (``__cb:<token>``). When the |
| 8 | +button is clicked, :meth:`Chat.process_action` decodes the token, restores |
| 9 | +the original value for handlers, and POSTs the action payload to the stored |
| 10 | +URL. Modal callback URLs are stored in the modal context and POSTed on |
| 11 | +submit. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import json |
| 17 | +import secrets |
| 18 | +from dataclasses import dataclass |
| 19 | +from typing import Any |
| 20 | + |
| 21 | +from chat_sdk.cards import ActionsElement, ButtonElement, CardChild, CardElement |
| 22 | +from chat_sdk.errors import ChatError |
| 23 | +from chat_sdk.types import StateAdapter |
| 24 | + |
| 25 | +CALLBACK_TOKEN_PREFIX = "__cb:" |
| 26 | +CALLBACK_CACHE_KEY_PREFIX = "chat:callback:" |
| 27 | +CALLBACK_TTL_MS = 30 * 24 * 60 * 60 * 1000 # 30 days |
| 28 | + |
| 29 | + |
| 30 | +# --------------------------------------------------------------------------- |
| 31 | +# Result types (TS uses inline object literals; port rule #9: typed objects) |
| 32 | +# --------------------------------------------------------------------------- |
| 33 | + |
| 34 | + |
| 35 | +@dataclass(frozen=True) |
| 36 | +class DecodedCallbackValue: |
| 37 | + """Result of :func:`decode_callback_value`.""" |
| 38 | + |
| 39 | + callback_token: str | None |
| 40 | + |
| 41 | + |
| 42 | +@dataclass(frozen=True) |
| 43 | +class ResolvedCallback: |
| 44 | + """A stored callback resolved from the state adapter.""" |
| 45 | + |
| 46 | + url: str |
| 47 | + original_value: str | None = None |
| 48 | + |
| 49 | + |
| 50 | +@dataclass(frozen=True) |
| 51 | +class CallbackPostResult: |
| 52 | + """Result of :func:`post_to_callback_url`.""" |
| 53 | + |
| 54 | + error: Exception | None = None |
| 55 | + status: int | None = None |
| 56 | + |
| 57 | + |
| 58 | +# --------------------------------------------------------------------------- |
| 59 | +# Token encoding |
| 60 | +# --------------------------------------------------------------------------- |
| 61 | + |
| 62 | + |
| 63 | +def encode_callback_value(token: str) -> str: |
| 64 | + """Encode a callback token into a button value.""" |
| 65 | + return f"{CALLBACK_TOKEN_PREFIX}{token}" |
| 66 | + |
| 67 | + |
| 68 | +def decode_callback_value(value: str | None) -> DecodedCallbackValue: |
| 69 | + """Extract the callback token from an encoded button value, if any.""" |
| 70 | + if not value or not value.startswith(CALLBACK_TOKEN_PREFIX): |
| 71 | + return DecodedCallbackValue(callback_token=None) |
| 72 | + return DecodedCallbackValue(callback_token=value[len(CALLBACK_TOKEN_PREFIX) :]) |
| 73 | + |
| 74 | + |
| 75 | +def _generate_token() -> str: |
| 76 | + # Upstream: crypto.randomUUID().replace(/-/g, "").slice(0, 16). |
| 77 | + # Port rule #12: the token gates where action payloads are POSTed, so |
| 78 | + # use `secrets` (16 hex chars = 64 bits, same shape as upstream). |
| 79 | + return secrets.token_hex(8) |
| 80 | + |
| 81 | + |
| 82 | +# --------------------------------------------------------------------------- |
| 83 | +# Card processing (runs at post time) |
| 84 | +# --------------------------------------------------------------------------- |
| 85 | + |
| 86 | + |
| 87 | +async def _process_actions_element( |
| 88 | + actions: ActionsElement, |
| 89 | + state_adapter: StateAdapter, |
| 90 | +) -> ActionsElement: |
| 91 | + children: list[Any] = [] |
| 92 | + for el in actions.get("children", []): |
| 93 | + if not isinstance(el, dict) or el.get("type") != "button" or not el.get("callback_url"): |
| 94 | + children.append(el) |
| 95 | + continue |
| 96 | + |
| 97 | + token = _generate_token() |
| 98 | + # Stored shape matches the TS SDK (`{url, originalValue}`) so state |
| 99 | + # written by either SDK resolves in both. `originalValue` is omitted |
| 100 | + # (not None) when the button has no value — hazard #7. |
| 101 | + stored: dict[str, Any] = {"url": el["callback_url"]} |
| 102 | + original_value = el.get("value") |
| 103 | + if original_value is not None: |
| 104 | + stored["originalValue"] = original_value |
| 105 | + await state_adapter.set(f"{CALLBACK_CACHE_KEY_PREFIX}{token}", stored, CALLBACK_TTL_MS) |
| 106 | + |
| 107 | + # Rebuild the button without `callback_url` (mirrors upstream's |
| 108 | + # explicit-key copy; keys absent on the source stay absent). |
| 109 | + processed: ButtonElement = {"type": "button", "id": el["id"], "label": el["label"]} |
| 110 | + if "style" in el: |
| 111 | + processed["style"] = el["style"] |
| 112 | + if "disabled" in el: |
| 113 | + processed["disabled"] = el["disabled"] |
| 114 | + processed["value"] = encode_callback_value(token) |
| 115 | + if "action_type" in el: |
| 116 | + processed["action_type"] = el["action_type"] |
| 117 | + children.append(processed) |
| 118 | + return {"type": "actions", "children": children} |
| 119 | + |
| 120 | + |
| 121 | +def _has_callback_buttons(children: list[CardChild]) -> bool: |
| 122 | + for child in children: |
| 123 | + if not isinstance(child, dict): |
| 124 | + continue |
| 125 | + if child.get("type") == "actions": |
| 126 | + for el in child.get("children", []): |
| 127 | + if isinstance(el, dict) and el.get("type") == "button" and el.get("callback_url"): |
| 128 | + return True |
| 129 | + if child.get("type") == "section" and "children" in child and _has_callback_buttons(child["children"]): |
| 130 | + return True |
| 131 | + return False |
| 132 | + |
| 133 | + |
| 134 | +async def _process_children( |
| 135 | + children: list[CardChild], |
| 136 | + state_adapter: StateAdapter, |
| 137 | +) -> list[CardChild]: |
| 138 | + result: list[CardChild] = [] |
| 139 | + for child in children: |
| 140 | + if isinstance(child, dict) and child.get("type") == "actions": |
| 141 | + result.append(await _process_actions_element(child, state_adapter)) # type: ignore[arg-type] |
| 142 | + elif isinstance(child, dict) and child.get("type") == "section" and "children" in child: |
| 143 | + result.append({**child, "children": await _process_children(child["children"], state_adapter)}) # type: ignore[misc] |
| 144 | + else: |
| 145 | + result.append(child) |
| 146 | + return result |
| 147 | + |
| 148 | + |
| 149 | +async def process_card_callback_urls( |
| 150 | + card: CardElement, |
| 151 | + state_adapter: StateAdapter, |
| 152 | +) -> CardElement: |
| 153 | + """Replace ``callback_url`` buttons with encoded token values. |
| 154 | +
|
| 155 | + Returns the *same* card object when no button carries a callback URL; |
| 156 | + otherwise returns a new card (the original is never mutated). |
| 157 | + """ |
| 158 | + if not _has_callback_buttons(card.get("children", [])): |
| 159 | + return card |
| 160 | + |
| 161 | + return {**card, "children": await _process_children(card.get("children", []), state_adapter)} |
| 162 | + |
| 163 | + |
| 164 | +# --------------------------------------------------------------------------- |
| 165 | +# Resolution + POST (runs at click/submit time) |
| 166 | +# --------------------------------------------------------------------------- |
| 167 | + |
| 168 | + |
| 169 | +async def resolve_callback_url( |
| 170 | + token: str, |
| 171 | + state_adapter: StateAdapter, |
| 172 | +) -> ResolvedCallback | None: |
| 173 | + """Look up a stored callback by token. Returns ``None`` when unknown.""" |
| 174 | + stored = await state_adapter.get(f"{CALLBACK_CACHE_KEY_PREFIX}{token}") |
| 175 | + if not stored: |
| 176 | + return None |
| 177 | + if isinstance(stored, str): |
| 178 | + # Legacy format: the URL was stored as a bare string. |
| 179 | + return ResolvedCallback(url=stored) |
| 180 | + original_value = stored["originalValue"] if "originalValue" in stored else stored.get("original_value") |
| 181 | + return ResolvedCallback(url=stored.get("url"), original_value=original_value) |
| 182 | + |
| 183 | + |
| 184 | +async def _fetch(url: str, *, method: str, headers: dict[str, str], body: str) -> tuple[int, str]: |
| 185 | + """POST ``body`` to ``url`` and return ``(status, text)``. |
| 186 | +
|
| 187 | + Thin seam over aiohttp so tests can stub the network the way upstream |
| 188 | + stubs global ``fetch``. aiohttp is an optional dependency, so it is |
| 189 | + imported lazily (hazard #10); only http(s) URLs are supported, matching |
| 190 | + the WHATWG ``fetch`` upstream relies on. |
| 191 | + """ |
| 192 | + import aiohttp |
| 193 | + |
| 194 | + async with ( |
| 195 | + aiohttp.ClientSession() as session, |
| 196 | + session.request(method, url, data=body.encode("utf-8"), headers=headers) as response, |
| 197 | + ): |
| 198 | + try: |
| 199 | + text = await response.text() |
| 200 | + except Exception: |
| 201 | + # Mirrors upstream's `response.text().catch(() => "")`. |
| 202 | + text = "" |
| 203 | + return response.status, text |
| 204 | + |
| 205 | + |
| 206 | +async def post_to_callback_url( |
| 207 | + callback_url: str, |
| 208 | + payload: dict[str, Any], |
| 209 | +) -> CallbackPostResult: |
| 210 | + """POST a JSON payload to a callback URL. |
| 211 | +
|
| 212 | + Never raises: network and HTTP errors are returned in |
| 213 | + :class:`CallbackPostResult` for the caller to log. |
| 214 | + """ |
| 215 | + try: |
| 216 | + status, text = await _fetch( |
| 217 | + callback_url, |
| 218 | + method="POST", |
| 219 | + headers={"Content-Type": "application/json"}, |
| 220 | + body=json.dumps(payload), |
| 221 | + ) |
| 222 | + if not 200 <= status < 300: |
| 223 | + return CallbackPostResult( |
| 224 | + error=ChatError(f"Callback URL returned {status}: {text}"), |
| 225 | + status=status, |
| 226 | + ) |
| 227 | + return CallbackPostResult(status=status) |
| 228 | + except Exception as error: |
| 229 | + return CallbackPostResult(error=error) |
0 commit comments