# sculk.network as an OpenID Connect provider

When the `oidcProvider` feature flag is enabled, sculk.network acts as an OpenID Connect 1.0 provider so relying parties such as Sculkworm can authenticate players and inspect which servers on the instance they may play on.

## Enabling the feature

`oidcProvider` is currently at the `nightly` [feature stage](https://docs.sculk.network/nightly/sculk/releases.md#feature-stages):

- Enabled by default on `dev` (`0.0.0-dev`) and `nightly` builds.
- Disabled by default on `stable` builds.
- Force on or off with `SCULK_FEATURES=oidcProvider` or `SCULK_FEATURES=-oidcProvider`.

When the flag is off, every OIDC endpoint (`/.well-known/openid-configuration`, `/oauth/*`, `/api/oidc/*`) responds `404 {"error":"not_found"}` with `Cache-Control: no-store`.

## Discovery document

`GET /.well-known/openid-configuration` (also served at `GET /oauth/.well-known/openid-configuration`) returns the provider metadata with `Cache-Control: no-store`. Replace `https://sculk.example` with your `SCULK_BASE_URL`:

```json
{
  "issuer": "https://sculk.example",
  "authorization_endpoint": "https://sculk.example/oauth/authorize",
  "token_endpoint": "https://sculk.example/oauth/token",
  "userinfo_endpoint": "https://sculk.example/oauth/userinfo",
  "jwks_uri": "https://sculk.example/oauth/jwks.json",
  "response_types_supported": ["code"],
  "grant_types_supported": ["authorization_code", "refresh_token"],
  "subject_types_supported": ["public"],
  "id_token_signing_alg_values_supported": ["RS256"],
  "scopes_supported": ["openid", "profile", "offline_access", "sculk:servers"],
  "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post", "none"],
  "code_challenge_methods_supported": ["S256"],
  "claims_supported": [
    "iss",
    "sub",
    "aud",
    "exp",
    "iat",
    "auth_time",
    "nonce",
    "preferred_username",
    "picture",
    "sculk_servers"
  ]
}
```

## Protocol rules and claims

- **Grant types:** `authorization_code` (with mandatory PKCE `S256`; `plain` is rejected) and `refresh_token` (only when `offline_access` was granted). Implicit, hybrid, and password grants are not supported.
- **Redirect URIs:** exact string match against the client's registered list. Clients flagged `native: true` may register `http://127.0.0.1/…` or `http://[::1]/…` loopback URIs and match any loopback port (RFC 8252 §7.3). All other redirect URIs must use `https://`. Unregistered redirect URIs render an HTML error page and never redirect.
- **Consent:** first-party clients (`firstParty: true`) auto-approve; third-party clients show a consent prompt the first time per subject and scope set.
- **ID tokens:** signed with RS256 using an RSA-2048 key generated asynchronously on first use and stored sealed under `SCULK_MASTER_KEY`. Lifetime is 10 minutes (`exp - iat = 600`).
  - Standard claims: `iss`, `sub` (opaque sculk user id, never the email), `aud`, `exp`, `iat`, `auth_time`, and `nonce` when requested.
  - `profile`: adds `preferred_username` and `picture` (when set).
  - `sculk:servers`: adds `sculk_servers`, an array of `{ "id", "name", "role", "is_player": true }` for every server on the instance where the subject holds `server.play`.
- **Access tokens:** opaque 256-bit tokens stored SHA-256 hashed, 1 hour TTL. `/oauth/userinfo` resolves live memberships on every call and rejects requests sending a bearer token in both the `Authorization` header and the form body (RFC 6750 §2).
- **Refresh tokens:** opaque 256-bit tokens stored SHA-256 hashed, 30-day sliding TTL, rotated on every refresh. Narrowing `scope` on a refresh request limits the minted tokens without shrinking the underlying grant's original scope set (RFC 6749 §6); if `offline_access` is omitted from the narrowed scope, no new `refresh_token` is returned. Reusing an already-rotated refresh token revokes the entire grant (all access and refresh tokens). Every refresh re-checks that the subject still exists and is not blocked, and re-resolves live `sculk_servers`.
- **Authorization codes:** 60-second TTL, single use, bound to client, redirect URI, subject, scopes, and PKCE challenge. Reusing a code revokes the tokens it already produced (RFC 6749 §4.1.2).
- **Rate limiting and caching:** every OIDC response (including redirects and errors) carries `Cache-Control: no-store`. Rate limits key on the direct socket peer address unless the peer matches `SCULK_TRUSTED_PROXIES`, in which case sculk.network uses the rightmost untrusted hop in `X-Forwarded-For` (IPv6 clients are grouped by `/64`; `X-Real-IP` is ignored). `/oauth/token` enforces a per-IP limit, per-IP and per-`(normalized client_id, IP)` failed-authentication buckets reserved before `scrypt` (refunded on auth success) plus a global `scrypt` concurrency limit, and a per-client limit applied after authentication (keyed by `(client_id, IP)` for public clients). Expired authorization requests, codes, access tokens, and refresh tokens are pruned opportunistically and by a periodic `oidc.cleanup-tokens` job (every 15 minutes).

## Client and key management API

Management endpoints require a signed-in session whose user ID is listed in `SCULK_OIDC_ADMINS` (comma-separated). When `SCULK_OIDC_ADMINS` is unset or empty, all `/api/oidc/*` endpoints return `403`. Authorization is enforced both at the route guard and inside each admin service function. All JSON responses carry `Cache-Control: no-store`.

| Endpoint | Purpose |
| --- | --- |
| `POST /api/oidc/clients` | Register a client (`name`, `redirectUris`, optional `native`, `firstParty`, `public`). Returns `clientSecret` once for confidential clients. |
| `GET /api/oidc/clients` | List registered clients (secret hashes are never returned). |
| `PATCH /api/oidc/clients/:clientId` | Disable or re-enable a client (`{"disabled": true\|false}`). Disabling revokes active grants and tokens. |
| `POST /api/oidc/clients/:clientId/rotate-secret` | Rotate a confidential client's secret (shown once). |
| `POST /api/oidc/keys/rotate` | Rotate the RS256 signing key. The new key becomes `current`; the old `current` stays published in `/oauth/jwks.json` as `previous` until the next rotation. Rejects with `409 rotation_cooldown` (`Retry-After`) while the `previous` key is younger than the 10-minute ID token TTL (`600 s`). |
| `DELETE /api/oidc/grants/:grantId` | Revoke a grant and its tokens immediately. |
| `GET /api/oidc/subjects/:userId/grants` | List a user's OIDC grants (`id`, `clientId`, `clientName`, `scopes`, `authTime`, `createdAt`, `revokedAt`). |
| `POST /api/oidc/subjects/:userId/block` | Block a user from OIDC (optional JSON `{"reason": "..."}`), immediately revoking all of their active grants and tokens and recording `oidc.subject.blocked`. |
| `DELETE /api/oidc/subjects/:userId/block` | Unblock a previously blocked OIDC subject and record `oidc.subject.unblocked`. |
| `GET /api/oidc/audit` | Read recent OIDC audit events (`oidc.client.*`, `oidc.grant.*`, `oidc.key.rotated`, `oidc.subject.*`). |

## Worked flow (against a dev lane)

Start a lane with `oidcProvider` enabled and the owner user ID in `SCULK_OIDC_ADMINS` (sign in once to read `users.id` or pass it via `pnpm lane svc 1 restart app --env SCULK_FEATURES=oidcProvider --env SCULK_OIDC_ADMINS=<owner_user_id>`), then create a server so the owner holds an `owner` seat:

```sh
APP=http://127.0.0.1:40010
OWNER_COOKIE=$(pnpm lane login 1 owner)

curl -sS -X POST "$APP/api/servers" \
  -H "Cookie: sculk_session=$OWNER_COOKIE" \
  -H "Content-Type: application/json" \
  -d '{"name":"Sculk Demo"}'
```

```json
{"id":"6uabltcpud3qpiy5","name":"Sculk Demo","createdAt":"2026-11-26T21:14:07.445Z"}
```

Read the discovery document:

```sh
curl -sS "$APP/.well-known/openid-configuration"
```

```json
{"issuer":"http://127.0.0.1:40010","authorization_endpoint":"http://127.0.0.1:40010/oauth/authorize","token_endpoint":"http://127.0.0.1:40010/oauth/token","userinfo_endpoint":"http://127.0.0.1:40010/oauth/userinfo","jwks_uri":"http://127.0.0.1:40010/oauth/jwks.json","response_types_supported":["code"],"grant_types_supported":["authorization_code","refresh_token"],"subject_types_supported":["public"],"id_token_signing_alg_values_supported":["RS256"],"scopes_supported":["openid","profile","offline_access","sculk:servers"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"code_challenge_methods_supported":["S256"],"claims_supported":["iss","sub","aud","exp","iat","auth_time","nonce","preferred_username","picture","sculk_servers"]}
```

Register a client:

```sh
curl -sS -X POST "$APP/api/oidc/clients" \
  -H "Cookie: sculk_session=$OWNER_COOKIE" \
  -H "Content-Type: application/json" \
  -d '{"name":"Sculkworm Live","redirectUris":["https://rp.example/cb"],"firstParty":true}'
```

```json
{"client":{"clientId":"vb3efdhxc2sbpqkmvbbd","name":"Sculkworm Live","redirectUris":["https://rp.example/cb"],"native":false,"firstParty":true,"public":false,"createdBy":"69bd3f16abf187baa9f3fdbc2116e120","createdAt":"2026-11-26T21:14:31.293Z","disabledAt":null},"clientSecret":"<shown once>"}
```

Authorize with PKCE `S256`, exchange the code at `/oauth/token`, verify the `id_token` signature against `/oauth/jwks.json`, call `/oauth/userinfo`, and test refresh rotation and reuse detection:

```text
authorize status: 302 cache-control: no-store
redirect state: demo-state code len: 43
token status: 200 cache-control: no-store keys: [ 'access_token', 'expires_in', 'id_token', 'refresh_token', 'scope', 'token_type' ]
jwks status: 200 kids: [ '5zmsp-s7_yt1_P4h' ]
id_token RS256 sig valid: true header: { alg: 'RS256', typ: 'JWT', kid: '5zmsp-s7_yt1_P4h' }
userinfo status: 200 body: {
  sub: '69bd3f16abf187baa9f3fdbc2116e120',
  preferred_username: 'Owner',
  picture: 'https://avatars.sculk.test/owner.png',
  sculk_servers: [ { id: '6uabltcpud3qpiy5', name: 'Sculk Demo', role: 'owner', is_player: true } ]
}
refresh status: 200 rotated: true
refresh reuse status: 400 body: { error: 'invalid_grant', error_description: 'Refresh token reuse detected.' }
userinfo after reuse status: 401
```

Disabling the feature flag returns `404` with `Cache-Control: no-store` on every OIDC route:

```sh
pnpm lane svc 1 restart app --env SCULK_FEATURES=-oidcProvider
curl -sS -i "$APP/.well-known/openid-configuration" | head -n 5
```

```text
HTTP/1.1 404 Not Found
cache-control: no-store
content-type: application/json
```
