From 860bfe87cc17da4f0b8fabd443c6b3a182596cbf Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 21:21:29 +0000 Subject: [PATCH 1/2] Chat API, waiting room middleware (ASGI/WSGI) and Live Chat user_hash Python apps can now run the Chat API, put a waiting room in front of FastAPI/Starlette or Flask pages, and sign Live Chat verified visitors. The waiting room check uses the shared server-signed test vector. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SHtsCCKScUUX9khSrU2wij --- CHANGELOG.md | 6 + README.md | 63 +++++++ src/hibira/_client.py | 227 +++++++++++++++++++++++- src/hibira/livechat.py | 32 ++++ src/hibira/waiting_room.py | 339 ++++++++++++++++++++++++++++++++++++ tests/test_chat_livechat.py | 80 +++++++++ tests/test_waiting_room.py | 177 +++++++++++++++++++ 7 files changed, 922 insertions(+), 2 deletions(-) create mode 100644 src/hibira/livechat.py create mode 100644 src/hibira/waiting_room.py create mode 100644 tests/test_chat_livechat.py create mode 100644 tests/test_waiting_room.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dc9410..5467d41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased + +- Chat API on `Client` and `AsyncClient`: `put_conversation`, `get_conversation`, `delete_conversation`, `add_members`, `remove_member`, `send_message`, `list_messages`, `mark_read`, `system_message`, `user_conversations`, and `chat_request` for any other call. +- `hibira.waiting_room`: `verify_pass`, `sign_user`, `waiting_room_url`, and `ASGIMiddleware` (FastAPI, Starlette) / `WSGIMiddleware` (Flask) with the same behaviour as the other Hibira waiting room packages. Tested against the shared server-signed pass. +- `hibira.livechat.user_hash` for Live Chat verified visitors. + ## 0.1.0 First release. diff --git a/README.md b/README.md index a3b3193..bd9e7e7 100644 --- a/README.md +++ b/README.md @@ -235,6 +235,65 @@ if result["status"] == "approved": `status` is `pending`, `approved`, `rejected` or `expired`. `get_approval(id, wait=25)` reads it once, waiting up to 25 seconds for an answer. +## Chat API + +Conversations with stored history, read receipts and offline push +([reference](https://hibira.io/chat-api)). Clients receive `chat.*` events on +`#server-to-user-` after `pusher.signin`. + +```python +client.put_conversation("order-1042", name="Order #1042", members=["cust_7", "agent_2"]) +client.send_message("order-1042", "agent_2", "Your parcel left the warehouse.", push="offline") +page = client.list_messages("order-1042", after=last_seq, limit=50) # {"messages", "last_seq"} +client.mark_read("order-1042", "cust_7", page["last_seq"]) +client.user_conversations("cust_7") # latest first, each with "unread" +``` + +Also `get_conversation`, `delete_conversation`, `add_members`, `remove_member`, +`system_message`, and `chat_request(method, path, params, body)` for every other +call (typing, reactions, edits, search, moderation). `AsyncClient` has the same +methods, awaitable. + +## Waiting rooms + +Put a [Hibira waiting room](https://hibira.io/waiting-room) in front of a +ticket drop or launch. Visitors without a pass go to the hosted queue page +(requests other than GET get a 403); when it's their turn they come back with +`?hibira_pass=...`, which is checked, kept in the HttpOnly cookie +`hibira_wr_` and removed from the URL. No extra dependencies. + +```python +from hibira.waiting_room import WaitingRoom, ASGIMiddleware, WSGIMiddleware + +room = WaitingRoom(app_key=os.environ["HIBIRA_KEY"], secret=os.environ["HIBIRA_SECRET"], room="presale") + +# FastAPI, Starlette, Litestar, Quart (ASGI): request.state.hibira_pass +app.add_middleware(ASGIMiddleware, room=room, paths=["/drop"]) + +# Flask, Bottle, Pyramid, Falcon (WSGI): request.environ["hibira.pass"] +app.wsgi_app = WSGIMiddleware(app.wsgi_app, room=room, paths=["/drop"]) +``` + +The pass has `number`, `ticket_id` (record it to allow one checkout per number) +and `expires_at`. During a secret rotation give `secret=[new, old]`. For rooms +with one place per signed-in customer, pass `user=lambda req: sign_user(SECRET, "presale", customer_id(req))` +and compare `pass.user_id` at checkout. `verify_pass(token, secret, room=...)` +checks a pass anywhere else. Django has its own middleware in +[django-hibira](https://github.com/hibira-io/django). + +## Live Chat verified visitors + +Let signed-in users chat as themselves on the [Hibira Live Chat](https://chat.hibira.io) +widget: sign their ID with the workspace's identity secret (Settings › Widget › +Verified visitors). + +```python +from hibira.livechat import user_hash + +# + +Or after load: ``HibiraLiveChat.identify({id, hash, name, email})``. +""" + +from __future__ import annotations + +import hashlib +import hmac + +__all__ = ["user_hash"] + + +def user_hash(identity_secret: str, user_id: object) -> str: + """hex(HMAC-SHA256(identity secret, user_id)), the widget's data-user-hash.""" + if not identity_secret: + raise ValueError("user_hash: identity_secret is required") + uid = str(user_id) + if not uid: + raise ValueError("user_hash: user_id is required") + return hmac.new(identity_secret.encode(), uid.encode(), hashlib.sha256).hexdigest() diff --git a/src/hibira/waiting_room.py b/src/hibira/waiting_room.py new file mode 100644 index 0000000..e78f25a --- /dev/null +++ b/src/hibira/waiting_room.py @@ -0,0 +1,339 @@ +"""Waiting rooms: send visitors to the Hibira queue, let them in with a pass. + +FastAPI, Starlette or any ASGI app:: + + from hibira.waiting_room import WaitingRoom, ASGIMiddleware + + room = WaitingRoom(app_key=KEY, secret=SECRET, room="presale") + app.add_middleware(ASGIMiddleware, room=room, paths=["/drop"]) + + @app.get("/drop") + async def drop(request: Request): + request.state.hibira_pass # Pass(number=42, ticket_id=..., ...) + +Flask or any WSGI app:: + + from hibira.waiting_room import WaitingRoom, WSGIMiddleware + + app.wsgi_app = WSGIMiddleware(app.wsgi_app, room=room, paths=["/drop"]) + # in the view: request.environ["hibira.pass"] + +A visitor without a valid pass is redirected to the hosted waiting page +(requests other than GET and HEAD get a 403). When it's their turn the page +sends them back with ``?hibira_pass=...``, which is checked, stored in an +HttpOnly cookie (``hibira_wr_``) and removed from the URL. This is the +same behaviour as ``@hibira-io/waiting-room/server`` and the framework +packages, with no dependencies. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import hmac +import json +import time +from dataclasses import dataclass, field +from typing import Any, Awaitable, Callable, Iterable, Literal, MutableMapping, Optional, Sequence, Union +from urllib.parse import parse_qsl, quote, urlencode, urlsplit, urlunsplit + +DEFAULT_HOST = "https://ws.hibira.io" +PARAM = "hibira_pass" +_PURPOSE = b"hibira-waitroom-pass." +_DENY_BODY = b'{"error":"waiting_room","message":"join the waiting room first"}' + +__all__ = [ + "DEFAULT_HOST", + "ASGIMiddleware", + "Decision", + "Pass", + "WSGIMiddleware", + "WaitingRoom", + "sign_user", + "verify_pass", + "waiting_room_url", +] + + +@dataclass(frozen=True) +class Pass: + app_id: str + room: str + number: int + """The visitor's queue number.""" + ticket_id: str + """The queue ticket's ID: record it to allow one checkout per number.""" + issued_at: int + expires_at: int + user_id: Optional[str] = None + """The signed user ID, in rooms with one place per signed-in customer.""" + + +def _b64decode(value: str) -> Optional[bytes]: + if not value or not all(c.isalnum() or c in "-_" for c in value): + return None + try: + return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + except (binascii.Error, ValueError): + return None + + +def _secrets(secret: Union[str, Sequence[str]]) -> list[str]: + return [secret] if isinstance(secret, str) else [s for s in secret if s] + + +def verify_pass( + token: Optional[str], + secret: Union[str, Sequence[str]], + room: Optional[str] = None, + app_id: Optional[str] = None, + now: Optional[float] = None, +) -> Optional[Pass]: + """Check a pass. Returns it, or None when it is missing, forged, expired, + or for another room or app. Give ``[new, old]`` as secret during a rotation.""" + secrets = _secrets(secret) + if not secrets: + raise ValueError("verify_pass: secret is required") + if not isinstance(token, str) or not token or len(token) > 1024: + return None + payload, dot, sig_part = token.partition(".") + if not dot or not payload: + return None + sig = _b64decode(sig_part) + if sig is None or len(sig) != 32: + return None + msg = _PURPOSE + payload.encode() + if not any(hmac.compare_digest(hmac.new(s.encode(), msg, hashlib.sha256).digest(), sig) for s in secrets): + return None + raw = _b64decode(payload) + try: + claims = json.loads(raw) if raw is not None else None + except ValueError: + return None + if not isinstance(claims, dict) or claims.get("v") != 1 or not isinstance(claims.get("exp"), (int, float)): + return None + if (time.time() if now is None else now) >= claims["exp"]: + return None + if room is not None and claims.get("room") != room: + return None + if app_id is not None and claims.get("app") != app_id: + return None + sub = claims.get("sub") + return Pass( + app_id=str(claims.get("app", "")), + room=str(claims.get("room", "")), + number=int(claims.get("n", 0)), + ticket_id=str(claims.get("tid", "")), + issued_at=int(claims.get("iat", 0)), + expires_at=int(claims["exp"]), + user_id=sub if isinstance(sub, str) else None, + ) + + +def sign_user(secret: str, room: str, user_id: str, ttl_seconds: int = 3600, now: Optional[float] = None) -> str: + """Sign a user token for rooms with one place per signed-in customer: the + same user_id gets the same place in every browser. user_id is 1 to 128 + characters without "."; ttl_seconds is capped at 7 days.""" + uid = str(user_id or "") + if not uid or len(uid) > 128 or "." in uid: + raise ValueError('sign_user: user_id must be 1 to 128 characters without "."') + exp = int(time.time() if now is None else now) + min(max(1, int(ttl_seconds)), 7 * 24 * 3600) + msg = f"hibira-waitroom-user.{room}.{uid}.{exp}".encode() + return f"{uid}.{exp}.{hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest()}" + + +def waiting_room_url( + app_key: str, + room: str, + return_url: Optional[str] = None, + host: str = DEFAULT_HOST, + lang: Optional[str] = None, + user: Optional[str] = None, +) -> str: + """The hosted waiting page address for a room.""" + query = {k: v for k, v in (("return", return_url), ("lang", lang), ("user", user)) if v} + url = f"{host.rstrip('/')}/wait/{quote(app_key, safe='')}/{quote(room, safe='')}" + return url + ("?" + urlencode(query) if query else "") + + +@dataclass(frozen=True) +class Decision: + action: Literal["allow", "redirect", "deny"] + location: Optional[str] = None + set_cookie: Optional[str] = None + """A Set-Cookie header value to send with the redirect.""" + pass_: Optional[Pass] = None + + +def _read_cookie(header: Optional[str], name: str) -> Optional[str]: + if not header: + return None + for part in header.split(";"): + key, eq, value = part.partition("=") + if eq and key.strip() == name: + return value.strip() + return None + + +UserToken = Callable[[Any], Optional[str]] + + +@dataclass +class WaitingRoom: + """One waiting room's settings, and the framework-neutral decision.""" + + app_key: str + secret: Union[str, Sequence[str]] + room: str + app_id: Optional[str] = None + host: str = DEFAULT_HOST + lang: Optional[str] = None + cookie_name: str = "" + user: Optional[UserToken] = field(default=None, repr=False) + """Optional: returns a sign_user() token for the request's signed-in customer.""" + + def __post_init__(self) -> None: + if not self.cookie_name: + self.cookie_name = f"hibira_wr_{self.room}" + + def verify(self, token: Optional[str], now: Optional[float] = None) -> Optional[Pass]: + return verify_pass(token, self.secret, room=self.room, app_id=self.app_id, now=now) + + def decide( + self, + url: str, + method: str = "GET", + cookie: Optional[str] = None, + request: Any = None, + now: Optional[float] = None, + ) -> Decision: + """What to do with a request: allow it, redirect it, or deny it.""" + parts = urlsplit(url) + query = parse_qsl(parts.query, keep_blank_values=True) + from_queue = next((v for k, v in query if k == PARAM), None) + if from_queue: + rest = [(k, v) for k, v in query if k != PARAM] + clean = urlunsplit(parts._replace(query=urlencode(rest))) + p = self.verify(from_queue, now) + if p is not None: + max_age = max(0, int(p.expires_at - (time.time() if now is None else now))) + secure = "; Secure" if parts.scheme == "https" else "" + cookie_value = f"{self.cookie_name}={from_queue}; Path=/; Max-Age={max_age}; HttpOnly; SameSite=Lax" + return Decision( + "redirect", + location=clean, + set_cookie=cookie_value + secure, + pass_=p, + ) + url = clean + p = self.verify(_read_cookie(cookie, self.cookie_name), now) + if p is not None: + return Decision("allow", pass_=p) + if method.upper() not in ("GET", "HEAD"): + return Decision("deny") + user = self.user(request) if self.user is not None and request is not None else None + location = waiting_room_url(self.app_key, self.room, return_url=url, host=self.host, lang=self.lang, user=user) + return Decision("redirect", location=location) + + +def _matches(path: str, paths: Optional[Iterable[str]]) -> bool: + if paths is None: + return True + for prefix in paths: + p = prefix.rstrip("/") + if path == p or path.startswith(p + "/") or (prefix.endswith("/") and path.startswith(prefix)): + return True + return False + + +Scope = MutableMapping[str, Any] +Receive = Callable[[], Awaitable[MutableMapping[str, Any]]] +Send = Callable[[MutableMapping[str, Any]], Awaitable[None]] +ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]] + + +class ASGIMiddleware: + """ASGI middleware for FastAPI, Starlette, Quart, Litestar and others. + + ``paths`` are path prefixes the room protects (all paths when None). The + pass is put in ``scope["state"]["hibira_pass"]``, which Starlette and + FastAPI show as ``request.state.hibira_pass``. ``room.user`` receives the + ASGI scope. Behind a proxy that ends TLS, run the server with + ``--proxy-headers`` so the scheme is https. + """ + + def __init__(self, app: ASGIApp, room: WaitingRoom, paths: Optional[Iterable[str]] = None) -> None: + self.app = app + self.room = room + self.paths = list(paths) if paths is not None else None + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http" or not _matches(scope.get("path", ""), self.paths): + await self.app(scope, receive, send) + return + headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])} + host = headers.get("host") or "{}:{}".format(*(scope.get("server") or ("localhost", 80))) + path = scope.get("root_path", "") + scope.get("path", "") + qs = scope.get("query_string", b"").decode("latin-1") + url = f"{scope.get('scheme', 'http')}://{host}{quote(path)}" + (f"?{qs}" if qs else "") + d = self.room.decide(url, scope.get("method", "GET"), headers.get("cookie"), request=scope) + if d.action == "allow": + scope.setdefault("state", {})["hibira_pass"] = d.pass_ + await self.app(scope, receive, send) + return + if d.action == "deny": + out = [(b"content-type", b"application/json"), (b"cache-control", b"no-store")] + await send({"type": "http.response.start", "status": 403, "headers": out}) + await send({"type": "http.response.body", "body": _DENY_BODY}) + return + out = [(b"location", (d.location or "/").encode("latin-1")), (b"cache-control", b"no-store")] + if d.set_cookie: + out.append((b"set-cookie", d.set_cookie.encode("latin-1"))) + await send({"type": "http.response.start", "status": 302, "headers": out}) + await send({"type": "http.response.body", "body": b""}) + + +Environ = dict[str, Any] +WSGIApp = Callable[[Environ, Callable[..., Any]], Iterable[bytes]] + + +class WSGIMiddleware: + """WSGI middleware for Flask, Bottle, Pyramid, Falcon and others. + + ``paths`` are path prefixes the room protects (all paths when None). The + pass is put in ``environ["hibira.pass"]``. ``room.user`` receives the + WSGI environ. Behind a proxy that ends TLS, use werkzeug's ProxyFix (or + your server's equivalent) so ``wsgi.url_scheme`` is https. + """ + + def __init__(self, app: WSGIApp, room: WaitingRoom, paths: Optional[Iterable[str]] = None) -> None: + self.app = app + self.room = room + self.paths = list(paths) if paths is not None else None + + def __call__(self, environ: Environ, start_response: Callable[..., Any]) -> Iterable[bytes]: + path = environ.get("PATH_INFO", "") + if not _matches(path, self.paths): + return self.app(environ, start_response) + server = f"{environ.get('SERVER_NAME', 'localhost')}:{environ.get('SERVER_PORT', '80')}" + host = environ.get("HTTP_HOST") or server + full = quote(environ.get("SCRIPT_NAME", "") + path) + qs = environ.get("QUERY_STRING", "") + url = f"{environ.get('wsgi.url_scheme', 'http')}://{host}{full}" + (f"?{qs}" if qs else "") + d = self.room.decide(url, environ.get("REQUEST_METHOD", "GET"), environ.get("HTTP_COOKIE"), request=environ) + if d.action == "allow": + environ["hibira.pass"] = d.pass_ + return self.app(environ, start_response) + if d.action == "deny": + length = str(len(_DENY_BODY)) + start_response( + "403 Forbidden", + [("Content-Type", "application/json"), ("Cache-Control", "no-store"), ("Content-Length", length)], + ) + return [_DENY_BODY] + headers = [("Location", d.location or "/"), ("Cache-Control", "no-store"), ("Content-Length", "0")] + if d.set_cookie: + headers.append(("Set-Cookie", d.set_cookie)) + start_response("302 Found", headers) + return [b""] diff --git a/tests/test_chat_livechat.py b/tests/test_chat_livechat.py new file mode 100644 index 0000000..a93e38f --- /dev/null +++ b/tests/test_chat_livechat.py @@ -0,0 +1,80 @@ +import asyncio +import hashlib +import hmac +import json + +import httpx +import pytest +from test_client import check_signature, make, recorder + +import hibira +from hibira.livechat import user_hash + + +def test_put_conversation_and_send_message(): + seen, handler = recorder(201, b'{"conversation": {"id": "support-42"}}') + c = make(handler) + c.put_conversation("support-42", name="Order #42", members=["u1", "agent"], roles={"agent": "staff"}) + c.send_message("support-42", "u1", "Hi", push="always", visible_to=["staff"]) + put, post = seen + assert put.method == "PUT" and put.url.path == "/apps/app1/chat/conversations/support-42" + assert json.loads(put.content) == {"name": "Order #42", "members": ["u1", "agent"], "roles": {"agent": "staff"}} + assert post.url.path == "/apps/app1/chat/conversations/support-42/messages" + assert json.loads(post.content) == {"user_id": "u1", "text": "Hi", "push": "always", "visible_to": ["staff"]} + check_signature(put) + check_signature(post) + + +def test_reads_and_members(): + seen, handler = recorder() + c = make(handler) + c.list_messages("a b", after=10, limit=50) + c.user_conversations("u/1", limit=20) + c.add_members("c1", "u2") + c.remove_member("c1", "u2") + c.mark_read("c1", "u1", 12) + c.system_message("c1", "Alice joined", {"event": "joined"}) + c.delete_conversation("c1") + c.chat_request("POST", "/conversations/c1/typing", body={"user_id": "u1"}) + paths = [(r.method, r.url.raw_path.decode().split("?")[0]) for r in seen] + assert paths == [ + ("GET", "/apps/app1/chat/conversations/a%20b/messages"), + ("GET", "/apps/app1/chat/users/u%2F1/conversations"), + ("POST", "/apps/app1/chat/conversations/c1/members"), + ("DELETE", "/apps/app1/chat/conversations/c1/members/u2"), + ("POST", "/apps/app1/chat/conversations/c1/read"), + ("POST", "/apps/app1/chat/conversations/c1/system"), + ("DELETE", "/apps/app1/chat/conversations/c1"), + ("POST", "/apps/app1/chat/conversations/c1/typing"), + ] + q = check_signature(seen[0]) + assert q["after"] == "10" and q["limit"] == "50" and "last" not in q + for r in seen: + check_signature(r) + assert json.loads(seen[2].content) == {"user_ids": ["u2"]} + with pytest.raises(ValueError): + c.send_message("c1", "", "x") + with pytest.raises(ValueError): + c.get_conversation("") + + +def test_async_chat(): + seen, handler = recorder() + + async def run(): + c = hibira.AsyncClient( + "app1", "key1", "secret1", http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)) + ) + await c.send_message("c1", "u1", "hi") + await c.get_conversation("c1") + + asyncio.run(run()) + assert [r.method for r in seen] == ["POST", "GET"] + check_signature(seen[0]) + + +def test_user_hash(): + want = hmac.new(b"lcid_secret", b"42", hashlib.sha256).hexdigest() + assert user_hash("lcid_secret", 42) == want + with pytest.raises(ValueError): + user_hash("", "1") diff --git a/tests/test_waiting_room.py b/tests/test_waiting_room.py new file mode 100644 index 0000000..9da1c45 --- /dev/null +++ b/tests/test_waiting_room.py @@ -0,0 +1,177 @@ +import hashlib +import hmac + +import pytest +from fastapi import FastAPI, Request +from fastapi.testclient import TestClient + +from hibira.waiting_room import ( + ASGIMiddleware, + Pass, + WaitingRoom, + WSGIMiddleware, + sign_user, + verify_pass, + waiting_room_url, +) + +# The shared test vector of hibira-io/waiting-room test/server.test.mjs: +# signed by the Hibira server (internal/waitroom NewPass) at 1800000000, ttl 30 min. +SECRET = "wr-secret-0123456789" +PASS = ( + "eyJ2IjoxLCJhcHAiOiJ3ci1hcHAiLCJyb29tIjoicHJlc2FsZSIsIm4iOjQyLCJ0aWQiOiJkNzlmZTc4OWEzOGI4NjMxYjUiLCJpYXQiOjE4MDAw" + "MDAwMDAsImV4cCI6MTgwMDAwMTgwMH0.q7Uc_O6XKwNA_LVLQITlgv_YtDi9dIwiRzUUUSsGa08" +) +TICKET = ( + "eyJ2IjoxLCJhcHAiOiJ3ci1hcHAiLCJyb29tIjoicHJlc2FsZSIsIm4iOjQyLCJ0aWQiOiJkNzlmZTc4OWEzOGI4NjMxYjUiLCJpYXQiOjE4MDAw" + "MDAwMDAsImV4cCI6MTgwMDA4NjQwMH0.l-KNMOVwV_xJJCQaQ-JXQKsrj-XlEdsTxG7X4Kp_2ck" +) +NOW = 1800000100 + + +def test_verifies_a_server_signed_pass(): + p = verify_pass(PASS, SECRET, room="presale", app_id="wr-app", now=NOW) + assert p == Pass("wr-app", "presale", 42, "d79fe789a38b8631b5", 1800000000, 1800001800) + assert verify_pass(PASS, ["old-secret", SECRET], now=NOW), "rotation: any secret" + + +@pytest.mark.parametrize( + "token,kw", + [ + (PASS, {"secret": "wrong"}), + (PASS, {"room": "other"}), + (PASS, {"app_id": "other"}), + (PASS, {"now": 1800001800}), + (TICKET, {}), + (PASS[:-3] + "AAA", {}), + ("", {}), + (None, {}), + ("a.b.c", {}), + ("x" * 1025, {}), + ], +) +def test_rejects(token, kw): + args = {"secret": SECRET, "room": "presale", "app_id": "wr-app", "now": NOW, **kw} + assert verify_pass(token, **args) is None + + +def test_sign_user_matches_the_server_format(): + tok = sign_user(SECRET, "presale", "cust_42", ttl_seconds=600, now=1800000000) + want = hmac.new(SECRET.encode(), b"hibira-waitroom-user.presale.cust_42.1800000600", hashlib.sha256).hexdigest() + assert tok == "cust_42.1800000600." + want + assert sign_user(SECRET, "presale", "u", ttl_seconds=30 * 86400, now=1800000000).startswith("u.1800604800.") + with pytest.raises(ValueError): + sign_user(SECRET, "presale", "a.b") + + +def test_waiting_room_url(): + url = waiting_room_url("key", "presale", return_url="https://shop.test/drop?a=1", lang="ja") + assert url == "https://ws.hibira.io/wait/key/presale?return=https%3A%2F%2Fshop.test%2Fdrop%3Fa%3D1&lang=ja" + + +ROOM = WaitingRoom(app_key="key", secret=SECRET, room="presale") + + +def test_decide_without_a_pass(): + d = ROOM.decide("https://shop.test/drop", now=NOW) + assert d.action == "redirect" + assert d.location == "https://ws.hibira.io/wait/key/presale?return=https%3A%2F%2Fshop.test%2Fdrop" + assert ROOM.decide("https://shop.test/drop", "POST", now=NOW).action == "deny" + + +def test_decide_from_the_queue_and_with_the_cookie(): + d = ROOM.decide(f"https://shop.test/drop?item=7&hibira_pass={PASS}", now=NOW) + assert d.action == "redirect" and d.location == "https://shop.test/drop?item=7" + assert d.set_cookie == f"hibira_wr_presale={PASS}; Path=/; Max-Age=1700; HttpOnly; SameSite=Lax; Secure" + d = ROOM.decide("http://shop.test/drop", "POST", cookie=f"a=1; hibira_wr_presale={PASS}", now=NOW) + assert d.action == "allow" and d.pass_ is not None and d.pass_.number == 42 + forged = ROOM.decide("https://shop.test/drop?hibira_pass=forged&x=1", now=NOW) + assert forged.set_cookie is None + assert forged.location is not None and "return=https%3A%2F%2Fshop.test%2Fdrop%3Fx%3D1" in forged.location + + +def fresh(room="presale"): + import base64 + import json + import time + + now = int(time.time()) + payload = base64.urlsafe_b64encode( + json.dumps({"v": 1, "app": "wr-app", "room": room, "n": 7, "tid": "t7", "iat": now, "exp": now + 600}).encode() + ).rstrip(b"=") + sig = hmac.new(SECRET.encode(), b"hibira-waitroom-pass." + payload, hashlib.sha256).digest() + return payload.decode() + "." + base64.urlsafe_b64encode(sig).rstrip(b"=").decode() + + +def asgi_app(): + room = WaitingRoom(app_key="key", secret=SECRET, room="presale", user=lambda scope: "u.1.sig") + app = FastAPI() + app.add_middleware(ASGIMiddleware, room=room, paths=["/drop"]) + + @app.api_route("/drop", methods=["GET", "POST"]) + async def drop(request: Request): + return {"number": request.state.hibira_pass.number} + + @app.get("/open") + async def open_page(): + return {"ok": True} + + return TestClient(app, base_url="https://shop.test", follow_redirects=False) + + +def test_asgi_middleware(): + c = asgi_app() + assert c.get("/open").json() == {"ok": True} + r = c.get("/drop") + assert r.status_code == 302 and r.headers["cache-control"] == "no-store" + assert r.headers["location"].startswith( + "https://ws.hibira.io/wait/key/presale?return=https%3A%2F%2Fshop.test%2Fdrop" + ) + assert "user=u.1.sig" in r.headers["location"] + assert c.post("/drop").status_code == 403 + token = fresh() + r = c.get(f"/drop?hibira_pass={token}&x=1") + assert r.status_code == 302 and r.headers["location"] == "https://shop.test/drop?x=1" + assert r.headers["set-cookie"].startswith(f"hibira_wr_presale={token}; Path=/;") + c.cookies.set("hibira_wr_presale", token) + assert c.post("/drop").json() == {"number": 7} + + +def wsgi_call(mw, path="/drop", method="GET", qs="", cookie=None): + environ = { + "REQUEST_METHOD": method, + "PATH_INFO": path, + "QUERY_STRING": qs, + "HTTP_HOST": "shop.test", + "wsgi.url_scheme": "https", + "SCRIPT_NAME": "", + } + if cookie: + environ["HTTP_COOKIE"] = cookie + out = {} + + def start_response(status, headers): + out["status"], out["headers"] = status, dict(headers) + + body = b"".join(mw(environ, start_response)) + return out["status"], out["headers"], body, environ + + +def test_wsgi_middleware(): + def app(environ, start_response): + start_response("200 OK", [("Content-Type", "text/plain")]) + return [str(environ["hibira.pass"].number).encode()] + + mw = WSGIMiddleware(app, ROOM, paths=["/drop/"]) + status, headers, _, _ = wsgi_call(mw) + assert status == "302 Found" and headers["Location"].startswith("https://ws.hibira.io/wait/key/presale?return=") + assert wsgi_call(mw, method="DELETE")[0] == "403 Forbidden" + token = fresh() + status, headers, _, _ = wsgi_call(mw, qs=f"hibira_pass={token}") + assert headers["Location"] == "https://shop.test/drop" and "Secure" in headers["Set-Cookie"] + status, _, body, _ = wsgi_call(mw, method="POST", cookie=f"hibira_wr_presale={token}") + assert status == "200 OK" and body == b"7" + assert ( + wsgi_call(WSGIMiddleware(lambda e, s: (s("200 OK", []), [b"open"])[1], ROOM, ["/drop"]), path="/other")[2] + == b"open" + ) From dc1d3782c7fd6525df190e48f97e8d40f6103cad Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 21:52:13 +0000 Subject: [PATCH 2/2] Mark body_md5 as a checksum (usedforsecurity=False) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SHtsCCKScUUX9khSrU2wij --- src/hibira/_signing.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/hibira/_signing.py b/src/hibira/_signing.py index 8083755..cccc7d0 100644 --- a/src/hibira/_signing.py +++ b/src/hibira/_signing.py @@ -49,7 +49,8 @@ def sign_query( q["auth_timestamp"] = str(int(now if now is not None else time.time())) q["auth_version"] = "1.0" if body: - q["body_md5"] = hashlib.md5(body).hexdigest() + # body_md5 is a checksum the Pusher-protocol signature requires, not a secret hash. + q["body_md5"] = hashlib.md5(body, usedforsecurity=False).hexdigest() string = "&".join(f"{k}={q[k]}" for k in sorted(q)) q["auth_signature"] = hmac_hex(secret, f"{method.upper()}\n{path}\n{string}") return q