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
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,31 @@ All notable changes to this package are documented here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
[Semantic Versioning](https://semver.org/).

## [0.5.2] - 2026-10-15

The public thesis API (`https://id.cabalspy.xyz/thesis/v1/...`) and its live socket
(`wss://id.cabalspy.xyz/thesis/v1/ws/{chain}/{mint}`) now require your instance's public
client_id on every call. It is shown in the dashboard next to the API key; it is not a secret
and not the API key. The Data API (`CabalSpyID`, API key) is unchanged.

### Changed (breaking for the thesis client)

- `ThesisClient` / `AsyncThesisClient` require `client_id`:
`ThesisClient(access_token=None, *, client_id="csid_...", scope=None, ...)`. Without it (or with
an empty string) the constructor raises `AuthenticationError` with `code == "client_id_required"`.
- Every call sends the header `X-CSID-Client-Id: <client_id>`; `live()` adds `client_id=<client_id>`
to the socket URL (`scope="instance"` keeps working with the same client_id). `post()` and
`reply()` always send `client_id` in the body.

### Added

- New server error codes, mapped to the existing exception classes: `client_id_required` and
`invalid_client` (401, `AuthenticationError`), `origin_not_allowed` (403, `PermissionError`),
`rate_limited` (429, `RateLimitError`, `retry_after` from Retry-After, 60 s).
- `ThesisLive` treats the close codes 4401 (`client_id_required` / `invalid_client`) and 4403
(`origin_not_allowed`) as final (no reconnect) and backs off 60 s after 4429 (`rate_limited`).
- `CLIENT_ID_HEADER` constant.

## [0.5.1] - 2026-10-15

### Changed
Expand Down Expand Up @@ -96,6 +121,7 @@ First release.
`NotFoundError`, `RateLimitError`, `ServerError`, `APIConnectionError`,
`InvalidResponseError`, `OAuthError`, `TokenVerificationError`, `WebhookVerificationError`.

[0.5.2]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.1...v0.5.2
[0.5.1]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.0...v0.5.1
[0.5.0]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.4.1...v0.5.0
[0.4.1]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.4.0...v0.4.1
Expand Down
24 changes: 19 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pip install "cabalspy-id[stream]"
|---|---|
| `CabalSpyIDAuth` / `AsyncCabalSpyIDAuth` | OpenID Connect for your server: PKCE, code exchange, refresh, revoke, userinfo, ID token verification (ES256 / JWKS) |
| `CabalSpyID` / `AsyncCabalSpyID` | Data API client for `https://api-id.cabalspy.xyz/v1`, typed responses, pagination, live trade stream |
| `ThesisClient` / `AsyncThesisClient` | public token thesis API with a user's access token, plus `live()` updates |
| `ThesisClient` / `AsyncThesisClient` | public token thesis API with your public `client_id` and a user's access token, plus `live()` updates |
| `verify_webhook` | Standard Webhooks signature verification |

Sync and async, fully typed (`py.typed`, `TypedDict` responses). Python 3.10+.
Expand Down Expand Up @@ -249,7 +249,9 @@ A thesis is a short opinion on a token (up to 1000 characters), optionally tagge

Writing needs the scope **`thesis`** in your login (`scope=["openid", "profile", "thesis"]`).

**Scope of reads.** Theses are shared across platforms. Every read (`list_theses`, `thesis_summary`, `latest_theses`, `ThesisClient`, the widget, the live sockets) takes `scope`: `global` (default, every platform) or `instance` (only theses written on your instance). In the Data API your key decides the instance; the public API and widget need your `client_id`.
**Scope of reads.** Theses are shared across platforms. Every read (`list_theses`, `thesis_summary`, `latest_theses`, `ThesisClient`, the widget, the live sockets) takes `scope`: `global` (default, every platform) or `instance` (only theses written on your instance). In the Data API your key decides the instance; the public API and widget use your `client_id`.

**Your public `client_id` is required** for the public thesis API (`ThesisClient`, `AsyncThesisClient`, `ThesisLive`) and the theses widget. It is your instance's client_id (`csid_...`), shown in the dashboard next to the API key. It is public, not a secret and **not the API key** (the API key must never reach a browser). The SDK sends it as the `X-CSID-Client-Id` header on every call to `https://id.cabalspy.xyz/thesis/v1/...` and as `client_id` on the live socket URL (`wss://id.cabalspy.xyz/thesis/v1/ws/{chain}/{mint}?client_id=...`). Without it `ThesisClient()` raises `AuthenticationError` with `code == "client_id_required"`. Browser calls must come from one of the instance's allowed origins or verified domains (instances in dev mode also allow `http://localhost:*`). The Data API (`CabalSpyID`, API key) is unchanged.

### Widget

Expand Down Expand Up @@ -329,12 +331,13 @@ Also over the trade stream (Pro plan): `csid.stream(events=["theses"], blockchai

### Public thesis API: `ThesisClient`

`https://id.cabalspy.xyz/thesis/v1` needs no API key: reading is open, writing uses the user's access token (scope `thesis`).
`https://id.cabalspy.xyz/thesis/v1` needs no API key, only your public `client_id` (required): reading needs nothing else, writing uses the user's access token (scope `thesis`).

```python
from cabalspy_id import ThesisClient

# client_id credits posts to your app; add scope="instance" to show only theses written on your platform
# client_id: your instance's PUBLIC client_id from the dashboard (not the API key); it also credits
# posts to your app. Add scope="instance" to show only theses written on your platform.
with ThesisClient(access_token=result.tokens["access_token"], client_id="csid_...") as theses:
page = theses.list("solana", mint, sort="top") # items, pagination, token, summary
if theses.me("solana", mint)["can_post"]:
Expand All @@ -345,12 +348,23 @@ with ThesisClient(access_token=result.tokens["access_token"], client_id="csid_..
Methods: `list`, `iterate`, `summary`, `get`, `replies`, `by_user`, `me`, `post`, `reply`, `react`, `report`, `delete`, `notifications`, `mark_notifications_read`, `appeal`, `live`, `set_access_token`. `AsyncThesisClient` has the same methods as coroutines. Live updates for one token (async):

```python
live = ThesisClient().live("solana", mint) # also takes scope=, client_id=
live = ThesisClient(client_id="csid_...").live("solana", mint) # ?client_id=... (also takes scope=)
live.on("thesis", lambda t: print("new", t["body"])) # also: reply, reaction, removed
await live.connect()
await live.run_forever()
```

client_id errors use the SDK's exception classes, so check `err.code` (docs: `https://docs.cabalspy.xyz/cabalspy-id/errors#<code>`):

| Code | HTTP | Live socket close | Exception | Meaning |
|---|---|---|---|---|
| `client_id_required` | 401 | 4401 | `AuthenticationError` | no client_id sent |
| `invalid_client` | 401 | 4401 | `AuthenticationError` | unknown or inactive client_id |
| `origin_not_allowed` | 403 | 4403 | `PermissionError` | the browser's Origin is not one of the instance's allowed origins / verified domains |
| `rate_limited` | 429 | 4429 | `RateLimitError` (`retry_after == 60`) | too many requests per client or per IP |

`ThesisLive` does not reconnect after 4401 or 4403 (`run_forever()` raises the error); after 4429 it waits 60 s before reconnecting.

## Live stream

Every trade of your users the moment it is indexed, with the trader's profile (Pro plan and up). Async only, needs `pip install "cabalspy-id[stream]"`.
Expand Down
2 changes: 2 additions & 0 deletions cabalspy_id/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from ._client import AsyncCabalSpyID, CabalSpyID, Envelope
from ._constants import (
CHAINS,
CLIENT_ID_HEADER,
CURRENCY_BY_CHAIN,
DEFAULT_BASE_URL,
DEFAULT_ISSUER,
Expand Down Expand Up @@ -205,6 +206,7 @@ def __getattr__(name: str) -> object:
"THESIS_MAX_BODY",
"DEFAULT_THESIS_URL",
"DEFAULT_THESIS_WS_URL",
"CLIENT_ID_HEADER",
"StreamTopic",
"ThesisStance",
"ThesisSort",
Expand Down
4 changes: 3 additions & 1 deletion cabalspy_id/_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from typing import Literal

SDK_VERSION = "0.5.1"
SDK_VERSION = "0.5.2"
USER_AGENT = f"cabalspy-id-python/{SDK_VERSION}"

DEFAULT_BASE_URL = "https://api-id.cabalspy.xyz/v1"
Expand Down Expand Up @@ -66,3 +66,5 @@
DEFAULT_THESES_STREAM_URL = "wss://api-id.cabalspy.xyz/v1/theses/stream"
DEFAULT_THESIS_URL = "https://id.cabalspy.xyz/thesis/v1"
DEFAULT_THESIS_WS_URL = "wss://id.cabalspy.xyz/thesis/v1/ws"
#: Header that carries the instance's public client_id on every public thesis API call.
CLIENT_ID_HEADER = "X-CSID-Client-Id"
7 changes: 4 additions & 3 deletions cabalspy_id/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,12 @@ class BadRequestError(CabalSpyIDError):


class AuthenticationError(CabalSpyIDError):
"""401 — missing_api_key."""
"""401 — missing_api_key; public thesis API: client_id_required, invalid_client."""


class PermissionError_(CabalSpyIDError):
"""403 — invalid_api_key, product_not_enabled, no_instance, scope_not_allowed."""
"""403 — invalid_api_key, product_not_enabled, no_instance, scope_not_allowed;
public thesis API: origin_not_allowed."""


class PlanUserLimitError(PermissionError_):
Expand All @@ -105,7 +106,7 @@ class NotFoundError(CabalSpyIDError):


class RateLimitError(CabalSpyIDError):
"""429 — rate_limit_exceeded."""
"""429 — rate_limit_exceeded; public thesis API: rate_limited (Retry-After 60)."""

def __init__(self, message: str, *, retry_after: float | None = None, **kwargs: Any) -> None:
super().__init__(message, **kwargs)
Expand Down
135 changes: 111 additions & 24 deletions cabalspy_id/_thesis.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
"""Public thesis API: https://id.cabalspy.xyz/thesis/v1 (no API key).

Reading needs nothing. Writing uses the signed-in user's CabalSpy ID access
token with the scope "thesis" (``result.tokens["access_token"]`` after login).
Every call carries your instance's PUBLIC client_id (``csid_...``, shown in the
dashboard next to the API key; not the API key): header ``X-CSID-Client-Id``,
and ``client_id`` on the websocket URL. Reading needs nothing else. Writing uses
the signed-in user's CabalSpy ID access token with the scope "thesis"
(``result.tokens["access_token"]`` after login).

from cabalspy_id import ThesisClient

theses = ThesisClient(access_token=tokens["access_token"])
theses = ThesisClient(tokens["access_token"], client_id="csid_...")
page = theses.list("solana", mint, sort="top")
if theses.me("solana", mint)["can_post"]:
theses.post("solana", mint, body="Strong community, still early.", stance="bull")

Live updates for one token (async, needs the ``stream`` extra):

live = AsyncThesisClient().live("solana", mint)
live = AsyncThesisClient(client_id="csid_...").live("solana", mint)
live.on("thesis", print)
await live.connect()
await live.run_forever()
Expand All @@ -34,6 +37,7 @@

from ._constants import (
CHAINS,
CLIENT_ID_HEADER,
DEFAULT_THESIS_URL,
DEFAULT_THESIS_WS_URL,
THESIS_EMOJIS,
Expand All @@ -54,10 +58,82 @@
InvalidResponseError,
PermissionError_,
RateLimit,
RateLimitError,
error_from_status,
)

__all__ = ["ThesisClient", "AsyncThesisClient", "ThesisLive", "TokenThesesPage", "ThesisPage", "LIVE_EVENTS"]
__all__ = [
"ThesisClient",
"AsyncThesisClient",
"ThesisLive",
"TokenThesesPage",
"ThesisPage",
"LIVE_EVENTS",
"WS_CLOSE_CLIENT",
"WS_CLOSE_ORIGIN",
"WS_CLOSE_RATE_LIMITED",
"thesis_close_error",
]

#: Live socket close codes for the client_id checks (the close reason is the error code).
WS_CLOSE_CLIENT = 4401 # client_id_required / invalid_client: final
WS_CLOSE_ORIGIN = 4403 # origin_not_allowed: final
WS_CLOSE_RATE_LIMITED = 4429 # rate_limited: reconnect after 60 s
#: Seconds to wait after a 4429 close (the server's Retry-After).
RATE_LIMIT_BACKOFF = 60.0

_DOCS = "https://docs.cabalspy.xyz/cabalspy-id/errors#"

_CLIENT_ID_REQUIRED = (
"ThesisClient needs your instance's public client_id (csid_..., shown in the dashboard next to the "
'API key): ThesisClient(client_id="csid_..."). It is not the API key; never put the API key in a browser.'
)


def _require_client_id(client_id: Any) -> str:
if not isinstance(client_id, str) or not client_id.strip():
raise AuthenticationError(
_CLIENT_ID_REQUIRED,
code="client_id_required",
parameter="client_id",
docs=f"{_DOCS}client_id_required",
)
return client_id.strip()


def thesis_close_error(code: int | None, reason: str | None = None) -> CabalSpyIDError | None:
"""The error for a refusing close code of the public live socket, or None for an ordinary close."""
if code == WS_CLOSE_CLIENT:
c = "invalid_client" if reason == "invalid_client" else "client_id_required"
msg = (
"The live socket was refused (4401): unknown or inactive client_id"
if c == "invalid_client"
else "The live socket was refused (4401): your instance's public client_id is required"
)
return AuthenticationError(msg, code=c, status=401, docs=f"{_DOCS}{c}")
if code == WS_CLOSE_ORIGIN:
return PermissionError_(
"The live socket was refused (4403): this origin is not one of the instance's allowed origins",
code="origin_not_allowed",
status=403,
docs=f"{_DOCS}origin_not_allowed",
)
if code == WS_CLOSE_RATE_LIMITED:
return RateLimitError(
"The live socket was refused (4429): rate limited; reconnecting in 60 s",
code="rate_limited",
status=429,
docs=f"{_DOCS}rate_limited",
retry_after=RATE_LIMIT_BACKOFF,
)
if code == 1008:
return PermissionError_(
"The live socket was refused (1008): invalid token address or too many sockets from this IP",
code="ws_refused",
status=403,
)
return None


#: Events of the public live socket.
LIVE_EVENTS = ("thesis", "reply", "reaction", "removed", "heartbeat", "open", "close", "error")
Expand Down Expand Up @@ -114,17 +190,19 @@ def __init__(
self,
access_token: str | None = None,
*,
scope: ThesisScope | None = None,
client_id: str | None = None,
scope: ThesisScope | None = None,
base_url: str = DEFAULT_THESIS_URL,
ws_url: str = DEFAULT_THESIS_WS_URL,
timeout: float = 15.0,
) -> None:
client_id = _require_client_id(client_id)
_scope_query(scope, client_id)
#: global (default) or instance: only theses written on ``client_id``'s instance.
#: global (default) or instance: only theses written on your instance.
self.scope = scope
#: Your instance's client_id: needed for scope="instance"; also credits posts to your app.
self.client_id = client_id
#: Required. Your instance's PUBLIC client_id (not the API key): sent as ``X-CSID-Client-Id``
#: on every call and as ``client_id`` on the live socket; also credits posts to your app.
self.client_id: str = client_id
self._access_token = access_token
self.base_url = base_url.rstrip("/")
self.ws_url = ws_url.rstrip("/")
Expand All @@ -141,7 +219,7 @@ def _request_args(self, auth: str | None) -> dict[str, str]:
status=401,
code="sign_in_required",
)
headers = {"Accept": "application/json", "User-Agent": USER_AGENT}
headers = {"Accept": "application/json", "User-Agent": USER_AGENT, CLIENT_ID_HEADER: self.client_id}
if auth and self._access_token:
headers["Authorization"] = f"Bearer {self._access_token}"
return headers
Expand All @@ -154,11 +232,16 @@ def _parse(response: httpx.Response, label: str) -> dict[str, Any]:
parsed = None
if response.status_code >= 400 or (isinstance(parsed, dict) and parsed.get("success") is False):
err = parsed.get("error") if isinstance(parsed, dict) else None
retry_after: float | None
try:
retry_after = float(response.headers["Retry-After"])
except (KeyError, ValueError):
retry_after = None
raise error_from_status(
response.status_code,
err if isinstance(err, dict) else None,
RateLimit(),
None,
retry_after,
f"HTTP {response.status_code} on {label}",
)
if not isinstance(parsed, dict) or "data" not in parsed:
Expand Down Expand Up @@ -204,7 +287,7 @@ def _scope(self, scope: str | None, client_id: str | None) -> dict[str, str]:
return _scope_query(scope or self.scope, client_id or self.client_id)

def _attributed(self, body: dict[str, Any]) -> dict[str, Any]:
return {**body, "client_id": self.client_id} if self.client_id else body
return {**body, "client_id": self.client_id}

def live(
self,
Expand All @@ -217,11 +300,11 @@ def live(
) -> ThesisLive:
"""Live updates for one token over the public websocket (async): thesis, reply, reaction, removed.

With ``scope="instance"`` (and ``client_id``) only theses written on that instance.
The socket URL carries ``client_id``. With ``scope="instance"`` only theses written on your instance.
"""
path = _token_path(chain, mint).removeprefix("/tokens")
query = urlencode(self._scope(scope, client_id))
return ThesisLive(f"{self.ws_url}{path}" + (f"?{query}" if query else ""), **kwargs)
query = urlencode({"client_id": self.client_id, **self._scope(scope, client_id)})
return ThesisLive(f"{self.ws_url}{path}?{query}", **kwargs)


class ThesisClient(_ThesisBase):
Expand Down Expand Up @@ -555,7 +638,9 @@ async def appeal(self, notification_id: int, message: str) -> dict[str, Any]:
class ThesisLive:
"""Public live socket for one token (async). Events: thesis, reply, reaction,
removed, heartbeat, open, close, error. Reconnects after drops or missed
heartbeats; close code 1008 (invalid token, too many sockets) is final."""
heartbeats. Close codes 1008 (invalid token, too many sockets), 4401
(client_id missing or invalid) and 4403 (origin not allowed) are final;
after 4429 (rate limited) it waits 60 s before reconnecting."""

def __init__(
self,
Expand Down Expand Up @@ -666,18 +751,20 @@ async def _read(self, ws: Any) -> None:
if self._ws is ws:
self._ws = None
await self._emit("close", info)
if info.get("code") == 1008:
self._final = PermissionError_(
"The live socket was refused (1008): invalid token address or too many sockets from this IP",
code="ws_refused",
status=403,
)
await self._emit("error", self._final)
refusal = thesis_close_error(info.get("code"), info.get("reason"))
rate_limited = info.get("code") == WS_CLOSE_RATE_LIMITED
if refusal is not None:
if not rate_limited:
self._final = refusal
await self._emit("error", refusal)
if self._closed or self._final or not self.reconnect:
self._done.set()
return
min_delay = RATE_LIMIT_BACKOFF if rate_limited else 0.0
while not self._closed:
delay = min(self.reconnect_delay * (2**self._attempt), self.max_reconnect_delay) + random.random() * 0.25
backoff = min(self.reconnect_delay * (2**self._attempt), self.max_reconnect_delay)
delay = max(min_delay, backoff) + random.random() * 0.25
min_delay = 0.0
self._attempt += 1
await asyncio.sleep(delay)
if self._closed:
Expand Down
Loading
Loading