# Tabulation hub API (v0, MVP)

Base URL, production: `https://api.tabutabu.app` (once the custom domain is attached; the public website is `https://tabutabu.app`).
Base URL, local dev: `http://localhost:8787` (Android emulator: `http://10.0.2.2:8787`; a phone on the LAN: run
`npm run dev -- --ip 0.0.0.0` and use the Mac's LAN address).

## Conventions

- JSON in and out (`Content-Type: application/json`), UTF-8. The exceptions are `GET /songs/:id/raw` (text/plain),
  the HTML pages, and `POST /dmca/notice`, which also accepts an HTML form post.
- **Auth:** `Authorization: Bearer <session_token>`. Tokens are opaque (`tbh_...`), last 90 days, and are stored hashed
  on the server. Keep them in the platform keychain.
- **Timestamps** are ISO-8601 UTC strings (`2026-11-27T15:55:08.362Z`). The one exception is `/sync`, which uses
  epoch milliseconds for its cursor.
- **IDs** are prefixed strings: `usr_`, `sng_`, `rev_`, `flg_`, `dmc_`, `ntf_`, `stk_`. Treat them as opaque.
- Optional header `X-Client: tabulation-ios/1.2.3` is recorded on revisions (uploader logging).
- **Errors** always have this shape, with an HTTP status that matches:

```json
{ "error": { "code": "invalid_tabu", "message": "The file failed validation", "details": { "diagnostics": [ ... ] } } }
```

| Status | Typical `code` values |
|---|---|
| 400 | `invalid_json`, `missing_field`, `invalid_field`, `invalid_param`, `consent_required`, `upload_terms_required`, `invalid_magic_link`, `deficient_notice`, `invalid_handle` |
| 401 | `auth_required`, `invalid_token`, `invalid_identity_token` |
| 403 | `invite_required`, `forbidden`, `admin_required`, `own_song`, `account_banned`, `account_suspended` |
| 404 | `not_found`, `songs_not_found` |
| 409 | `no_change`, `handle_taken`, `already_countered`, `not_pending`, ... |
| 413 | `file_too_large` (over 262144 bytes of UTF-8), `payload_too_large` |
| 422 | `invalid_tabu` (`details.diagnostics`) |
| 429 | `rate_limited` (`details.retry_after` seconds, and a `Retry-After` header), `upload_quota_exceeded` |
| 451 | `unavailable_legal`: the song is disabled by a copyright notice (`details.status`) |
| 502 | `email_send_failed` (magic-link email could not be sent) |
| 503 | `email_not_configured` (server has no email provider) |

A **diagnostic** is `{ "code": "E001", "severity": "error" | "warning", "message": "...", "line"?: 3 }`.

### Shared objects

**User** (`email` only appears for yourself):

```json
{ "id": "usr_...", "handle": "user-eggmncdi", "role": "user", "trust_level": 0, "status": "active",
  "created_at": "2026-11-27T15:55:08.362Z", "email": "me@example.com" }
```

`role`: `user` | `admin`. `trust_level`: 0 new, 1 member, 2 trusted, 3 maintainer. `status`: `active` | `suspended` | `banned`.

**Song** (fields mirror the Tabu header; `null` when absent):

```json
{
  "id": "sng_yrywynsr2rdaln5d",
  "title": "Amazing Grace",
  "artist": "Traditional",
  "key": "G",
  "tempo": "84",
  "time": "3/4",
  "tuning": "standard",
  "capo": 0,
  "tags": ["hymn", "waltz", "fingerstyle", "beginner"],
  "rights": "public-domain",
  "explicit": null,
  "status": "live",
  "owner": { "id": "usr_eggmncditoasycva", "handle": "user-eggmncdi" },
  "head_revision": {
    "id": "rev_2m64sdoehoeuweqz", "number": 1,
    "content_hash": "1611f9fd0b51ebfd8153744595446d9e6588c64d9edb0c8eed6e57802d9fba1e",
    "bytes": 4500, "created_at": "2026-11-27T15:55:08.362Z"
  },
  "rating": { "average": null, "count": 0 },
  "created_at": "2026-11-27T15:55:08.362Z",
  "updated_at": "2026-11-27T15:55:08.362Z"
}
```

- `tempo` and `time` are the raw header strings (`"q=84"` is possible). `capo` is an integer or null. `tags` are lowercased.
- `rights` defaults to `"user-submitted"` when the file has no `Rights:` header. `explicit` is `true`, `false`, or `null` (undeclared).
- `status`: `live` | `disabled` (taken down) | `pending_restore` (counter-notice filed, still hidden) | `removed`.
  Only `live` songs appear in lists and search. The owner and admins can still `GET` a non-live song, and it then also has `status_reason`.
- `content_hash` is the SHA-256 (hex) of the exact UTF-8 bytes. Use it as the cache key and to detect updates.

**Revision:**

```json
{
  "id": "rev_...", "song_id": "sng_...", "number": 2, "parent_id": "rev_...",
  "author": { "id": "usr_...", "handle": "..." },
  "content_hash": "…64 hex…", "bytes": 4512, "summary": "fixed the bridge chords",
  "state": "published", "reverted_from": null, "reviewed_at": null, "created_at": "..."
}
```

`state`: `published` | `pending` (waiting for review) | `rejected`. `reverted_from` is set when the revision restores an older one.

---

## Auth

**Invite-only mode** (`INVITE_ONLY=true`, the default for now): sign-in through either method is allowed only for
emails on the server's invite list (or admin emails). Everything else gets **403 `invite_required`**: on
`POST /auth/magic-link`, on `POST /auth/verify` (if the invite was removed in between) and on `POST /auth/apple`. The app
should show something like "Tabulation's library is invite-only for now". Browsing (`GET /songs`, `/search`,
`/songs/:id`, `/raw`, `/revisions`, `/sync`) needs no account. With Sign in with Apple, the gate checks the verified
email in the identity token. A user who hides their email can only get in if their `@privaterelay.appleid.com`
address is invited, so offer magic-link sign-in as the fallback. If an admin removes an invite, that account's
sessions are revoked, so expect 401 on the next call.

### `POST /auth/magic-link`
Request: `{ "email": "me@example.com" }`.
Response 200: `{ "ok": true, "expires_in": 900 }`.
**Local dev only:** the response also has `"dev_link"` and `"dev_token"`, but only when the server runs with
`ENVIRONMENT=development` **and** is reached at a local or private address (localhost, 10.0.2.2, 192.168.x.x, ...).
The link is also printed in the `wrangler dev` console. In production these fields are never present: the link is
emailed, and the app must not depend on them. Rate limits: 5 per email and 10 per IP every 10 minutes.
Errors: 403 `invite_required`, 429 `rate_limited`, 502 `email_send_failed`, 503 `email_not_configured`.

The emailed link is `<PUBLIC_BASE_URL>/auth/verify?token=ml_...`. Opening it in a browser shows a page with an
**Open Tabulation** button that goes to `tabulation://auth/verify?token=ml_...` (configurable as `APP_DEEP_LINK`; use a
universal link / App Link in production). The app takes `token` from the deep link and calls:

### `POST /auth/verify`
Request:

```json
{ "token": "ml_...", "accept_terms": true, "age_13_plus": true, "client": "tabulation-ios/0.1.0" }
```

`accept_terms` and `age_13_plus` are **required when the email has no account yet**. Without them the response is
400 `consent_required` and the token is **not** used up, so the app can show the terms and age checkbox and retry with
the same token. Simplest is to show the checkbox on the sign-in screen and always send both.
Response 200:

```json
{ "session_token": "tbh_...", "expires_at": "2027-02-25T...Z", "created": true, "user": { ...User with email } }
```

Errors: 400 `invalid_magic_link` (expired after 15 minutes, already used, or unknown), 403 `account_banned`.

### `POST /auth/apple`
Request:

```json
{ "identity_token": "<JWT from Sign in with Apple>", "nonce": "<raw nonce, optional>",
  "accept_terms": true, "age_13_plus": true, "client": "..." }
```

The server checks the JWT against Apple's JWKS: RS256 signature, `iss`, `aud` in `APPLE_AUDIENCE`, `exp`, and `nonce`,
which may be the raw nonce or its SHA-256 hex. If the token carries a verified email that matches an existing account,
the Apple identity is linked to that account. The response is the same as `/auth/verify`. **Local dev with
`APPLE_AUDIENCE` empty:** the claims are accepted without checking the signature, so a hand-made JWT with a `sub` works.
In production with no audience configured, the response is 501 `apple_not_configured`.

### `POST /auth/logout` (auth)
Revokes the current token. Response: `{ "ok": true }`.

### `GET /me` (auth)
Response: `{ "user": {...}, "active_strikes": 0, "unread_notifications": 2 }`.

### `PATCH /me` (auth)
Request: `{ "handle": "new_handle" }`. A handle is 3-24 characters `[a-z0-9_-]` and starts with a letter or digit.
Response: `{ "user": {...} }`. Errors: 400 `invalid_handle`, 409 `handle_taken`.

### `GET /me/notifications` (auth)
Response: `{ "notifications": [ { "id": "ntf_...", "kind": "dmca_takedown", "title": "...", "body": "...", "data": {...} | null, "created_at": "...", "read_at": null } ] }`
(newest first, at most 100).
`kind` values: `suggested_edit`, `edit_approved`, `edit_rejected`, `dmca_takedown`, `dmca_counter_received`,
`dmca_restored`, `dmca_rejected`, `dmca_suit_filed`, `song_disabled`, `song_restored`, `account_banned`.
`data` usually has `song_id` / `song_ids`, `revision_id`, `notice_id`, `restore_after`.

### `POST /me/notifications/:id/read` (auth)
Response: `{ "ok": true }`.

### `GET /me/dmca` (auth)
Notices against the caller's songs, so the app can offer a counter-notice:

```json
{ "notices": [ {
  "id": "dmc_...", "kind": "notice", "parent_id": null, "state": "actioned", "song_ids": ["sng_..."],
  "received_at": "...", "restore_after": null, "restored_at": null,
  "claimant": "Example Music Publishing", "work_described": "...",
  "counter_notice": null, "can_counter": true
} ] }
```

---

## Songs

### `POST /songs` (auth): upload
Request:

```json
{ "text": "Tabu: 0.1\nTitle: ...\n...", "accept_upload_terms": true, "summary": "optional", "client": "optional" }
```

- `text` is the whole `.tabu` file, at most 262144 bytes of UTF-8. Larger files get 413 `file_too_large`.
- `accept_upload_terms: true` is required. It records that the user confirmed the upload terms (they have the right
  to share it, and they grant a licence to host and display it). Without it: 400 `upload_terms_required`.
- The server reads the header. The first non-empty line must be `Tabu: <version>` (optionally inside `---`) and
  `Title:` must be present, otherwise 422 `invalid_tabu` with diagnostics `E001`/`E002`. Full lint with the shared
  parser comes later, so the app should keep running its own `upload` lint first.
- **TL0 accounts can upload 5 songs per rolling 24 hours.** The 6th gets 429 `upload_quota_exceeded`.

Response 201:

```json
{ "song": { ...Song }, "revision": { ...Revision }, "published": true,
  "diagnostics": [ { "code": "W_EXPLICIT", "severity": "warning", "message": "..." } ] }
```

### `PUT /songs/:id` (auth): new revision. Alias: `POST /songs/:id/revisions`
The request body is the same as for `POST /songs`. Who publishes directly:

| Caller | Result |
|---|---|
| admin | published |
| owner, TL1 or higher | published |
| owner, TL0 | `pending` (review queue) |
| not the owner, TL2 or higher | published |
| not the owner, TL0/TL1 | `pending` suggested edit; the owner gets a `suggested_edit` notification |

Response 201: `{ "song": {...}, "revision": {...}, "published": true|false, "diagnostics": [...] }`. While a revision is
pending, the song's head and metadata stay unchanged.
Errors: 409 `no_change` (identical to the head), 451 (song disabled).

### `POST /songs/:id/revisions/:rev/approve` | `/reject` (auth)
Allowed for admins, TL2+, or the owner (TL1+) for other people's suggestions. Response: `{ "song": {...}, "revision": {...} }`.

### `POST /songs/:id/revert/:rev` (auth: owner, TL2+ or admin)
Creates a new published revision with the content of `:rev`, which must be published. Response 201: `{ "song", "revision" }`.

### `GET /songs/:id`
Optional auth. Response:

```json
{ "song": { ...Song }, "text": "Tabu: 0.1\n...", "my_rating": 4 }
```

`text` is the head revision; add `?text=0` to leave it out. `my_rating` is only present when signed in (`null` if not rated).
404 if unknown. 451 `unavailable_legal` if taken down (the owner and admins still get 200 with `status_reason`).

### `GET /songs/:id/raw[?rev=rev_...]`
`text/plain; charset=utf-8`, the exact file bytes. `ETag` is `"<content_hash>"`. Send `If-None-Match` and get 304 when
nothing changed. Public songs are sent with `Cache-Control: public, max-age=60`.

### `GET /songs/:id/revisions`
Response: `{ "song_id": "...", "head_revision_id": "rev_...", "revisions": [ ...Revision, newest first ] }`. Pending
and rejected revisions are listed only for their author, the owner, TL2+ and admins.

### `GET /songs?sort=new|top&limit=20&offset=0`
Response: `{ "songs": [ ...Song ], "next_offset": 20 | null }`. `top` uses a Bayesian average of ratings (prior 3.0,
weight 5). `limit` is at most 100.

### `GET /search?q=&artist=&key=&limit=20&offset=0`
At least one of the parameters is required, otherwise 400.
- `q`: words matched against title, artist and tags (FTS5). Every word must match, as a prefix (`gree` finds Greensleeves).
  Query syntax is neutralised.
- `artist`: case-insensitive substring of `artist`.
- `key`: exact match on the `Key:` header (`Am`, `F#m`, `D dorian`).

Response: `{ "songs": [ ...Song ], "next_offset": null }`, ranked by relevance and then rating.

### `GET /sync?since=<epoch ms>`
For the app's cache of downloaded songs:

```json
{ "now": 1795794914640,
  "changed": [ { "id": "sng_...", "head_revision_id": "rev_...", "content_hash": "...", "updated_at": "..." } ],
  "removed": ["sng_..."], "truncated": false, "next_since": 1795794908551 }
```

`removed` is the **denylist**: songs that were taken down or disabled. Delete any cached copies. Store `next_since`
and send it next time. If `truncated` is true, call again straight away.

### `PUT /songs/:id/rating` (auth)
Request: `{ "stars": 1..5 }` (integer). One rating per user per song; sending again replaces it. You cannot rate your own song (403 `own_song`).
Response: `{ "my_rating": 4, "rating": { "average": 3.5, "count": 2 } }`.

### `DELETE /songs/:id/rating` (auth)
Response: `{ "my_rating": null, "rating": {...} }`.

### `POST /songs/:id/flags` (auth): report
Request: `{ "reason": "copyright" | "wrong" | "spam" | "offensive", "detail": "optional text", "revision_id": "optional" }`.
Response 201 (or 200 with `"duplicate": true` if you already have an open flag with the same reason):

```json
{ "flag": { "id": "flg_...", "song_id": "sng_...", "reason": "copyright", "state": "open" }, "duplicate": false,
  "notice": "A flag is not a DMCA notice. ...", "dmca_url": "http://localhost:8787/dmca" }
```

`notice` and `dmca_url` are only present for `copyright`. Show them to the reporter so a rights holder files a real notice.

---

## DMCA

### `POST /dmca/notice` (public, no auth): takedown notice, 17 USC 512(c)(3)
JSON request (the `/dmca` HTML form posts the same field names form-encoded, with `targets` as a textarea):

```json
{
  "name": "Rita Rights", "organization": "Example Music Publishing (optional)",
  "email": "claims@publisher.test", "address": "1 Music Row, Nashville, TN", "phone": "optional",
  "signature": "Rita Rights",
  "work_described": "\"Example Song\" (words and music by A. Writer)",
  "song_ids": ["sng_..."], "urls": ["https://hub.example/songs/sng_..."],
  "good_faith": true, "accurate": true, "authorized": true
}
```

Song ids are taken from `song_ids`, `urls` and `targets`, anything that contains `sng_<16 chars>`. Missing elements
give 400 `deficient_notice` with `details: { "missing": [...fields], "unconfirmed": [...statements] }`.
On success, effective immediately:
1. each identified song gets `status=disabled` and drops out of lists, search and `/sync` (it appears under `removed`);
2. each uploader gets a `dmca_takedown` notification (claimant name or organisation and the work described, not the claimant's contact details);
3. each uploader gets one strike for this notice, which expires after 12 months. **3 active strikes ban the account** and revoke its sessions;
4. the claimant gets an acknowledgement email (console only in local dev), and audit-log rows are written.

Response 201: `{ "notice": { "id": "dmc_...", "kind": "notice", "state": "actioned", "song_ids": [...], "received_at": "...", ... }, "disabled_song_ids": [...], "unresolved": [...] }`.
A form post gets an HTML confirmation page instead. Rate limit: 10 per IP per hour.

### `POST /dmca/counter` (auth: the uploader): counter-notice, 512(g)(3)

```json
{
  "notice_id": "dmc_...", "name": "Up Loader", "address": "2 Main St, Springfield", "phone": "+1 555 0199",
  "email": "optional, defaults to the account email",
  "signature": "Up Loader",
  "material_described": "What was removed and where it appeared",
  "good_faith_mistake": true, "consent_jurisdiction": true, "accept_service": true
}
```

The app must tell the user that **the name, address, phone and email are forwarded to the claimant**.
Effect: the caller's songs in that notice go to `pending_restore` (still hidden), the counter-notice is forwarded to the
claimant, and `restore_after` is set to 10 business days later. The hourly cron restores the songs after that date
unless an admin records that the claimant filed suit. On restoration the strike is voided.
Response 201: `{ "counter_notice": { "id": "dmc_...", "kind": "counter", "parent_id": "dmc_...", "state": "received", "song_ids": [...], "restore_after": "...", ... } }`.
Errors: 403 if the caller has no songs in the notice, 409 `already_countered` / `notice_not_counterable`.

---

## Admin (`role = admin`)
All admin endpoints return 403 `admin_required` for everyone else. Every state change writes `audit_log`.

| Endpoint | Body | Purpose |
|---|---|---|
| `GET /admin/queue` | | `{ pending_revisions: [...], unscreened_songs: [...Song] }` |
| `POST /admin/songs/:id/screened` | | Clear a TL0 upload from the screening queue |
| `GET /admin/flags?state=open\|upheld\|dismissed` | | List flags, oldest first |
| `POST /admin/flags/:id/resolve` | `{ state: "upheld"\|"dismissed", note?, disable_song?: true }` | |
| `GET /admin/dmca?kind=notice\|counter&state=` | | Full notices, including claimant contact details |
| `GET /admin/dmca/:id` | | `{ notice, counter_notices, strikes }` |
| `POST /admin/dmca/:id/reject` | `{ note }` | Invalid notice: restore its songs, void its strikes |
| `POST /admin/dmca/:id/suit-filed` | `{ note? }` | Claimant sued: stop the restoration and keep the songs disabled |
| `POST /admin/songs/:id/disable` | `{ reason }` | |
| `POST /admin/songs/:id/restore` | `{ note?, override_notices? }` | 409 `notices_outstanding` unless overridden |
| `GET /admin/users/:id` | | `{ user, active_strikes, strikes, bans }` |
| `POST /admin/users/:id/ban` | `{ reason, until?: ISO date }` | Revokes sessions; `until` makes the ban temporary |
| `POST /admin/users/:id/unban` | `{ note? }` | |
| `POST /admin/users/:id/trust` | `{ trust_level: 0..3, note? }` | |
| `POST /admin/strikes/:id/void` | `{ reason }` | |
| `GET /admin/audit?target_type=&target_id=&action=&actor_id=&limit=` | | Audit log, newest first |
| `POST /admin/maintenance/run` | | Run the hourly job now (restorations, ban expiry, TL0→TL1 promotion) |
| `GET /admin/invites` | | `{ invite_only, invites: [{ email, invited_by: {id, handle}\|null, note, created_at, signed_up_user_id }], config_invites: [...], admin_emails: [...] }` |
| `POST /admin/invites` | `{ email }` or `{ emails: [...] }`, `note?` | 201 `{ added: [...], already_invited: [...] }` (200 if nothing new). Idempotent, lowercased |
| `DELETE /admin/invites` | `{ email }` (or `DELETE /admin/invites/:email`) | `{ removed, sessions_revoked }`. Signs the account out unless it is still allowed by config or is an admin |

## Pages
`GET /` · `/terms` · `/privacy` · `/dmca` (with the notice form). All are placeholders marked "DRAFT – needs lawyer
review", with canonical links to `https://tabutabu.app/...` (`SITE_URL`). `GET /health` → `{ "ok": true }`.

## Docs (read-only, cacheable, no auth)

| Path | Source | Content-Type |
|---|---|---|
| `/guide.md` | `docs/guide.md` | `text/markdown; charset=utf-8` |
| `/llms.txt` | `docs/llms.txt` | `text/plain; charset=utf-8` |
| `/spec.md` | `docs/SPEC.md` | `text/markdown; charset=utf-8` |
| `/api.md` | `services/hub/API.md` (this file) | `text/markdown; charset=utf-8` |

They are bundled into the Worker at build time, so they change only when the Worker is redeployed. Responses have an
`ETag` (send `If-None-Match` and get 304) and `Cache-Control: public, max-age=3600, stale-while-revalidate=86400`. If a
source file is missing at build time, the path serves a short placeholder with `X-Doc-Placeholder: 1` and `max-age=60`.
