Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<user_id>` 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_<room>` 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

# <script src="https://chat.hibira.io/w/v1.js" ... data-user-id="{{ user.id }}"
# data-user-hash="{{ user_hash(IDENTITY_SECRET, user.id) }}" data-user-name="{{ user.name }}">
```

## Errors

Every error is a `hibira.HibiraError`. HTTP errors are `hibira.HTTPError`
Expand Down Expand Up @@ -263,6 +322,10 @@ client):發送事件、私人 / presence 頻道授權、驗證 webhook、推
`useStream()` 直接接收)。支援 OpenAI、Anthropic、OpenAI Agents SDK、LangGraph、
Gemini 的串流格式,並附 FastAPI 授權路由與 webhook 驗證。

另有 Chat API(對話、訊息、已讀、離線推播)、等候室 middleware(`hibira.waiting_room`,
FastAPI / Starlette 等 ASGI 與 Flask 等 WSGI 皆可用),以及 Live Chat 已驗證訪客的
`user_hash()`。

## License

MIT
227 changes: 225 additions & 2 deletions src/hibira/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,41 @@ def _delete_push_user_req(self, user_id: str) -> _Request:
return self._push_req("DELETE", f"/customer_api/v1/instances/{{instance}}/users/{quote(str(user_id), safe='')}")


def _q(value: Any) -> str:
return quote(str(value), safe="")


def _drop_none(fields: Mapping[str, Any]) -> dict[str, Any]:
return {k: v for k, v in fields.items() if v is not None}


def _chat_path(conversation_id: str, rest: str = "") -> str:
if not conversation_id:
raise ValueError("conversation_id is required")
return f"/conversations/{_q(conversation_id)}{rest}"


class _ChatRequests:
"""Request builders for the Chat API (https://hibira.io/chat-api)."""

def _signed(self, method: str, path: str, params: Mapping[str, Any] | None = None, body: Any = None) -> _Request:
raise NotImplementedError # pragma: no cover

def _chat_req(self, method: str, path: str, params: Mapping[str, Any] | None = None, body: Any = None) -> _Request:
if not path.startswith("/"):
raise ValueError('path must start with "/", such as /conversations/support-42')
clean = _drop_none(params or {})
return self._signed(method.upper(), "/chat" + path, {k: str(v) for k, v in clean.items()} or None, body)

def _put_conversation_req(self, conversation_id: str, **fields: Any) -> _Request:
return self._chat_req("PUT", _chat_path(conversation_id), body=_drop_none(fields))

def _send_message_req(self, conversation_id: str, **fields: Any) -> _Request:
if not fields.get("user_id"):
raise ValueError("user_id is required")
return self._chat_req("POST", _chat_path(conversation_id, "/messages"), body=_drop_none(fields))


def _info(info: str | Iterable[str] | None) -> str | None:
if info is None or isinstance(info, str):
return info or None
Expand Down Expand Up @@ -276,7 +311,7 @@ def _approval_fields(
}


class Client(_Base):
class Client(_Base, _ChatRequests):
"""Server client for a Hibira app: publish events, authorize channels,
verify webhooks, send push notifications and ask for approvals.

Expand Down Expand Up @@ -385,8 +420,101 @@ def wait_for_approval(self, approval_id: str, timeout: float = 3600) -> Any:
if out.get("status") != "pending" or time.monotonic() >= deadline:
return out

# Chat API: conversations with stored history (https://hibira.io/chat-api)

def chat_request(self, method: str, path: str, params: Mapping[str, Any] | None = None, body: Any = None) -> Any:
"""Any Chat API call, signed: path is relative to /apps/APP_ID/chat, such as /conversations/ID/typing."""
return self._send(self._chat_req(method, path, params, body))

def put_conversation(
self,
conversation_id: str,
*,
name: str | None = None,
members: Sequence[str] | None = None,
metadata: Mapping[str, Any] | None = None,
roles: Mapping[str, str] | None = None,
watchers: Sequence[str] | None = None,
) -> Any:
"""Create or replace a conversation; members and watchers left as None keep the current ones."""
return self._send(
self._put_conversation_req(
conversation_id,
name=name,
members=list(members) if members is not None else None,
metadata=dict(metadata) if metadata is not None else None,
roles=dict(roles) if roles is not None else None,
watchers=list(watchers) if watchers is not None else None,
)
)

def get_conversation(self, conversation_id: str) -> Any:
return self._send(self._chat_req("GET", _chat_path(conversation_id)))

def delete_conversation(self, conversation_id: str) -> Any:
"""Delete a conversation with its members, messages and files."""
return self._send(self._chat_req("DELETE", _chat_path(conversation_id)))

def add_members(self, conversation_id: str, user_ids: str | Iterable[str]) -> Any:
ids = [user_ids] if isinstance(user_ids, str) else list(user_ids)
return self._send(self._chat_req("POST", _chat_path(conversation_id, "/members"), body={"user_ids": ids}))

def remove_member(self, conversation_id: str, user_id: str) -> Any:
return self._send(self._chat_req("DELETE", _chat_path(conversation_id, f"/members/{_q(user_id)}")))

def send_message(
self,
conversation_id: str,
user_id: str,
text: str | None = None,
*,
name: str | None = None,
metadata: Mapping[str, Any] | None = None,
push: str | None = None,
push_title: str | None = None,
push_url: str | None = None,
visible_to: Sequence[str] | None = None,
idempotency_key: str | None = None,
) -> Any:
"""Post a message as a member. push is "offline" (default), "always" or "never"."""
return self._send(
self._send_message_req(
conversation_id,
user_id=user_id,
text=text,
name=name,
metadata=dict(metadata) if metadata is not None else None,
push=push,
push_title=push_title,
push_url=push_url,
visible_to=list(visible_to) if visible_to is not None else None,
idempotency_key=idempotency_key,
)
)

def list_messages(
self, conversation_id: str, *, after: int | None = None, limit: int | None = None, last: int | None = None
) -> Any:
"""Messages oldest first: after a seq (with limit), or the last n."""
params = {"after": after, "limit": limit, "last": last}
return self._send(self._chat_req("GET", _chat_path(conversation_id, "/messages"), params))

def mark_read(self, conversation_id: str, user_id: str, seq: int) -> Any:
body = {"user_id": user_id, "seq": seq}
return self._send(self._chat_req("POST", _chat_path(conversation_id, "/read"), body=body))

def system_message(self, conversation_id: str, text: str, metadata: Mapping[str, Any] | None = None) -> Any:
"""A message with no sender, such as "Alice joined"."""
body = _drop_none({"text": text, "metadata": dict(metadata) if metadata is not None else None})
return self._send(self._chat_req("POST", _chat_path(conversation_id, "/system"), body=body))

def user_conversations(self, user_id: str, *, limit: int | None = None, before: str | None = None) -> Any:
"""A user's conversations, latest activity first, each with its unread count."""
params = {"limit": limit, "before": before}
return self._send(self._chat_req("GET", f"/users/{_q(user_id)}/conversations", params))

class AsyncClient(_Base):

class AsyncClient(_Base, _ChatRequests):
"""asyncio version of Client: the same methods, HTTP ones are awaitable.

authenticate_channel, authenticate_user, verify_webhook and push_token
Expand Down Expand Up @@ -477,3 +605,98 @@ async def wait_for_approval(self, approval_id: str, timeout: float = 3600) -> An
out = await self.get_approval(approval_id, wait=max(0, min(MAX_APPROVAL_WAIT, int(left))))
if out.get("status") != "pending" or time.monotonic() >= deadline:
return out

# Chat API: conversations with stored history (https://hibira.io/chat-api)

async def chat_request(
self, method: str, path: str, params: Mapping[str, Any] | None = None, body: Any = None
) -> Any:
"""Any Chat API call, signed: path is relative to /apps/APP_ID/chat, such as /conversations/ID/typing."""
return await self._send(self._chat_req(method, path, params, body))

async def put_conversation(
self,
conversation_id: str,
*,
name: str | None = None,
members: Sequence[str] | None = None,
metadata: Mapping[str, Any] | None = None,
roles: Mapping[str, str] | None = None,
watchers: Sequence[str] | None = None,
) -> Any:
"""Create or replace a conversation; members and watchers left as None keep the current ones."""
return await self._send(
self._put_conversation_req(
conversation_id,
name=name,
members=list(members) if members is not None else None,
metadata=dict(metadata) if metadata is not None else None,
roles=dict(roles) if roles is not None else None,
watchers=list(watchers) if watchers is not None else None,
)
)

async def get_conversation(self, conversation_id: str) -> Any:
return await self._send(self._chat_req("GET", _chat_path(conversation_id)))

async def delete_conversation(self, conversation_id: str) -> Any:
"""Delete a conversation with its members, messages and files."""
return await self._send(self._chat_req("DELETE", _chat_path(conversation_id)))

async def add_members(self, conversation_id: str, user_ids: str | Iterable[str]) -> Any:
ids = [user_ids] if isinstance(user_ids, str) else list(user_ids)
return await self._send(self._chat_req("POST", _chat_path(conversation_id, "/members"), body={"user_ids": ids}))

async def remove_member(self, conversation_id: str, user_id: str) -> Any:
return await self._send(self._chat_req("DELETE", _chat_path(conversation_id, f"/members/{_q(user_id)}")))

async def send_message(
self,
conversation_id: str,
user_id: str,
text: str | None = None,
*,
name: str | None = None,
metadata: Mapping[str, Any] | None = None,
push: str | None = None,
push_title: str | None = None,
push_url: str | None = None,
visible_to: Sequence[str] | None = None,
idempotency_key: str | None = None,
) -> Any:
"""Post a message as a member. push is "offline" (default), "always" or "never"."""
return await self._send(
self._send_message_req(
conversation_id,
user_id=user_id,
text=text,
name=name,
metadata=dict(metadata) if metadata is not None else None,
push=push,
push_title=push_title,
push_url=push_url,
visible_to=list(visible_to) if visible_to is not None else None,
idempotency_key=idempotency_key,
)
)

async def list_messages(
self, conversation_id: str, *, after: int | None = None, limit: int | None = None, last: int | None = None
) -> Any:
"""Messages oldest first: after a seq (with limit), or the last n."""
params = {"after": after, "limit": limit, "last": last}
return await self._send(self._chat_req("GET", _chat_path(conversation_id, "/messages"), params))

async def mark_read(self, conversation_id: str, user_id: str, seq: int) -> Any:
body = {"user_id": user_id, "seq": seq}
return await self._send(self._chat_req("POST", _chat_path(conversation_id, "/read"), body=body))

async def system_message(self, conversation_id: str, text: str, metadata: Mapping[str, Any] | None = None) -> Any:
"""A message with no sender, such as "Alice joined"."""
body = _drop_none({"text": text, "metadata": dict(metadata) if metadata is not None else None})
return await self._send(self._chat_req("POST", _chat_path(conversation_id, "/system"), body=body))

async def user_conversations(self, user_id: str, *, limit: int | None = None, before: str | None = None) -> Any:
"""A user's conversations, latest activity first, each with its unread count."""
params = {"limit": limit, "before": before}
return await self._send(self._chat_req("GET", f"/users/{_q(user_id)}/conversations", params))
3 changes: 2 additions & 1 deletion src/hibira/_signing.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
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()
Comment thread
deflinhec marked this conversation as resolved.
Dismissed
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
Expand Down
32 changes: 32 additions & 0 deletions src/hibira/livechat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Hibira Live Chat helpers for your server.

Verified visitors: sign the signed-in user's ID with the workspace's
identity secret (Live Chat › Settings › Widget › Verified visitors) and put
it on the widget's script tag, so the chat shows who they are and nobody can
pretend to be them::

from hibira.livechat import user_hash

<script src="https://chat.hibira.io/w/v1.js" data-workspace="..."
data-user-id="{{ user.id }}" data-user-hash="{{ user_hash(SECRET, user.id) }}"
data-user-name="{{ user.name }}" data-user-email="{{ user.email }}" async></script>

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()
Loading
Loading