Authentication and authorization
For your own scripts, create an API key in the web app at /settings/api-keys. For an
application acting for other people, use OAuth. For a remote AI client, start with the
hosted MCP connection instructions. The
quickstart walks through key creation and a first request.
Three bearer credential families resolve to a per-request RLS user client. Content reads use that client; credential resolution and AI accounting use only the restricted admin-RPC allowlist.
Authorization: Bearer <credential>
| Credential | Prefix | Who uses it | Resolution |
|---|---|---|---|
| Supabase session JWT | (none) | web, mobile | verified locally against the cached JWKS; full scopes |
| API key | tm_live_ / tm_test_ | scripts, stdio MCP, integrations | SHA-256 of the key, then resolve_api_key, then a minted 120-second user JWT, then the user client; a fire-and-forget touch_api_key |
| OAuth access token | tm_mcp_ | remote MCP, third-party apps | SHA-256 of the token, then oauth_resolve_access_token, then a minted user JWT, then the user client |
The prefix routes the bearer. tm_mcp_r_ (refresh token) and tm_mcp_cs_ (confidential client
secret) start with tm_mcp_ but are never bearers; the API refuses them with 401 before any lookup,
and so does the remote MCP server. Access tokens are minted so their body never begins with r_ or
cs_, which keeps the two sets apart.
The API signs minted JWTs with SUPABASE_JWT_SIGNING_KEY (D-204, API signing
key). Credential scopes are ceilings over the same Postgres
access-state checks that govern a session; a credential adds no second authorization policy.
An API key or OAuth access token never leaves the API. The deterministic page/image fetcher
(recipe-import) receives the member's user JWT,
never the API key or OAuth token. Provider calls run directly in the API with provider credentials;
no user JWT, API key, or OAuth token is sent to a model provider.
Rules:
- Fail closed: auth-store or admin-seam errors, and a failure to mint, answer 503, never forced re-auth and never fail-open. An unknown, malformed, revoked or expired credential answers 401.
- Scopes:
read,write,delete,admin. Routes declarex-required-scopein contracts; a scope guard enforces it before the handler (403). Session JWTs get all scopes; API keys and OAuth tokens carry granted subsets. Scopes are independent:write,delete, andadmindo not implyread. A tool that reads before writing usually needs bothreadandwrite. Scopes do not replace your role in the target Meal Space. - Sync push:
POST /api/v1/sync/pushrequireswrite, and each command in the batch also needs the scope of the REST route that runs the same mutation (SYNC_COMMAND_SCOPESin contracts). A batch with any delete-class command (delete,recipe_delete,variation_remove,note_delete,idea_delete,recurrence_delete) needsdelete; without it the whole batch answers 403 and no command runs. - Only SHA-256 hashes of API keys, OAuth tokens, codes and client secrets are stored. Plaintext is shown once, at creation.
Credential scopes are ceilings, not Meal Space authorization. After authentication and scope checks, RLS or a focused database mutation derives the current account and Meal Space access state from Postgres. Handlers never authorize from a token-captured role, Sponsor, entitlement or client-supplied action.
Credential surfaces and Pro access
Every route declares x-credential-surface, and the surface check runs before the scope check:
| Surface | Accepted credentials |
|---|---|
first-party | Supabase session JWT only |
programmatic | API key or OAuth access token only |
any | Any of the three (the default) |
These routes are first-party (D-202): trial activation (POST /api/v1/me/trial), the plan read and
promo redemption (GET /api/v1/me/plan, POST /api/v1/me/promo-redemptions), API-key create and
revoke, OAuth authorization decisions, client lookup and Connected apps, notification registration,
TogetherDone connect, callback and disconnect, public Recipe-link management, and account deletion
(GET and POST /api/v1/me/account-deletion, POST /api/v1/me/account-deletion/cancel, D-263). Reading,
publishing, listing or revoking your public links and changing the account sharing switch all
require a session; importing someone else's public Recipe is an ordinary content write.
A leaked key or MCP token therefore can't mint another credential or move the account's
integrations. These first-party routes never enter the MCP catalog. No route is
programmatic yet.
Programmatic access requires the owner's own Pro or an active Pro trial (D-111), and it's checked on
every request, not at creation. resolve_api_key and oauth_resolve_access_token evaluate
account.use_programmatic_access each time and return no row when it fails, so the request answers
401. Losing Pro stops existing keys and tokens on the next request. Subscribing again restores them.
OAuth code issue, code exchange and refresh rotation need it too, and answer a refusal when it's gone.
A pending account-deletion request revokes the account's keys and tokens (D-149). An API key or OAuth
token for that account answers 401. A session for it answers 403 account_deletion_pending.
Credentials are rate-limited by tier (D-203): sessions 600/min, sync 300/min, and programmatic
credentials 300/min on Pro or 60/min on a trial, all set by the database. Promo redemption also
spends a promo bucket of 10/min per account, on top of the session bucket (D-207).
Source: services/api/src/middleware/auth.ts, services/api/src/authz/surface.ts,
packages/contracts/src/routes/api-keys.ts and packages/contracts/src/routes/oauth-authorizations.ts.
API keys
POST /api/v1/api-keys (first-party, write scope, Idempotency-Key) returns a new plaintext key once.
The key is tm_live_ and 32 characters from [A-Za-z0-9]. TogetherMeals stores its SHA-256 hash and
a display prefix (the first 12 characters). A lost key can't be recovered: revoke it and create
another. Every create attempt mints a new key, so a retry with the same Idempotency-Key answers a
conflict instead of replaying a plaintext that is gone. After a lost response, read the key list
before creating again.
The API-key routes list metadata (GET /api/v1/api-keys), retrieve one key
(GET /api/v1/api-keys/{keyId}), create, and revoke (DELETE /api/v1/api-keys/{keyId}). Keys are
created with a name (unique among active keys), a scope subset and an optional expiry. A trial may
hold one active key, and a second create answers 403 api_key_limit_reached. Pro has no count cap.
The limit applies at creation only. Revoking needs no Pro, so a lapsed account can put its keys away.
The /settings/api-keys page drives these routes. Request and response shapes are defined in
api-keys.ts. The public /api-docs reference and
/openapi.json download expose the generated authenticated contract.
An API key is independent of OAuth: disabling an OAuth client never disables a user's API keys.
OAuth 2.1 authorization server
TogetherMeals runs its own authorization server in services/api, so MCP clients and third parties
act for users. The issuer is the API origin. The endpoints are public routes outside /api/v1:
| Endpoint | Purpose |
|---|---|
GET /.well-known/oauth-authorization-server | RFC 8414 metadata |
POST /oauth/register | Dynamic Client Registration (RFC 7591), 5 per minute per IP |
POST /oauth/token | authorization_code and refresh_token grants |
POST /oauth/revoke | RFC 7009 revocation, bound to the calling client |
The protected resource is the remote MCP server, which publishes
/.well-known/oauth-protected-resource (RFC 9728) and challenges an unauthenticated or expired
bearer with a 401. The consent page is the web app's /oauth/authorize. The endpoints have separate
owners:
| Owner | Endpoints |
|---|---|
| API origin | The four endpoints above, and the first-party GET /api/v1/oauth/clients/{clientId}, POST /api/v1/oauth/authorizations and /api/v1/me/oauth-connections routes |
| Web origin | /oauth/authorize (consent), /settings/api-keys, /settings/connections |
| MCP origin | /.well-known/oauth-protected-resource, /mcp, and the bearer challenge pointing at it |
Authorization-code flow
The flow is authorization code with PKCE, for public clients and clients that registered as confidential:
- The client discovers the authorization server and the protected resource metadata.
- The client sends the person to the web
/oauth/authorize. A signed-out person signs in on that URL, and the query survives. - The consent page checks the request shape (PKCE challenge required,
S256only, no repeated parameters), asksGET /api/v1/oauth/clients/{clientId}who is asking, and checks the redirect and scopes against the client's registration. A request wider than the registration is narrowed to the registered scopes (RFC 6749 §3.3) and the screen shows exactly what will be granted. No registered scope, or an unknown one, is refused. The page offers Approve only to an account with Pro or an active trial (and a path to start the trial). Deny is always available. - Approve posts
POST /api/v1/oauth/authorizations. The API validates again, mints a 300-second single-use code, stores its hash through the signed-in user's database session, and returnsredirect_towithcode,stateandiss. Deny returnserror=access_denied,stateandiss. Aresourceparameter, if present, must equal the MCP resource URL (RFC 8707). The page followsredirect_toonly when it starts with the requested redirect. - The client posts the code and verifier to
/oauth/token. A public client sends only itsclient_id; a confidential client also proves its secret. The API checks the client, consumes the code, verifies PKCE, and issues an access token (1 hour) and a refresh token (30 days, sliding). - A refresh rotates both tokens after the same client check. Replaying a rotated refresh token revokes every token of that grant (D-200 item 1). Expiry, client shutdown, or loss of Pro refuses the refresh and leaves the token usable if Pro returns.
Only PKCE S256 is supported. A redirect URI is either an HTTPS URL that matches a registered URI
exactly, or an RFC 8252 loopback URL (http://localhost, http://127.0.0.1 or http://[::1]) for
native clients, matched with the port ignored. Private-use schemes such as myapp:// are refused. The
code records the redirect actually used, and the exchange must repeat it. The rules live in
packages/contracts/src/oauth-client-metadata.ts and are mirrored in SQL
(oauth_redirect_uri_is_valid, oauth_redirect_uri_matches). A shared fixture,
packages/contracts/src/oauth-redirect-cases.ts, holds the two implementations and the operator CLI
to the same results.
offline_access is accepted and ignored, because a refresh token is always issued. Consent is asked
on every authorization and nothing is remembered. The metadata advertises
authorization_response_iss_parameter_supported: true: both the approve and the deny redirect carry
iss equal to the issuer, and clients compare it as a string.
Client authentication. token_endpoint_auth_methods_supported and
revocation_endpoint_auth_methods_supported are both none, client_secret_post and
client_secret_basic. A client registered with either secret method presents its secret on every
token and revocation request, in the body as client_secret or with HTTP Basic; either form is
accepted for either method. The check runs before the code is consumed or the refresh token rotated,
so a request without the secret changes nothing. A missing or wrong secret, or a client_id that
isn't registered, answers 401 invalid_client (RFC 6749 §5.2), with a Basic challenge when the
request used Basic. An unknown client_id writes no audit row, because the id is caller-chosen. Sending both forms, or a body
client_id that differs from the Basic one, is invalid_request. Secrets are stored as hashes in
oauth_client_secrets, which no database role can read directly. PKCE is required of every client.
Revocation. /oauth/revoke authenticates the calling client as the token endpoint does, so an
unknown client_id or a confidential client's missing or wrong secret is 401 invalid_client
(RFC 7009 §2.1). Once the client is authenticated, a token that belongs to another client or an
unknown token returns the same empty success and revokes nothing (RFC 7009 §2.2). A refresh token revokes the access tokens minted
from it. A person can disconnect an app at /settings/connections, which revokes all their tokens and
pending codes for that client.
Bodies and headers. The token, revocation and registration endpoints prefer
application/x-www-form-urlencoded and also accept a JSON object of flat string members. Duplicate
form or JSON keys, malformed JSON, arrays, nested values and non-string members are refused, and a
body over 64 KiB answers 413. Responses carry Cache-Control: no-store. The metadata, token,
registration and revocation endpoints allow any origin with no credentials (GET/POST/OPTIONS,
authorization and content-type headers), so browser-based MCP clients can complete the flow.
Rate limits. /oauth/token and /oauth/revoke spend oauth-token-ip:<ip> (120 per minute) and
oauth-token:<client_id>:<ip> (60 per minute). /oauth/register spends dcr:<ip> (5 per minute). A
refusal answers 429 temporarily_unavailable with Retry-After; a limiter that can't answer answers
503. The API reads the address from the connection, or from X-Real-IP when TRUSTED_PROXY=1 (see
the runbook).
Client registration and shutdown
An MCP client needs only the MCP server URL. A client is known to TogetherMeals in one of three ways,
recorded as oauth_clients.registration_source:
| Source | How it is registered | What the consent screen says |
|---|---|---|
seeded, operator | By a migration, or by an operator with scripts/oauth-client-ops.mjs | The client's name |
metadata_document | The client's client_id is the HTTPS URL of its own Client ID Metadata Document, which the API fetches through an SSRF guard, validates and caches | "Published by domain", the domain the document came from |
dynamic | RFC 7591 Dynamic Client Registration at /oauth/register | A warning that TogetherMeals hasn't verified the app, whose name is self-chosen |
A self-registered client gets at most read write delete, enforced by a table constraint as well as
the endpoint. admin is reachable only through an operator registration. Operators list, disable or
revoke clients with the audited CLI (see the runbook). A disabled
client can't authorize, exchange, refresh, or use an existing access token. Every consent, code,
token, revocation, reuse detection and client change writes an oauth_events row, kept 90 days.
account_events doesn't exist yet (D-204).
First-party Google sign-in
Web starts a Supabase PKCE flow and exchanges its code at /auth/callback. Native exchanges a Google
SDK ID token through signInWithIdToken. Both produce ordinary Supabase sessions and use the same
request authentication and RLS checks as email-code sign-in. Google credentials never become a second
API bearer format. See provider setup and verification.
First-party Apple and demo password sign-in
Apple's web popup and native iOS sheet exchange identity tokens and nonces through
signInWithIdToken. They produce the same first-party Supabase session as Google and email.
Web validates popup state and prepares the nonce before the click; Supabase verifies token
signature, audience, and nonce. See Apple configuration and acceptance.
POST /auth/login-method is public and accepts only an email address. It returns raw
{"method":"password"} for exact addresses in the API's STORE_REVIEW_EMAILS, otherwise
{"method":"otp"}. It does not query Auth accounts. Responses are not cached, and independent
IP and email-plus-IP budgets limit discovery. Both apps call the public API origin directly;
web uses NEXT_PUBLIC_API_URL, and mobile uses EXPO_PUBLIC_API_URL. Credential-free CORS is
enabled only for this discovery path. It is outside the authenticated /api/v1 contract.
The selected password form calls Supabase signInWithPassword, including a CAPTCHA token when
configured, and receives an ordinary session. The list selects a UI and grants no authorization.
These clients do not implement MFA challenges or assurance-level enforcement. Use dedicated
reviewer accounts without enrolled factors. Account setup, deployment order, and retirement are documented in
store reviewer login.
Database authorization boundary
- User-facing mutations derive the actor from
auth.uid()and select one fixed action internally. - RLS wrappers protect shared reads and return no denial detail. A nonmember sees no rows or public
not_found. - Shared tables grant authenticated users no direct INSERT, UPDATE, or DELETE grants. REST and sync call the same focused lifecycle and domain RPCs.
- Internal access reasons map exhaustively to the closed public error set in
packages/contracts. Unknown actions or impossible relationships fail closed as 503 without database detail. - An unavailable access summary disables presentation controls. Cached summaries never grant access.
- A pending account-deletion request blocks ordinary session, API-key, and OAuth use. Account deletion cannot begin while the user owns a shared Meal Space.
For third-party access, TogetherMeals is an authorization server for its own MCP and API
consumers, and separately an OAuth client of TogetherDone for the grocery integration (see
../integrations/togetherdone.md).