# 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<string \| null>` 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"
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Doorbell</title>
  <!-- Drop-in web components. Use a publishable token: origin-bound, one topic, small daily cap. -->
  <script src="https://subetha.us/sdk.js"></script>
  <style>
    subetha-feed::part(item) { padding: 4px 0; border-bottom: 1px solid #ddd; }
  </style>
</head>
<body>
  <h1>Doorbell</h1>
  <subetha-send topic="@me/doorbell" token="se_publishable_send_token" placeholder="Say something" label="Send"></subetha-send>
  <subetha-feed topic="@me/doorbell" token="se_publishable_read_token" since="1h" max="20"></subetha-feed>

  <script>
    // Each element dispatches a "message" event with the envelope.
    document.querySelector("subetha-feed").addEventListener("message", (e) => {
      if ((e.detail.priority ?? 3) >= 4) document.title = `🔔 ${e.detail.message}`;
    });

    // The SDK client class is window.SubEtha (protocol helpers on SubEtha.protocol):
    //   const se = new SubEtha({ token: "se_…" });
    //   se.subscribe("@me/doorbell", (m) => console.log(m.message));
  </script>
</body>
</html>
```

`<subetha-feed>` 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. `<subetha-send>` 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=<last id> 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).
