# 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; the console's session after signing in with devicebasedauth.org (an `admin` token that expires in 30 days, listed under Tokens) |
| devicebasedauth.org device | `Authorization: DBA …` and `DPoP: …` | [devices](devices.md), within their grants |
| Device signature | `X-Device-Id`, `X-Device-Time`, `X-Device-Nonce`, `X-Device-Signed-Headers`, `X-Device-Signature` | devices with an [attached key](devices.md#signing-keys-e2ee-and-signed-messages) |
| OAuth access token | `Authorization: Bearer …` | [MCP clients](agents.md) (where Clerk is configured) |
| Clerk session | `Authorization: Bearer eyJ…` | the web console, where Clerk is configured |

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`, `deny_transports` | Allow- and deny-lists of transports its publishes may use, e.g. deny `sms` and `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. |

Only `admin` tokens create tokens, and a token can't create one with more power than it has: its scopes, caps, expiry, transports, origins, and IPs bound the new token's.

### 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 [`<subetha-feed>` / `<subetha-send>`](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). |
| `rate_per_min`, `burst` | Topic-wide publish rate limit (messages per minute) and burst size, for every publisher. |
| `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", "tz": "America/Chicago"}` (`tz` is an IANA zone, default 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.
