# 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: <url>` 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 devices'
[attached keys](devices.md#signing-keys-e2ee-and-signed-messages) 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 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).
