DeveloperWebhooks & Integrations

Webhooks and Integrations

StudioBrain’s SaaS runs on Cloudflare Workers. The real-time and integration surfaces are: a Stripe webhook for billing events, a tenant-scoped realtime WebSocket (/api/ws), the desktop sync engine, and the REST API with API-key authentication.

There is no Google Drive push-notification webhook. The old /api/drive/webhook/* routes are not implemented in this repo.

Stripe Webhook

Stripe sends events to POST /api/billing/webhook. It is served by the sb-accounts-billing Worker (packages/cloudflare-worker/accounts-billing/src/stripe-webhook.ts, routed from billing-routes.ts), which is part of the fenced identity/billing lane.

Handled events

Only these event types change state:

EventBackend action
checkout.session.completed (mode = subscription)Links the Stripe customer and subscription IDs to the tenant named in metadata.tenant_id
customer.subscription.created / .updatedSets the tenant plan_tier from the subscription’s metadata.plan_tier, reconciles project and seat ceilings, and syncs the storage entitlement
customer.subscription.deletedResets the tenant to the free plan and clears the subscription ID

Other event types (for example invoice.*) pass signature verification and are recorded as completed, but make no tenant changes. A subscription event without a supported metadata.plan_tier fails and is retried.

Verification

  1. The Worker reads the raw request body.
  2. It verifies the Stripe-Signature header against STRIPE_WEBHOOK_SECRET with a 300-second timestamp tolerance.
  3. Invalid signatures get 400. If the secret is unset or still the placeholder value, the route returns 503 stripe_not_configured.

Idempotency

Each event ID is claimed in the stripe_webhook_events table (D1) with a lease. A replayed completed event returns {"received": true, "replayed": true}. An event still being processed returns 409 with retry-after. A processing failure returns 500 with retryable: true so Stripe retries.

Realtime WebSocket (/api/ws)

Clients connect to wss://api.studiobrain.ai/api/ws. sb-server-worker proxies the socket to the accounts Worker (REALTIME_ORIGIN), which verifies the JWT and forwards to the tenant’s RealtimeStore Durable Object (hosted by sb-do-realtime). One DO per tenant; a user’s feed spans every project they can see.

Connection

const ws = new WebSocket(`wss://api.studiobrain.ai/api/ws?token=${jwt}`);

Browsers cannot set an Authorization header on a WebSocket handshake, so the token goes in the token query parameter; non-browser clients may send Authorization: Bearer ... instead. There is no first-message auth handshake. A token without tenant_id and sub claims is closed with code 1011.

On success the server sends:

{ "type": "connection_established", "tenant_id": "...", "user_id": "..." }

Server-to-client frames

Entity mutations on the seam are published by the ProjectStore event tap to every socket of the tenant:

{
  "type": "entity_updated",
  "tenant_id": "...",
  "entity_id": "rex_marshall",
  "entity_type": "character",
  "project_id": "...",
  "timestamp": "2026-11-18T12:00:00.000Z"
}
typeSource topic
entity_created / entity_updated / entity_deletedentity.created / .updated / .deleted
schema_added / schema_updated / schema_deletedschema.*; also carries a strictly increasing revision

Any other event-tap topic is passed through unchanged under its dotted name. Frames carry identifiers only, not field values; refetch the entity or pull GET /api/project/changes?since=<seq>.

Client-to-server messages

MessageReply
ping (plain text or {"type":"ping"}){"type":"pong"}
{"type":"heartbeat"}{"type":"heartbeat_ack"}
{"type":"hello"}{"type":"welcome","rebootstrap":true,...}
{"type":"editing_start"} / {"type":"editing_end"}Relayed to the tenant’s other sockets as a lightweight editing-presence frame

Frontend hook

The desktop and mobile frontend overlays ship useRealtimeUpdates (clients/desktop/frontend-overlay/hooks/useRealtimeUpdates.ts, same file under clients/mobile/). The hook’s option names are defined there; check that file rather than relying on older examples.

Presence REST API

GET /api/presence/{tenant_id} is part of the enterprise/self-hosted edition (crates/sb-enterprise/src/routes/presence.rs, mounted when a Valkey connection is injected). It is not served by the SaaS Workers. GET /api/presence/{tenant_id}/editing returns 501 Not Implemented.

Desktop Sync

The desktop app (Tauri, clients/desktop) syncs a local project with the cloud through a sync engine in sb-desktop (clients/desktop/crates/sb-desktop/src/sync_engine/). It publishes local changes and pulls the project change feed (GET /api/project/changes?since=<seq> on api.studiobrain.ai).

The /api/desktop/sync/* paths are local loopback routes on the embedded desktop server that the desktop UI calls, not cloud endpoints. Examples from routes/sync.rs:

MethodPathPurpose
POST/api/desktop/sync/nowTrigger a sync round
POST/api/desktop/sync/publishPublish local changes
POST/api/desktop/sync/pullPull remote changes
GET/api/desktop/sync/statusSync status
GET/api/desktop/sync/parityParity view of local vs. cloud
GET/api/desktop/sync/queue-lengthPending operation count
GET / POST/api/desktop/sync/conflictsList / resolve conflicts
PUT/api/desktop/sync/conflicts/strategySet the conflict strategy
GET / PUT/api/desktop/sync/assets/modePer-project asset cache mode

See routes/sync.rs for the full list (auth, asset prefetch, parity pause/resume). Older push, start, stop, force-push, and force-pull routes do not exist.

Integration Patterns

Headless REST API usage

# Authenticate
TOKEN=$(curl -s -X POST https://auth.studiobrain.ai/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"secret"}' \
  | jq -r '.access_token')
 
# List characters in a project
curl -s https://api.studiobrain.ai/api/entity/character \
  -H "Authorization: Bearer $TOKEN" \
  -H "X-Project-Id: $PROJECT_ID"

Writes to /api/entity/* require the X-Project-Id header (reads may fall back to the account’s active project). Login is served by the accounts Worker (worker/src/auth-core-routes.ts); the exact response shape of each route is not documented here, so check the route handlers before scripting against them.

API keys

POST /api/api-keys creates a key and GET /api/api-keys lists the caller’s keys (packages/cloudflare-worker/worker/src/api-key-routes.ts). Personal API key management UI lives in the accounts app at /settings/account/keys.

Testing webhooks locally

Expose a local wrangler dev instance of sb-accounts-billing with a tunnel such as ngrok, then point a Stripe test-mode endpoint (or stripe listen --forward-to .../api/billing/webhook) at it and set STRIPE_WEBHOOK_SECRET in .dev.vars (see accounts-billing/.dev.vars.example).