# SubEtha documentation (all pages) Source: https://curtcox.github.io/subetha/docs/ # SubEtha docs SubEtha is a hosted pub/sub relay. You publish a message to a **topic**, and every device subscribed to that topic gets it over whatever path works: a WebSocket, a phone push, a webhook, email, Slack, SMS, a phone call, an MCP agent, or a Reticulum mesh. Publishers never need to know who is listening or how they're reached. It speaks ntfy's wire protocol, so this works: ```bash title="samples/curl/publish.sh" #!/usr/bin/env bash # Publish a message: the body is the message text. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -d "Backup done" \ "$SUBETHA_URL/@me/backups" ``` ## Where to start | If you want to… | Read | |---|---| | Send your first message in two minutes | [Getting started](getting-started.md) | | Understand topics, devices, endpoints, routing, and who pays | [Concepts](concepts.md) | | Publish with headers, JSON, signatures, E2EE, attachments, retries, or dry runs | [Publishing](publishing.md) | | Receive as JSON, SSE, raw text, WebSocket, or by polling | [Subscribing](subscribing.md) | | Deliver to push, email, Slack, SMS, voice, webhooks, or LXMF | [Transports](transports.md) | | Know what it costs and how the balance works | [Pricing & billing](pricing.md) | | Hand out safe credentials and set topic rules | [Tokens & policies](tokens.md) | | Enroll phones, Pis, and CLIs as devices | [Devices](devices.md) | | Use the TypeScript, Python, or Rust SDKs, the CLI, or web components | [SDKs & CLI](sdks.md) | | Connect an AI agent | [Agents (MCP, llms.txt)](agents.md) | | Run locally, or bridge your own transport | [Self-hosting & gateways](self-hosting.md) | | Look up a route, header, or error code | [API reference](api.md) | ## Principles - **Topics, not addresses.** Devices only know topic names (and optionally keys). - **The relay picks the route.** Transport selection, fallback, escalation, retries, and dedupe happen in the relay and the SDKs. - **The owner stays in control.** Allow-lists, spend caps, rate limits, quiet hours, and a per-message trace showing the route and its cost. - **No surprises on the bill.** Every action is prepaid and checked against your balance before it runs. `X-Dry-Run: 1` tells you the price first. Every code sample in these docs is a real file under [`docs/samples/`](https://github.com/curtcox/subetha/tree/main/docs/samples) and runs in CI, so the snippets you copy are known to work. --- # Getting started You need an account with a little credit, and a token. Then publishing is one HTTP request. ## 1. Get a token 1. Sign in at [subetha.us/console](https://subetha.us/console/) and pick a **handle**. Your topics live under `@handle/…`. 2. Top up your balance (minimum $5). See [Pricing & billing](pricing.md). 3. Create a token under **Tokens**. For scripts, scope it narrowly and give it a daily cap (see [Tokens & policies](tokens.md)). ```bash export SUBETHA_TOKEN=se_xxxxxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` Prefer to try it locally first? Run the relay on your machine and get a funded account without signing up: ```bash title="samples/curl/local-dev.sh" #!/usr/bin/env bash # Run the relay locally and get a funded account and admin token. set -euo pipefail # In one terminal (from the repository root): # pnpm install && pnpm --filter @subetha/sdk build && pnpm --filter @subetha/site build # pnpm --filter @subetha/api exec wrangler d1 migrations apply DB --local # pnpm --filter @subetha/api dev # http://localhost:8787 # In another: export SUBETHA_URL=http://localhost:8787 SUBETHA_TOKEN=$(curl -sS -X POST "$SUBETHA_URL/v1/dev/bootstrap" \ -d '{"secret":"local-dev-only","handle":"me","credit_usd":5}' | jq -r .token) export SUBETHA_TOKEN curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" -d "hello from localhost" "$SUBETHA_URL/@me/test" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/@me/test/json?poll=1" ``` ## 2. Publish ```bash title="samples/curl/publish.sh" #!/usr/bin/env bash # Publish a message: the body is the message text. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -d "Backup done" \ "$SUBETHA_URL/@me/backups" ``` The response is the stored message, with its `id`. The `X-Cost-Micros` response header says what you were charged, in micro-dollars (µ$; 1,000,000 µ$ = $1). Topics are created on first publish in your own namespace (`@yourhandle/anything`) or as secret `t_…` topics (see [Concepts](concepts.md#topics)). ## 3. Subscribe In another terminal: ```bash title="samples/curl/subscribe-json.sh" #!/usr/bin/env bash # Stream messages as newline-delimited JSON (one envelope per line). # The first line is an "open" event; "keepalive" events arrive periodically. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" \ "$SUBETHA_URL/@me/doorbell/json" # Pipe it through jq to print just the messages: # curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/@me/doorbell/json" \ # | jq --unbuffered -r 'select(.event == null or .event == "message") | .message' ``` Publish again and the message appears on the stream immediately. Or open `https://subetha.us/@me/backups` in a browser: topic URLs open in the web console. ## 4. Use an SDK The TypeScript SDK (`npm i @subetha/sdk`) handles reconnects, dedupe, acks, signatures, and encryption. It runs in browsers, Node 18+, Deno, Bun, and Workers. ```ts title="samples/ts/publish.ts" const se = new SubEtha({ baseUrl, token, fetch }); const msg = await se.publish(topic, "Backup finished in 4m12s", { title: "nightly-backup", priority: 4, tags: ["backup", "white_check_mark"], click: "https://example.com/backups/latest", }); console.log(`published ${msg.id} to ${msg.topic}`); ``` ```ts title="samples/ts/subscribe.ts" const first = new Promise((resolve, reject) => { const sub = se.subscribe(topic, (m) => { console.log(`${m.title ?? ""} ${m.message}`); sub.close(); resolve(m); }, { transport: "stream", // "auto" (the default) prefers a WebSocket when there is one priority: [3, 4, 5], // filtered on the server onOpen: () => void se.publish(topic, "hello, subscriber").catch(reject), onError: (e) => console.warn("reconnecting:", e.message), }); }); const message = await first; ``` There are also a [Python SDK, a Rust core, a CLI, and drop-in web components](sdks.md). ## Built-in tools - [Pricing calculator](/tools/pricing.html): a month of usage, priced from the same table the relay charges from, and the top-up that covers it. - [Route simulator](/tools/simulator.html): which transports a message would use, in what order, and at what cost. It runs the relay's planner in your browser, so it needs no account. - In the [console](https://subetha.us/console/): **Copy as** curl, JavaScript, Python, Swift, Kotlin, or Dart for any message you compose; **Simulate route & cost** (a dry run against your real topic); a token builder; a trace viewer; and an **API explorer** that sends any operation in the [OpenAPI document](/openapi.yaml) with your credential. ## Next - Deliver to phones, email, Slack, or SMS: [Transports](transports.md). - Control cost and routing per message: [Publishing](publishing.md#routing-and-cost). - Let an AI agent publish and wait for replies: [Agents](agents.md). --- # Concepts SubEtha has a small vocabulary. Once these click, the rest of the API follows. | Concept | What it is | |---|---| | **Account** | Holds the prepaid balance and owns topics, devices, endpoints, tokens, and policies. | | **Topic** | The rendezvous point. Publishers and subscribers only ever name topics. | | **Message** | An ntfy-compatible JSON envelope plus SubEtha extensions. | | **Device** | Something running an SDK with its own Ed25519 key: a phone, a browser, a Pi, a CLI, an agent. | | **Endpoint** | A non-SDK destination: an email address, a phone number, a Slack channel, a webhook URL, a push token, an LXMF address. | | **Subscription** | Topic → endpoint, with filters and an optional escalation delay. | | **Transport** | A path a message can take: `ws`, `sse`, `poll`, `webpush`, `apns`, `fcm`, `webhook`, `email`, `slack`, `sms`, `voice`, `mcp`, `lxmf`, and the edge transports `ble`, `audio`, `qr`, `lan`. | | **Trace** | Per-message record of the route plan, each delivery attempt, acks, and cost. Only the topic owner sees it. | ## Topics A topic name is one of: | Form | Example | Notes | |---|---|---| | Namespaced | `@alice/doorbell` | `@handle/name`. Only Alice's account can create topics under `@alice/`. Names are `[A-Za-z0-9_-]{1,64}`. | | Secret | `t_mfrggzdfmztwq2lknnwg23tpoa` | `t_` + 26 base32 characters (128 random bits). Anyone who knows the name can read it, like an ntfy "secret URL". Stock ntfy clients accept these names unchanged. | Global names like `subetha.us/mytopic` are not accepted. A topic is created by its owner's first publish to it, or explicitly with `PUT /v1/topics/{topic}` (which also sets its [policy](tokens.md#topic-policies)). Subscribing to a topic that doesn't exist yet returns 404. Namespaced topics are private by default: only the owner's credentials can read and publish. A policy can open them up (`public_read`, `public_publish`, `allowed_publishers`, `allowed_readers`). ## Messages A message is a superset of ntfy's message JSON: ```json { "id": "01JD5Z8W3V6X0M3K9Q2T4R7B1C", "time": 1763750000, "expires": 1763793200, "event": "message", "topic": "@alice/doorbell", "title": "Front door", "message": "Opened", "priority": 4, "tags": ["door", "warning"], "click": "https://cam.example.com/front", "attachment": { "name": "snap.jpg", "url": "https://subetha.us/file/01jd…/snap.jpg", "size": 81234, "type": "image/jpeg" }, "route": { "mode": "any", "max_cost_usd_micros": 20000, "deny": ["voice"] } } ``` - `id` is a ULID and the dedupe key everywhere: the same message arriving over a WebSocket and a push notification is shown once. - `priority` is 1–5 (3 is the default and is omitted). - `message` is at most 4096 bytes. Larger content goes in an [attachment](publishing.md#attachments). - Messages are kept until `expires` (12 hours by default; a topic's `retention_s` can raise it to 30 days), so subscribers that reconnect can catch up with `since=`. - Optional extensions: `sender` + `sig` ([signatures](publishing.md#signed-messages)), `enc` ([end-to-end encryption](publishing.md#end-to-end-encryption)), `route`, `content_type`, and `hops` (edge relaying). The normative definition is the [protocol spec](https://github.com/curtcox/subetha/blob/main/spec/README.md) and its [JSON Schema](https://github.com/curtcox/subetha/blob/main/spec/schema/message.schema.json). ## Devices and endpoints There are two ways to receive: - **Devices** run an SDK and connect: a WebSocket, an SSE or NDJSON stream, or polling. Live delivery is cheap, and SDKs ack messages so escalation stops. A device has its own key and can sign messages and requests ([Devices](devices.md)). - **Endpoints** are destinations the relay pushes to: push tokens, email addresses, phone numbers, Slack channels, webhooks, LXMF addresses. The topic owner adds them and subscribes them to topics. Paid destinations a third party could be spammed through (email, SMS, voice) must be **verified** with a code first ([Transports](transports.md)). ## Routing On every publish the relay builds a **delivery plan**. For each subscriber it intersects what's allowed by the account, the topic policy, the subscription, the token, and the message (`allow` and `deny` lists, priority thresholds, quiet hours, cost caps), then orders what's left by the **route mode**: | Mode | Behavior | |---|---| | `any` (default) | Deliver once, by the cheapest viable path. Escalation steps run only if the message is still unacked. | | `fast` | Lowest latency first. | | `all` | Every allowed transport at once (alarms). | | `cheap` | Free/live transports only; never escalate to paid ones. | **Escalation** is configured per subscription with `after_s`: for example push immediately, SMS after 60 s, a phone call after 180 s. Each step is queued with its own reservation and is skipped (and its reservation released) once anyone acks the message: an SDK, a WebSocket ack frame, a Web Push service worker, replying `ACK ` by SMS, pressing 1 on the call, or `POST /v1/ack`. See the [escalation example](transports.md#escalation). The relay never tells a device which other devices exist or how they were reached. Only the owner sees that, in the [trace](pricing.md#traces). ## Who pays? - The **publisher** pays for the publish (and for any attachment it uploads). - The **topic owner** pays for fan-out and delivery: live deliveries, pushes, emails, SMS, storage, and reads (polls, stream connections, attachment downloads). - **Anonymous** publishing works only on topics whose owner allows it (`public_publish`), with a per-minute rate limit and a daily cap, charged to the owner. If the owner can't pay, the publish fails with `402 no_funded_owner`. So `curl -d hi subetha.us/@alice/doorbell` can be free for the person ringing the bell, while Alice decides exactly how much ringing she's willing to pay for. Details: [Pricing & billing](pricing.md). --- # Publishing There are three ways to publish, all equivalent: | Form | Request | Use it for | |---|---|---| | ntfy headers | `PUT`/`POST /{topic}`, the body is the message, options in headers | `curl`, shell scripts, ntfy clients | | Query string | `POST /{topic}?title=…&priority=…&message=…` | places that can't set headers | | JSON | `POST /` with a JSON envelope | signed or encrypted messages, extension fields, SDKs | The publisher's token (or account) is charged for the publish; the topic owner pays for delivery ([who pays](concepts.md#who-pays)). ## Headers ```bash title="samples/curl/publish-headers.sh" #!/usr/bin/env bash # Publish with ntfy headers: title, priority, tags, click URL, action buttons, Markdown. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -H "Title: Front door" \ -H "Priority: high" \ -H "Tags: door,warning" \ -H "Click: https://cam.example.com/front" \ -H "Actions: view, Open camera, https://cam.example.com/front; http, Lock door, https://home.example.com/lock, clear=true" \ -H "Markdown: yes" \ -d "**Opened** at $(date +%H:%M)" \ "$SUBETHA_URL/@me/doorbell" # The same thing with query parameters (handy where you can't set headers): curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" -X POST \ "$SUBETHA_URL/@me/doorbell?title=Front%20door&priority=4&tags=door&message=Opened" ``` | Header | Aliases (and query parameter) | Meaning | |---|---|---| | `X-Title` | `Title`, `t` (`?title=`) | Title. Non-ASCII works with RFC 2047 encoded words, or use JSON. | | `X-Priority` | `Priority`, `prio`, `p` (`?priority=`) | `1`–`5`, or `min`, `low`, `default`, `high`, `max`/`urgent`. | | `X-Tags` | `Tags`, `Tag`, `ta` (`?tags=`) | Comma-separated. ntfy clients show emoji for tags like `warning` or `white_check_mark`. | | `X-Click` | `Click` | URL opened when the notification is tapped. | | `X-Icon` | `Icon` | Notification icon URL. | | `X-Actions` | `Actions` | Up to three ntfy action buttons: `view, Label, url; http, Label, url, clear=true`, or a JSON array. | | `X-Markdown` | `Markdown`, `md` | `yes` sets `content_type: text/markdown`. | | `X-Attach` | `Attach`, `a` | Link an attachment by URL. | | `X-Filename` | `Filename`, `f` | Upload the body as an attachment with this name (see [Attachments](#attachments)). | | `X-Message` | `Message`, `m` (`?message=`) | Message text when the body is empty or is an attachment. | | `X-Expires` | | Unix seconds; capped at the topic's retention. | | `X-Route-Mode` | | `any`, `fast`, `all`, `cheap` (see [Routing and cost](#routing-and-cost)). | | `X-Max-Cost` | | Maximum delivery cost for this message, in USD. | | `X-Deny` / `X-Allow` | | Comma-separated transport ids never to use / the only ones to use. | | `Idempotency-Key` | | Makes retries safe (see [Idempotency](#idempotency)). | | `X-Dry-Run` | | `1`: plan and price only, nothing delivered (see [Dry runs](#dry-runs)). | | `X-Sender`, `X-Signature`, `X-Message-Id`, `X-Time` | | A signed message in header form. JSON is easier. | | `X-Delay` | `Delay`, `X-At`, `X-In` | Scheduled delivery isn't supported yet: rejected with `unsupported`. | The same thing from code, without the SDK: ```ts title="samples/ts/publish-fetch.ts" const r = await fetch(`${baseUrl}/${topic}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "x-title": "Front door", "x-priority": "high", "x-tags": "door,warning", }, body: "Opened", }); if (!r.ok) throw new Error(`publish failed: ${r.status} ${await r.text()}`); const msg = (await r.json()) as { id: string; priority?: number; tags?: string[] }; console.log(`published ${msg.id}; charged ${r.headers.get("x-cost-micros")} µ$`); ``` ## JSON `POST /` takes a whole envelope. ntfy's JSON aliases work too: `priority` as a name, `attach` and `filename`, and `markdown: true`. ```bash title="samples/curl/publish-json.sh" #!/usr/bin/env bash # Publish a JSON envelope to POST / (ntfy JSON publishing, plus every SubEtha field). set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "topic": "@me/alerts", "title": "Disk almost full", "message": "/var is at 91%", "priority": "high", "tags": ["warning", "disk"], "click": "https://grafana.example.com/d/disk", "route": { "mode": "any", "max_cost_usd_micros": 20000, "deny": ["voice"] } }' \ "$SUBETHA_URL/" ``` ## Routing and cost Per message you can choose the [route mode](concepts.md#routing), cap the delivery cost, and allow or deny transports. These narrow what the topic owner's policies already allow; they can never widen it. ```bash title="samples/curl/publish-route.sh" #!/usr/bin/env bash # Control routing and cost per message. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" # An alarm: every allowed transport at once, but never more than 5 cents, and never a phone call. curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -H "Priority: urgent" \ -H "X-Route-Mode: all" \ -H "X-Max-Cost: 0.05" \ -H "X-Deny: voice" \ -d "Smoke detected in the garage" \ "$SUBETHA_URL/@me/alarm" # Chatter: free transports only (live WebSocket/SSE/poll), never escalate to paid ones. curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -H "X-Route-Mode: cheap" \ -d "build 1234 passed" \ "$SUBETHA_URL/@me/ci" # Only these transports may be used. curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -H "X-Allow: ws,webpush,email" \ -d "Weekly report is ready" \ "$SUBETHA_URL/@me/reports" ``` If no allowed transport is left for a delivery, it is dropped from the plan. The trace says why (`transport denied by policy`, `below minimum priority`, `quiet hours`, `route mode cheap`, …). ## Dry runs `X-Dry-Run: 1` returns the delivery plan and a worst-case estimate in µ$, and delivers nothing. It costs one API request. The plan lists each subscriber's transport, its price, and its escalation delay; it is shown only to the topic owner (others see an empty plan and the price). ```bash title="samples/curl/dry-run.sh" #!/usr/bin/env bash # Dry run: the route plan and a worst-case cost estimate. Nothing is delivered; # you pay for one API request. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -H "X-Dry-Run: 1" \ -H "Priority: 5" \ -H "X-Route-Mode: all" \ -d "Smoke detected" \ "$SUBETHA_URL/@me/alarm" # {"dry_run":true,"estimate_usd_micros":16612,"plan":[{"transport":"ws",...},{"transport":"sms","after_s":60,...}],"message":{...}} ``` ```ts title="samples/ts/dry-run.ts" const est = await se.estimate(topic, "Smoke detected", { priority: 5, route: { mode: "all", maxCostUsd: 0.05, deny: ["voice"] }, }); console.log(`would cost up to $${(est.estimate_usd_micros / 1e6).toFixed(6)}`); for (const step of est.plan) console.log(step); ``` ## Idempotency Networks fail after the server has acted. Send an `Idempotency-Key` and a retry returns the original message with `X-Duplicate: 1` instead of delivering and charging again. Reusing a key with a *different* request is `409 conflict`. A message's `id` works the same way: publishing an `id` that already exists returns the stored message. ```bash title="samples/curl/idempotency.sh" #!/usr/bin/env bash # Safe retries: the same Idempotency-Key returns the original message (with X-Duplicate: 1) # instead of delivering and charging again. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" for attempt in 1 2 3; do if curl -sS --fail-with-body --max-time 10 \ -H "Authorization: Bearer $SUBETHA_TOKEN" \ -H "Idempotency-Key: invoice-2041-paid" \ -d "Invoice 2041 was paid" \ "$SUBETHA_URL/@me/billing"; then break fi sleep "$attempt" done ``` ```ts title="samples/ts/idempotency.ts" const key = "order-1234-shipped"; const a = await se.publish(topic, "Order 1234 shipped", { idempotencyKey: key }); const b = await se.publish(topic, "Order 1234 shipped", { idempotencyKey: key }); // e.g. a retry after a timeout console.log(a.id === b.id); // true: one message, charged once ``` ## Attachments Send a file as the request body with `X-Filename` (up to 15 MB). The relay stores it until the message expires and puts a download URL in `attachment.url`. The message text goes in `X-Message`. The publisher pays an upload fee plus storage for the message's lifetime; each download is charged to the topic owner as one API request. Images, audio, video, plain text, and PDF open inline; everything else downloads. ```bash title="samples/curl/attachment.sh" #!/usr/bin/env bash # Attach a file (up to 15 MB): the body is the file, X-Filename names it, and the message text # goes in X-Message. The publisher pays for the upload and its storage until the message expires. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -T snapshot.jpg \ -H "X-Filename: snapshot.jpg" \ -H "Content-Type: image/jpeg" \ -H "X-Message: Motion at the front door" \ "$SUBETHA_URL/@me/doorbell" # {"id":"01JD…","attachment":{"name":"snapshot.jpg","url":"https://subetha.us/file/01jd…/snapshot.jpg","size":81234,"type":"image/jpeg"},…} # Or link a file that's already hosted somewhere (no upload, no storage charge): curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" \ -H "X-Attach: https://example.com/reports/weekly.pdf" \ -d "Weekly report" \ "$SUBETHA_URL/@me/reports" ``` ```ts title="samples/ts/attachment.ts" const r = await fetch(`${baseUrl}/${topic}`, { method: "PUT", headers: { authorization: `Bearer ${token}`, "x-filename": "energy.csv", "content-type": "text/csv", "x-message": "Yesterday's energy report", // the body is the file, so the text goes in a header }, body: csv, }); const msg = (await r.json()) as { id: string; attachment: { name: string; url: string; size: number; type: string } }; console.log(msg.attachment); // { name: "energy.csv", url: "https://subetha.us/file/…/energy.csv", size: 53, type: "text/csv" } // Anyone with the URL can download it until the message expires (the topic owner pays per download). const file = await fetch(msg.attachment.url); ``` To link something that's already hosted, use `X-Attach: ` instead; nothing is uploaded. ## Signed messages A device can sign a message with its Ed25519 key. The signature covers the whole envelope except `sig` and `hops`, and the public key is inside the `sender` id, so any receiver (or edge relay) can verify it without a lookup. A topic policy can require signatures (`require_signature`); then unsigned or badly signed messages get `401 signature_required` / `bad_signature`. ```ts title="samples/ts/signed.ts" const deviceKey = await generateDeviceKey(); // persist deviceKey.seed somewhere safe const se = new SubEtha({ baseUrl, token, fetch, deviceKey }); const sent = await se.publish(topic, "Temperature 21.5C"); // signed automatically console.log(sent.sender, sent.sig); // Any receiver can check the signature: the public key is inside the sender id. const [received] = await se.poll(topic); console.log("valid:", await verifyEnvelope(received!)); ``` Signed and encrypted messages must carry their own `id` and `time` (the SDKs set them), with `time` no more than 5 minutes ahead or 7 days behind the relay's clock. The relay delivers them exactly as sent apart from `event`, which is outside the signature, so they still verify on the way out. ## End-to-end encryption With a 32-byte topic key shared out of band, the SDK encrypts `title`, `message`, `attachment`, `click`, `actions`, and `content_type` with XChaCha20-Poly1305 before the message leaves the device. The relay routes ciphertext and never sees keys. Push, email, SMS, and Slack deliveries of encrypted messages show a short "encrypted message" notice instead of the text. ```ts title="samples/ts/e2ee.ts" // Share these 32 bytes out of band (QR code, password manager…) with every device on the topic. const key = crypto.getRandomValues(new Uint8Array(32)); const topicKeys = { [topic]: { kid: "k1", key } }; const se = new SubEtha({ baseUrl, token, fetch, topicKeys }); await se.publish(topic, "The door code is 4721", { title: "Secret" }); const [plain] = await se.poll(topic); // decrypted for us const [wire] = await new SubEtha({ baseUrl, token, fetch }).poll(topic); // what the relay stores console.log(plain!.message, "|", wire!.enc, wire!.message); ``` If you sign *and* encrypt, the SDK encrypts first and signs the ciphertext. ### Sharing keys with devices Instead of copying the key to each device by hand, the owner can seal it to enrolled devices' identity keys and leave the sealed copies on the relay ([spec §5.1](https://github.com/curtcox/subetha/blob/main/spec/README.md#51-wrapped-topic-keys)). Each device fetches only the copies addressed to it, with a signed request, and opens them with its own key; the relay can't. To rotate, share a new `kid`: devices switch to the newest one the next time they load keys (the SDK holds one key per topic, so messages sent under the old `kid` need the old key to read). To stop sharing with a device, delete its copies (and rotate, since it may have kept the old key). ```ts title="samples/ts/key-sharing.ts" // Owner (admin token): create the topic, then wrap a fresh key for each device that should read it. const owner = new SubEtha({ baseUrl, token, fetch }); await owner.configureTopic(topic, {}); const key = crypto.getRandomValues(new Uint8Array(32)); await owner.shareTopicKey(topic, "2026-11", key, [deviceKey.deviceId]); const sender = new SubEtha({ baseUrl, token, fetch, topicKeys: { [topic]: { kid: "2026-11", key } } }); await sender.publish(topic, "Gate code is 0451"); // Device: fetch and open its wrapped keys with a signed request, then read as usual. const device = new SubEtha({ baseUrl, fetch, deviceKey, signRequests: true }); await device.loadTopicKeys(); const [msg] = await device.poll(topic); console.log(msg!.message); // "Gate code is 0451" ``` In the console, **Topics → End-to-end encryption keys** does the same without code: **New key** makes a key, wraps it for the enrolled devices you tick, and shows it once so you can share it by hand. The console then encrypts what it sends to the topic and decrypts its inbox. Keys pasted under **Keys in this browser** work the same way; they're kept in memory unless you choose to remember them in the browser's local storage. | Endpoint | Who | Does | |---|---|---| | `PUT /v1/keys` | admin | Stores up to 100 wrapped keys (`{"keys": [...]}`) for topics you own; same topic + kid + device replaces. | | `GET /v1/keys[?topic=]` | device | The wrapped keys addressed to the calling device. | | `GET /v1/keys[?topic=]` | admin | Every wrapped key for your topics. | | `DELETE /v1/keys?topic=[&kid=][&device=]` | admin | Deletes matching wrapped keys. | Each call is metered as one API request. In the TS SDK: `shareTopicKey`, `loadTopicKeys`, `listWrappedKeys`, `deleteWrappedKeys`, and `setTopicKey` (use a key you already hold); in the Rust core, `keywrap::wrap_topic_key` and `unwrap_topic_key`. ## Responses and errors A successful publish returns `200` with the stored envelope, plus `X-Message-Id` and `X-Cost-Micros` headers. Errors are JSON with a stable code: ```json { "error": "insufficient_balance", "http": 402, "message": "…", "shortfall_usd_micros": 1234 } ``` The ones you'll meet most when publishing: `invalid_topic`, `message_too_large` (body over 4096 bytes without `X-Filename`), `forbidden` (token scope or policy), `insufficient_balance` / `no_funded_owner` (402), `spend_cap_exceeded`, `topic_paused`, `rate_limited` (429, with `Retry-After`). The full list is in the [API reference](api.md#errors). --- # Subscribing Devices and scripts receive messages by connecting to a topic. (To have the relay *push* to an email address, phone, Slack channel, or webhook instead, see [Transports](transports.md).) | Path | Format | |---|---| | `GET /{topics}/json` | Newline-delimited JSON, one envelope per line | | `GET /{topics}/sse` | Server-sent events | | `GET /{topics}/raw` | Message bodies only, one per line | | `GET /{topics}/ws` | WebSocket, one JSON envelope per frame (one topic per socket) | | `GET /{topics}/json?poll=1` | Cached messages, then the connection closes | `{topics}` is one topic (`@alice/doorbell`) or several separated by commas (`@alice/doorbell,@alice/alarm`). The stream starts with an `open` event and sends `keepalive` events periodically; treat any envelope without an `event`, or with `event: "message"`, as a message. Reading is charged to the topic owner: one API request per connection or poll, a live-delivery fee per message, and connection time for long-lived streams ([Pricing](pricing.md)). The topic must exist: subscribing to one that doesn't is a 404. ## JSON stream ```bash title="samples/curl/subscribe-json.sh" #!/usr/bin/env bash # Stream messages as newline-delimited JSON (one envelope per line). # The first line is an "open" event; "keepalive" events arrive periodically. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" \ "$SUBETHA_URL/@me/doorbell/json" # Pipe it through jq to print just the messages: # curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/@me/doorbell/json" \ # | jq --unbuffered -r 'select(.event == null or .event == "message") | .message' ``` ## Server-sent events ```bash title="samples/curl/subscribe-sse.sh" #!/usr/bin/env bash # Server-sent events: "id: " and "data: " per event. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" \ "$SUBETHA_URL/@me/doorbell/sse?since=10m" # In a browser (EventSource can't set headers, so pass the token as ?auth=): # const auth = btoa(`Bearer ${token}`).replace(/=+$/, ""); # new EventSource(`https://subetha.us/@me/doorbell/sse?auth=${auth}`) # .onmessage = (e) => console.log(JSON.parse(e.data).message); ``` ## Raw ```bash title="samples/curl/subscribe-raw.sh" #!/usr/bin/env bash # Raw: message bodies only, one per line. Good for shell pipelines. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/@me/doorbell/raw" | while IFS= read -r line; do [ -z "$line" ] && continue # keepalive notify-send "doorbell" "$line" || echo "doorbell: $line" done ``` ## WebSocket ```bash title="samples/curl/subscribe-ws.sh" #!/usr/bin/env bash # WebSocket (one topic per socket). Each frame is one JSON envelope. Send # {"event":"ack","id":""} to acknowledge a message and stop escalation. # Uses websocat (https://github.com/vi/websocat). set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" WS_URL="${SUBETHA_URL/https:/wss:}" WS_URL="${WS_URL/http:/ws:}" websocat -H "Authorization: Bearer $SUBETHA_TOKEN" "$WS_URL/@me/doorbell/ws" # Browsers can't set headers on WebSockets, so use ?auth=: # const auth = btoa(`Bearer ${token}`).replace(/=+$/, ""); # const ws = new WebSocket(`wss://subetha.us/@me/doorbell/ws?auth=${auth}`); # ws.onmessage = (e) => { const m = JSON.parse(e.data); if (m.event === "message") ws.send(JSON.stringify({ event: "ack", id: m.id })); }; ``` ## Polling, `since`, and filters ```bash title="samples/curl/poll.sh" #!/usr/bin/env bash # Poll: return cached messages and close. since= takes a message id, Unix seconds, a duration, or "all". set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN") # Everything still retained: curl -sS "${AUTH[@]}" "$SUBETHA_URL/@me/doorbell/json?poll=1&since=all" # The last hour, high priority only, tagged "door": curl -sS "${AUTH[@]}" "$SUBETHA_URL/@me/doorbell/json?poll=1&since=1h&priority=4,5&tags=door" # Several topics at once (comma-separated), resuming after a message id: curl -sS "${AUTH[@]}" "$SUBETHA_URL/@me/doorbell,@me/alarm/json?poll=1&since=01JD5Z8W3V6X0M3K9Q2T4R7B1C" ``` | Parameter | Meaning | |---|---| | `since` | Replay cached messages first: a message id (messages after it), Unix seconds, a duration (`30s`, `10m`, `2h`, `1d`), or `all`. Without it, a stream starts with new messages only. Polls default to `all`. | | `poll=1` | Return what's cached and close. | | `priority` | Only these priorities, comma-separated numbers or names (`4,5`, `high,urgent`). Aliases `prio`, `p`. | | `tags` | Only messages carrying all of these tags. Aliases `tag`, `ta`. | A replay returns at most 1,000 messages. To resume after a disconnect without gaps or duplicates, reconnect with `since=`. The SDKs do this for you, and dedupe by id. With the SDK: ```ts title="samples/ts/poll.ts" const urgent = await se.poll(topic, { since: "1h", priority: [4, 5] }); for (const m of urgent) console.log(m.id, m.priority, m.message); ``` ## Authentication Send `Authorization: Bearer `. For clients that can't (browsers' `EventSource` and `WebSocket`, some ntfy apps), use HTTP Basic with an empty user name, or `?auth=`: ```bash title="samples/curl/ntfy-auth.sh" #!/usr/bin/env bash # Credentials the way ntfy clients send them. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" # HTTP Basic with an empty username and the token as the password: curl -sS -u ":$SUBETHA_TOKEN" -d "hi" "$SUBETHA_URL/@me/test" # ?auth= with base64url("Bearer ") (no padding), for clients that can't set headers: AUTH=$(printf 'Bearer %s' "$SUBETHA_TOKEN" | base64 | tr -d '=\n' | tr '+/' '-_') curl -sS "$SUBETHA_URL/@me/test/json?poll=1&auth=$AUTH" # The ntfy CLI and apps work too: point them at the server and use the token. # ntfy publish --token "$SUBETHA_TOKEN" https://subetha.us/t_mfrggzdfmztwq2lknnwg23tpoa "hi" ``` A token needs the `subscribe` scope for the topic. Secret `t_…` topics are readable by anyone who knows the name, and a topic's policy can make a namespaced topic public (`public_read`) or list extra readers (`allowed_readers`). On public pages use a [publishable token](tokens.md#publishable-tokens), never an admin one. ## Acknowledging An ack tells the relay a message was seen, which cancels pending [escalation steps](concepts.md#routing) (SMS, phone calls…) and releases their reservations. The SDKs ack automatically. Over a WebSocket, send `{"event":"ack","id":""}`. Otherwise: ```bash title="samples/curl/trace-ack.sh" #!/usr/bin/env bash # Publish, look at the message's trace, and acknowledge it. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" TOPIC="@me/alarm" ID=$(curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" -H "Priority: 5" -d "Water leak" \ "$SUBETHA_URL/$TOPIC" | jq -r .id) # Route plan, each delivery attempt, acks, and µ$ per step (topic owner only): curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/v1/traces/$ID?topic=$TOPIC" # Acknowledge: pending escalation steps (SMS, voice…) are cancelled and their reservations released. curl -sS -H "Content-Type: application/json" -d "{\"topic\":\"$TOPIC\",\"id\":\"$ID\",\"via\":\"http\"}" \ "$SUBETHA_URL/v1/ack" ``` Acking needs read access to the topic. Acks are idempotent. ## ntfy apps The ntfy Android/iOS apps and CLI can subscribe to SubEtha: add `https://subetha.us` as a server, use a token as the password (empty user name), and subscribe to a secret `t_…` topic (ntfy's apps only accept topic names without `@` or `/`, which secret topics satisfy). Signed and encrypted messages need a SubEtha SDK to verify or decrypt. --- # Transports A transport is a path a message can take. Some are **live** (a device holds a connection), some are **relay-pushed** to an endpoint (push, email, SMS…), and some are **edge** transports that run entirely on devices and never touch the relay. | Transport | id | Kind | Endpoint address | Verified by code? | |---|---|---|---|---| | WebSocket / SSE / JSON stream / poll | `ws`, `sse`, `poll` | live | – | – | | Web Push | `webpush` | push | browser push subscription JSON | no (the browser owns it) | | Apple Push (APNs) | `apns` | push | hex device token | no | | Firebase Cloud Messaging | `fcm` | push | FCM registration token | no | | Webhook | `webhook` | relay | `https://` URL | no (signed; secret shown once) | | Email | `email` | relay, in/out | email address | **yes** | | Slack | `slack` | relay, in/out | channel (via the Slack app) | OAuth install | | SMS | `sms` | relay, in/out | E.164, US or an opt-in country | **yes** | | Voice | `voice` | relay | E.164, US or an opt-in country | **yes** | | WhatsApp | `whatsapp` | relay, in/out | E.164, US or an opt-in country | **yes** | | MCP | `mcp` | live (agents) | – | – | | Reticulum / LXMF | `lxmf` | gateway | 32-hex LXMF destination | no | | Bluetooth LE, audio, QR, LAN | `ble`, `audio`, `qr`, `lan` | edge | – | – (free, SDK only) | The general recipe for relay-pushed transports: 1. `POST /v1/endpoints` with a `kind` and `address`. Email, SMS, and voice endpoints receive a 6-digit code (charged like one delivery), which you confirm with `POST /v1/endpoints/{id}/verify` within 30 minutes (5 attempts). 2. `POST /v1/subscriptions` to deliver a topic to that endpoint, optionally with a `filter` (priorities, tags), `min_priority`, and `after_s` (an escalation delay). Only the topic owner can subscribe endpoints to a topic, because the owner pays for delivery. Deliveries are queued, retried with backoff on transient failures (timeouts, 429, 5xx), and dropped on permanent ones (4xx, a revoked push token, an unverified endpoint). Every attempt is in the message's [trace](pricing.md#traces). `GET /v1/status` shows which transports a deployment has configured. Each section below also lists the secrets an operator must set for the transport to work (see [`infra/secrets.md`](https://github.com/curtcox/subetha/blob/main/infra/secrets.md) for where to get each one). ## Live: WebSocket, SSE, JSON, poll Covered in [Subscribing](subscribing.md). These are the cheapest transports and need no setup. In `cheap` route mode they're the only ones used. ## Web Push Browsers (desktop and Android, and iOS 16.4+ for installed web apps) receive notifications even when the page is closed. The relay encrypts each push with aes128gcm (RFC 8291) and signs it with a VAPID token (RFC 8292). Urgency follows priority (1–2 `low`, 3 `normal`, 4–5 `high`), the TTL follows `expires` (default 24 h), and the push `Topic` is the message id, so a retried send replaces an undelivered copy. In the browser: read `vapid_public_key` from `GET /v1/config`, register a service worker (the site's [`/sw.js`](https://github.com/curtcox/subetha/blob/main/apps/site/public/sw.js) shows the notification, opens the click URL, and acks), call `subscribeWebPush()` from the SDK, and register the result as an endpoint: ```js title="samples/web/webpush.js" // Register this browser for Web Push and subscribe it to topics, from a page that loads // https://subetha.us/sdk.js and serves the service worker at /sw.js (copy apps/site/public/sw.js). // Run it from a click handler so the browser can ask for notification permission. Use a token // that can manage endpoints (your own console session, not a public page). async function enableWebPush({ baseUrl = "https://subetha.us", token, topics }) { const api = async (path, body) => { const r = await fetch(`${baseUrl}${path}`, { method: body ? "POST" : "GET", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: body && JSON.stringify(body), }); if (!r.ok) throw new Error(`${path}: ${(await r.json()).message}`); return r.json(); }; const { vapid_public_key: vapidKey } = await api("/v1/config"); if (!vapidKey) throw new Error("Web Push isn't configured on this relay"); const registration = await navigator.serviceWorker.register("/sw.js"); await navigator.serviceWorker.ready; const address = await SubEtha.subscribeWebPush(registration, vapidKey); // or import { subscribeWebPush } from "@subetha/sdk" const endpoint = await api("/v1/endpoints", { kind: "webpush", address, name: navigator.userAgent.slice(0, 60) }); for (const topic of topics) await api("/v1/subscriptions", { topic, endpoint_id: endpoint.id }); return endpoint.id; } document.querySelector("#enable-push")?.addEventListener("click", () => enableWebPush({ token: localStorage.getItem("subetha_token"), topics: ["@me/doorbell"] }).then( (id) => console.log("push endpoint", id), (e) => alert(e.message), ), ); ``` The console's "Notify this browser for these topics" button does exactly this. **Operator setup:** generate keys with `node workers/api/scripts/vapid-keys.mjs`, then set `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, and `VAPID_SUBJECT` (a `mailto:` or `https:` contact). ## APNs and FCM Native apps register their push token as an endpoint (the SDKs do this): ```bash title="samples/curl/endpoint-push.sh" #!/usr/bin/env bash # Register phone and browser push endpoints. Apps normally do this through the SDK; these are # the raw calls. Push endpoints need no verification code: the app owns the token. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json") # iOS (APNs device token, hex): curl -sS "${AUTH[@]}" -d '{"kind":"apns","address":"3f1c…64-or-more-hex-chars…a9","name":"my iPhone"}' "$SUBETHA_URL/v1/endpoints" # Android (FCM registration token): curl -sS "${AUTH[@]}" -d '{"kind":"fcm","address":"dQw4w9WgXcQ:APA91b…","name":"my Pixel"}' "$SUBETHA_URL/v1/endpoints" # Browser (Web Push subscription JSON, as a string; see samples/web/webpush.js): curl -sS "${AUTH[@]}" -d "$(jq -n --arg sub '{"endpoint":"https://fcm.googleapis.com/fcm/send/…","keys":{"p256dh":"…","auth":"…"}}' \ '{kind:"webpush", address:$sub, name:"laptop"}')" "$SUBETHA_URL/v1/endpoints" # Then subscribe each endpoint to topics with POST /v1/subscriptions. ``` Each push carries the SubEtha envelope, trimmed to fit the service's payload limit: large optional fields go first, and `id`, `topic`, `title`, `message`, and `priority` are always kept (the message may be shortened). A trimmed envelope has `truncated: true`, so the app can fetch the full message by id. When a push service says a token is gone (Web Push 404/410, FCM `UNREGISTERED`, APNs 410 `BadDeviceToken`/`Unregistered`), the endpoint is marked unverified and removed from its topics; the app must register again. **FCM setup:** set `FCM_SERVICE_ACCOUNT` to the service-account JSON from the Firebase console. The relay mints and caches OAuth2 access tokens itself. FCM also reaches iOS apps that use Firebase. **APNs setup:** set `APNS_KEY_P8` (the `.p8` key, PEM), `APNS_KEY_ID`, `APNS_TEAM_ID`, and `APNS_TOPIC` (the app's bundle id). **BYO credentials (your own app):** to push to your own iOS bundle ID or Firebase project, upload your APNs `.p8` key or Firebase service-account JSON via `POST /v1/push/credentials`. Private keys are verified with WebCrypto on upload, stored write-only, and never returned by `GET`. The first credential of each kind becomes your account default; you can also pin a specific `credential_id` when creating or updating an `apns` or `fcm` endpoint (including `sandbox: true` for APNs development builds). > **HTTP/2.** APNs only accepts HTTP/2, and a Worker's outbound `fetch()` isn't guaranteed to > negotiate it with `api.push.apple.com`. Run the APNs relay in > [`gateways/apns-relay`](https://github.com/curtcox/subetha/tree/main/gateways/apns-relay) (a > zero-dependency Node service that forwards `POST /3/device/{token}` over one long-lived HTTP/2 > connection) and set `APNS_ENDPOINT` to its URL and `APNS_RELAY_SECRET` to its secret. Or > deliver to iOS through FCM instead. ## Webhooks The relay POSTs each message as JSON to your HTTPS URL, signed like Stripe webhooks. Webhooks can't target the relay itself or private addresses. Requests time out after 10 seconds; 4xx responses (other than 408 and 429) aren't retried. ```bash title="samples/curl/endpoint-webhook.sh" #!/usr/bin/env bash # Deliver a topic to your server as signed JSON. The secret is shown once. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json") RESP=$(curl -sS "${AUTH[@]}" -d '{"kind":"webhook","address":"https://example.com/hooks/subetha"}' "$SUBETHA_URL/v1/endpoints") EP=$(jq -r .id <<<"$RESP") echo "signing secret: $(jq -r .secret <<<"$RESP")" curl -sS "${AUTH[@]}" -d "{\"topic\":\"@me/deploys\",\"endpoint_id\":\"$EP\",\"filter\":{\"priority\":[4,5]}}" \ "$SUBETHA_URL/v1/subscriptions" # Your server receives: # POST /hooks/subetha # Content-Type: application/json # X-SubEtha-Topic: @me/deploys # X-SubEtha-Message-Id: 01JD… # X-SubEtha-Signature: t=1763750000,v1=")> # {"id":"01JD…","topic":"@me/deploys","message":"…",…} ``` ```ts title="samples/ts/webhook.ts" await se.configureTopic(topic, {}); // the topic must exist, and you must own it const ep = await se.request<{ id: string; secret: string }>("POST", "/v1/endpoints", { kind: "webhook", address: "https://example.com/hooks/subetha", name: "my server", }); // ep.secret is shown once. Store it and check X-SubEtha-Signature with it (see verify-webhook.ts). const sub = await se.request<{ id: string }>("POST", "/v1/subscriptions", { topic, endpoint_id: ep.id, filter: { tags: ["deploy"] }, // only messages tagged "deploy" }); ``` Verify the signature before trusting the body: ```ts title="samples/ts/verify-webhook.ts" export async function verifyWebhook(secret: string, header: string | null, rawBody: string, toleranceS = 300): Promise { const parts = Object.fromEntries((header ?? "").split(",").map((kv) => kv.split("=", 2) as [string, string])); const t = Number(parts.t); if (!parts.v1 || !Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > toleranceS) return false; const enc = new TextEncoder(); const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(`${t}.${rawBody}`))); const expected = [...mac].map((b) => b.toString(16).padStart(2, "0")).join(""); let diff = expected.length ^ parts.v1.length; // constant-time comparison for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ (parts.v1.charCodeAt(i) || 0); return diff === 0; } /** A handler for any runtime with Request/Response (Workers, Deno, Bun, Node 18+ frameworks). */ export async function handleWebhook(req: Request, secret: string): Promise { const body = await req.text(); if (!(await verifyWebhook(secret, req.headers.get("x-subetha-signature"), body))) return new Response("bad signature", { status: 401 }); const message = JSON.parse(body) as { id: string; topic: string; message?: string }; console.log(`${message.topic}: ${message.message}`); return new Response("ok"); } ``` ```python title="samples/python/verify_webhook.py" """Verify X-SubEtha-Signature on an incoming webhook (standard library only).""" import hashlib import hmac import time def verify_webhook(secret: str, header: str | None, raw_body: bytes, tolerance_s: int = 300) -> bool: parts = dict(kv.split("=", 1) for kv in (header or "").split(",") if "=" in kv) try: t = int(parts["t"]) except (KeyError, ValueError): return False if abs(time.time() - t) > tolerance_s or "v1" not in parts: return False expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, parts["v1"]) # Flask: # @app.post("/hooks/subetha") # def hook(): # if not verify_webhook(SECRET, request.headers.get("X-SubEtha-Signature"), request.get_data()): # abort(401) # msg = request.get_json() # print(msg["topic"], msg.get("message")) # return "ok" ``` No operator secrets are needed: each endpoint gets its own signing secret. ### Testing an endpoint `POST /v1/endpoints/{id}/test` sends one sample message to a verified endpoint right away. For a webhook, the response shows the exact request the relay sent (headers, `X-SubEtha-Signature`, raw body) and what your server answered (status, headers, the first 4 KB of the body), so you can debug a signature check without publishing. Other transports report the provider's outcome. A test costs one delivery of that transport, whether or not the receiver accepts it. ```bash title="samples/curl/endpoint-test.sh" #!/usr/bin/env bash # Send one test message to an endpoint and see exactly what happened (charged as one delivery). set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" EP="${1:?usage: endpoint-test.sh ep_…}" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json" \ -d '{"title":"Hello","message":"Does my signature check work?","priority":4}' \ "$SUBETHA_URL/v1/endpoints/$EP/test" | jq '{result, error, latency_ms, request, response}' # For a webhook: # "result": "delivered", # "request": {"method":"POST","url":"https://example.com/hooks/subetha", # "headers":{"x-subetha-signature":"t=1763750000,v1=…",…},"body":"{\"id\":\"01JD…\",…}"}, # "response": {"status":200,"headers":{…},"body":"ok","truncated":false} ``` The console's **Endpoints** tab has a **Test** button on each verified endpoint and a signature checker that runs in the browser, so the secret never leaves the page. ## Email **Outbound** email goes only to verified addresses. The subject is the message title (or the topic and the start of the message), and the body has the message, the click URL, and a manage link. ```bash title="samples/curl/endpoint-email.sh" #!/usr/bin/env bash # Deliver a topic by email: add the address, verify it with the emailed code, subscribe it. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json") EP=$(curl -sS "${AUTH[@]}" -d '{"kind":"email","address":"me@example.com","name":"inbox"}' \ "$SUBETHA_URL/v1/endpoints" | jq -r .id) read -rp "Code from the email: " CODE curl -sS "${AUTH[@]}" -d "{\"code\":\"$CODE\"}" "$SUBETHA_URL/v1/endpoints/$EP/verify" curl -sS "${AUTH[@]}" -d "{\"topic\":\"@me/alerts\",\"endpoint_id\":\"$EP\"}" "$SUBETHA_URL/v1/subscriptions" ``` **Inbound:** mail sent to a topic's address publishes to the topic, charged to the topic owner. The address is `.@in.subetha.us` for `@handle/name`, or `t_…@in.subetha.us` for a secret topic. The subject becomes the title and the plain-text body (quoted replies and signatures removed) the message, tagged `email`. Only senders allowed by the topic's `email_senders` policy get through: exact addresses, `@example.com` for a whole domain, or `*`. Messages over 512 KB are rejected. **Operator setup:** outbound uses the Cloudflare Email Service `send_email` binding `EMAIL` when bound, otherwise Amazon SES (`SES_ACCESS_KEY_ID`, `SES_SECRET_ACCESS_KEY`, `SES_REGION`). Set `EMAIL_FROM` (default `SubEtha `) and authenticate the sending domain (SPF, DKIM, DMARC). Inbound needs Cloudflare Email Routing on `in.subetha.us` with a catch-all rule that sends to the Worker (`INBOUND_EMAIL_DOMAIN`). ## Slack Install the SubEtha Slack app in a workspace, then bind channels to topics. Outbound, topic messages are posted to the channel; inbound, channel messages publish to the topic (tagged `slack`, never echoed back into the same channel). In the console, **Endpoints → Add to Slack** installs the app and **Bind channel** binds one; from scripts, `GET /v1/slack/teams` lists the workspaces you installed it in (their `team_id`s): ```bash title="samples/curl/slack.sh" #!/usr/bin/env bash # Slack: install the app in a workspace, then bind a channel to a topic (both directions). set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json") # 1. Open the install URL in a browser and approve. You land back in the console. curl -sS "${AUTH[@]}" "$SUBETHA_URL/v1/slack/install" | jq -r .url # 2. The workspaces you installed it in, with their team ids. curl -sS "${AUTH[@]}" "$SUBETHA_URL/v1/slack/teams" | jq -r '.teams[] | "\(.team_id) \(.team_name)"' # 3. Bind #alerts (channel id C0123456789) in team T0123456 to @me/alerts. # inbound: channel messages publish to the topic; outbound: topic messages post to the channel. curl -sS "${AUTH[@]}" -d '{ "team_id": "T0123456", "channel": "C0123456789", "topic": "@me/alerts", "inbound": true, "outbound": true }' "$SUBETHA_URL/v1/slack/bindings" ``` **Operator setup:** create a Slack app with the bot scopes `chat:write`, `channels:history`, `groups:history`, and `channels:read`, the OAuth redirect URL `https://subetha.us/v1/slack/oauth`, and Event Subscriptions (`message.channels`, `message.groups`) sent to `https://subetha.us/v1/hooks/slack/events`. Set `SLACK_CLIENT_ID`, `SLACK_CLIENT_SECRET`, and `SLACK_SIGNING_SECRET`. ## SMS and voice SMS and voice calls are for things that matter: alarms and escalation. Limits that keep them safe for everyone: - **US numbers by default** (`+1NXXNXXXXXX`), each verified with a code sent to it. Premium-rate (`+1 900`) and non-geographic codes are never served, and numbers in Canada, Puerto Rico, and the Caribbean are not US numbers (Twilio prices them separately). - **Other countries are opt-in, one at a time**, and priced per destination: see [below](#numbers-outside-the-us). - **Recipients stay in control.** Replying `STOP` (or `UNSUBSCRIBE`, `CANCEL`, `END`, `QUIT`) unverifies the number for SMS and voice on every account. `HELP` gets the help message. Replying `ACK ` acknowledges a message; pressing 1 on a call does the same. - **New-funds hold.** Until your first top-up is 7 days old, total SMS and voice spend is capped at $5 (PLAN §8: chargeback and SMS-pumping protection). - **Circuit breaker.** If Twilio's US prices rise above what SubEtha's prices assume, SMS and voice pause (`GET /v1/status` shows `telephony_circuit`) until prices are regenerated. - SMS bodies are cut to 459 characters (3 segments) and billed per segment; calls are billed per started minute. A topic policy can require a minimum priority (`"min_priority": {"sms": 4}`). - **Texting in.** `PATCH /v1/endpoints/{id}` with `{"inbound_topic": "@you/texts"}` makes texts from that verified number to the SubEtha number publish to a topic you own (tagged `sms`, charged as `inbound_sms_us`). A text with a JPEG, PNG, or GIF picture is charged as `inbound_mms_us`, and the picture becomes the message's attachment (stored and billed like any other attachment). Replying `ACK ` acknowledges an escalation instead. - **Pictures go as MMS.** When a message has a JPEG, PNG, or GIF attachment of up to 5 MB (and isn't end-to-end encrypted), US numbers get one MMS with the picture and up to 1,600 characters of text, billed as one `deliver_mms_us` message instead of per segment. Numbers outside the US get the text as SMS. Dry runs show which SKU each subscriber will be billed. ### Numbers outside the US Enable each country you want to reach on the account, then add numbers there as usual: ```bash curl -X PATCH -H "Authorization: Bearer $SUBETHA_TOKEN" -d '{"telephony_countries":["CA","GB"]}' \ https://subetha.us/v1/account curl https://subetha.us/v1/prices/destinations # today's per-country prices (public) ``` - Countries on offer: CA, GB, IE, DE, FR, NL, BE, ES, IT, PT, AT, CH, SE, NO, DK, FI, PL, AU, NZ, JP, SG, MX, BR, IN, IL, ZA, and PR. Adding a number in a country that isn't enabled fails with `forbidden`. - **Live prices.** A daily job reads Twilio's current prices for each country and prices SMS segments and call minutes from the highest of them (the `deliver_sms_intl` and `deliver_voice_intl` SKUs: same margin floor as every other SKU). Prices go in `GET /v1/prices/destinations` per tier. - **Unknown means no.** A country with no current price (Twilio didn't report one, the price is above $0.50 a unit, or the table is more than three days old) can't get new endpoints (`provider_unavailable`), and its numbers drop out of delivery plans with the reason `destination price unknown` in the trace. - Removing a country from `telephony_countries` stops deliveries to its numbers at once; the endpoints stay, and deliver again if you re-enable it. ### Escalation ```bash title="samples/curl/escalation.sh" #!/usr/bin/env bash # An escalation chain for alarms: push now, SMS after 60 s, a phone call after 180 s, each only # if nobody has acknowledged the message yet. US numbers only; each is verified with a code. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json") TOPIC="@me/alarm" SMS=$(curl -sS "${AUTH[@]}" -d '{"kind":"sms","address":"+14155550123"}' "$SUBETHA_URL/v1/endpoints" | jq -r .id) read -rp "SMS code: " CODE curl -sS "${AUTH[@]}" -d "{\"code\":\"$CODE\"}" "$SUBETHA_URL/v1/endpoints/$SMS/verify" VOICE=$(curl -sS "${AUTH[@]}" -d '{"kind":"voice","address":"+14155550123"}' "$SUBETHA_URL/v1/endpoints" | jq -r .id) read -rp "Code read out on the call: " CODE curl -sS "${AUTH[@]}" -d "{\"code\":\"$CODE\"}" "$SUBETHA_URL/v1/endpoints/$VOICE/verify" curl -sS "${AUTH[@]}" -d "{\"topic\":\"$TOPIC\",\"endpoint_id\":\"$SMS\",\"after_s\":60,\"min_priority\":4}" "$SUBETHA_URL/v1/subscriptions" curl -sS "${AUTH[@]}" -d "{\"topic\":\"$TOPIC\",\"endpoint_id\":\"$VOICE\",\"after_s\":180,\"min_priority\":5}" "$SUBETHA_URL/v1/subscriptions" # Acknowledge from anywhere to stop the chain: an SDK does it automatically, or reply # "ACK " to the SMS, press 1 on the call, or: # curl -sS -d '{"topic":"@me/alarm","id":""}' "$SUBETHA_URL/v1/ack" ``` **Operator setup:** a Twilio account with a US number registered for A2P 10DLC. Set `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN`, and `TWILIO_FROM`, and point the number's incoming message webhook at `https://subetha.us/v1/hooks/twilio/sms` (HTTP POST). Voice acks call back to `/v1/hooks/twilio/voice-ack` automatically. The SMS consent, STOP, and HELP language is in the [Acceptable Use Policy](legal/aup.md). ## MCP AI agents connect to the remote MCP server at `/mcp` and publish, poll, and wait for messages like any other device. See [Agents](agents.md). ## Reticulum / LXMF Every mesh user on Sideband, NomadNet, or MeshChat can be a subscriber. Two directions: - **Topic → an LXMF address:** add an `lxmf` endpoint; the hosted gateway delivers it over the mesh. - **A topic gets its own LXMF address:** run the [Reticulum gateway](self-hosting.md#reticulum-gateway), which bridges both ways and lets mesh users `/subscribe`. ```bash title="samples/curl/endpoint-lxmf.sh" #!/usr/bin/env bash # Deliver a topic to a Reticulum/LXMF address (Sideband, NomadNet, MeshChat…) through the hosted gateway. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json") EP=$(curl -sS "${AUTH[@]}" -d '{"kind":"lxmf","address":"9ecc3b10bc264d1543b9be044d6fda7a","name":"sideband"}' \ "$SUBETHA_URL/v1/endpoints" | jq -r .id) curl -sS "${AUTH[@]}" -d "{\"topic\":\"@me/mesh\",\"endpoint_id\":\"$EP\"}" "$SUBETHA_URL/v1/subscriptions" ``` **Operator setup:** `LXMF_GATEWAY_URL` (the gateway's base URL) and `LXMF_GATEWAY_SECRET` (the HMAC secret it verifies `POST /deliver` with). ## Edge transports: BLE, audio, QR, LAN Bluetooth LE store-and-forward, data-over-sound, animated QR codes, and LAN discovery run inside the SDKs (the Rust core's `edge` modules) between nearby devices. They never touch the relay and are free. Signatures and end-to-end encryption mean an edge relay can neither forge nor read what it carries, and `hops` limits how far a message travels. A device with internet access can bridge edge traffic to the relay; that leg is billed as a normal relay delivery. See [Edge transports](edge.md) for the SDK APIs, the browser shims, and the [Edge lab](/tools/edge.html). --- # Edge transports Edge transports move messages between nearby devices without the relay: **sound** (speaker → microphone), **animated QR codes** (screen → camera), **Bluetooth LE**, and LAN. They're free, work offline and air-gapped, and use the same envelopes as everything else. Sign messages so receivers can check who sent them, and encrypt them if the content is private: edge relays can neither forge nor read what they carry. Try it in the browser with the [Edge lab](/tools/edge.html). Open it on two devices. | Link | Direction | Speed | Range | Browser support | |---|---|---|---|---| | Sound (16-FSK, 2–5 kHz) | one way, broadcast | ~50 bytes/s | a metre or two | all (Web Audio + microphone) | | Animated QR (fountain coded) | one way | ~1–3 KB/s at 6 fps | line of sight | display: all; scan: all with a camera (`BarcodeDetector` where present, else jsQR through `jsQrDetector`) | | Bluetooth LE (GATT + gossip) | both ways | ~1–10 KB/s | ~10 m | Chrome and Edge, central role only (the peer must be a native app or gateway) | | LAN (UDP multicast + gossip) | both ways | network speed | the local network | none (browsers have no UDP). Node, the CLI, and native apps | ## How it works Every edge node keeps a **gossip node**: the topics it subscribes to or relays, recent message ids, and the messages it can still forward. When two nodes meet over a two-way link (BLE, LAN), they swap summaries, request what they're missing, and deliver it with `hops` reduced by one. A message published with `hops: 2` can travel two edge hops beyond its first receiver. One-way links (sound, QR) carry a single `deliver` message, so the receiver runs the same checks: - no id, wrong topic, `hops` outside 0–16, or expired → dropped - seen before (on any transport, the relay included) → dropped - a signature that doesn't verify → dropped (and optionally unsigned → dropped) The wire formats are specified in [spec §11](https://github.com/curtcox/subetha/blob/main/spec/README.md#11-edge-framings) and pinned by shared test vectors, so the TypeScript SDK and the Rust core used by the mobile SDKs interoperate. ## TypeScript `@subetha/sdk/edge` has the protocol logic and runs anywhere (browser, Node, Workers). The browser shims (`playAudioFrame`, `listenAudio`, `showAnimatedQr`, `scanAnimatedQr`, `connectBlePeer`) are in the same module. The script-tag bundle is `https://subetha.us/edge.js`, which sets `window.SubEthaEdge`. ```ts title="samples/ts/edge.ts" const key = await generateDeviceKey(); const now = Math.floor(Date.now() / 1000); const env = await signEnvelope({ id: ulid(), time: now, expires: now + 3600, topic, message: "Door opened", hops: 2 }, key); const payload = deliverPayload([env]); // one-way links carry a gossip "deliver" message // The receiving device subscribes; its node checks signatures, expiry, hops, and duplicates. const receiver = new GossipNode(); receiver.subscribe(topic); // Sound: 48 kHz PCM for the speaker (playAudioFrame does this in a browser)… const pcm = modulate(payload); // …and what the other device's microphone hears (listenAudio scans for frames). const [viaSound] = await acceptPayload(receiver, demodulate(pcm)!); // Animated QR: an endless stream of fountain-coded frames (showAnimatedQr draws them). const frames = qrFrameTexts(payload, 10, "L"); let viaQr: Uint8Array | null = null; const scanner = new QrFrameReceiver((p) => (viaQr = p)); // scanAnimatedQr feeds this for (let seq = 3; !viaQr; seq += 2) scanner.push(frames.text(seq)); // joined late, saw every other frame const again = await acceptPayload(receiver, viaQr); // same message: deduplicated console.log(viaSound!.message, `${(pcm.length / 48000).toFixed(1)} s of audio`, again.length); ``` In a page: ```html title="samples/web/edge.html" SubEtha over sound
    ``` ### Browser APIs | Function | What it does | |---|---| | `playAudioFrame(payload, { volume })` | Plays one modem frame. Resolves when playback ends. | | `listenAudio(onPayload, { windowSeconds })` | Microphone → frames (echo cancellation and noise suppression off). Returns `{ stop() }`. `windowSeconds` must cover the longest frame you expect: 50 bytes per second, plus 0.6 s. | | `showAnimatedQr(canvas, payload, { version, ecl, fps })` | Draws an endless frame stream. Version 10–15 with level L scans well on phones. | | `scanAnimatedQr(video, onPayload, { detect, onProgress })` | Camera → frames → payload. `detect` is any `(video) => Promise`. Defaults to `barcodeDetector()` (Chrome on Android, macOS, ChromeOS). | | `jsQrDetector(jsQR, { maxSide })` | A `detect` for every other browser, from the [jsQR](https://github.com/cozmo/jsQR) function you load (the SDK doesn't bundle it). The Edge lab loads `/tools/jsqr.js` the first time it needs it. | | `connectBlePeer(node, onMessage)` | Web Bluetooth central: connects to a peer advertising the SubEtha service and gossips. Must be called from a click. | Without the browser shims, `AudioFrameReceiver`, `QrFrameReceiver`, and `BleLink` take raw samples, scanned strings, or GATT chunks. Native shims (and tests) drive them the same way. ## LAN Devices on the same network find each other with UDP multicast beacons and gossip directly, with no internet connection needed. From the CLI: ```bash subetha lan @me/doorbell # print messages from peers on this network subetha lan @me/doorbell --send "Door opened" --hops 2 --for 10 ``` In Node, `startLan(node, onMessage)` from `@subetha/sdk/edge/lan-node` joins the LAN and returns `{ resync(), peers(), stop() }`. Call `resync()` after publishing so peers hear about the new message right away. `startLanWith(dgram, node, onMessage)` does the same over any UDP module shaped like `node:dgram`, such as `react-native-udp`, and `LanGossip` is the socket-free core, for other runtimes. ## Mobile and Rust The Rust core (`subetha_core::edge`) has the same modem, fountain codec, BLE chunking, and gossip node. The Swift, Kotlin, and Flutter SDKs reach it through the core bindings, and the platform supplies the radio, speaker, microphone, or camera. React Native uses the TypeScript implementation instead (next section). ### React Native `@subetha/react-native/edge` re-exports `@subetha/sdk/edge`, which runs on Hermes, and adds glue for the usual libraries: `connectBlePlxPeer` (a central over `react-native-ble-plx`), `audioFrameWav` and `listenPcm16` (play a WAV with any player; hear PCM16 from `react-native-live-audio-stream`), `animateQr` and `qrSvgPath` (draw frames with `react-native-svg`; feed `expo-camera` scans to `QrFrameReceiver`), and `startLanWith` over `react-native-udp`. Hermes can't verify Ed25519, so `createEdgeNode({ core })` checks signatures with the Rust core when the app installs it, and otherwise drops signed messages. The Expo sample's Edge tab ([`samples/react-native`](https://github.com/curtcox/subetha/tree/main/samples/react-native)) uses all of them. See the [package README](https://github.com/curtcox/subetha/tree/main/sdk/react-native#edge-transports-subethareact-nativeedge). ### Kotlin, Swift, and Flutter The Kotlin (`us.subetha:subetha-core`), Swift (`SubEthaCore`), and Flutter (`subetha_core`) SDKs add drivers that do everything except move bytes, the same as the TypeScript ones: | Driver | Feed it | It gives you | |---|---|---| | `AudioLink` | microphone samples at the device's rate | decoded payloads; samples to play for yours | | `QrSender` / `QrReceiver` | scanned QR strings | base45 text for each animated frame; completed payloads | | `BleLink` | each notification or write from a peer, and the negotiated ATT MTU | chunks to write or notify | | `GossipSession` | gossip messages over any two-way link | replies and new envelopes | | `EdgeBridge` | a `SubEtha` client and a gossip node | relay messages in the node; `uplink` for edge messages | The sample apps wire them to the platform APIs, and are the place to copy from: - **Android** ([`samples/android`](https://github.com/curtcox/subetha/tree/main/samples/android)): `AndroidBle.kt` (BluetoothGattServer and advertising as a peripheral, scanning and GATT client connections as a central, one queued GATT operation at a time), `AndroidAudio.kt` (AudioTrack/AudioRecord), and `QrViews.kt` (ZXing on CameraX frames). - **iOS** ([`samples/ios`](https://github.com/curtcox/subetha/tree/main/samples/ios)): `AppleBle.swift` (CBPeripheralManager and CBCentralManager), `AppleAudio.swift` (AVAudioEngine in measurement mode), and `QrViews.swift` (CoreImage and AVCaptureMetadataOutput). - **Flutter** ([`samples/flutter`](https://github.com/curtcox/subetha/tree/main/samples/flutter)): `lib/edge.dart` with `record`/`audioplayers`, `qr_flutter`/`mobile_scanner`, and `flutter_reactive_ble` as a BLE central (it connects to the native samples). A phone running either sample is a BLE **peripheral** as well as a central, advertising the service in [spec §11.3](https://github.com/curtcox/subetha/blob/main/spec/README.md#113-bluetooth-le), so browsers (which can only be centrals) connect to it. Phones that see each other connect and gossip. Each envelope's `hops` limits how many phones it passes through. iOS only does BLE in the foreground for this, and can't put data in its advertisements, so two phones may end up with two connections between them. That's harmless because gossip drops duplicates. ## Bridging to the relay A device with internet access can act as a gateway for nearby offline devices. `bridgeEdge` subscribes to the relay and feeds new messages into the gateway's gossip node, giving them `hops` if they have none, so edge peers pick them up. In the other direction, messages that arrive over edge links are published to the relay unchanged (`client.publishEnvelope`). The signature still verifies because `hops` isn't signed, and the relay drops a message it has already seen by id. Uplinked publishes are billed to the gateway's token like any other. ```ts title="samples/ts/edge-bridge.ts" // The gateway (a phone with internet) and an offline device, linked over BLE. const gateway = new GossipNode(); const device = new GossipNode(); device.subscribe(topic); let toDevice!: BleLink; const toGateway = new BleLink(device, (chunk) => toDevice.receive(chunk), (m) => offline.push(m)); toDevice = new BleLink(gateway, (chunk) => toGateway.receive(chunk), (m) => void bridge.uplink(m)); const bridge = bridgeEdge(se, gateway, { topics: [topic], hops: 1, since: "10m", // catch up on what was missed while offline transport: "stream", onDownlink: () => void toDevice.resync(), // tell the device something new arrived }); // Offline device → gateway → relay. const now = Math.floor(Date.now() / 1000); device.publish({ id: ulid(), time: now, expires: now + 600, topic, message: "Battery low", hops: 1 }); await toGateway.resync(); // Relay → gateway → offline device. await se.publish(topic, "Firmware update available"); ``` On phones, the samples' **Bridge to relay** button does the same with `EdgeBridge`. The [offline BLE-hop demo](https://github.com/curtcox/subetha/tree/main/samples/android#offline-ble-hop-demo) uses one online phone as the gateway for an offline one. --- # Pricing & billing SubEtha is **prepaid**. You top up a balance, every action is priced above what it costs to run, and every action is checked against your balance *before* it runs. There's no subscription, no free tier, and no bill after the fact. Edge transports (BLE, audio, QR, LAN) never touch the relay and are free. ## The rules 1. **Prepaid only.** Top up with Stripe Checkout (minimum $5). Each top-up carries a fee of 4.5% + $0.35, which covers card processing and fixed costs; the rest becomes credit. 2. **Reserve before acting.** Each action reserves its worst-case cost first, then settles to the actual cost (an SMS's real segment count, for example) and releases the rest. If the balance can't cover the reservation, the request fails with **HTTP 402** and nothing happens. 3. **Every SKU has a positive margin**, at every volume tier. Prices are generated from measured costs in [`pricing/costs.yaml`](https://github.com/curtcox/subetha/blob/main/pricing/costs.yaml), and CI fails if any margin drops below 15%. The live table is at `GET /v1/prices`. 4. **State costs rent.** Retained messages, attachments, enrolled devices, verified endpoints, and open connections are metered by time. 5. **Live prices where providers' prices vary.** SMS and voice outside the US are priced per country every day from Twilio's current prices (`GET /v1/prices/destinations`); a destination without a current price is rejected. See [Transports](transports.md#numbers-outside-the-us). 6. **Volume tiers** lower prices as trailing-12-month top-ups grow (`standard`, `bulk` from $500, `volume` from $5,000), without ever crossing the margin floor. ## Prices Money in the API is integer **micro-dollars** (µ$): 1,000,000 µ$ = $1. The table below is generated from the price list at build time, so it always matches what the relay charges. ## SubEtha pricing invariant report Generated from `pricing/costs.yaml`. Every SKU at every tier must have a margin ≥ 15% — this report only exists if that held. | SKU | Unit | Cost | Price (standard) | Price (bulk) | Price (volume) | Margin (standard) | Margin (bulk) | Margin (volume) | |---|---|---:|---:|---:|---:|---:|---:|---:| | `publish` | message | $0.0000015 | $0.000006 | $0.000006 | $0.000006 | 75.0% | 75.0% | 75.0% | | `deliver_live` | delivery | $0.0000003 | $0.000002 | $0.000002 | $0.000001 | 85.0% | 85.0% | 70.0% | | `deliver_push` | delivery | $0.000002 | $0.000006 | $0.000006 | $0.000005 | 66.7% | 66.7% | 60.0% | | `deliver_webhook` | delivery | $0.0000023 | $0.00001 | $0.00001 | $0.000009 | 77.0% | 77.0% | 74.4% | | `deliver_slack` | delivery | $0.0000023 | $0.00001 | $0.00001 | $0.000009 | 77.0% | 77.0% | 74.4% | | `deliver_mcp` | delivery | $0.00000085 | $0.000007 | $0.000007 | $0.000007 | 87.9% | 87.9% | 87.9% | | `deliver_email` | email | $0.0001212 | $0.000443 | $0.000413 | $0.000382 | 72.6% | 70.7% | 68.3% | | `inbound_email` | email | $0.00001 | $0.00007 | $0.000068 | $0.000065 | 85.7% | 85.3% | 84.6% | | `deliver_sms_us` | segment | $0.0115 | $0.0166 | $0.0155 | $0.0143 | 30.7% | 25.6% | 19.6% | | `deliver_mms_us` | message | $0.0323 | $0.0462 | $0.0430 | $0.0398 | 30.1% | 24.9% | 18.8% | | `inbound_sms_us` | segment | $0.0110 | $0.0159 | $0.0148 | $0.0137 | 30.8% | 25.7% | 19.7% | | `inbound_mms_us` | message | $0.0268 | $0.0385 | $0.0358 | $0.0332 | 30.4% | 25.2% | 19.2% | | `deliver_voice_us` | minute | $0.0169 | $0.0247 | $0.0230 | $0.0213 | 31.5% | 26.4% | 20.6% | | `deliver_sms_intl` | segment | $0.0505 | $0.0717 | $0.0667 | $0.0616 | 29.6% | 24.2% | 18.0% | | `deliver_voice_intl` | minute | $0.0534 | $0.0768 | $0.0714 | $0.0661 | 30.4% | 25.2% | 19.2% | | `deliver_whatsapp` | message | $0.0205 | $0.0297 | $0.0277 | $0.0256 | 31.0% | 25.9% | 19.9% | | `inbound_whatsapp` | message | $0.005302 | $0.007923 | $0.007393 | $0.006863 | 33.1% | 28.3% | 22.8% | | `deliver_lxmf` | delivery | $0.0000152 | $0.000051 | $0.000047 | $0.000043 | 70.2% | 67.7% | 64.6% | | `api_request` | request | $0.000001 | $0.000003 | $0.000003 | $0.000003 | 66.7% | 66.7% | 66.7% | | `attachment_upload` | upload | $0.0000068 | $0.000017 | $0.000015 | $0.000014 | 60.0% | 54.7% | 51.4% | | `retention_message_day` | message-day | $0.00000004 | $0.0000001 | $0.00000009 | $0.00000008 | 60.0% | 55.6% | 50.0% | | `attachment_mb_day` | MB-day | $0.0000006 | $0.0000016 | $0.00000145 | $0.0000013 | 62.5% | 58.6% | 53.8% | | `device_day` | device-day | $0.0000005 | $0.000002 | $0.000001875 | $0.00000175 | 75.0% | 73.3% | 71.4% | | `endpoint_day` | endpoint-day | $0.0000021 | $0.0000092 | $0.000008675 | $0.00000815 | 77.2% | 75.8% | 74.2% | | `connection_hour` | connection-hour | $0.000001 | $0.000003 | $0.00000275 | $0.0000025 | 66.7% | 63.6% | 60.0% | Edge transports (BLE, audio, QR, LAN) never touch the relay and are free. ### Fixed costs and break-even | Item | USD / month | |---|---:| | cloudflare_workers_paid | $5.00 | | cloudflare_containers_base | $5.00 | | domain_subetha_us | $1.25 | | clerk_pro | $25.00 | | twilio_number | $1.15 | | twilio_10dlc_campaign | $10.00 | | apple_developer | $8.25 | | google_play | $0.00 | | github | $0.00 | | monitoring_status_page | $0.00 | | **Total** | **$55.65** | - Top-up fee: 4.5% + $0.35. On an average $20 top-up (domestic card) it contributes $0.370 to fixed costs. - Break-even on top-up fees alone: **151 top-ups / month**. - Margin per published message with 2 live deliveries: $0.0000079; break-even on messages alone: **7,044,304 messages / month**. - Profit = Σ(volume × unit margin) − fixed costs, so it only rises with volume. ## Who pays for what | Action | Paid by | |---|---| | Publish (and dry runs, and uploads) | the publisher's token or account | | Live delivery, push, webhook, email, Slack, SMS, voice, LXMF | the topic owner | | Reading: polls, stream connections and connection time, attachment downloads | the topic owner | | Message retention and attachment storage | the topic owner (retention), the publisher (attachment storage) | | Anonymous publishes (when the topic allows them) | the topic owner, within the topic's anonymous caps | | Endpoint verification codes | the account adding the endpoint | | Inbound email and SMS | the owner of the receiving topic | ## Balance, ledger, and top-ups ```bash title="samples/curl/billing.sh" #!/usr/bin/env bash # Balance, ledger, prices, and a Stripe Checkout top-up. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN") curl -sS "${AUTH[@]}" "$SUBETHA_URL/v1/balance" # {"available_usd_micros":4981234,"reserved_usd_micros":15000} curl -sS "${AUTH[@]}" "$SUBETHA_URL/v1/ledger?limit=20" curl -sS "$SUBETHA_URL/v1/prices" | jq '.skus.publish' # Top up $20: open the returned URL to pay. curl -sS "${AUTH[@]}" -H "Content-Type: application/json" -d '{"amount_usd": 20}' \ "$SUBETHA_URL/v1/billing/checkout" | jq -r .url # A 402 looks like this: # {"error":"insufficient_balance","http":402,"message":"…","shortfall_usd_micros":1234} ``` ### Auto-recharge Optional, and not a subscription: top up once with `"save_card": true` in the checkout request (or tick **Save card for optional auto-recharge** in the console's Billing tab), then turn it on in the console or with `PATCH /v1/account`: ```json { "auto_recharge": { "threshold_usd": 2, "amount_usd": 20 } } ``` When the balance drops below the threshold, the saved card is charged `amount_usd` (same fee as any top-up). A declined charge turns auto-recharge off. `{"auto_recharge": null}` turns it off. ### Payments and receipts `GET /v1/payments` (admin) lists the card payments credited to the account: amount paid, top-up fee, credit added, and any refund or dispute. `GET /v1/payments/{id}/receipt` returns a printable HTML receipt for one of them, and the console's Billing tab links to each. Stripe also emails its own receipt to the account's address. ### Ledger The ledger is append-only: `topup`, `reserve`, `settle`, `release`, `refund`, and `adjust` entries, journaled and reconciled nightly against Stripe. Refunds and chargebacks are deducted from the balance (a chargeback also recovers the dispute fee where possible). ### Usage `GET /v1/usage?days=30` (admin) breaks spend down by category and day, computed from the ledger: publishing, paid deliveries, live delivery and storage (with the top topics), device and endpoint rent, and API requests and other charges. In-flight deliveries and credit that topics still hold are reported as `pending_micros`, so counted plus pending equals what left the balance. The console's Billing tab charts it. To estimate future spend, use the [pricing calculator](/tools/pricing.html). ## 402 Payment Required ```json { "error": "insufficient_balance", "http": 402, "message": "…", "shortfall_usd_micros": 1234 } ``` - `insufficient_balance`: the payer can't cover the worst-case cost. `shortfall_usd_micros` says how much more is needed. `"payer": "topic_owner"` means the *topic owner's* balance is short (for delivery), not yours. - `no_funded_owner`: an anonymous publish to a topic whose owner can't pay. Clients should treat 402 as permanent until someone tops up; retrying won't help. ## Caps and holds Several independent limits stop spending before it surprises anyone. Each returns `403 spend_cap_exceeded` when it would be crossed: | Limit | Set with | |---|---| | Per token, per day and in total | `daily_cap_usd`, `total_cap_usd` on [`POST /v1/tokens`](tokens.md) | | Per topic, per day and per month (owner-side spend, including reads) | topic policy `daily_cap_micros`, `monthly_cap_micros` | | Per message | topic policy `max_cost_per_message_micros`; per publish `X-Max-Cost` | | Anonymous publishing, per topic per day | topic policy `anon_daily_cap_micros` (default $1) | | Per account, per day and per month | `PATCH /v1/account {"daily_cap_micros": …, "monthly_cap_micros": …}` | | **New-funds hold** | automatic: until your first top-up is 7 days old, SMS and voice spend is capped at $5 in total | Plus a kill switch at every level: `paused` on a topic policy, on a device (`PATCH /v1/devices/{id}`), or on the account. ## Running out With a zero balance, every paid action fails with 402 before it runs. Rent for devices and endpoints is charged daily; when it can't be paid the account is marked **frozen** (records are kept). After 30 days frozen, its endpoints and subscriptions are deleted and its devices revoked. A top-up before then unfreezes it at the next daily run. If the account has an email address, it gets a notice when it's frozen, a warning 7 days before the deletion date, and a notice when the deletion happens (each one is also in the audit log as `account.notice`). ## Traces Every message has a trace, visible only to the topic owner: the route plan, what was dropped and why, each delivery attempt and its result, acks, and the µ$ charged for each step. ```ts title="samples/ts/trace.ts" const trace = await se.trace(topic, msg.id!); console.log(JSON.stringify(trace, null, 2)); // plan, deliveries, acks, µ$ per step ``` ## Estimating before you spend `X-Dry-Run: 1` on any publish returns the plan and a worst-case price without sending anything ([Dry runs](publishing.md#dry-runs)). `subetha cost ` does the same from the CLI, and the MCP tool `estimate_cost` does it for agents. --- # Tokens & policies Two tools control who can do what, and how much it can cost: **tokens** (credentials with scopes and caps) and **topic policies** (rules attached to a topic). ## Credentials | Credential | How it's sent | For | |---|---|---| | API token `se_…` | `Authorization: Bearer se_…` (or Basic with an empty user, or `?auth=`) | scripts, servers, agents, web pages | | Clerk session | `Authorization: Bearer eyJ…` | the web console | | Device signature | `X-Device-Id`, `X-Device-Time`, `X-Device-Signature` | [enrolled devices](devices.md) | All requests are rate limited: 600 per minute per credential, 60 per minute per IP without one. Over the limit you get `429 rate_limited` with `Retry-After`. ## Tokens ```bash title="samples/curl/tokens.sh" #!/usr/bin/env bash # Create, list, and revoke API tokens. Needs a token with the admin scope. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json") # A token for a backup script: publish to one namespace, no telephony, $1/day. curl -sS "${AUTH[@]}" -d '{ "name": "backup-script", "scopes": ["publish:@me/*"], "transports": ["ws", "sse", "poll", "webpush", "email"], "daily_cap_usd": 1, "expires_in_s": 7776000 }' "$SUBETHA_URL/v1/tokens" # A publishable token for a public web page: one topic, bound to your origin, tightly capped. curl -sS "${AUTH[@]}" -d '{ "name": "website feed", "scopes": ["subscribe:@me/status"], "origins": ["https://example.com"], "daily_cap_usd": 0.25 }' "$SUBETHA_URL/v1/tokens" curl -sS "${AUTH[@]}" "$SUBETHA_URL/v1/tokens" curl -sS "${AUTH[@]}" -X DELETE "$SUBETHA_URL/v1/tokens/abcdefghijklmnop" ``` ```ts title="samples/ts/tokens.ts" const { token: publishOnly } = await admin.createToken({ name: "backup-script", scopes: [`publish:${topic}`], transports: ["ws", "sse", "poll", "webpush", "email"], // never SMS or voice daily_cap_usd: 0.5, expires_in_s: 90 * 86400, }); const script = new SubEtha({ baseUrl, token: publishOnly, fetch }); await script.publish(topic, "backup ok"); // allowed const denied = await script.poll(topic).catch((e: SubEthaError) => e.code); // "forbidden" ``` | Field | Meaning | |---|---| | `scopes` | What the token may do (below). Required. | | `transports` | Allow-list of transports its publishes may use, e.g. no `sms`/`voice`. | | `daily_cap_usd`, `total_cap_usd` | Spend caps for everything charged to the token. | | `origins` | Makes it a [publishable token](#publishable-tokens). | | `ips` | Client addresses or CIDR ranges it works from, e.g. `["203.0.113.0/24", "2001:db8::/32"]` (up to 32). Requests from anywhere else get `403 forbidden`. | | `expires_in_s` | Lifetime. | | `name` | For your own bookkeeping. | The secret is returned once. `GET /v1/tokens` lists tokens without secrets, and `DELETE /v1/tokens/{id}` revokes one immediately. ### Scopes | Scope | Allows | |---|---| | `admin` (or `*`) | Everything: account, billing, tokens, topics, endpoints, devices. | | `publish`, `subscribe` | Publish to / read any topic the account can. | | `publish:@alice/*` | Publish to any topic under `@alice/`. | | `subscribe:@alice/doorbell` | Read one topic. | | `publish:t_…` | One secret topic. | A token can't create a token with more power than it has (only `admin` tokens create tokens). ### Publishable tokens For a public web page, create a token with `origins` set. Such a token: - only works on requests whose `Origin` header is one of `origins`; - has exactly one non-wildcard topic scope (`subscribe:@me/status` or `publish:@me/guestbook`); - must have a `daily_cap_usd`. Anyone can read it from the page, so assume it's public; the scope, origin, and cap bound what it can cost you. Use one for [`` / ``](sdks.md#web-components). ## Topic policies `PUT /v1/topics/{topic}` creates a topic or replaces its policy: ```bash title="samples/curl/topic-policy.sh" #!/usr/bin/env bash # Create or configure a topic. PUT replaces the whole policy. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" curl -sS -X PUT -H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json" -d '{ "policy": { "public_publish": true, "anon_rate_per_min": 10, "anon_daily_cap_micros": 200000, "require_signature": false, "allow_transports": ["ws", "sse", "poll", "webpush", "email", "sms"], "min_priority": { "sms": 4 }, "max_cost_per_message_micros": 20000, "daily_cap_micros": 1000000, "retention_s": 86400, "quiet_hours": { "start": "22:00", "end": "07:00" } } }' "$SUBETHA_URL/v1/topics/@me/doorbell" # Pause it (kill switch), then list your topics: curl -sS -X PUT -H "Authorization: Bearer $SUBETHA_TOKEN" -d '{"policy":{"paused":true}}' "$SUBETHA_URL/v1/topics/@me/doorbell" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/v1/topics" ``` ```ts title="samples/ts/topic-policy.ts" await se.configureTopic(topic, { public_publish: true, // anonymous publishes are charged to you… anon_rate_per_min: 10, // …rate limited… anon_daily_cap_micros: 200_000, // …and capped at $0.20/day deny_transports: ["voice"], min_priority: { sms: 4 }, // SMS only for high-priority messages }); // Now no token is needed: const r = await fetch(`${baseUrl}/${topic}`, { method: "POST", body: "doorbell rang" }); ``` | Policy field | Meaning | |---|---| | `public_publish` | Anyone may publish without credentials. Charged to you, within the anonymous limits. | | `anon_rate_per_min` | Anonymous publishes per minute (default 60). | | `anon_daily_cap_micros` | Daily cap on what anonymous publishes may cost you (default $1). | | `public_read` | Anyone may subscribe to this namespaced topic. (Secret topics are always readable by name.) | | `allowed_publishers`, `allowed_readers` | Extra account, token, or device ids allowed to publish / read. | | `require_signature` | Reject messages without a valid device signature. | | `allow_transports`, `deny_transports` | Transports deliveries may / may not use. | | `min_priority` | Per-transport minimum priority, e.g. `{"sms": 4, "voice": 5}`. | | `max_cost_per_message_micros` | Drop deliveries beyond this cost per message. | | `daily_cap_micros`, `monthly_cap_micros` | Daily and monthly caps on owner-side spend for this topic (deliveries and reads). | | `retention_s` | How long messages are kept (default 12 h, up to 30 days). Longer costs more rent. | | `quiet_hours` | `{"start": "22:00", "end": "07:00"}` (UTC): paid transports are suppressed. | | `email_senders` | Who may publish by [inbound email](transports.md#email): addresses, `@domain`, or `*`. | | `paused` | Kill switch: reject publishes. | The effective rules for any delivery are the intersection of the account, topic, subscription, device, token, and message settings. Nothing a publisher sends can widen what the owner allows. ## Account- and device-level controls `PATCH /v1/account` sets account-wide `daily_cap_micros`, `monthly_cap_micros`, `allow_transports` / `deny_transports`, and an account kill switch (`paused`). `PATCH /v1/devices/{id}` pauses or resumes a single device (`paused`) and sets per-device `allow_transports` / `deny_transports`. Every change to tokens, topics, endpoints, and devices is written to an audit log: `GET /v1/audit` (admin), or the console's **Audit log** tab. --- # Devices A **device** is a phone app, a browser, a Raspberry Pi, a CLI, an ESP32 bridge, an agent: anything that holds its own key. Devices enroll at **[devicebasedauth.org](https://devicebasedauth.org)** (DBA): the key is made on the device and never leaves it, you approve the device there and choose what it may do, and you can revoke it there or here. subetha checks each request's DBA credential itself (offline: the issuer's signature, its revocation list, and a fresh proof of the device's key). A device: - authenticates with its **DBA credential and a proof of its key** on each request, so no bearer token is stored on it; - can **publish and subscribe** within its grants (subject to topic policies), but can't manage the account (tokens, billing, endpoints); - can be listed, **paused**, limited to some transports, and **revoked** at any time, here or at devicebasedauth.org; - costs a little rent per day while enrolled ([Pricing](pricing.md)). Devices can also sign *messages* so receivers know who sent them: see [Signed messages](publishing.md#signed-messages). ## Enrolling a device 1. **Link devicebasedauth.org once.** In the console, **Devices → Link devicebasedauth.org** signs you in there and links that account to this one (`POST /v1/dba/link/start`, then `/finish`). One devicebasedauth.org account links to one subetha account. 2. **Enroll the device at devicebasedauth.org** for the audience `subetha.us`, with grants for `subetha:publish` and `subetha:subscribe`. Resources limit them to topics: a topic name (`@me/doorbell`) or a prefix (`@me/*`); none means every topic. You approve it there. - CLI or server: `dba enroll --aud subetha.us --action subetha:publish --action subetha:subscribe --resource "@me/*"`, then `dba curl …` (or `dba headers METHOD URL` for any HTTP client). - Browser: `const dba = new DBA()` from `https://devicebasedauth.org/sdk/v1.4.0/dba.js`, then `dba.enroll({ aud: ["subetha.us"], grants: [{ actions: ["subetha:publish", "subetha:subscribe"] }] })`; pass it to the SDK as `new SubEtha({ dba })`. - Android and iOS: devicebasedauth.org's Keystore and Secure Enclave samples. 3. **Use it.** Requests carry `Authorization: DBA ` and `DPoP: `. The device shows up under **Devices** as `dba:` on first use. ```ts title="samples/ts/devices.ts" // On the device, once: enroll at devicebasedauth.org and have the owner approve it there. // Browser: const dba = new DBA(); await dba.enroll({ aud: ["subetha.us"], grants: [{ actions: ["subetha:publish", "subetha:subscribe"], resources: [topic] }] }); // CLI: dba enroll --aud subetha.us --action subetha:publish --action subetha:subscribe // (The owner links that devicebasedauth.org account to their subetha account in the console first.) // Every request then carries the device's credential and a fresh proof of its key. const url = `${baseUrl}/${topic}`; const sent = await fetch(url, { method: "POST", headers: await dba.headers("POST", url), body: "garage door closed" }); console.log(sent.status); // 200 // Optional: attach an Ed25519 key, so topic keys can be sealed to the device and it can sign // requests and messages. Persist key.seed on the device. const key = await generateDeviceKey(); const attachUrl = `${baseUrl}/v1/devices/dba`; await fetch(attachUrl, { method: "POST", headers: { ...(await dba.headers("POST", attachUrl)), "content-type": "application/json" }, body: JSON.stringify({ ...(await enrollmentProof(key)), name: "garage-pi", capabilities: ["ws", "lan"] }) }); const device = new SubEtha({ baseUrl, fetch, deviceKey: key, signRequests: true }); const msg = await device.publish(topic, "garage door open"); ``` ```bash title="samples/curl/devices-dba.sh" #!/usr/bin/env bash # Devices enroll at devicebasedauth.org; subetha checks their credentials. Once, on the device # (the dba CLI keeps its key in the OS keychain or TPM where there is one): # dba enroll --aud subetha.us --action subetha:publish --action subetha:subscribe --resource "@me/*" # You approve it at devicebasedauth.org. After you link that account here (console → Devices → # Link devicebasedauth.org), the device publishes and subscribes with its own credential: set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" dba curl -sS -d "Backup done" "$SUBETHA_URL/@me/backups" dba curl -sS "$SUBETHA_URL/@me/backups/json?poll=1" # The owner lists devices (dba:… for devicebasedauth.org devices, dev_… for signing keys they # attached) and can pause or revoke them here too: AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN") curl -sS "${AUTH[@]}" "$SUBETHA_URL/v1/devices" curl -sS "${AUTH[@]}" "$SUBETHA_URL/v1/dba/link" ``` ### Signing keys (E2EE and signed messages) E2EE topic keys are sealed to an Ed25519 key, and signed messages are signed by one. A DBA device attaches such a key with **`POST /v1/devices/dba`**, proving it holds it with `enrollmentProof(key)` (an Ed25519 signature over `"subetha-enroll-v1\n" + device_id + "\n" + time`). The device needs grants on every topic for this. The key, `dev_` followed by its public key in base32, is then listed beside its DBA device and signs requests as below; revoking the DBA credential stops it too. `attachDeviceKey(key)` in the TypeScript SDK does this, and so does **Devices → This browser → Enroll this browser** in the console and bare `subetha login` in the CLI (through the `dba` CLI). subetha's own device-code flow (`/v1/device/code`, `/approve`, `/token`) and direct registration (`POST /v1/devices`) are retired and answer `410`. ## Signed requests Every request signed with an attached key carries: ```http X-Device-Id: dev_kxisxbay4mtidk6z454fh3jcjhf3wfpggcprvnuu42wa2fvbeiwa X-Device-Time: 1763750000 X-Device-Nonce: 9f2Kx_Lq0aZ7mW3vB8cR1g X-Device-Signed-Headers: x-device-id,x-device-time,x-device-nonce,content-type,x-priority,x-title X-Device-Signature: ``` The signature covers `"subetha-req-v2\n" + METHOD + "\n" + host + "\n" + path?query + "\n" + hex(sha256(body))`, followed by `"\n" + name + ":" + value` for each header named in `X-Device-Signed-Headers`, in that order ([spec §8.1](https://github.com/curtcox/subetha/blob/main/spec/README.md#81-device-signed-requests)). - `X-Device-Time` must be within 5 minutes of the relay's clock, and the nonce is 16–64 random base64url characters. Each signature is accepted once; a replay gets `401`. - Headers that change what a request does must be signed: `Content-Type`, `Idempotency-Key`, every ntfy publish header and its aliases (`X-Title`, `Title`, `t`, …), and the routing and cost headers (`X-Route-Mode`, `X-Max-Cost`, `X-Allow`, `X-Deny`, `X-Dry-Run`, …). If one is present but not signed, the request gets `401`, so nobody relaying a captured request can change its content, route, or cost. Other headers (`User-Agent`, proxy headers) can be added in transit. - The host is signed, so a signature made for staging isn't valid in production. Every SDK does this for you: `new SubEtha({ deviceKey, signRequests: true })` in TypeScript, `Client(device_key=key, sign_requests=True)` in Python (or `httpx.Client(auth=DeviceAuth(key))`), the device signer in the Kotlin, Swift, and Dart SDKs, and `createClient({ core, deviceSeed, signRequests: true })` in React Native (signing with the Rust core). The shared test vectors are in `spec/vectors/requests.json`. The older `subetha-req-v1` form, without `X-Device-Signed-Headers`, is still accepted for requests that carry none of those headers. It's deprecated. ## Keys Generate the key on the device and never move it: `generateDeviceKey()` (TypeScript), `generate_device_key()` (Python), or `DeviceKey::generate()` (Rust). Persist the 32-byte seed in the platform's secure storage (Keychain, Android Keystore, a file readable only by the service user) and restore it with `deviceKeyFromSeed` / `device_key_from_seed` / `DeviceKey::from_seed`. A lost key means attaching a new one; a leaked key means revoking the device (or its devicebasedauth.org credential). --- # SDKs & CLI You never *need* an SDK (the API is plain HTTP), but the SDKs handle the fiddly parts: reconnecting with `since=`, dedupe across transports, acks, signatures, end-to-end encryption, and typed errors. All of them pass the same [conformance vectors](https://github.com/curtcox/subetha/tree/main/spec/vectors), so a message signed or encrypted by one verifies and decrypts in all the others. | SDK | Package | Runs on | Source | |---|---|---|---| | TypeScript (+ CLI, web components) | `@subetha/sdk` | browsers, Node 18+, Deno, Bun, Workers | [`sdk/js`](https://github.com/curtcox/subetha/tree/main/sdk/js) | | Python | `subetha` | Python 3.11+ | [`sdk/python`](https://github.com/curtcox/subetha/tree/main/sdk/python) | | Rust core | `subetha-core` | anywhere; the base for Swift, Kotlin, Flutter, and React Native bindings | [`sdk/core`](https://github.com/curtcox/subetha/tree/main/sdk/core) | | Swift | `SubEtha` (+ `SubEthaCore`) | iOS, macOS | [`sdk/swift`](https://github.com/curtcox/subetha/tree/main/sdk/swift) | | Kotlin | `us.subetha:subetha` (+ `subetha-core`) | Android, JVM | [`sdk/kotlin`](https://github.com/curtcox/subetha/tree/main/sdk/kotlin) | | Dart / Flutter | `subetha` (+ the `subetha_core` plugin) | Flutter on Android and iOS; Dart VM | [`sdk/flutter`](https://github.com/curtcox/subetha/tree/main/sdk/flutter), [`sdk/flutter_core`](https://github.com/curtcox/subetha/tree/main/sdk/flutter_core) | | React Native | `@subetha/react-native` (+ `@subetha/react-native-core`) | React Native and Expo (Hermes) | [`sdk/react-native`](https://github.com/curtcox/subetha/tree/main/sdk/react-native), [`sdk/react-native-core`](https://github.com/curtcox/subetha/tree/main/sdk/react-native-core) | The packages in parentheses carry the Rust core for that platform: device keys, signatures, E2EE, and the edge transports. The mobile SDKs work without them for relay messaging. Package registry releases are pending; install from the repository until then. Build status and versions are on the [build info page](https://curtcox.github.io/subetha/build-info.html). ## TypeScript Dependency-free and small enough for web pages. ```ts title="samples/ts/publish.ts" // Publish a message with the TypeScript SDK. import { SubEtha } from "@subetha/sdk"; import type { SampleContext } from "./_context.ts"; export async function run({ baseUrl, token, topic, fetch }: SampleContext) { // #region snippet const se = new SubEtha({ baseUrl, token, fetch }); const msg = await se.publish(topic, "Backup finished in 4m12s", { title: "nightly-backup", priority: 4, tags: ["backup", "white_check_mark"], click: "https://example.com/backups/latest", }); console.log(`published ${msg.id} to ${msg.topic}`); // #endregion snippet return msg; } ``` The client also covers attachments, polling, subscriptions, dry runs, tokens, topics, traces, and billing (`publishFile`, `estimateFile`, `poll`, `subscribe`, `estimate`, `createToken`, `configureTopic`, `trace`, `balance`, `checkout`), plus `request()` for any other route. Useful options: | Option | Effect | |---|---| | `token` | Bearer token (or a `() => Promise` provider for rotating JWTs). | | `deviceKey` | Sign every publish ([signed messages](publishing.md#signed-messages)). | | `signer`, `verifyEnvelope` | Sign and check signatures with something other than WebCrypto Ed25519, e.g. the Rust core in React Native (`createClient({ core, deviceSeed })` in `@subetha/react-native`). | | `signRequests: true` | Authenticate with device signatures instead of a token ([Devices](devices.md)). | | `topicKeys` | Per-topic E2EE keys: messages to those topics are encrypted, received ones decrypted. `loadTopicKeys()` adds the ones [shared with this device](publishing.md#sharing-keys-with-devices) (in React Native, pass `unwrapper: coreKeyUnwrapper(core, seed)` and `wrapper: coreKeyWrapper(core)`; in Swift and Kotlin, `CoreDeviceSigner.unwrapTopicKey` and `CoreKeyWrap.wrap`). | | `fetch`, `WebSocket` | Bring your own (tests, older runtimes). | `subscribe()` picks a WebSocket when it can and falls back to an NDJSON stream; pass `transport: "stream" | "ws" | "poll"` to choose. It acks automatically (`autoAck: false` to disable) and can drop unsigned or badly signed messages (`verify`, `requireSignature`). Errors are `SubEthaError` with `code`, `status`, and the JSON `body`. The protocol layer (`@subetha/sdk/protocol`) has canonical JSON, ULIDs, the topic grammar, device keys, Ed25519 signatures, XChaCha20-Poly1305 encryption, wrapped topic keys (`wrapTopicKey`, `unwrapTopicKey`), and the `Deduper`. `subscribeWebPush()` registers a browser for [Web Push](transports.md#web-push). ## Web components One script tag gives you a live feed and a send box. Use [publishable tokens](tokens.md#publishable-tokens): they're visible to anyone who views the page. ```html title="samples/web/feed.html" Doorbell

    Doorbell

    ``` `` takes `topic` (comma-separated for several), `token`, `since`, `max`, `priority`, `tags`, and `base-url`; its items are styleable with `::part(list)` and `::part(item)`, and it fires a `message` event. `` takes `topic`, `token`, `placeholder`, `label`, `title`, `priority`, and `tags`, and fires `sent` and `error`. ## CLI ```bash title="samples/cli/cli.sh" #!/usr/bin/env bash # The subetha CLI (npx subetha …, or install @subetha/sdk globally). set -euo pipefail npx subetha login "$SUBETHA_TOKEN" # saves the token (and --url) to your config npx subetha pub @me/backups "Backup done" -t nightly -p high --tags backup echo "from stdin" | npx subetha pub @me/backups npx subetha cost @me/alarm "Smoke" -p 5 --mode all # dry run: route plan + estimate npx subetha poll @me/backups --since 1h npx subetha sub @me/backups,@me/alarm --json # stream (Ctrl-C to stop) npx subetha tail @me/backups # everything retained, then live npx subetha balance npx subetha token create --scopes "publish:@me/*" --daily-cap 1 --name ci npx subetha token list # Offline: gossip with SubEtha peers on the local network (no relay, no charge) npx subetha lan @me/doorbell --send "Door opened" --for 10 ``` `SUBETHA_TOKEN` and `SUBETHA_URL` override the saved login. Running `subetha login` with no token attaches a fresh signing key through this machine's devicebasedauth.org device (enroll it first with `dba enroll --aud subetha.us --action subetha:publish --action subetha:subscribe`) and saves it, so the CLI signs requests without storing a bearer token. `subetha pub --file PATH` uploads an attachment, and `subetha trace` / `subetha ack` inspect or acknowledge messages. ## Python ```python title="samples/python/publish.py" """Publish with the Python SDK (pip install subetha).""" import os from subetha import Client, SubEthaError client = Client(os.environ.get("SUBETHA_URL", "https://subetha.us"), token=os.environ["SUBETHA_TOKEN"]) msg = client.publish( "@me/backups", "Backup finished in 4m12s", title="nightly-backup", priority="high", tags=["backup"], idempotency_key="backup-2026-11-21", ) print("published", msg["id"]) # Route control and a dry run: what would an alarm cost? estimate = client.publish("@me/alarm", "Smoke detected", priority=5, route={"mode": "all", "deny": ["voice"]}, dry_run=True) print("estimate:", estimate["estimate_usd_micros"], "µ$") try: client.publish("@someone-else/topic", "hi") except SubEthaError as e: print(e.code, e.http, e.message) # e.g. forbidden 403 ``` ```python title="samples/python/subscribe.py" """Poll and subscribe with the Python SDK.""" import os from subetha import Client client = Client(os.environ.get("SUBETHA_URL", "https://subetha.us"), token=os.environ["SUBETHA_TOKEN"]) # Cached messages from the last hour, from two topics: for msg in client.poll(["@me/doorbell", "@me/alarm"], since="1h"): print(msg["topic"], msg.get("title"), msg.get("message")) # A live stream: deduplicated, and it reconnects with since= after network errors. for msg in client.subscribe("@me/doorbell"): print(msg.get("message")) if msg.get("message") == "stop": break ``` ```python title="samples/python/signed.py" """Signed publishing and E2EE primitives in Python.""" import os from subetha import Client, decrypt_envelope, device_key_from_seed, encrypt_envelope, generate_device_key, verify_envelope client = Client(os.environ.get("SUBETHA_URL", "https://subetha.us"), token=os.environ["SUBETHA_TOKEN"]) # A device key. Persist key.seed (32 bytes) and restore it with device_key_from_seed(seed). key = generate_device_key() assert device_key_from_seed(key.seed).device_id == key.device_id sent = client.publish("@me/sensors", "Temperature 21.5C", sign_with=key) print(sent["sender"], verify_envelope(sent)) # E2EE: encrypt locally with a 32-byte topic key shared out of band; the relay sees ciphertext. topic_key = os.urandom(32) sealed = encrypt_envelope({"topic": "@me/secrets", "title": "Door code", "message": "4721"}, topic_key, "k1") print(sealed["enc"], decrypt_envelope(sealed, topic_key)["message"]) ``` `Client.publish` uses ntfy headers for simple messages and switches to JSON for signed messages, extension fields, or text that can't travel in a header. Errors raise `SubEthaError` with `code`, `http`, `message`, and `body`. ## Rust core `subetha-core` implements the protocol (canonical JSON, signatures, E2EE, dedupe), a store-and-forward outbox, routing and policy intersection, and the edge transports' protocol logic (audio modem, fountain-coded QR, BLE chunking, gossip). Platform shims supply radios, speakers, and cameras. Bindings for Swift and Kotlin (UniFFI), Flutter, and React Native are generated from it; see [`BINDINGS.md`](https://github.com/curtcox/subetha/blob/main/sdk/core/BINDINGS.md). ```rust title="samples/rust/sign_and_encrypt.rs" //! Sign, encrypt, verify, and dedupe envelopes with the Rust core (`subetha-core`). //! Built and run by `cargo test` / `cargo run -p subetha-core --example sign_and_encrypt`. use subetha_core::e2ee::generate_topic_key; use subetha_core::{decrypt_envelope, encrypt_envelope, sign_envelope, verify_envelope, Deduper, DeviceKey, Envelope}; fn main() -> Result<(), subetha_core::Error> { // A device identity. Persist key.seed() and restore it with DeviceKey::from_seed(&seed). let key = DeviceKey::generate(); println!("device id: {}", key.device_id()); let mut env = Envelope::new("@me/sensors", "Temperature 21.5C").with_id_and_time(); env.title = Some("Garage".into()); // Encrypt first (the relay will only see ciphertext), then sign the ciphertext. let topic_key = generate_topic_key(); let sealed = encrypt_envelope(&env, &topic_key, "k1")?; let signed = sign_envelope(&sealed, &key)?; assert!(verify_envelope(&signed)); println!("{}", serde_json::to_string(&signed).expect("json")); // A receiver: drop duplicates (the same id can arrive over BLE and WebSocket), then decrypt. let mut seen = Deduper::new(10_000); let now = signed.time.unwrap_or_default() as u64; assert!(seen.accept_envelope(&signed, now)); assert!(!seen.accept_envelope(&signed, now)); let plain = decrypt_envelope(&signed, &topic_key).expect("right key"); assert_eq!(plain.message.as_deref(), Some("Temperature 21.5C")); Ok(()) } ``` ## Mobile SDKs (Swift, Kotlin, Flutter, React Native) All four mobile SDKs share the same API shape (`publish`, `publishFile`, `estimate`, `poll`, `subscribe`, `ack`, `setTopicKey`, wrapped topic keys, and control-plane helpers) and optionally link `subetha-core` for Ed25519 signing, E2EE, store-and-forward outbox, and edge transports (BLE, audio, animated QR, LAN): - **Swift (`sdk/swift`)**: `SubEtha(token: ...)` + `SubEthaCore` (UniFFI). See [`sdk/swift/README.md`](https://github.com/curtcox/subetha/blob/main/sdk/swift/README.md) and [`samples/ios`](https://github.com/curtcox/subetha/tree/main/samples/ios). - **Kotlin / Android (`sdk/kotlin`)**: `SubEtha(token = ...)` + `subetha-core` (UniFFI). See [`sdk/kotlin/README.md`](https://github.com/curtcox/subetha/blob/main/sdk/kotlin/README.md) and [`samples/android`](https://github.com/curtcox/subetha/tree/main/samples/android). - **Dart / Flutter (`sdk/flutter`, `sdk/flutter_core`)**: `SubEtha(token: ...)` + `subetha_core` (`flutter_rust_bridge`). See [`sdk/flutter/README.md`](https://github.com/curtcox/subetha/blob/main/sdk/flutter/README.md) and [`samples/flutter`](https://github.com/curtcox/subetha/tree/main/samples/flutter). - **React Native / Expo (`sdk/react-native`, `sdk/react-native-core`)**: `createClient({ core, deviceSeed, token })` (`uniffi-bindgen-react-native` Turbo Module) with `coreSigner`, `coreVerifier`, `coreKeyWrapper`, and `coreKeyUnwrapper`. See [`sdk/react-native/README.md`](https://github.com/curtcox/subetha/blob/main/sdk/react-native/README.md) and [`samples/react-native`](https://github.com/curtcox/subetha/tree/main/samples/react-native). --- # Agents (MCP, llms.txt) Agents are devices too. An AI agent can publish to a topic (notify a person, trigger a device, hand work to another agent) and wait for a reply, over the same relay and with the same prepaid, capped billing as everything else. ## The MCP server SubEtha runs a remote [Model Context Protocol](https://modelcontextprotocol.io) server at **`https://subetha.us/mcp`** (Streamable HTTP, JSON responses). Authenticate with a bearer token. | Tool | What it does | |---|---| | `publish` | Publish a message (`topic`, `message`, and optionally `title`, `priority`, `tags`, `click`, `route_mode`, `max_cost_usd`, `idempotency_key`). Returns the stored message. | | `poll` | Cached messages on one or more topics (comma-separated) since an id, a Unix time, a duration like `10m`, or `all`; optional `priority` and `tags` filters. | | `wait_for_message` | Long-poll: wait up to `timeout_s` (≤ 50) seconds for the next message on a topic after `since` (default: now). Returns the message or `{"timeout": true}`. | | `list_topics` | Topics the account owns, with their policies. | | `create_topic` | Create a topic in your namespace (or a secret `t_` topic), or update its policy. | | `estimate_cost` | Dry run: the delivery plan and price of a message, without sending it. | Tools call the public API in-process with the agent's own credentials, so token scopes, topic policies, spend caps, and prepaid charges apply exactly as they would to any other client. ### Connecting Claude Code: ```bash title="samples/mcp/claude-code.sh" #!/usr/bin/env bash # Add SubEtha as a remote MCP server in Claude Code. Use a scoped, spend-capped token. set -euo pipefail claude mcp add --transport http subetha https://subetha.us/mcp \ --header "Authorization: Bearer $SUBETHA_TOKEN" ``` Clients that read an `mcp.json` (or similar) configuration: ```json title="samples/mcp/mcp.json" { "mcpServers": { "subetha": { "type": "http", "url": "https://subetha.us/mcp", "headers": { "Authorization": "Bearer ${SUBETHA_TOKEN}" } } } } ``` There are two ways to authenticate. **An API token (recommended for unattended agents).** Give the agent its own token: scoped to the topics it needs, with a daily cap and no `sms`/`voice` unless you mean it. For example `{"scopes": ["publish:@me/agent-out", "subscribe:@me/agent-in"], "daily_cap_usd": 0.5}`. **Sign in with OAuth.** MCP clients that support the [MCP authorization spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) can connect with no token at all. An unauthenticated request gets a 401 whose `WWW-Authenticate` header points at `/.well-known/oauth-protected-resource` (RFC 9728); that names SubEtha's authorization server (Clerk), where you sign in with your SubEtha login and approve the client. The client then sends the access token it got as a bearer token. An OAuth-connected client is deliberately limited: - It can **publish and subscribe** on your topics (so `publish`, `poll`, `wait_for_message`, and `estimate_cost` work), but not manage the account: `list_topics`, `create_topic`, tokens, endpoints, and billing need an admin token. - Each client has its own **daily spend cap**: $1 by default. Change it, or set it to 0 to turn OAuth access off, with `PATCH /v1/account {"oauth_daily_cap_micros": 5000000}` or in the console's Billing tab. - A token that names an audience must name this server (`https://subetha.us/mcp`); one issued for another resource gets `401` with `error="invalid_token"`, as does an expired one. ### On the wire What an MCP client sends, as raw JSON-RPC: ```bash title="samples/mcp/tools-call.sh" #!/usr/bin/env bash # Talk to the MCP server with raw JSON-RPC (Streamable HTTP). Agents' MCP clients do this for you. set -euo pipefail SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}" H=(-H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream") curl -sS "${H[@]}" -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}' "$SUBETHA_URL/mcp" curl -sS "${H[@]}" -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' "$SUBETHA_URL/mcp" # Publish, then block until a reply arrives on another topic (or 50 s pass): curl -sS "${H[@]}" -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"publish","arguments":{"topic":"@me/agent-out","message":"Deploy v1.2 to prod? Reply yes/no."}}}' "$SUBETHA_URL/mcp" curl -sS "${H[@]}" -d '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"wait_for_message","arguments":{"topic":"@me/agent-in","timeout_s":50}}}' "$SUBETHA_URL/mcp" ``` ```ts title="samples/ts/mcp.ts" let id = 0; const rpc = async (method: string, params: Record = {}) => { const r = await fetch(`${baseUrl}/mcp`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }), }); return ((await r.json()) as { result: any }).result; // eslint-disable-line @typescript-eslint/no-explicit-any }; const callTool = async (name: string, args: Record) => (await rpc("tools/call", { name, arguments: args })).structuredContent; await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "sample", version: "1" } }); const tools = (await rpc("tools/list")).tools.map((t: { name: string }) => t.name); const estimate = await callTool("estimate_cost", { topic, message: "Deploy finished", priority: 4 }); const sent = await callTool("publish", { topic, message: "Deploy finished", priority: 4, tags: ["deploy"] }); const inbox = await callTool("poll", { topic, since: "all" }); console.log(tools, estimate.estimate_usd_micros, sent.id, inbox.messages.length); ``` ### Patterns - **Human in the loop:** `publish` a question to a topic your phone subscribes to (push or SMS), then `wait_for_message` on a reply topic. Reply from the console, ntfy, or Slack. - **Agent to agent:** each agent waits on its own inbox topic and publishes to the other's. - **Check before spending:** call `estimate_cost` before an `all`-mode alarm. ## llms.txt Machine-readable docs for agents that read the web: - [`/llms.txt`](https://subetha.us/llms.txt): a summary and links in the [llmstxt.org](https://llmstxt.org) format. - [`/llms-full.txt`](https://subetha.us/llms-full.txt): every docs page in one file. - Every docs page is also available as Markdown: replace `.html` with `.md`. - [`/openapi.yaml`](https://subetha.us/openapi.yaml): the complete HTTP API (OpenAPI 3.1). ## Agent-friendly API details - Errors are JSON with stable codes ([list](api.md#errors)); `402` responses say exactly how much money is missing. - `Idempotency-Key` makes retries safe; `X-Dry-Run: 1` previews cost. - Tokens can be capped per day and in total, limited to transports, and expire. --- # Self-hosting & gateways There are three ways to run SubEtha pieces yourself: run the whole relay locally (for development or your own deployment), run a **gateway** that bridges another network to topics, or write your own gateway with an SDK. ## Run the relay locally The relay is one Cloudflare Worker with Durable Objects, D1, KV, R2, and a Queue. `wrangler dev` simulates all of them on your machine. ```bash title="samples/curl/local-dev.sh" #!/usr/bin/env bash # Run the relay locally and get a funded account and admin token. set -euo pipefail # In one terminal (from the repository root): # pnpm install && pnpm --filter @subetha/sdk build && pnpm --filter @subetha/site build # pnpm --filter @subetha/api exec wrangler d1 migrations apply DB --local # pnpm --filter @subetha/api dev # http://localhost:8787 # In another: export SUBETHA_URL=http://localhost:8787 SUBETHA_TOKEN=$(curl -sS -X POST "$SUBETHA_URL/v1/dev/bootstrap" \ -d '{"secret":"local-dev-only","handle":"me","credit_usd":5}' | jq -r .token) export SUBETHA_TOKEN curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" -d "hello from localhost" "$SUBETHA_URL/@me/test" curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/@me/test/json?poll=1" ``` `POST /v1/dev/bootstrap` exists only when `ENVIRONMENT=local` and `DEV_BOOTSTRAP_SECRET` is set (both are, in the default local config in `workers/api/wrangler.jsonc`). Provider integrations (Stripe, Twilio, Slack, push, email) stay disabled until you set their secrets in `workers/api/.dev.vars`; see [`infra/secrets.md`](https://github.com/curtcox/subetha/blob/main/infra/secrets.md). ## Deploy your own [`infra/README.md`](https://github.com/curtcox/subetha/blob/main/infra/README.md) has the one-time Cloudflare setup (D1, KV, R2, Queues, rate limits, custom domains) and the GitHub Actions deploy workflow (staging on every push to `main`, production on `v*` tags). Point SDKs and clients at your deployment with `baseUrl` / `SUBETHA_URL`. To deliver to iOS through APNs, also run the [APNs relay](https://github.com/curtcox/subetha/tree/main/gateways/apns-relay): APNs needs HTTP/2, which a Worker can't be relied on to speak. It's one dependency-free Node process (or Docker image) with no Apple credentials; set `APNS_ENDPOINT` and `APNS_RELAY_SECRET` to point the Worker at it. ## Reticulum gateway [`gateways/reticulum`](https://github.com/curtcox/subetha/tree/main/gateways/reticulum) bridges [Reticulum](https://reticulum.network)/LXMF meshes to topics. Each mapped topic gets its own LXMF address, so anyone on the mesh (Sideband, NomadNet, MeshChat) can publish to it and `/subscribe` to it with no IP connectivity at all. ```bash pip install -e sdk/python -e "gateways/reticulum[rns]" cp gateways/reticulum/gateway.example.toml gateway.toml # list your topics export SUBETHA_TOKEN=se_… # publish + subscribe on those topics, with a spend cap subetha-reticulum --config gateway.toml ``` It runs anywhere Reticulum does (a Raspberry Pi with an RNode, a home server, a VPS) and needs no special access: it uses only the public API. Several gateways can serve the same topic, and they won't echo each other's messages. The gateway's token pays for what mesh users publish, so scope it and cap it. The hosted gateway also accepts relay-pushed deliveries for `lxmf` endpoints on `POST /deliver` (HMAC-signed with `LXMF_GATEWAY_SECRET`). Docker and Cloudflare Containers notes are in the gateway's README. ## Bring your own gateway Anything that can subscribe and publish is a gateway. The pattern: subscribe to the topic and forward to your transport; read from your transport and publish to the topic; remember the ids you published so you don't echo them back. ```python title="samples/python/byo_gateway.py" """A minimal bring-your-own gateway: bridge a topic to any local transport. Anything that can subscribe and publish over the public API is a gateway. This one bridges a topic to lines on a serial port (a LoRa modem, an Arduino…). Replace send_local/read_local with your transport. gateways/reticulum is a complete example of the same pattern. """ import os import threading from subetha import Client TOPIC = os.environ.get("TOPIC", "@me/mesh") client = Client(os.environ.get("SUBETHA_URL", "https://subetha.us"), token=os.environ["SUBETHA_TOKEN"]) seen: set[str] = set() # ids we published, so we don't echo them back def send_local(text: str) -> None: print(f"-> local: {text}") # e.g. serial.write(text.encode() + b"\n") def read_local(): while True: # e.g. yield serial.readline().decode().strip() yield input() def relay_to_local() -> None: for msg in client.subscribe(TOPIC): # reconnects and resumes from the last id if msg["id"] in seen: continue send_local(msg.get("message", "")) def local_to_relay() -> None: for line in read_local(): if line: sent = client.publish(TOPIC, line, tags=["gateway"], route={"deny": ["sms", "voice"]}) seen.add(sent["id"]) threading.Thread(target=relay_to_local, daemon=True).start() local_to_relay() ``` Tips: - Use a dedicated token scoped to the bridged topics, with a daily cap and a transport allow-list. - Tag bridged messages (`tags=["lora"]`) and deny expensive transports on them if they can be noisy (`route={"deny": ["sms", "voice"]}`). - Persist the last message id and resume with `since=` after restarts. - Sign messages with the gateway's device key if downstream devices require signatures; E2EE messages pass through unreadable, which is the point. --- # API reference The complete HTTP API is described in OpenAPI 3.1: **[openapi.yaml](/openapi.yaml)** (source: [`spec/openapi.yaml`](https://github.com/curtcox/subetha/blob/main/spec/openapi.yaml)). Load it into any OpenAPI viewer or client generator. A test fails the build if a route the relay serves is missing from it. Base URLs: `https://subetha.us` (production), `https://staging.subetha.us` (staging, providers in test mode), `http://localhost:8787` (`wrangler dev`). ## Routes at a glance | Area | Routes | |---|---| | Publish (ntfy) | `PUT`/`POST /{topic}`, `POST /` (JSON), `GET /file/{id}/{name}` (attachments) | | Subscribe (ntfy) | `GET /{topics}/json`, `/sse`, `/raw`, `/ws`, `/auth`; `?poll=1`, `since`, `priority`, `tags` | | Meta | `GET /v1/health`, `/v1/status`, `/v1/prices`, `/v1/config` | | Account & billing | `GET`/`POST`/`PATCH /v1/account`, `GET /v1/balance`, `GET /v1/ledger`, `GET /v1/payments`, `GET /v1/payments/{id}/receipt`, `POST /v1/billing/checkout` | | Tokens | `GET`/`POST /v1/tokens`, `DELETE /v1/tokens/{id}` | | Topics | `GET /v1/topics`, `GET`/`PUT /v1/topics/{topic}` | | Traces & acks | `GET /v1/traces/{id}?topic=`, `POST /v1/ack` | | Endpoints | `GET`/`POST /v1/endpoints`, `POST /v1/endpoints/{id}/verify`, `DELETE /v1/endpoints/{id}` | | Subscriptions | `GET`/`POST /v1/subscriptions`, `DELETE /v1/subscriptions/{id}` | | Slack | `GET /v1/slack/install`, `GET /v1/slack/oauth`, `POST /v1/slack/bindings` | | Devices | `GET /v1/devices`, `PATCH`/`DELETE /v1/devices/{id}`, `POST /v1/devices/dba` (attach a signing key), `GET`/`DELETE /v1/dba/link`, `POST /v1/dba/link/start`, `/v1/dba/link/finish` (devicebasedauth.org). Retired (410): `POST /v1/devices`, `/v1/device/code`, `/approve`, `/token` | | Agents | `POST /mcp`, `GET /.well-known/oauth-protected-resource` | | Provider hooks | `POST /v1/hooks/stripe`, `/v1/hooks/twilio/sms`, `/v1/hooks/twilio/voice-ack`, `/v1/hooks/slack/events` | | Local only | `POST /v1/dev/bootstrap` | ## Conventions - **Auth:** `Authorization: Bearer `; HTTP Basic with an empty user and the token as the password; `?auth=")>`; or device request signatures ([Devices](devices.md#signed-requests)). - **Money** is integer micro-dollars in responses (`*_usd_micros`); request fields that take dollars are named `*_usd`. - **Times** are Unix seconds in messages and milliseconds in control-plane records (`created_at`). - **CORS** is open: the API is meant to be called from web pages with publishable tokens. `X-Cost-Micros`, `X-Message-Id`, and `Retry-After` are exposed to scripts. - **Rate limits:** 600 requests/minute per credential, 60/minute per IP without one; `429` with `Retry-After` when exceeded. ## Errors Every error is JSON with a stable `error` code, the HTTP status, and a human-readable `message`, plus fields specific to the error (`shortfall_usd_micros` on 402): ```json { "error": "spend_cap_exceeded", "http": 403, "message": "topic daily cap reached", "cap": "topic_daily" } ``` | Code | HTTP | Meaning | |---|---:|---| | `bad_request` | 400 | Malformed request. | | `invalid_topic` | 400 | Topic name does not match the topic grammar. | | `invalid_message` | 400 | Envelope failed validation. | | `message_too_large` | 413 | Message body exceeds 4096 bytes (use an attachment). | | `unsupported` | 400 | Feature not supported in this version (e.g. X-Delay). | | `unauthorized` | 401 | Missing or invalid credentials. | | `signature_required` | 401 | Topic policy requires a device signature. | | `bad_signature` | 401 | Signature does not verify against the sender id. | | `insufficient_balance` | 402 | Payer balance cannot cover the worst-case cost. Body carries shortfall_usd_micros. | | `no_funded_owner` | 402 | Anonymous publish to a topic with no funded owner. | | `forbidden` | 403 | Token scope or policy forbids this action. | | `spend_cap_exceeded` | 403 | A token, topic, or account spend cap would be exceeded. | | `transport_denied` | 403 | Policy leaves no allowed transport for a required delivery. | | `topic_paused` | 403 | Topic, device, or account kill switch is on. | | `not_found` | 404 | No such resource. | | `conflict` | 409 | Resource already exists or idempotency key reused with a different body. | | `rate_limited` | 429 | Rate or burst limit reached. Retry-After is set. | | `internal` | 500 | Unexpected error. | | `provider_unavailable` | 503 | An upstream provider is unavailable. | The codes come from [`spec/errors.json`](https://github.com/curtcox/subetha/blob/main/spec/errors.json) and won't change meaning; new ones may be added. ## Protocol The message envelope, canonical JSON, signatures, encryption, dedupe, and topic grammar are specified in [`spec/README.md`](https://github.com/curtcox/subetha/blob/main/spec/README.md), with a [JSON Schema](https://github.com/curtcox/subetha/blob/main/spec/schema/message.schema.json) and cross-SDK [test vectors](https://github.com/curtcox/subetha/tree/main/spec/vectors). --- # SubEtha Terms of Service (DRAFT) _Last updated: [DATE]. Draft for legal review._ These Terms govern your use of subetha.us, its APIs, SDKs, gateways, and related services (the "Service"), operated by [ENTITY] ("we"). By creating an account or using the API you agree to these Terms and to the [Acceptable Use Policy](aup.md). ## 1. Accounts You need an account to use relay features. You're responsible for your account, your API tokens, your devices, and everything done with them. Keep tokens secret; revoke them in the console if they leak. Organizations may share an account; the person who creates it confirms they can bind the organization. ## 2. Prepaid balance - The Service is prepaid. You add funds by card through Stripe. There is no subscription; optional auto-recharge tops up your balance when it falls below a threshold you choose. - A top-up fee (shown before you pay) covers card processing and fixed costs. - Every metered action is priced in advance (see the pricing page and `X-Dry-Run` estimates) and is checked against your balance **before** it runs. If your balance can't cover an action, it is refused (HTTP 402); we never bill you after the fact. - Prices may change for future usage with notice on the pricing page. Usage already performed is never repriced. - Stored resources (retained messages, attachments, devices, verified endpoints) accrue daily rent. If your balance can't pay it, resources are frozen and, after [30] days and notice to your account email, deleted. - **Refunds:** [TO DECIDE — PLAN open question 3: either "unused balance is refundable on request minus processing fees" or "balance is non-refundable service credit".] Chargebacks of legitimate top-ups may lead to suspension; we recover dispute fees from remaining balance where possible. - New funds may be subject to limits on SMS and voice spend for a period after your first top-up. ## 3. Your content You keep all rights to messages and attachments you send ("Content"). You grant us the limited rights needed to store, route, and deliver Content through the transports your policies allow (including third-party providers such as push services, email, Slack, and SMS/voice carriers). End-to-end encrypted Content is never readable by us. ## 4. Acceptable use You must follow the [Acceptable Use Policy](aup.md). In particular, you may send SMS, voice, or email only to recipients who have consented, and we require recipients to verify paid endpoints. ## 5. Third-party services Delivery depends on providers we don't control (Cloudflare, Stripe, Clerk, Apple, Google, Slack, Twilio, email providers, Reticulum networks). Their terms may apply to you when you connect them (for example, installing the Slack app). Edge transports (Bluetooth, audio, QR, LAN) run on your devices; we don't operate them. ## 6. Availability and changes We aim for high availability but provide the Service "as is". Delivery over any transport is best effort; use multiple transports and acknowledgements (escalation) for important alerts. **Do not use the Service as your only means of life-safety notification.** We may change or discontinue features with reasonable notice. ## 7. Suspension and termination We may suspend accounts or tokens that violate these Terms or the AUP, endanger the Service, or create legal risk, and we may block destinations (for example, numbers flagged for SMS pumping). You may close your account at any time; [refund terms per §2]. ## 8. Disclaimers and limitation of liability [Standard disclaimers and a liability cap — for example, the greater of the amount you paid in the 12 months before the claim or US$100 — to be drafted by counsel.] ## 9. Indemnity [To be drafted by counsel: you indemnify us for claims arising from your Content and from messages sent to recipients who didn't consent.] ## 10. Governing law These Terms are governed by the laws of [JURISDICTION]. [Dispute resolution clause.] ## 11. Contact [ENTITY], [ADDRESS], [CONTACT EMAIL]. --- # SubEtha Privacy Policy (DRAFT) _Last updated: [DATE]. Draft for legal review._ This policy explains what [ENTITY] collects when you use SubEtha, why, and for how long. It is written to match how the system actually works (see PLAN.md and the source code). ## What we collect | Data | Why | Retention | |---|---|---| | Account: Clerk user/org id, email, handle | sign-in, billing receipts, notices | while the account exists | | Billing: Stripe customer/session ids, amounts, ledger entries | prepaid balance, reconciliation, tax | as required by law (typically 7 years) | | API tokens (hashed), device public keys and names, last-seen times | authentication | until revoked or deleted | | Endpoints you add: email addresses, phone numbers, webhook URLs, push tokens, Slack channel ids, LXMF addresses | delivering messages you route there | until you delete them, or [30] days after a frozen account's grace period | | Messages and attachments | store-and-forward delivery | until the message expires (topic retention, default 12 hours, max 30 days) | | Message traces (route, costs, delivery results, acks) | showing the topic owner what happened | until the message expires | | Audit log of account changes | security | [1 year] | | Request logs and metrics (IP address, user agent, timing) | abuse prevention, rate limiting, debugging | [30 days] | We don't sell personal data and don't use Content for advertising or model training. ## End-to-end encryption If a topic uses E2EE, message bodies, titles, and attachments are encrypted on your devices; we only see metadata needed for routing (topic, id, time, priority, tags, sender device id if signed). ## Who processes data for us Cloudflare (hosting, storage, email routing), Stripe (payments), Clerk (sign-in), and — only for transports you enable — Apple/Google push services, Slack, Twilio (SMS/voice), email providers (Cloudflare Email Service or Amazon SES), and the Reticulum network via our gateway. [List with links to each processor's privacy policy and DPA.] ## Visibility between users Devices never learn which other devices subscribe to a topic or how they're reached. Topic owners see traces of their own topics, including masked destination addresses. ## Your rights You can export or delete your data from the console or by contacting [CONTACT EMAIL]. [GDPR/CCPA rights, legal bases, and international transfer language to be completed by counsel.] ## Children The Service is not directed to children under 13 (or the age required by local law). ## Changes and contact We'll post changes here and notify account emails of material changes. Contact: [CONTACT EMAIL]. --- # SubEtha Acceptable Use Policy (DRAFT) _Last updated: [DATE]. Draft for legal review._ You may not use SubEtha to: 1. Send messages to people who haven't agreed to receive them (spam), including bulk unsolicited email, SMS, or calls. 2. Send content that is illegal, harassing, threatening, fraudulent, or that infringes others' rights; or malware, phishing, or credential-collection pages. 3. Generate artificial traffic to premium or high-cost numbers ("SMS pumping", toll fraud), or try to make the Service spend money it isn't paid for. 4. Evade rate limits, spend caps, verification, or other controls, including by creating many accounts or tokens. 5. Interfere with the Service, other users, or connected networks (including Reticulum and Bluetooth meshes), for example by flooding topics or gossip. 6. Use the Service as the sole means of life-safety or emergency notification. ## SMS and voice (US A2P 10DLC) SubEtha sends SMS and calls only to **numbers verified by their owner** with a one-time code. If you route messages to phone numbers, you confirm that: - each recipient opted in to receive messages about the topic they subscribed to, and you can show that consent on request; - messages are transactional or alert notifications the recipient asked for, not marketing; - recipients can opt out at any time by replying **STOP** (we stop all messages to that number immediately and keep a record), and get help by replying **HELP**. Consent language shown when a number is verified: > By entering this code, you agree to receive automated notification texts and calls from SubEtha > for the topics you've subscribed to. Message frequency varies. Msg & data rates may apply. Reply > STOP to opt out, HELP for help. See subetha.us/terms and subetha.us/privacy. HELP reply text: > SubEtha notifications. Manage at subetha.us/console. Reply STOP to opt out. Support: [CONTACT EMAIL]. International SMS and voice are disabled by default and enabled per country only after review. ## Email Outbound email goes only to addresses verified by their owner. Every message identifies the topic and links to the console to stop delivery. Inbound email to `…@in.subetha.us` is accepted only from senders the topic owner allows. ## Enforcement We may remove content, revoke tokens, block destinations, pause topics, or suspend accounts that violate this policy, and report illegal activity to authorities. Report abuse to [ABUSE EMAIL].