Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
API tokens docs: scopes, presets, /tokens/current, /capabilities, per-token rate limits; OpenAPI x-required-scopes read from the routes (mailr spec G1 docs)
Murtaza Nasir4a8a04259dc4
diff --git a/config/env.asr.example b/config/env.asr.exampleindex 15e414d9..38c0e9af 100644--- a/config/env.asr.example+++ b/config/env.asr.example@@ -379,6 +379,17 @@ MAX_CONCURRENT_UPLOADS=3# these. Default: true.# RATELIMIT_ENABLED=true+# API token limits, one budget per token per kind of request (read, write,+# process). A request over the limit gets 429 with Retry-After.+# API_TOKEN_RATE_LIMIT_READ=120 per minute+# API_TOKEN_RATE_LIMIT_WRITE=30 per minute+# API_TOKEN_RATE_LIMIT_PROCESS=10 per minute++# Set to true only when the text, chat and embedding models all run on machines+# you control. API clients read it from /api/v1/capabilities (models_local).+# Default: false.+# MODELS_ARE_LOCAL=false+# --- Server-Side Recording Sessions (optional) ---# Opt-in: in-app recordings stream audio chunks to the server as they record,# instead of buffering the entire recording in browser RAM. This enablesdiff --git a/config/env.transcription.example b/config/env.transcription.exampleindex d55be104..76b8436f 100644--- a/config/env.transcription.example+++ b/config/env.transcription.example@@ -537,6 +537,17 @@ MAX_CONCURRENT_UPLOADS=3# these. Default: true.# RATELIMIT_ENABLED=true+# API token limits, one budget per token per kind of request (read, write,+# process). A request over the limit gets 429 with Retry-After.+# API_TOKEN_RATE_LIMIT_READ=120 per minute+# API_TOKEN_RATE_LIMIT_WRITE=30 per minute+# API_TOKEN_RATE_LIMIT_PROCESS=10 per minute++# Set to true only when the text, chat and embedding models all run on machines+# you control. API clients read it from /api/v1/capabilities (models_local).+# Default: false.+# MODELS_ARE_LOCAL=false+# =============================================================================# SERVER-SIDE RECORDING SESSIONS (optional)# =============================================================================diff --git a/config/env.whisper.example b/config/env.whisper.exampleindex 5b56c8cd..0f93f8be 100644--- a/config/env.whisper.example+++ b/config/env.whisper.example@@ -375,6 +375,17 @@ MAX_CONCURRENT_UPLOADS=3# these. Default: true.# RATELIMIT_ENABLED=true+# API token limits, one budget per token per kind of request (read, write,+# process). A request over the limit gets 429 with Retry-After.+# API_TOKEN_RATE_LIMIT_READ=120 per minute+# API_TOKEN_RATE_LIMIT_WRITE=30 per minute+# API_TOKEN_RATE_LIMIT_PROCESS=10 per minute++# Set to true only when the text, chat and embedding models all run on machines+# you control. API clients read it from /api/v1/capabilities (models_local).+# Default: false.+# MODELS_ARE_LOCAL=false+# --- Server-Side Recording Sessions (optional) ---# Opt-in: in-app recordings stream audio chunks to the server as they record,# instead of buffering the entire recording in browser RAM. This enablesdiff --git a/config/env.whisperx.example b/config/env.whisperx.exampleindex a7665c73..d4099f59 100644--- a/config/env.whisperx.example+++ b/config/env.whisperx.example@@ -293,6 +293,17 @@ MAX_CONCURRENT_UPLOADS=3# these. Default: true.# RATELIMIT_ENABLED=true+# API token limits, one budget per token per kind of request (read, write,+# process). A request over the limit gets 429 with Retry-After.+# API_TOKEN_RATE_LIMIT_READ=120 per minute+# API_TOKEN_RATE_LIMIT_WRITE=30 per minute+# API_TOKEN_RATE_LIMIT_PROCESS=10 per minute++# Set to true only when the text, chat and embedding models all run on machines+# you control. API clients read it from /api/v1/capabilities (models_local).+# Default: false.+# MODELS_ARE_LOCAL=false+# --- Background Processing Queues ---# Separate queues for transcription (slow) and summary (fast) jobs# This prevents slow ASR jobs from blocking quick summary generationdiff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.mdindex 672aa76c..5ee927ba 100644--- a/docs/user-guide/api-reference.md+++ b/docs/user-guide/api-reference.md@@ -34,6 +34,79 @@ All endpoints require authentication. See [API Tokens](api-tokens.md) for detailcurl "https://speakr.example.com/api/v1/stats?token=YOUR_TOKEN"```+The query parameter works only with full-access tokens.++### Scopes++A token has full access or a set of scopes. Each endpoint below lists the scope it needs; `/api/v1/openapi.json` gives the same as `x-required-scopes` per operation.++| Scope | Allows |+|-------|--------|+| `read` | Every GET under `/api/v1` except webhook management: recordings, transcripts, summaries, notes, events, speakers, tags, folders, statistics, audio download |+| `write` | Editing recordings, notes and summaries; adding and removing tags; creating and editing tags, folders and speakers; assigning speakers |+| `upload` | `POST /recordings/upload` and the ASR Voice Recorder upload |+| `process` | Requests that use model or GPU time: transcribe, summarize, regenerate title, identify speakers, chat |+| `share` | Creating, listing and revoking shares |+| `delete` | Deleting recordings, audio, tags, folders and speakers |+| `webhooks` | Everything under `/api/v1/webhooks` |+| `account` | Account settings under `/api/v1/settings` |++A token with no scopes is a full-access token and is reported as `["full"]`. Every token created before scopes existed is a full-access token. Scoped tokens work only in a header and only on API v1 routes. A scoped token without a needed scope gets `403` before anything changes:++```json+{+ "error": "This token does not have the 'write' scope",+ "code": "insufficient_scope",+ "required_scopes": ["write"],+ "token_scopes": ["read"]+}+```++with the header `WWW-Authenticate: Bearer error="insufficient_scope", scope="write"`.++### Current Token++```http+GET /api/v1/tokens/current+```++**Scope:** none (any valid token)++Returns the token used for the request. A request signed in through the web interface gets `404` with `"code": "not_found"`.++```json+{+ "id": 14,+ "name": "mailr",+ "scopes": ["read", "write", "upload"],+ "created_at": "2026-10-02T09:00:00.000000Z",+ "expires_at": "2027-10-02T09:00:00.000000Z",+ "last_used_at": "2026-10-02T09:05:11.000000Z",+ "via": "header"+}+```++### Capabilities++```http+GET /api/v1/capabilities+```++**Scope:** none (any valid token or a signed-in session)++Lists the features this instance supports. Read features here, not from the version string; a feature missing from `features` is not supported.++```json+{+ "speakr_version": "v0.10.11-alpha",+ "api_version": "1.1",+ "features": {"token_scopes": true},+ "models_local": false+}+```++`models_local` is `true` only when the administrator sets `MODELS_ARE_LOCAL=true`, which states that the text, chat and embedding models all run on machines the administrator controls.+## OpenAPI Specification| Endpoint | Description |@@ -58,6 +131,8 @@ Dashboard-compatible statistics endpoint, designed for integration with homepageGET /api/v1/stats```+**Scope:** `read`+**Query Parameters:**| Parameter | Type | Default | Description |@@ -136,6 +211,8 @@ GET /api/v1/statsGET /api/v1/users/me```+**Scope:** `read`+Returns the authenticated user's profile, preferences, and group memberships. Useful for companion apps and automation flows that need to display the current user's identity.**Response:**@@ -185,6 +262,8 @@ Returns the authenticated user's profile, preferences, and group memberships. UsPOST /api/v1/recordings/upload```+**Scope:** `upload`+Upload a recording as multipart form-data and immediately queue transcription.**Form Fields:**@@ -235,6 +314,8 @@ curl -X POST \POST /api/v1/integrations/asr-voice-recorder/upload```+**Scope:** `upload`+This adapter accepts the multipart webhook format sent by the Android **ASR Voice Recorder** app and queues the completed recording through Speakr's normal upload and transcription pipeline. Unlike other API endpoints, authentication comes from the required multipart `secret` field because the recorder cannot set a custom Authorization header.**Form Fields:**@@ -292,6 +373,8 @@ curl -X POST \GET /api/v1/recordings```+**Scope:** `read`+**Query Parameters:**| Parameter | Type | Default | Description |@@ -361,6 +444,8 @@ GET /api/v1/recordingsGET /api/v1/recordings/{id}```+**Scope:** `read`+**Query Parameters:**| Parameter | Type | Default | Description |@@ -423,6 +508,8 @@ GET /api/v1/recordings/{id}GET /api/v1/recordings/{id}/transcript```+**Scope:** `read`+**Query Parameters:**| Parameter | Type | Default | Description |@@ -475,6 +562,8 @@ GET /api/v1/recordings/{id}/transcriptGET /api/v1/recordings/{id}/summary```+**Scope:** `read`+**Response:**```json@@ -490,6 +579,8 @@ GET /api/v1/recordings/{id}/summaryGET /api/v1/recordings/{id}/notes```+**Scope:** `read`+**Response:**```json@@ -505,6 +596,8 @@ GET /api/v1/recordings/{id}/notesGET /api/v1/recordings/{id}/status```+**Scope:** `read`+**Response:**```json@@ -533,6 +626,8 @@ GET /api/v1/recordings/{id}/statusPATCH /api/v1/recordings/{id}```+**Scope:** `write`+**Request Body:**```json@@ -557,6 +652,8 @@ All fields are optional. Set `folder_id` to an integer to move the recording intPUT /api/v1/recordings/{id}/notes```+**Scope:** `write`+**Request Body:**```json@@ -571,6 +668,8 @@ PUT /api/v1/recordings/{id}/notesPUT /api/v1/recordings/{id}/summary```+**Scope:** `write`+**Request Body:**```json@@ -585,6 +684,8 @@ PUT /api/v1/recordings/{id}/summaryPOST /api/v1/recordings/{id}/delete-audio```+**Scope:** `delete`+Deletes the recording's media file (the video, for a recording with retained video) and keeps the transcript, summary and notes. Requires the same permission as deleting the recording. Returns `409` when the audio is already removed or the recording is still processing.**Response:**@@ -602,6 +703,8 @@ Deletes the recording's media file (the video, for a recording with retained vidDELETE /api/v1/recordings/{id}```+**Scope:** `delete`+**Response:**```json@@ -621,6 +724,8 @@ DELETE /api/v1/recordings/{id}GET /api/v1/tags```+**Scope:** `read`+Returns both personal tags and group tags you have access to.**Response:**@@ -651,6 +756,8 @@ Returns both personal tags and group tags you have access to.POST /api/v1/tags```+**Scope:** `write`+**Request Body:**```json@@ -671,6 +778,8 @@ POST /api/v1/tagsPUT /api/v1/tags/{id}```+**Scope:** `write`+**Request Body:**```json@@ -687,12 +796,16 @@ PUT /api/v1/tags/{id}DELETE /api/v1/tags/{id}```+**Scope:** `delete`+### Add Tags to Recording```httpPOST /api/v1/recordings/{id}/tags```+**Scope:** `write`+**Request Body:**```json@@ -707,6 +820,8 @@ POST /api/v1/recordings/{id}/tagsDELETE /api/v1/recordings/{id}/tags/{tag_id}```+**Scope:** `write`+---## Speakers@@ -717,6 +832,8 @@ DELETE /api/v1/recordings/{id}/tags/{tag_id}GET /api/v1/speakers```+**Scope:** `read`+**Response:**```json@@ -740,6 +857,8 @@ GET /api/v1/speakersPOST /api/v1/speakers```+**Scope:** `write`+**Request Body:**```json@@ -754,6 +873,8 @@ POST /api/v1/speakersPUT /api/v1/speakers/{id}```+**Scope:** `write`+Updates the speaker name and cascades changes to all recordings.**Request Body:**@@ -770,12 +891,16 @@ Updates the speaker name and cascades changes to all recordings.DELETE /api/v1/speakers/{id}```+**Scope:** `delete`+### Get Recording Speakers```httpGET /api/v1/recordings/{id}/speakers```+**Scope:** `read`+Returns speakers in the recording with voice-based identification suggestions.**Response:**@@ -808,6 +933,8 @@ Returns speakers in the recording with voice-based identification suggestions.POST /api/v1/recordings/{id}/transcribe```+**Scope:** `process`+**Request Body:**```json@@ -849,6 +976,8 @@ All parameters are optional.POST /api/v1/recordings/{id}/summarize```+**Scope:** `process`+**Request Body:**```json@@ -869,6 +998,8 @@ The custom prompt overrides the recording's tag prompts and user defaults.POST /api/v1/recordings/{id}/chat```+**Scope:** `process`+Ask questions about a recording's content using AI.**Request Body:**@@ -902,6 +1033,8 @@ Ask questions about a recording's content using AI.GET /api/v1/recordings/{id}/events```+**Scope:** `read`+Returns calendar events extracted from the recording.**Response:**@@ -927,6 +1060,8 @@ Returns calendar events extracted from the recording.GET /api/v1/recordings/{id}/events/ics```+**Scope:** `read`+Returns an ICS file containing all events from the recording.---@@ -939,6 +1074,8 @@ Returns an ICS file containing all events from the recording.GET /api/v1/recordings/{id}/audio```+**Scope:** `read`+**Query Parameters:**| Parameter | Type | Default | Description |@@ -955,6 +1092,8 @@ GET /api/v1/recordings/{id}/audioPATCH /api/v1/recordings/batch```+**Scope:** `write`+**Request Body:**```json@@ -993,6 +1132,8 @@ Supported `updates` fields: `is_inbox`, `is_highlighted`, `add_tag_ids`, `removeDELETE /api/v1/recordings/batch```+**Scope:** `delete`+**Request Body:**```json@@ -1007,6 +1148,8 @@ DELETE /api/v1/recordings/batchPOST /api/v1/recordings/batch/transcribe```+**Scope:** `process`+**Request Body:**```json@@ -1032,6 +1175,8 @@ Folders can be personal or group-scoped. Personal folders are editable only by tGET /api/v1/folders```+**Scope:** `read`+Returns personal folders plus any group folders you have access to.**Response:**@@ -1074,6 +1219,8 @@ Returns personal folders plus any group folders you have access to.GET /api/v1/folders/{id}```+**Scope:** `read`+Returns a single folder. You must own a personal folder, or be a member of the group for a group folder. The response is the folder object above (with `can_edit`).### Create Folder@@ -1082,6 +1229,8 @@ Returns a single folder. You must own a personal folder, or be a member of the gPOST /api/v1/folders```+**Scope:** `write`+**Request Body:**```json@@ -1107,6 +1256,8 @@ Only `name` is required. Set `group_id` to create a group folder (you must be an```httpPATCH /api/v1/folders/{id}PUT /api/v1/folders/{id}++**Scope:** `write````Accepts the same fields as create; all are optional. Only the folder owner (personal) or a group admin (group folder) may update. Returns the updated folder.@@ -1117,6 +1268,8 @@ Accepts the same fields as create; all are optional. Only the folder owner (persDELETE /api/v1/folders/{id}```+**Scope:** `delete`+Recordings in the deleted folder are unassigned (their `folder_id` becomes `null`); they are not deleted. Only the folder owner (personal) or a group admin (group folder) may delete.**Response:**@@ -1138,6 +1291,8 @@ Recordings in the deleted folder are unassigned (their `folder_id` becomes `nullGET /api/v1/transcription```+**Scope:** `read`+Returns the active transcription connector, the optional fields it accepts, the admin-curated list of selectable models, and the configured default model. Use this to drive client UIs and to know which values are valid for the `transcription_model` override on `/recordings/{id}/transcribe` and `/recordings/upload`.**Response:**@@ -1197,6 +1352,8 @@ These are the event types a webhook can subscribe to:GET /api/v1/webhooks```+**Scope:** `webhooks`+**Response:**```json@@ -1241,6 +1398,8 @@ The webhook's HMAC `secret` is **never** returned by this endpoint. It is shownPOST /api/v1/webhooks```+**Scope:** `webhooks`+**Request Body:**```json@@ -1281,6 +1440,8 @@ POST /api/v1/webhooksGET /api/v1/webhooks/{id}```+**Scope:** `webhooks`+Returns the webhook object (without the secret).### Update Webhook@@ -1289,6 +1450,8 @@ Returns the webhook object (without the secret).PATCH /api/v1/webhooks/{id}```+**Scope:** `webhooks`+**Request Body** (all fields optional):```json@@ -1309,6 +1472,8 @@ When provided, `events` must be a non-empty array of known event types. SettingDELETE /api/v1/webhooks/{id}```+**Scope:** `webhooks`+Returns `204 No Content`.### Rotate Secret@@ -1317,6 +1482,8 @@ Returns `204 No Content`.POST /api/v1/webhooks/{id}/rotate-secret```+**Scope:** `webhooks`+Generates a fresh HMAC secret and returns the webhook object with the new `secret` included once. Existing deliveries already signed with the old secret are not re-signed.### Test Webhook@@ -1325,6 +1492,8 @@ Generates a fresh HMAC secret and returns the webhook object with the new `secrePOST /api/v1/webhooks/{id}/test```+**Scope:** `webhooks`+Enqueues a synthetic `webhook.test` delivery against this single webhook so you can verify reachability before subscribing to production events. The webhook must be enabled (otherwise `409`).**Response** (`202`): the created delivery object (see below).@@ -1335,6 +1504,8 @@ Enqueues a synthetic `webhook.test` delivery against this single webhook so youGET /api/v1/webhooks/{id}/deliveries```+**Scope:** `webhooks`+**Query Parameters:**| Parameter | Type | Default | Description |@@ -1373,6 +1544,8 @@ Delivery `status` is one of `pending`, `success`, `failed` (retryable), or `permGET /api/v1/webhooks/{id}/deliveries/{delivery_id}```+**Scope:** `webhooks`+Returns a single delivery. This response additionally includes the full serialized `payload` (the exact JSON body that was/will be POSTed) for debugging.### Replay Delivery@@ -1381,6 +1554,8 @@ Returns a single delivery. This response additionally includes the full serializPOST /api/v1/webhooks/{id}/deliveries/{delivery_id}/replay```+**Scope:** `webhooks`+Re-enqueues the delivery as a brand-new attempt with the same payload (with a fresh `event_id` and timestamp, plus a `replayed_from` reference to the original). Returns the new delivery object with `202`.---@@ -1391,10 +1566,13 @@ All endpoints return consistent error responses:```json{- "error": "Error message description"+ "error": "Error message description",+ "code": "insufficient_scope"}```+`code` is a machine-readable value, present on newer errors (for example `insufficient_scope`, `invalid_parameter`, `not_found`).+**Common HTTP Status Codes:**| Code | Description |@@ -1403,23 +1581,24 @@ All endpoints return consistent error responses:| `201` | Created || `400` | Bad Request - Invalid parameters || `401` | Unauthorized - Invalid or missing token |-| `403` | Forbidden - No permission for this resource |+| `403` | Forbidden - No permission for this resource, or the token lacks a scope (`insufficient_scope`) || `404` | Not Found - Resource doesn't exist |+| `429` | Too Many Requests - Rate limit reached; wait `Retry-After` seconds || `500` | Internal Server Error |---## Rate Limits-API endpoints are rate-limited to prevent abuse:+Requests made with an API token are limited per token, so two integrations on the same machine do not share a limit. Each token has one budget per kind of request:++| Kind | Endpoints | Default limit | Setting |+|------|-----------|---------------|---------|+| Read | Endpoints that need only `read` | 120 requests/minute | `API_TOKEN_RATE_LIMIT_READ` |+| Write | Endpoints that need `write`, `upload`, `share`, `delete`, `webhooks` or `account` | 30 requests/minute | `API_TOKEN_RATE_LIMIT_WRITE` |+| Process | Endpoints that need `process` | 10 requests/minute | `API_TOKEN_RATE_LIMIT_PROCESS` |-| Endpoint Type | Limit |-|---------------|-------|-| Stats | 60 requests/minute |-| GET endpoints | 100 requests/minute |-| PATCH/DELETE | 30 requests/minute |-| Processing operations | 10 requests/minute |-| Batch operations | 10 requests/minute |+The limits apply to full-access and scoped tokens alike. A request over the limit gets `429` with a `Retry-After` header in seconds, and responses carry `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset`. Requests from the web interface keep the per-address limits of the application.---diff --git a/docs/user-guide/api-tokens.md b/docs/user-guide/api-tokens.mdindex b42029c5..8a998485 100644--- a/docs/user-guide/api-tokens.md+++ b/docs/user-guide/api-tokens.md@@ -1,6 +1,6 @@# API Tokens-API tokens enable programmatic access to your Speakr instance, allowing you to integrate with automation tools like n8n, Zapier, Make, or custom scripts. Each token is tied to your user account and provides the same access as logging in through the web interface.+API tokens enable programmatic access to your Speakr instance, allowing you to integrate with automation tools like n8n, Zapier, Make, or custom scripts. Each token is tied to your user account. A token can have full access, the same as logging in through the web interface, or only the scopes you choose.## Overview@@ -12,7 +12,7 @@ API tokens are personal access tokens that authenticate API requests on your beh- **Mobile apps** - Access your recordings from custom applications!!! warning "Security Notice"- Treat API tokens like passwords. They provide full access to your account. Never share tokens publicly, commit them to version control, or expose them in client-side code.+ Treat API tokens like passwords. A full-access token can do everything you can do in the web interface. Never share tokens publicly, commit them to version control, or expose them in client-side code.## Creating a Token@@ -22,11 +22,43 @@ API tokens are personal access tokens that authenticate API requests on your beh4. Choose an expiration period:- **No expiration** - Token remains valid until manually revoked- **30 days**, **90 days**, **1 year** - Token automatically expires-5. Click **Create**+5. Choose the access the token needs (see [Scopes](#scopes)):+ - **Read only** - reads recordings and their content+ - **Integration** - read, write and upload+ - **Recorder** - upload only+ - **Full access** - everything, including deleting, sharing and webhooks+ - **Custom** - any set of scopes+6. Click **Create**!!! important "Save Your Token"The token value is only shown once after creation. Copy it immediately and store it securely. If you lose it, you'll need to create a new token.+## Scopes++A token with scopes can call only the API v1 routes those scopes cover. The scope each route needs is listed in the [API Reference](api-reference.md) and in `/api/v1/openapi.json` (`x-required-scopes`).++| Scope | Allows |+|-------|--------|+| `read` | Every GET under `/api/v1` except webhook management: recordings, transcripts, summaries, notes, events, speakers, tags, folders, statistics, audio download |+| `write` | Editing recordings, notes and summaries; adding and removing tags; creating and editing tags, folders and speakers; assigning speakers |+| `upload` | `POST /recordings/upload` and the ASR Voice Recorder upload |+| `process` | Requests that use model or GPU time: transcribe, summarize, regenerate title, identify speakers, chat |+| `share` | Creating, listing and revoking shares |+| `delete` | Deleting recordings, audio, tags, folders and speakers |+| `webhooks` | Everything under `/api/v1/webhooks` |+| `account` | Account settings under `/api/v1/settings` |++- **Existing tokens have full access.** Tokens created before scopes existed, and tokens created through the API without `scopes`, keep full access. The token list shows them as **Full access**.+- **Scoped tokens work only in a header.** A scoped token sent as `?token=` gets `401`. Full tokens still accept the query parameter.+- **Scoped tokens work only on API v1.** Web-interface routes, token management and every route without a declared scope refuse a scoped token with `403`.+- **Scopes can be narrowed, never widened.** `PATCH /api/tokens/{id}` with a smaller `scopes` list removes scopes from a token. A token that needs more scopes needs a new token.+- A request a token is not allowed to make is refused before anything changes, with `403` and the code `insufficient_scope`.++To see the scopes of the token in use, call `GET /api/v1/tokens/current`.++!!! tip "Give each integration its own scoped, expiring token"+ An integration that only reads recordings needs **Read only**. A phone recorder needs **Recorder**. If such a token leaks, it cannot delete recordings, share them or change webhooks.+## Using Your TokenSpeakr accepts tokens through multiple methods, giving you flexibility based on your integration needs.@@ -60,7 +92,7 @@ curl -H "API-Token: YOUR_TOKEN_HERE" \### Query Parameter-For simple integrations (less secure - token visible in logs):+For simple integrations with a full-access token (less secure - token visible in logs). Scoped tokens do not work in the query string:```bashcurl "https://your-speakr-instance.com/api/v1/recordings?token=YOUR_TOKEN_HERE"@@ -71,7 +103,7 @@ curl "https://your-speakr-instance.com/api/v1/recordings?token=YOUR_TOKEN_HERE"The Android **ASR Voice Recorder** app can automatically send each completed recording to Speakr through its webhook cloud service.1. Create a token named something descriptive, such as **ASR Voice Recorder**.-2. Give it an expiration appropriate for the phone's expected use rather than choosing no expiration.+2. Choose the **Recorder** access (the `upload` scope only), and an expiration that matches how long the phone will be used.3. In ASR Voice Recorder, add a webhook destination with this URL:```text@@ -85,7 +117,7 @@ The Android **ASR Voice Recorder** app can automatically send each completed recThe integration stores ASR's note as Speakr notes, preserves the supplied recording date, measures the media duration itself, and returns HTTP 200 so ASR marks the connection test or completed delivery successful. Safe retries of the same completed file reuse the existing Speakr recording.!!! warning "Dedicated token strongly recommended"- ASR stores the token on the Android device, and Speakr API tokens currently provide full access to the owner's account. Use a separate expiring token for this integration. Revoke it immediately if the phone is lost, the recorder is uninstalled, or the integration is no longer used. Never place the real token in screenshots, support posts, configuration examples, or source control.+ ASR stores the token on the Android device. Use a separate expiring token with only the `upload` scope for this integration. A full-access token on the phone would allow deleting and sharing recordings. Revoke it immediately if the phone is lost, the recorder is uninstalled, or the integration is no longer used. Never place the real token in screenshots, support posts, configuration examples, or source control.This endpoint is intentionally different from normal API authentication: ASR sends the token in its multipart `secret` field because it cannot add a Bearer or API-token header. Session cookies and normal API headers do not substitute for the Secret field.@@ -114,6 +146,8 @@ Speakr provides a comprehensive REST API with endpoints for recordings, tags, sp| `/api/v1/folders` | GET / POST | List or create folders (requires folders enabled) || `/api/v1/transcription` | GET | Discover the active transcription connector and selectable models || `/api/v1/webhooks` | GET / POST | List or create event webhooks |+| `/api/v1/tokens/current` | GET | The token in use and its scopes |+| `/api/v1/capabilities` | GET | Features this instance supports |### Example: List Recordings@@ -152,6 +186,7 @@ Response:The API Tokens tab shows all your active tokens with:- **Name** - The descriptive name you assigned+- **Access** - Full access, or the token's scopes- **Status** - Active, expired, or revoked- **Created date** - When the token was created- **Last used** - When the token was last used for authentication@@ -245,6 +280,11 @@ curl -s -H "Authorization: Bearer $TOKEN" \- Token is valid but you don't have permission for that resource- Check if the recording belongs to your account+- With `"code": "insufficient_scope"`, the token lacks a scope the route needs. The answer lists `required_scopes` and the token's own `token_scopes`. Create a token with the missing scope.++### 429 Too Many Requests++- The token sent more requests than its limit allows (see [Rate Limits](api-reference.md#rate-limits)). Wait the number of seconds in the `Retry-After` header.---diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex 7f1709e5..47f287ce 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -121,7 +121,12 @@ OPENAPI_SPEC = {"servers": [{"url": "/api/v1", "description": "API v1"}],"components": {"securitySchemes": {- "bearerAuth": {"type": "http", "scheme": "bearer"},+ "bearerAuth": {"type": "http", "scheme": "bearer",+ "description": "A personal API token. Tokens may carry scopes: read, write, upload, "+ "process, share, delete, webhooks, account. A token with no scopes "+ "(reported as [\"full\"]) has every scope. Each operation lists the "+ "scopes it needs in x-required-scopes; a scoped token without them "+ "gets 403 insufficient_scope. Scoped tokens work only in a header."},"apiKeyHeader": {"type": "apiKey", "in": "header", "name": "X-API-Token"},"apiKeyQuery": {"type": "apiKey", "in": "query", "name": "token"}},@@ -199,12 +204,54 @@ OPENAPI_SPEC = {},"Error": {"type": "object",- "properties": {"error": {"type": "string"}}+ "properties": {"error": {"type": "string"},+ "code": {"type": "string", "description": "Machine-readable error code, e.g. insufficient_scope"}}+ },+ "TokenInfo": {+ "type": "object",+ "properties": {+ "id": {"type": "integer"},+ "name": {"type": "string"},+ "scopes": {"type": "array", "items": {"type": "string"}},+ "created_at": {"type": "string", "format": "date-time"},+ "expires_at": {"type": "string", "format": "date-time", "nullable": True},+ "last_used_at": {"type": "string", "format": "date-time", "nullable": True},+ "via": {"type": "string", "enum": ["header", "query"]}+ }+ },+ "Capabilities": {+ "type": "object",+ "properties": {+ "speakr_version": {"type": "string"},+ "api_version": {"type": "string"},+ "features": {"type": "object", "additionalProperties": True,+ "description": "Feature flags; a missing key means false"},+ "models_local": {"type": "boolean"}+ }}}},"security": [{"bearerAuth": []}, {"apiKeyHeader": []}, {"apiKeyQuery": []}],"paths": {+ "/tokens/current": {+ "get": {+ "tags": ["Tokens"],+ "summary": "The API token used for this request",+ "description": "Any valid token, no scope needed. A session request gets 404.",+ "responses": {"200": {"description": "Token details",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/TokenInfo"}}}},+ "404": {"description": "No API token in this request"}}+ }+ },+ "/capabilities": {+ "get": {+ "tags": ["Tokens"],+ "summary": "Features this instance supports",+ "description": "Any valid token or session. Clients read features here, never from the version string.",+ "responses": {"200": {"description": "Capabilities",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Capabilities"}}}}}+ }+ },"/stats": {"get": {"tags": ["Stats"],@@ -513,16 +560,43 @@ OPENAPI_SPEC = {{"name": "Transcription", "description": "Transcription connector and model discovery"},{"name": "Speakers", "description": "Speaker management"},{"name": "Batch", "description": "Batch operations"},- {"name": "Settings", "description": "User settings"}+ {"name": "Settings", "description": "User settings"},+ {"name": "Tokens", "description": "Token introspection and instance capabilities"}]}+def _openapi_with_scopes():+ """OPENAPI_SPEC with x-required-scopes on every operation, read from the+ routes' require_scope marks so the document cannot drift from the code."""+ import copy+ import re+ from flask import current_app+ spec = copy.deepcopy(OPENAPI_SPEC)+ norm = lambda path: re.sub(r'<[^>]+>|\{[^}]+\}', '{}', path)+ by_route = {}+ for rule in current_app.url_map.iter_rules():+ if not rule.rule.startswith('/api/v1/'):+ continue+ view = current_app.view_functions.get(rule.endpoint)+ scopes = getattr(view, '_required_scopes', None)+ if scopes is None:+ continue+ for method in rule.methods - {'HEAD', 'OPTIONS'}:+ by_route[(norm(rule.rule[len('/api/v1'):]), method.lower())] = sorted(scopes)+ for path, operations in spec.get('paths', {}).items():+ for method, operation in operations.items():+ scopes = by_route.get((norm(path), method))+ if scopes is not None and isinstance(operation, dict):+ operation['x-required-scopes'] = scopes+ return spec++@api_v1_bp.route('/openapi.json', methods=['GET'])@require_scope('read')def get_openapi_spec():"""Return OpenAPI specification."""- return jsonify(OPENAPI_SPEC)+ return jsonify(_openapi_with_scopes())@api_v1_bp.route('/docs', methods=['GET'])diff --git a/tests/test_api_scope_docs.py b/tests/test_api_scope_docs.pynew file mode 100644index 00000000..7bd08079--- /dev/null+++ b/tests/test_api_scope_docs.py@@ -0,0 +1,58 @@+"""The documented scopes match the routes (mailr spec G1, section 3.7).++Every API v1 request block in the API reference carries a **Scope:** line,+and every operation in /api/v1/openapi.json carries x-required-scopes, both+equal to the scopes the route declares with require_scope.+"""++import os+import re+import sys++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+_norm = lambda path: re.sub(r'<[^>]+>|\{[^}]+\}', '{}', path.split('?')[0].rstrip('/'))+++def _route_scopes():+ table = {}+ for rule in app.url_map.iter_rules():+ scopes = getattr(app.view_functions.get(rule.endpoint), '_required_scopes', None)+ if scopes is None or not rule.rule.startswith('/api/v1'):+ continue+ for method in rule.methods - {'HEAD', 'OPTIONS'}:+ table[(method, _norm(rule.rule))] = sorted(scopes)+ return table+++def test_every_documented_request_states_its_scope():+ routes = _route_scopes()+ text = open(os.path.join(ROOT, 'docs/user-guide/api-reference.md'), encoding='utf-8').read()+ blocks = re.findall(r'```http\n(GET|POST|PUT|PATCH|DELETE) (/api/v1\S*)\n```\n\n(\*\*Scope:\*\* [^\n]*)?', text)+ assert len(blocks) > 40+ problems = []+ for method, path, line in blocks:+ scopes = routes.get((method, _norm(path)))+ if scopes is None:+ problems.append(f'{method} {path}: no such route')+ continue+ expected = 'none (any valid token' if not scopes else ', '.join(f'`{s}`' for s in scopes)+ if not line or expected not in line:+ problems.append(f'{method} {path}: documented {line!r}, route needs {scopes}')+ assert not problems, '\n'.join(problems)+++def test_openapi_operations_carry_their_scopes():+ routes = _route_scopes()+ with app.test_request_context():+ from src.api.api_v1 import _openapi_with_scopes+ spec = _openapi_with_scopes()+ assert 'insufficient_scope' in spec['components']['securitySchemes']['bearerAuth']['description']+ for path, operations in spec['paths'].items():+ for method, operation in operations.items():+ expected = routes.get((method.upper(), _norm('/api/v1' + path)))+ assert expected is not None, f'{method} {path} is documented but has no route'+ assert operation.get('x-required-scopes') == expected, (method, path)