# KodaMailer — Agent & Service Instructions

Central email sending service for Koda Games, backed by Resend (`mail.koda.games`).

- **Base URL:** `https://mailer.koda.games`
- **Default sender:** `Koda Games <contact@mail.koda.games>`
- **Allowed senders:** Any `<local>@mail.koda.games` address (e.g. `contact@mail.koda.games`, `auth@mail.koda.games`, `ai@mail.koda.games`, `alerts@mail.koda.games`). Any other domain is rejected with `400`.
- **Auth:** `Authorization: Bearer <km_...>`

---

## 1. Provision or Revoke an API Key

Keys are stored as SHA-256 hashes under `/srv/koda-mailer/keys/<name>.json` on `199.168.101.102` and are read from disk on every request (no restart required).

**Create a new key for a service or agent:**
```bash
ssh koda@199.168.101.102 "cd /srv/koda-mailer && ./generate_key.sh <key_name_or_purpose>"
```
The script prints the raw `km_...` Bearer token **once**. Save it in your service's environment/secrets (e.g. `KODA_MAILER_KEY`). Never commit keys to git or paste them into public logs/chat.

**List active keys:**
```bash
ssh koda@199.168.101.102 "ls -la /srv/koda-mailer/keys/"
```

**Revoke a key immediately:**
```bash
ssh koda@199.168.101.102 "rm /srv/koda-mailer/keys/<key_name_or_purpose>.json"
```

---

## 2. Endpoints

| Method | Path | Auth | Description |
| --- | --- | --- | --- |
| `GET` | `/instructions.md` (also `/` and `/llms.txt`) | Public | Returns this Markdown guide. |
| `GET` | `/health` | Public | Returns `{"ok": true, "domain": "mail.koda.games"}`. |
| `POST` | `/v1/send` | Bearer | Sends an email through Resend and returns `{"id", "from", "key"}`. |

---

## 3. Sending Emails (`POST /v1/send`)

### Headers
- `Authorization: Bearer km_...` (required)
- `Content-Type: application/json` (required)
- `Idempotency-Key: <unique-key>` (optional, max 256 chars — strongly recommended for login codes, receipts, and retries)

### Mode A — Send a Resend Template (recommended for transactional emails)

Pass `template: { id, variables }`. Do **not** include `html` or `text` when using `template`.

**Available templates:**
- **Email Authentication Code**
  - `id`: `d2009877-08cc-4087-be49-89ad3e1bb81b` (alias: `email-auth-code`)
  - `variables`:
    - `CODE` (`string`, required) — one-time verification code
    - `EXPIRES_MINUTES` (`number`, optional, default `10`)

```bash
curl -sS -X POST https://mailer.koda.games/v1/send \
  -H "Authorization: Bearer $KODA_MAILER_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: auth-code/user-123-attempt-1" \
  -d '{
    "to": "player@example.com",
    "template": {
      "id": "d2009877-08cc-4087-be49-89ad3e1bb81b",
      "variables": {
        "CODE": "482913",
        "EXPIRES_MINUTES": 10
      }
    }
  }'
```

### Mode B — Send Raw Subject + Text/HTML

Include `subject` and at least one of `text` or `html` (best practice: include both `text` and `html`). Omit `from` to use `Koda Games <contact@mail.koda.games>`, or specify any `<local>@mail.koda.games` address.

```bash
curl -sS -X POST https://mailer.koda.games/v1/send \
  -H "Authorization: Bearer $KODA_MAILER_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: alert/deploy-2026-12-02-1" \
  -d '{
    "from": "Koda AI <ai@mail.koda.games>",
    "to": ["you@example.com"],
    "subject": "Deployment complete",
    "text": "Build #42 deployed cleanly.",
    "html": "<p>Build <strong>#42</strong> deployed cleanly.</p>"
  }'
```

### Optional Body Fields
- `from`: `string` — defaults to `Koda Games <contact@mail.koda.games>`; must be under `@mail.koda.games`
- `to`: `string | string[]` (required, max 50 recipients)
- `cc`, `bcc`, `replyTo`: `string | string[]`
- `headers`: `Record<string, string>`
- `tags`: `Array<{ name: string; value: string }>`
- `scheduledAt`: `string` (ISO 8601 timestamp or natural language, e.g. `"in 1 hour"`)
- `idempotencyKey`: `string` (alternative to `Idempotency-Key` header)

### TypeScript / Node Example
```ts
const res = await fetch('https://mailer.koda.games/v1/send', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.KODA_MAILER_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': `auth-code/${attemptId}`,
  },
  body: JSON.stringify({
    to: userEmail,
    template: {
      id: 'd2009877-08cc-4087-be49-89ad3e1bb81b',
      variables: { CODE: otpCode, EXPIRES_MINUTES: 10 },
    },
  }),
});

if (!res.ok) {
  throw new Error(`KodaMailer failed (${res.status}): ${await res.text()}`);
}
const { id } = (await res.json()) as { id: string; from: string; key: string };
```

---

## 4. Responses, Retries & Testing

- **`200 OK`**: `{"id": "<resend-email-id>", "from": "...", "key": "<key-name>"}`
- **`400 Bad Request`**: invalid JSON, disallowed `from` domain, missing required fields, or mixing `template` with `html`/`text`
- **`401 Unauthorized`**: missing, invalid, or revoked Bearer key
- **`413 Payload Too Large`**: request body exceeds 1 MB
- **`422 Unprocessable Entity`**: upstream Resend validation error (e.g., wrong template variable type)
- **`429` / `5xx`**: KodaMailer automatically retries Resend with exponential backoff (honoring `Retry-After`). If your client retries after a network timeout, reuse the same `Idempotency-Key`.
- **Safe test recipient:** send to `delivered@resend.dev` to test end-to-end delivery without emailing a real inbox.
