# Comms API reference

A private messaging service: one API to send **email** and **Telegram** messages, receive replies and button choices, and get them back as signed webhooks. It runs serverless on AWS, so it's always on and costs nothing while idle.

- **Base URL:** `https://api.kunalgalav.com`
- **Format:** JSON in and out (`content-type: application/json`)
- **Access:** private. API keys are issued only by the owner, from the command line with AWS credentials. There is no sign-up, and no endpoint or web page creates keys.

> For agents and code generators: [`agents.md`](https://kunalgalav.com/messaging_service/agents.md) is a shorter, task-oriented guide with copy-paste helpers.

---

## Authentication

Every endpoint except `/v1/health` needs an app's API key as a bearer token:

```http
Authorization: Bearer ck_...
```

- Each app (a project that uses the service) has its own key, its own optional webhook URL, and its own Telegram bot.
- Keys start with `ck_`. Only a SHA-256 hash is stored, so a lost key can't be recovered, only rotated.
- A missing or wrong key gets `401 unauthorized`.
- An app can only read its own messages. Other apps' message ids return `404`.

---

## Endpoints

| Method | Path | What it does |
|---|---|---|
| `GET` | `/v1/health` | Liveness check, no auth. Returns `{"ok":true}` |
| `POST` | `/v1/messages` | Send an email or Telegram message |
| `GET` | `/v1/messages/{id}` | Get a message: status, button response, errors |
| `POST` | `/v1/contacts/telegram-link` | Create a "tap to connect" Telegram link for a contact |

### POST /v1/messages

Queues a message and returns immediately (`202`). A worker sends it within a second or two, retrying temporary failures up to 5 times.

#### Email

```json
{
  "channel": "email",
  "to": "someone@example.com",
  "subject": "Water heater",
  "body": "The water heater has been on for 3 hours. Turn it off?",
  "html": "<p>Optional HTML version</p>",
  "buttons": [
    { "id": "yes", "label": "Yes, turn it off" },
    { "id": "no", "label": "No, leave it" }
  ],
  "metadata": { "device": "heater-1" },
  "idempotency_key": "heater-1-2026-11-15T20:00"
}
```

| Field | Rules |
|---|---|
| `to` | One email address |
| `subject` | 1–998 characters |
| `body` | Plain text, 1–100,000 characters |
| `html` | Optional HTML alternative, up to 200,000 characters |
| `buttons` | Optional, 1–8. In email they become reply keywords (see [Replies and buttons](#replies-and-buttons)) |
| `metadata` | Optional JSON object, up to 4 KB. Returned unchanged on the message and in every event about it |
| `idempotency_key` | Optional, up to 128 characters. See [Idempotency](#idempotency) |

Emails come from `"Kunal Home" <noreply@kunalgalav.com>`, with `Reply-To` set to a per-message address so replies come back to the service.

> **Sandbox:** while the account's email sending is in SES sandbox mode, email only reaches addresses the owner has verified. Anything else ends with `status: "failed"` and an `error` saying the address isn't verified.

#### Telegram

```json
{
  "channel": "telegram",
  "to": "me",
  "subject": "🔥 Water heater",
  "body": "On for 3 hours. Turn it off?",
  "buttons": [
    { "id": "yes", "label": "Yes, turn off" },
    { "id": "no", "label": "No, leave it" }
  ],
  "metadata": { "device": "heater-1" }
}
```

| Field | Rules |
|---|---|
| `to` | A **contact id** linked to Telegram (e.g. `"me"`), or a raw numeric Telegram chat id |
| `subject` | Optional, up to 256 characters, shown as the first line |
| `body` | 1–4096 characters (subject + body must fit in 4096) |
| `buttons` | Optional, 1–8, shown as tappable buttons, two per row |
| `metadata`, `idempotency_key` | As for email |

Contact ids start with a letter and use letters, digits and `_` (up to 24 characters). A contact must have [connected Telegram](#telegram-contacts) before you can message it.

#### Button rules

- `id`: 1–32 characters of `A–Z a–z 0–9 _ -`. This is what your app gets back.
- `label`: 1–64 characters. This is what the person sees.

#### Responses

`202 Accepted` for a new message, or `200 OK` when an `idempotency_key` repeats (it returns the original message):

```json
{
  "id": "msg_0mwia3jj7a1b2c3d4e5f60718",
  "channel": "telegram",
  "direction": "outbound",
  "to": "me",
  "subject": "🔥 Water heater",
  "body": "On for 3 hours. Turn it off?",
  "buttons": [{ "id": "yes", "label": "Yes, turn off" }, { "id": "no", "label": "No, leave it" }],
  "status": "queued",
  "metadata": { "device": "heater-1" },
  "created_at": "2026-11-15T20:19:57.475Z",
  "updated_at": "2026-11-15T20:19:57.475Z"
}
```

### GET /v1/messages/{id}

Returns the [message object](#the-message-object). Poll this to see delivery status and which button was chosen, if your app has no webhook.

### POST /v1/contacts/telegram-link

```json
{ "contact_id": "me" }
```

`201 Created`:

```json
{
  "contact_id": "me",
  "url": "https://t.me/your_app_bot?start=me-abc123-0123456789abcdef01234567",
  "expires_at": "2026-11-22T20:00:00.000Z",
  "already_linked": false
}
```

Send the `url` to the person. When they open it and tap **Start**, their chat is linked to `contact_id` for your app. Links are signed, valid for 7 days, and work only for the app that created them. Opening a new link for the same contact moves the contact to the new chat.

---

## The message object

| Field | Meaning |
|---|---|
| `id` | `msg_…`, sortable by creation time |
| `channel` | `email` or `telegram` |
| `direction` | `outbound` (sent by your app) or `inbound` (a reply) |
| `to` | Recipient: email address, contact id or chat id. For inbound messages, the address or bot it was sent to |
| `from` | Inbound only: the sender's email address or contact id |
| `subject`, `body`, `buttons`, `metadata` | As sent |
| `status` | See below |
| `error` | Why it failed, bounced or was rejected |
| `in_reply_to` | Inbound only: the id of the outbound message this answers, when known |
| `response` | Outbound with buttons: the first choice made, as `{ button_id, label, contact_id?, at }`. Later taps are ignored |
| `created_at`, `updated_at` | ISO 8601 timestamps |

### Statuses

| Status | Meaning |
|---|---|
| `queued` | Accepted, waiting to send |
| `sent` | Handed to the provider (SES or Telegram) |
| `delivered` | Email only: the receiving mail server accepted it |
| `bounced` | Email only: permanently rejected. The address is then suppressed |
| `complained` | Email only: the recipient marked it as spam. The address is then suppressed |
| `failed` | Couldn't be sent (bad address, contact not linked, bot blocked, sandbox …); see `error` |
| `received` | Inbound messages (replies) |

---

## Replies and buttons

**Telegram.** Buttons are tappable. The first tap is recorded as the message's `response`, the person sees a confirmation, and the buttons are replaced by "✅ *label*". Text the person sends the bot becomes an `inbound` message. If they use Telegram's reply feature, `in_reply_to` points at your message.

**Email.** Buttons are listed under the body as reply keywords:

```text
Reply with one of:
  • Yes, turn it off — reply "yes"
  • No, leave it — reply "no"
```

A reply goes to `r+<message id>@in.kunalgalav.com` (set as `Reply-To`). The service:
- keeps only the new text, dropping the quoted original;
- records the reply as an `inbound` message;
- treats the reply as a button choice if its first word is a button `id`, or its first line is exactly a button `label`.

Replies are accepted only from the address the email was sent to, only if they pass DMARC (so the From address can't be forged), and only if they aren't flagged as spam or a virus.

---

## Webhooks

If your app has a webhook URL (the owner sets it), every event about its messages is `POST`ed there as JSON.

### Events

| Type | When |
|---|---|
| `message.status` | An outbound message changed status (`sent`, `delivered`, `bounced`, `complained`, `failed`) |
| `button.clicked` | Someone chose a button: a Telegram tap, or an email reply with the button keyword |
| `message.received` | Someone replied with text (Telegram or email) |

```json
{
  "id": "evt_mi0abc12d4e5f6a7b8c9d0e1",
  "type": "button.clicked",
  "app_id": "app_0123456789ab",
  "created_at": "2026-11-15T20:22:08.487Z",
  "data": {
    "message": { "id": "msg_…", "status": "sent", "response": { "button_id": "yes", "label": "Yes, turn off", "contact_id": "me", "at": "…" }, "metadata": { "device": "heater-1" }, "…": "…" },
    "button": { "id": "yes", "label": "Yes, turn off" }
  }
}
```

- `data.message` is the full [message object](#the-message-object), including your `metadata`.
- For `message.received`, `data.message` is the inbound reply, and `data.in_reply_to` is your original message with its `metadata`, when the reply could be matched to it.

### Headers

```http
content-type: application/json
x-comms-event-id: evt_…
x-comms-event-type: button.clicked
x-comms-signature: t=1763238128,v1=5f2c…
```

### Verifying the signature

`v1` is the hex HMAC-SHA256 of `"<t>.<raw request body>"`, keyed with the app's `webhook_secret`. Check it against the **raw** body, before parsing JSON, and reject timestamps more than 5 minutes old.

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyCommsWebhook(secret: string, header: string | undefined, rawBody: string): boolean {
  if (!header) return false;
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || !/^[0-9a-f]{64}$/.test(parts.v1 ?? "")) return false;
  if (Math.abs(Date.now() / 1000 - t) > 300) return false;
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
  return timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected));
}
```

```python
import hmac, hashlib, time

def verify_comms_webhook(secret: str, header: str | None, raw_body: bytes) -> bool:
    if not header:
        return False
    parts = dict(p.split("=", 1) for p in header.split(","))
    try:
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if abs(time.time() - t) > 300:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(parts.get("v1", ""), expected)
```

### Delivery

- Return any **2xx within 10 seconds**. Do slow work after responding.
- Anything else (non-2xx, timeout, network error) is retried with backoff: 30 s, 1 m, 2 m, 4 m, … capped at 15 m, for 10 attempts (about 1.5 hours). After that the event is parked in a dead-letter queue the owner can inspect.
- Redirects are not followed. Use the final `https://` URL.
- Delivery is **at least once**: use `id` to ignore duplicates. Events can arrive out of order, so use `created_at` and the message's `status` to decide.
- Without a webhook URL, events are skipped and apps poll `GET /v1/messages/{id}` instead.

---

## Telegram contacts

Each app has its own Telegram bot. Telegram only lets a bot message people who have started it, so contacts are linked once:

1. Your app calls `POST /v1/contacts/telegram-link` with a contact id it chooses (e.g. `"me"`, `"mum"`).
2. The person opens the returned link and taps **Start**. The bot replies "✅ Connected".
3. From then on, send with `"to": "<contact id>"`.

If you send to a contact that isn't linked, you get `422 contact_not_linked` and the message isn't queued.

---

## Idempotency

Send an `idempotency_key` to make retries safe. Within 7 days, repeating a request with the same key (for the same app) returns the original message with `200` instead of sending again. Good keys describe the event, such as `"heater-1-alert-2026-11-15T20:00"`.

---

## Errors

```json
{ "error": { "code": "validation_failed", "message": "Invalid message", "details": [{ "field": "to", "message": "Invalid email address" }] } }
```

| HTTP | `code` | Meaning |
|---|---|---|
| 400 | `invalid_json` | Body isn't valid JSON |
| 401 | `unauthorized` | Missing or wrong API key |
| 404 | `not_found` | Unknown route, or a message that isn't yours |
| 422 | `validation_failed` | Field errors in `details[]` |
| 422 | `telegram_not_configured` | Your app has no Telegram bot connected |
| 422 | `contact_not_linked` | The contact hasn't connected Telegram yet |
| 429 | `rate_limited` | Your app hit its sending limit (see [Rate limits](#rate-limits)). Nothing was created. Wait `Retry-After` seconds |
| 429 | (no body code) | The whole API is over its overall ceiling. Retry after a second |
| 500 | `internal_error` | Something broke on the server. Safe to retry with an `idempotency_key` |

Send failures after queueing (bounces, blocked bots, sandbox) don't produce HTTP errors. They show up as `status: "failed"`, `"bounced"` or `"complained"` plus `error` on the message, and as a `message.status` event.

---

## Rate limits

Each app may call `POST /v1/messages` at most **60 times a minute** and **1,000 times a day** (UTC), unless the owner set different limits for it. Every call counts, including idempotent replays and calls that were refused. A refused call returns:

```http
HTTP/1.1 429 Too Many Requests
Retry-After: 42

{ "error": { "code": "rate_limited", "message": "This app may send at most 60 messages per minute. Retry after 42 s",
             "details": { "window": "minute", "limit": 60, "retry_after": 42 } } }
```

Wait `Retry-After` seconds before trying again. The TypeScript client does this for you when the wait is under a minute. If you hit the **daily** limit, something is probably looping: stop and fix it rather than retrying. Every refusal also alerts the owner.

Separately, the whole API accepts about 20 requests a second (bursts to 40) across all apps.

---

## Limits

| What | Limit |
|---|---|
| Sends per app | 60 per minute, 1,000 per day, unless the owner changed them. See [Rate limits](#rate-limits) |
| Buttons per message | 8 |
| `metadata` | 4 KB of JSON |
| Email body / HTML | 100,000 / 200,000 characters |
| Telegram text | 4096 characters (subject + body) |
| Email sending (sandbox) | Verified recipients only, 200 per day |
| Telegram | About 1 message per second per chat (Telegram's limit). Bursts are retried automatically |

---

## For the owner: managing apps

These run on the owner's laptop with AWS credentials (`AWS_PROFILE=comms`). Nobody without that AWS login can create or change keys.

```bash
npm run create-app -- --name <app> [--telegram-bot <bot_username>] [--key-file .secrets/<app>.key]
npm run app -- list
npm run app -- set-webhook --app <app_id> --url https://example.com/comms-webhook
npm run app -- set-webhook --app <app_id> --clear
npm run app -- rotate-key  --app <app_id> [--key-file .secrets/<app>.key]
npm run app -- set-limits  --app <app_id> --per-minute 60 --per-day 1000   # or --default
npm run telegram -- connect --app <app_id> --bot <bot_username>
npm run telegram -- link    --app <app_id> --contact me
npm run telegram -- status  --app <app_id>
```

A Telegram bot is created with [@BotFather](https://t.me/BotFather). Its token goes in AWS Secrets Manager as `comms/telegram/<bot_username>` before `connect`.
