Add an MCP server at SITE_URL/mcp so AI assistants (claude.ai connectors, Claude Code) can search, read and write notes. - starpunk/mcp_server: official MCP SDK 2.3, stateless Streamable HTTP with JSON responses, served by uvicorn as a sidecar from the same image. Ten tools; writes go through the Micropub handlers. - IndieAuth: RFC 8707 resource indicators bound to codes and tokens (migration 022), client ID metadata document + public client metadata, draft in scopes_supported, default MCP scopes, consent screen note. - BACKGROUND_WORKERS_ENABLED flag so the sidecar runs no workers. - Docs: ADR-075, architecture/mcp.md and updates; CHANGELOG. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
17 KiB
Authentication and Authorization Architecture
Current as of v2.14.0 (no auth changes since v2.11.0). Decision record: ADR-064, which supersedes the "no self-hosted IndieAuth" decisions (ADR-050, ADR-056) and the external token verification of ADR-030 / ADR-036.
The filename is historical: it described the v1.x "external provider only" design. Other documents link to it, so it is kept.
Overview
StarPunk is a single-user site with two kinds of client and two auth mechanisms:
| Who | Mechanism | Credential | Code |
|---|---|---|---|
| The site owner in a browser (admin UI, consent screen) | OpenID Connect login against an external provider (e.g. Pocket ID) | starpunk_session cookie, backed by a hashed row in sessions |
starpunk/auth.py, starpunk/routes/auth.py |
| Micropub apps (Quill, Indigenous, ...) | StarPunk's own IndieAuth authorization server | Bearer access token, backed by a hashed row in indieauth_tokens |
starpunk/indieauth.py, starpunk/routes/indieauth.py |
The two are chained: a Micropub app is approved on a consent screen that requires an admin session, so every token ultimately rests on the OIDC login. StarPunk stores no passwords.
Browser (owner) StarPunk OIDC provider
─────────────── ──────── ─────────────
POST /auth/login ─────────────▶ initiate_login() ── redirect ──▶ authorize (PKCE, nonce)
owner authenticates
GET /auth/callback?code&state ◀────────────────────── redirect ───┘
handle_callback(): code exchange, ID token checks,
sub == OIDC_ADMIN_SUB → create_session(ADMIN_ME)
◀── Set-Cookie: starpunk_session
Micropub app StarPunk
──────────── ────────
discovers indieauth-metadata / authorization_endpoint / token_endpoint
GET /auth/authorize?... ────────▶ validate request → (OIDC login if no session) → consent page
owner approves ─────────────────▶ POST /auth/authorize/approve → redirect: code, state, iss
POST /auth/token (code, verifier) ▶ access token (hash stored in indieauth_tokens)
POST /micropub, /micropub/media ─▶ verify_access_token() + scope check
1. Admin login (OIDC)
Flow
GET /auth/loginshowstemplates/admin/login.html, or redirects to the dashboard if the session cookie is already valid.POST /auth/logincallsauth.initiate_login(next):- Fetches
{OIDC_ISSUER}/.well-known/openid-configuration(cached for an hour per process). The document'sissuermust equalOIDC_ISSUER, and it must nameauthorization_endpoint,token_endpointandjwks_uri. - Generates
state,nonceand a PKCEcode_verifier, and stores them inoidc_login_statewith the sanitizednextURL (same site only) and a 10-minute expiry. - Redirects to the provider with
response_type=code,scope=openidandcode_challenge_method=S256.
- Fetches
GET /auth/callback:- A provider
errorparameter, or a missingcode/state, flashes an error and returns to the login page. - The
staterow is fetched and deleted in one step: it is single use and must not have expired. - If the provider sent
iss(RFC 9207), it must match the issuer. - The code is exchanged at the token endpoint along with the
code_verifier. StarPunk authenticates as a confidential client (HTTP Basic,OIDC_CLIENT_ID/OIDC_CLIENT_SECRET). - The ID token is verified with PyJWT against the provider's JWKS. The
checks are: the signature (algorithms from the provider metadata, never
none),iss,audequal to the client id,exp, requirediatandsub, a 60 s leeway, and anonceequal to the stored one. submust equalOIDC_ADMIN_SUB(constant-time comparison). Any other account gets "Not authorized as admin".- A session is created for
ADMIN_ME, the owner's identity URL. It is also themeof every issued token. The author h-card is refreshed fromADMIN_MEon a best-effort basis that never blocks login (see ADR-061).
- A provider
Sessions
create_session(me)makes a random 32-byte URL-safe token. Only its SHA-256 hash is stored insessions, withme,expires_at(SESSION_LIFETIMEdays, default 30), the user agent and the IP. Expired sessions and login states are cleaned up each time a session is created.- Cookie
starpunk_session:HttpOnly,SameSite=Lax,SecurewhenSITE_URLis https,max-ageequal to the session lifetime. verify_session(token)looks up the hash, checks expiry and updateslast_used_at.@require_authprotects/admin/*. Without a valid session it remembers the URL and redirects to/auth/login. It setsg.userandg.me.- A
before_requesthook also resolves the session on public pages that carry the cookie, so the header can show "Admin" instead of "Log in". POST /auth/logoutdeletes the session row and the cookie.
Configuration
Outside DEV_MODE, OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET,
OIDC_ADMIN_SUB and ADMIN_ME are required, and startup fails without them.
The provider must have {SITE_URL}/auth/callback registered as a redirect
URI.
Development mode
With DEV_MODE=true (and DEV_ADMIN_ME), /dev/login creates a session
without OIDC. The blueprint is registered only in dev mode, and its
before_request guard returns 404 if DEV_MODE is off. Every page shows a
warning banner while it is on. Never enable it in production.
2. Built-in IndieAuth authorization server
StarPunk issues tokens for exactly one identity, ADMIN_ME. It implements
the authorization code flow of the current IndieAuth spec
(https://indieauth.spec.indieweb.org/), with PKCE required.
Endpoints
| Method | Path | Purpose |
|---|---|---|
| GET | /.well-known/oauth-authorization-server |
Server metadata (the target of rel=indieauth-metadata) |
| GET | /auth/authorize |
Validate the request; show the consent screen (admin session required) |
| POST | /auth/authorize/approve |
Consent decision from the screen |
| POST | /auth/authorize |
Profile-only code redemption, returns {"me": ...} |
| POST | /auth/token |
Exchange a code for an access token; also legacy action=revoke |
| GET | /auth/token |
Legacy token verification (Bearer token → me, client_id, scope) |
| POST | /auth/revoke |
RFC 7009 revocation (always 200) |
All JSON responses carry Cache-Control: no-store. Errors use the OAuth
form {"error", "error_description"}.
Metadata
{
"issuer": "<SITE_URL>/",
"authorization_endpoint": "<SITE_URL>/auth/authorize",
"token_endpoint": "<SITE_URL>/auth/token",
"revocation_endpoint": "<SITE_URL>/auth/revoke",
"revocation_endpoint_auth_methods_supported": ["none"],
"scopes_supported": ["create", "update", "delete", "media", "draft", "profile"],
"response_types_supported": ["code"],
"token_endpoint_auth_methods_supported": ["none"],
"client_id_metadata_document_supported": true,
"grant_types_supported": ["authorization_code"],
"code_challenge_methods_supported": ["S256"],
"authorization_response_iss_parameter_supported": true
}
StarPunk has no introspection or userinfo endpoint. Only StarPunk itself checks its tokens.
Authorization request validation (validate_authorization_request)
client_idmust be an http(s) URL without a fragment.redirect_urimust be present and have no fragment. It must either share theclient_id's scheme, host and port, or be published by the client. To check the second case, StarPunk fetches theclient_idURL (5 s timeout, with an SSRF check on the URL unlessDEV_MODEis on). It readsredirect_urisfrom a JSON client metadata document, orrel="redirect_uri"from theLinkheader and from<link>/<a>elements.- Problems with
client_idorredirect_uriare shown to the user on an error page (HTTP 400). They are never redirected, because the redirect target can't be trusted. - Other problems are redirected to the client with
error,error_description,stateandiss. These are: aresponse_typeother thancode(unsupported_response_type), a missingstate, a missingcode_challenge, or acode_challenge_methodother thanS256. scopeis split on spaces. Requested scopes are not filtered againstscopes_supported.
Consent screen
If GET /auth/authorize gets a valid request but there is no admin session,
StarPunk stores the request URL and redirects to the OIDC login, which
returns to that URL afterwards. With a session, it renders
templates/admin/authorize.html. The page shows the client id, the identity
the client will act as, the redirect URI, and one checkbox per requested
scope (all checked). A request without scopes is described as "only wants to
confirm your identity".
POST /auth/authorize/approve checks the session again and re-validates the
request from hidden form fields. "Deny" redirects with
error=access_denied. "Approve" grants only the scopes that were both
requested and left checked, issues a code, and redirects with code,
state and iss.
Codes and tokens
| Authorization code | Access token | |
|---|---|---|
| Table | indieauth_codes |
indieauth_tokens |
| Value | 32 random bytes, URL-safe | 32 random bytes, URL-safe |
| Stored as | SHA-256 hash | SHA-256 hash |
| Lifetime | 10 minutes | INDIEAUTH_TOKEN_LIFETIME_DAYS (default 90) |
| Bound to | client_id, redirect_uri, scope, code_challenge, resource |
client_id, scope, resource |
redeem_authorization_code handles redemption for both POST /auth/token
and POST /auth/authorize:
codeandcode_verifierare required.- An atomic
UPDATE ... SET used_at = now WHERE code_hash = ? AND used_at IS NULL AND expires_at > nowmakes the code single-use, even across gunicorn workers. client_idandredirect_urimust match the code exactly.BASE64URL(SHA256(code_verifier))must equal the stored challenge (constant-time comparison).
The token endpoint accepts only grant_type=authorization_code. It refuses
a code issued with no scope (invalid_grant), because such codes are for
the profile-only flow at the authorization endpoint. The response is
{access_token, token_type: "Bearer", scope, me, expires_in}. There are no
refresh tokens: a client re-authorizes when its token expires.
Expired codes are deleted whenever a new code is issued.
Resource indicators (v2.15.0, ADR-075). An authorization request may
include resource (RFC 8707). The only accepted value is SITE_URL/mcp
(a trailing slash is ignored); anything else is invalid_target. With it,
a request without scope is offered create update delete media draft, and
the consent screen says the client is an AI assistant using MCP. The resource
is stored on the code and then on the token. A token request that names a
different resource gets invalid_target. Micropub clients send no resource
and their tokens have none. The MCP endpoint only accepts tokens for its
resource; see mcp.md.
Verification and revocation
verify_access_token(token)hashes the token and accepts it if it is neither revoked nor expired, then updateslast_used_at. It returns{me: ADMIN_ME, client_id, scope, resource, expires_at}. The legacyGET /auth/tokenstill answers with onlyme,client_idandscope.check_scope(required, scope)matches whole words in the space-separated scope string.- Revocation sets
revoked_at. It can happen by token value, throughPOST /auth/revokeor the legacyPOST /auth/tokenwithaction=revoke(unknown tokens are ignored, per RFC 7009). It can also happen by id, from the admin page. /admin/tokens("Connected Apps") lists active tokens with their client, scope, dates and last use. Each has a Revoke button.
Scopes
| Scope | Allows |
|---|---|
create |
Micropub create (published or draft), media upload, q=source, q=category |
draft |
Micropub create, always saved as a draft (v2.9.0); q=source, q=category |
update |
Micropub update; q=source, q=category |
delete |
Micropub delete and undelete; q=source, q=category |
media |
Media endpoint uploads |
profile |
Nothing beyond identity (there is no profile or userinfo endpoint) |
q=config and q=syndicate-to work with any valid token.
3. Token use at the Micropub and media endpoints
routes/micropub.py handles GET/POST /micropub and
POST /micropub/media. The old POST /media path is kept for existing
clients.
Extracting the token (micropub.extract_bearer_token)
- The token comes from
Authorization: Bearer <token>, with the scheme matched case-insensitively (RFC 7235). - Or it comes from
access_tokenin the form body (POST) or the query string (GET). - A token in both places gets 400
invalid_request(RFC 6750 §2, v2.9.0). - No token gets 401
unauthorized, "No access token provided". - An unknown, expired or revoked token gets 401
unauthorized, "Invalid or expired access token".
Every 401 carries WWW-Authenticate: Bearer realm="micropub". When a token
was sent but isn't valid, error="invalid_token" is added (RFC 6750 §3,
v2.9.0).
Scope rules
| Operation | Required scope | Notes |
|---|---|---|
| create | create or draft |
With only draft, the post is saved unpublished whatever post-status says |
| update | update |
|
| delete / undelete | delete |
|
q=source, q=category |
any of create, update, delete, draft |
These show drafts and tags (v2.9.0) |
q=config, q=syndicate-to |
any valid token | |
| media upload | media or create |
create is accepted for older clients |
A missing scope gets 403 insufficient_scope (RFC 6750). The Micropub
Recommendation's error table lists 401 for this case. StarPunk keeps 403 on
purpose (see the v2.9.0 review,
"Kept as is").
Micropub request handling itself is described in indieweb-protocols.md.
4. Discovery
templates/base.html puts these links on every page, whether or not
WEBMENTION_ENABLED is set (v2.8.0):
<link rel="micropub" href="<SITE_URL>/micropub">
<link rel="indieauth-metadata" href="<SITE_URL>/.well-known/oauth-authorization-server">
<link rel="authorization_endpoint" href="<SITE_URL>/auth/authorize">
<link rel="token_endpoint" href="<SITE_URL>/auth/token">
<link rel="me" href="<author home>">
<link rel="author" href="<author home>">
Micropub clients start from the URL the user types, which is normally
ADMIN_ME. If ADMIN_ME is the StarPunk site itself, the links above are
enough. If it is another page, that page must advertise StarPunk's
indieauth-metadata (or authorization_endpoint and token_endpoint) and
micropub links. Otherwise clients won't find StarPunk
(ADR-064 §3).
5. Data (migration 011)
| Table | Purpose | Key columns |
|---|---|---|
sessions |
Admin browser sessions | session_token_hash, me, expires_at, last_used_at, user_agent, ip_address |
oidc_login_state |
One pending OIDC login | state (PK), nonce, code_verifier, next_url, expires_at |
indieauth_codes |
Authorization codes | code_hash, client_id, redirect_uri, scope, code_challenge, resource (migration 022), expires_at, used_at |
indieauth_tokens |
Access tokens | token_hash, client_id, scope, resource (migration 022), expires_at, last_used_at, revoked_at |
The legacy v1 tables auth_state, tokens and authorization_codes are
not used (see the migration's header comment).
6. Security properties and known gaps
In place:
- No secrets at rest: session tokens, codes and access tokens are stored only as SHA-256 hashes.
- OIDC: PKCE S256, a nonce, single-use expiring state, issuer checks (in the
metadata and the RFC 9207
iss), full ID-token validation, and a single allowedsub. - IndieAuth: PKCE S256 required, single-use 10-minute codes bound to the
client and redirect URI,
issin every authorization response, and untrusted redirect URIs never followed. - Post-login redirects are limited to this site.
CSRF (v2.11.0): admin form POSTs, /auth/logout and the consent form's
approve button need a csrf_token field (or X-CSRF-Token header) equal to
an HMAC-SHA256 of the starpunk_session cookie under SECRET_KEY; anything
else gets 400. The token changes with every login and needs no storage.
Endpoints apps call with bearer tokens are not affected. The client metadata
fetch uses webmention_ssrf.safe_get (every redirect hop checked, the
connection pinned, a 5-second limit).
Known gaps:
- Unknown scopes are shown and granted as requested; they just have no
effect. (
drafthas been listed inscopes_supportedsince v2.15.0.) - No token introspection endpoint and no refresh tokens.