Public: anyone can read this; the crew can change it.
One authorization server in the forge: people, agents, MCP clients, hosted apps, and later other forges #781
torque/forge:torque/666-one-authorization-server-in-the-forge-pe → main 3 commits fork 3 threads · 3 unresolved
19 files
changed +1527
−41
CLAUDE.md +5 −2
| @@ -105,14 +105,17 @@ src/ | ||
| 105 | 105 | app.ts composition root — one data dir = one forge (dataDir is resolved |
| 106 | 106 | absolute here; the hook socket depends on it) |
| 107 | 107 | kernel/ zero-dep primitives: result, error, id (monotonic ULID), log, |
| 108 | db (sqlite/WAL), hash | |
| 108 | db (sqlite/WAL), hash, jwt (ES256 over WebCrypto) | |
| 109 | 109 | git/ env (runGit*), read (cat-file batch readers), diff, merge (bare |
| 110 | 110 | plumbing, no work tree), write (commit via plumbing, deletes as |
| 111 | 111 | index-info mode 0, a `land` hook so an origin answers first), |
| 112 | 112 | branches (create/delete via update-ref leases, ahead/behind), |
| 113 | 113 | repos (fork via alternates), smart-http, smart-ssh |
| 114 | 114 | (exec-channel git), hooks (+ hook-entry, guard) |
| 115 | core/ domain: users (kind user|org), sessions, tokens (ro/rw/admin), | |
| 115 | core/ domain: users (kind user|org), sessions, tokens (ro/rw/admin; | |
| 116 | every credential the forge mints is a row here), the | |
| 117 | authorization server's oauth (clients), oauth_codes (PKCE | |
| 118 | codes, scopes), oidc (claims, id_token), oidc_keys (rotation), | |
| 116 | 119 | repos (access checks, grouped `countsForRepos`), issues |
| 117 | 120 | (issue|pull, grouped `labelsForIssues`/`commentCounts`), pulls, |
| 118 | 121 | reviews, orgs/teams, webhooks, keys (ssh public keys), search |
docs/APPS.md +26
| @@ -466,6 +466,32 @@ not land. The table the door reads knows two signed identities, `user` | ||
| 466 | 466 | and `admin`; a role such as a team's (`manage`) waits on the forge |
| 467 | 467 | signing one (see [](CONTRACT.md)). |
| 468 | 468 | |
| 469 | ## Signing a person in with OpenID Connect | |
| 470 | ||
| 471 | The forge is an OpenID Connect provider, and the same authorization server | |
| 472 | that hands the MCP its tokens signs people into apps — hosted here, or | |
| 473 | anywhere else, another forge in the fork tree included. `$FORGE_URL` is the | |
| 474 | issuer: | |
| 475 | ||
| 476 | - discovery: `$FORGE_URL/.well-known/openid-configuration` | |
| 477 | - register once: `POST $FORGE_URL/oauth/register` with `client_name` and | |
| 478 | `redirect_uris` (https, or http on `localhost` / `*.localhost`); a public | |
| 479 | client, no secret, PKCE `S256` required | |
| 480 | - send the person to `/oauth/authorize?response_type=code&client_id=…&redirect_uri=…&scope=openid profile email&state=…&nonce=…&code_challenge=…&code_challenge_method=S256` | |
| 481 | - trade the code at `/oauth/token` for an `id_token` (ES256, checked | |
| 482 | against `/oauth/jwks`; `sub` is the account id and never changes, | |
| 483 | `preferred_username`, `name`, `email`) and an access token for | |
| 484 | `/oauth/userinfo` | |
| 485 | ||
| 486 | Asked for OpenID scopes alone, the access token is a sign-in token: it | |
| 487 | answers `userinfo` for an hour and the API refuses it. Add `ro` or `rw` to | |
| 488 | the scope and the person is also asked to let the app act as them. Signing | |
| 489 | keys rotate every 30 days and stay in the JWKS for 60, so a relying party | |
| 490 | that caches the JWKS for a day never misses one. Every token minted this | |
| 491 | way is the person's to list and revoke, like any other. | |
| 492 | ||
| 493 | The signed headers below remain for apps already built on them. | |
| 494 | ||
| 469 | 495 | ## Who is there: identity from the forge |
| 470 | 496 | |
| 471 | 497 | An app never writes sign-in. The forge tells it who is there, on every |
docs/MCP.md +24 −5
| @@ -67,11 +67,30 @@ claude mcp add --transport http forge https://<your-forge>/mcp \ | ||
| 67 | 67 | --header "Authorization: Bearer <token>" |
| 68 | 68 | |
| 69 | 69 | |
| 70 | Any MCP client that can send a header works the same way. The Claude apps on | |
| 71 | the web and the phone add custom connectors through OAuth, which the forge | |
| 72 | does not speak yet; that is the next step here, and it changes nothing above | |
| 73 | — the same tools, a token the forge mints for the connector instead of one a | |
| 74 | person pastes. | |
| 70 | Any MCP client that can send a header works the same way. | |
| 71 | ||
| 72 | ### Through OAuth | |
| 73 | ||
| 74 | A client that speaks OAuth needs only the URL. A `401` from `/mcp` names | |
| 75 | `/.well-known/oauth-protected-resource`, which names the forge as its | |
| 76 | authorization server; the client registers itself (`POST /oauth/register`, | |
| 77 | RFC 7591), sends the person to `/oauth/authorize` with a PKCE `S256` | |
| 78 | challenge, and trades the code at `/oauth/token`. The person sees the | |
| 79 | client's name and where they go back to, picks `ro` or `rw` (never more than | |
| 80 | was asked), and names the token. What the client gets is an ordinary forge | |
| 81 | token — listed under **Settings → Access tokens** as "via <client>", and | |
| 82 | revoked there, through `DELETE /api/v1/tokens/:id`, or by the client itself | |
| 83 | at `/oauth/revoke`. | |
| 84 | ||
| 85 | - **Claude (web and phone):** Settings → Connectors → Add custom connector, | |
| 86 | URL `https://<your-forge>/mcp`. Claude registers itself with the callback | |
| 87 | `https://claude.ai/api/mcp/auth_callback`. | |
| 88 | - **Grok custom connectors:** add the same URL; the connector discovers and | |
| 89 | registers the same way. | |
| 90 | ||
| 91 | A code is single-use, lives 60 seconds and is stored hashed; a wrong | |
| 92 | verifier burns it. `src/http/oauth.ts`, `src/web/pages/oauth.ts`, | |
| 93 | `src/core/oauth_codes.ts`, `test/authorization-server.test.ts`. | |
| 75 | 94 | |
| 76 | 95 | `src/http/mcp.ts`, `src/actions/tell.ts`, `test/mcp.test.ts`. |
| 77 | 96 |
scripts/gate.ts +1
| @@ -166,6 +166,7 @@ export const GATE: readonly string[] = [ | ||
| 166 | 166 | "test/hollow.test.ts", |
| 167 | 167 | "test/home-feed.test.ts", |
| 168 | 168 | "test/oauth-discovery.test.ts", |
| 169 | "test/authorization-server.test.ts", | |
| 169 | 170 | "test/data-home.test.ts", |
| 170 | 171 | "test/tree.test.ts", |
| 171 | 172 | "test/reports.test.ts", |
scripts/hollow-allow.ts +6
| @@ -31,4 +31,10 @@ export const ALLOWED: readonly Allowed[] = [ | ||
| 31 | 31 | "the fleet graph shipped ahead of the fleet page that is to link to it", |
| 32 | 32 | issue: 448, |
| 33 | 33 | }, |
| 34 | { | |
| 35 | orphan: "GET /oauth/authorize", | |
| 36 | reason: | |
| 37 | "the consent screen is reached by an OAuth client's redirect, named in the discovery documents, never by a link a person follows", | |
| 38 | issue: 666, | |
| 39 | }, | |
| 34 | 40 | ]; |
src/actions/oauth.ts added +146
| @@ -0,0 +1,146 @@ | ||
| 1 | /** | |
| 2 | * The authorization server's two mutations: a person consents (a code), | |
| 3 | * and a client trades the code for a token. The token is a row in `token` | |
| 4 | * like any other — the same kind Settings mints and a run is handed — so | |
| 5 | * it is listed, scoped and revoked the same way. There is one credential | |
| 6 | * system; OAuth is a door into it. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import type { OAuthClient } from "../core/oauth.ts"; | |
| 11 | import { | |
| 12 | issueCode, | |
| 13 | redeemCode, | |
| 14 | scopeString, | |
| 15 | type Requested, | |
| 16 | } from "../core/oauth_codes.ts"; | |
| 17 | import { issueIdToken } from "../core/oidc.ts"; | |
| 18 | import { createToken, revokePresented } from "../core/tokens.ts"; | |
| 19 | import { getUserById, type User } from "../core/users.ts"; | |
| 20 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 21 | import { requireUser } from "./access.ts"; | |
| 22 | ||
| 23 | /** A sign-in token answers `userinfo` for this long, then stops. */ | |
| 24 | export const SIGNIN_TOKEN_TTL_S = 60 * 60; | |
| 25 | ||
| 26 | export interface Consent { | |
| 27 | readonly client: OAuthClient; | |
| 28 | readonly redirectUri: string; | |
| 29 | readonly requested: Requested; | |
| 30 | readonly challenge: string; | |
| 31 | readonly nonce: string | null; | |
| 32 | readonly name: string; | |
| 33 | } | |
| 34 | ||
| 35 | /** | |
| 36 | * A person allows a client. Only a person: an agent's credential is the | |
| 37 | * one its run is minted, and an organisation never signs in. | |
| 38 | */ | |
| 39 | export function consent( | |
| 40 | app: App, | |
| 41 | actor: User | undefined, | |
| 42 | input: Consent, | |
| 43 | ): Result<string, "unauthorized" | "forbidden"> { | |
| 44 | const user = requireUser(actor); | |
| 45 | if (!user.ok) return user; | |
| 46 | if (user.value.kind !== "user") return err("forbidden"); | |
| 47 | if (!input.client.redirectUris.includes(input.redirectUri)) | |
| 48 | return err("forbidden"); | |
| 49 | const code = issueCode(app.db, { | |
| 50 | clientId: input.client.id, | |
| 51 | userId: user.value.id, | |
| 52 | redirectUri: input.redirectUri, | |
| 53 | scope: input.requested.scope, | |
| 54 | claims: input.requested.claims, | |
| 55 | challenge: input.challenge, | |
| 56 | nonce: input.nonce, | |
| 57 | name: input.name, | |
| 58 | authTime: Math.floor(Date.now() / 1000), | |
| 59 | }); | |
| 60 | app.bus.append({ | |
| 61 | kind: "oauth.consented", | |
| 62 | actorId: user.value.id, | |
| 63 | payload: { clientId: input.client.id, scope: scopeString(input.requested) }, | |
| 64 | }); | |
| 65 | return ok(code); | |
| 66 | } | |
| 67 | ||
| 68 | /** RFC 6749 §5.1, plus OpenID's `id_token` when `openid` was granted. */ | |
| 69 | export interface TokenResponse { | |
| 70 | readonly access_token: string; | |
| 71 | readonly token_type: "Bearer"; | |
| 72 | readonly scope: string; | |
| 73 | readonly expires_in?: number; | |
| 74 | readonly id_token?: string; | |
| 75 | } | |
| 76 | ||
| 77 | export async function exchange( | |
| 78 | app: App, | |
| 79 | issuer: string, | |
| 80 | presented: { code: string; clientId: string; redirectUri: string; verifier: string }, | |
| 81 | ): Promise<Result<TokenResponse, "invalid_grant">> { | |
| 82 | const grant = redeemCode(app.db, presented); | |
| 83 | if (!grant.ok) return grant; | |
| 84 | const user = getUserById(app.db, grant.value.userId); | |
| 85 | if (user === undefined || user.kind !== "user") return err("invalid_grant"); | |
| 86 | const signIn = grant.value.scope === null; | |
| 87 | const minted = createToken( | |
| 88 | app.db, | |
| 89 | user.id, | |
| 90 | grant.value.name, | |
| 91 | grant.value.scope ?? "ro", | |
| 92 | { | |
| 93 | clientId: grant.value.clientId, | |
| 94 | claims: grant.value.claims, | |
| 95 | api: !signIn, | |
| 96 | ...(signIn | |
| 97 | ? { | |
| 98 | expiresAt: new Date( | |
| 99 | Date.now() + SIGNIN_TOKEN_TTL_S * 1000, | |
| 100 | ).toISOString(), | |
| 101 | } | |
| 102 | : {}), | |
| 103 | }, | |
| 104 | ); | |
| 105 | app.bus.append({ | |
| 106 | kind: "token.created", | |
| 107 | actorId: user.id, | |
| 108 | payload: { | |
| 109 | tokenId: minted.id, | |
| 110 | name: grant.value.name, | |
| 111 | scope: scopeString(grant.value), | |
| 112 | clientId: grant.value.clientId, | |
| 113 | }, | |
| 114 | }); | |
| 115 | const idToken = grant.value.claims.includes("openid") | |
| 116 | ? await issueIdToken(app.db, app.config.dataDir, { | |
| 117 | issuer, | |
| 118 | clientId: grant.value.clientId, | |
| 119 | user, | |
| 120 | scopes: grant.value.claims, | |
| 121 | nonce: grant.value.nonce, | |
| 122 | authTime: grant.value.authTime, | |
| 123 | }) | |
| 124 | : undefined; | |
| 125 | return ok({ | |
| 126 | access_token: minted.token, | |
| 127 | token_type: "Bearer", | |
| 128 | scope: scopeString(grant.value), | |
| 129 | ...(signIn ? { expires_in: SIGNIN_TOKEN_TTL_S } : {}), | |
| 130 | ...(idToken === undefined ? {} : { id_token: idToken }), | |
| 131 | }); | |
| 132 | } | |
| 133 | ||
| 134 | /** | |
| 135 | * RFC 7009: whoever holds a token may end it. An unknown token is not an | |
| 136 | * error — the answer is the same either way, so it says nothing. | |
| 137 | */ | |
| 138 | export function revokeHeld(app: App, presented: string): void { | |
| 139 | const gone = revokePresented(app.db, presented); | |
| 140 | if (gone === undefined) return; | |
| 141 | app.bus.append({ | |
| 142 | kind: "token.deleted", | |
| 143 | actorId: gone.userId, | |
| 144 | payload: { tokenId: gone.id }, | |
| 145 | }); | |
| 146 | } |
src/core/oauth.ts +5 −1
| @@ -42,7 +42,11 @@ function redirectOk(raw: string): boolean { | ||
| 42 | 42 | if (url.username !== "" || url.password !== "" || url.hash !== "") |
| 43 | 43 | return false; |
| 44 | 44 | if (url.protocol === "https:") return url.hostname !== ""; |
| 45 | return url.protocol === "http:" && LOCAL.has(url.hostname); | |
| 45 | // `*.localhost` is loopback too (RFC 6761): a hosted app's local preview. | |
| 46 | return ( | |
| 47 | url.protocol === "http:" && | |
| 48 | (LOCAL.has(url.hostname) || url.hostname.endsWith(".localhost")) | |
| 49 | ); | |
| 46 | 50 | } |
| 47 | 51 | |
| 48 | 52 | export interface Registration { |
src/core/oauth_codes.ts added +166
| @@ -0,0 +1,166 @@ | ||
| 1 | /** | |
| 2 | * Authorization codes (RFC 6749 §4.1, PKCE RFC 7636): what a person's | |
| 3 | * consent turns into, and what a client trades for a token. A code is | |
| 4 | * stored only as its hash, lives `CODE_TTL_MS`, and is consumed by the | |
| 5 | * first attempt to redeem it — a wrong verifier burns it too, so a code | |
| 6 | * that leaked into a log is worth one guess at most. | |
| 7 | * | |
| 8 | * Scopes are the forge's three (`ro < rw < admin`, the same ones Settings | |
| 9 | * mints) and the OpenID standard ones. A request for OpenID scopes alone | |
| 10 | * is a sign-in: it yields an id_token and a token that reaches `userinfo` | |
| 11 | * and nothing else. | |
| 12 | */ | |
| 13 | ||
| 14 | import type { Database } from "bun:sqlite"; | |
| 15 | import { createHash, timingSafeEqual } from "node:crypto"; | |
| 16 | import { sha256 } from "../kernel/hash.ts"; | |
| 17 | import { secret } from "../kernel/id.ts"; | |
| 18 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 19 | import type { TokenScope } from "./tokens.ts"; | |
| 20 | ||
| 21 | export const CODE_TTL_MS = 60_000; | |
| 22 | ||
| 23 | export const FORGE_SCOPES: readonly TokenScope[] = ["ro", "rw", "admin"]; | |
| 24 | export const OIDC_SCOPES = ["openid", "profile", "email"] as const; | |
| 25 | export type OidcScope = (typeof OIDC_SCOPES)[number]; | |
| 26 | ||
| 27 | export interface Requested { | |
| 28 | /** The forge scope asked for, or null for a sign-in only. */ | |
| 29 | readonly scope: TokenScope | null; | |
| 30 | /** OpenID scopes asked for; empty unless `openid` is among them. */ | |
| 31 | readonly claims: readonly OidcScope[]; | |
| 32 | } | |
| 33 | ||
| 34 | /** | |
| 35 | * Read a `scope` parameter. Nothing asked is `ro` — the least a client can | |
| 36 | * be given. Two forge scopes at once, or a word the forge does not know, | |
| 37 | * is refused rather than guessed at. | |
| 38 | */ | |
| 39 | export function parseScope(raw: string | null): Result<Requested, string> { | |
| 40 | const words = (raw ?? "").split(/[ +]+/).filter((w) => w !== ""); | |
| 41 | if (words.length > 8) return err("too many scopes"); | |
| 42 | const forge: TokenScope[] = []; | |
| 43 | const oidc = new Set<OidcScope>(); | |
| 44 | for (const word of words) { | |
| 45 | if ((FORGE_SCOPES as readonly string[]).includes(word)) | |
| 46 | forge.push(word as TokenScope); | |
| 47 | else if ((OIDC_SCOPES as readonly string[]).includes(word)) | |
| 48 | oidc.add(word as OidcScope); | |
| 49 | else return err(`unknown scope "${word.slice(0, 40)}"`); | |
| 50 | } | |
| 51 | if (new Set(forge).size > 1) | |
| 52 | return err("ask for one of ro, rw or admin, not several"); | |
| 53 | // `profile` and `email` mean something only inside an OpenID request. | |
| 54 | const claims = oidc.has("openid") | |
| 55 | ? OIDC_SCOPES.filter((s) => oidc.has(s)) | |
| 56 | : []; | |
| 57 | const scope = forge[0] ?? (claims.length > 0 ? null : "ro"); | |
| 58 | return ok({ scope, claims }); | |
| 59 | } | |
| 60 | ||
| 61 | /** The scope string a token response reports. */ | |
| 62 | export function scopeString(requested: Requested): string { | |
| 63 | return [...(requested.scope ? [requested.scope] : []), ...requested.claims].join( | |
| 64 | " ", | |
| 65 | ); | |
| 66 | } | |
| 67 | ||
| 68 | export interface Grant extends Requested { | |
| 69 | readonly clientId: string; | |
| 70 | readonly userId: string; | |
| 71 | readonly redirectUri: string; | |
| 72 | readonly challenge: string; | |
| 73 | readonly nonce: string | null; | |
| 74 | /** The token's name in Settings. */ | |
| 75 | readonly name: string; | |
| 76 | /** When the person consented, in seconds (OpenID `auth_time`). */ | |
| 77 | readonly authTime: number; | |
| 78 | } | |
| 79 | ||
| 80 | /** Record a consent; the code is returned once and never stored. */ | |
| 81 | export function issueCode( | |
| 82 | db: Database, | |
| 83 | grant: Grant, | |
| 84 | now: Date = new Date(), | |
| 85 | ): string { | |
| 86 | const code = secret(); | |
| 87 | db.query( | |
| 88 | `INSERT INTO oauth_code (code_hash, client_id, user_id, redirect_uri, scope, | |
| 89 | claims, challenge, nonce, name, auth_time, expires_at) | |
| 90 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)`, | |
| 91 | ).run( | |
| 92 | sha256(code), | |
| 93 | grant.clientId, | |
| 94 | grant.userId, | |
| 95 | grant.redirectUri, | |
| 96 | grant.scope, | |
| 97 | grant.claims.join(" "), | |
| 98 | grant.challenge, | |
| 99 | grant.nonce, | |
| 100 | grant.name, | |
| 101 | grant.authTime, | |
| 102 | new Date(now.getTime() + CODE_TTL_MS).toISOString(), | |
| 103 | ); | |
| 104 | // Codes nobody redeemed go here, on the next one issued. | |
| 105 | db.query("DELETE FROM oauth_code WHERE expires_at <= ?1").run( | |
| 106 | now.toISOString(), | |
| 107 | ); | |
| 108 | return code; | |
| 109 | } | |
| 110 | ||
| 111 | /** RFC 7636 §4.1: 43–128 characters of the unreserved set. */ | |
| 112 | export const isVerifier = (v: string): boolean => | |
| 113 | /^[A-Za-z0-9._~-]{43,128}$/.test(v); | |
| 114 | ||
| 115 | /** The S256 challenge a verifier answers. */ | |
| 116 | export const challengeOf = (verifier: string): string => | |
| 117 | createHash("sha256").update(verifier).digest("base64url"); | |
| 118 | ||
| 119 | interface CodeRow { | |
| 120 | client_id: string; | |
| 121 | user_id: string; | |
| 122 | redirect_uri: string; | |
| 123 | scope: TokenScope | null; | |
| 124 | claims: string; | |
| 125 | challenge: string; | |
| 126 | nonce: string | null; | |
| 127 | name: string; | |
| 128 | auth_time: number; | |
| 129 | expires_at: string; | |
| 130 | } | |
| 131 | ||
| 132 | /** | |
| 133 | * Trade a code for the grant behind it. The row is deleted before any | |
| 134 | * check, so every outcome — success or not — is the code's last. | |
| 135 | */ | |
| 136 | export function redeemCode( | |
| 137 | db: Database, | |
| 138 | presented: { code: string; clientId: string; redirectUri: string; verifier: string }, | |
| 139 | now: Date = new Date(), | |
| 140 | ): Result<Grant, "invalid_grant"> { | |
| 141 | const row = db | |
| 142 | .query<CodeRow, [string]>( | |
| 143 | "DELETE FROM oauth_code WHERE code_hash = ?1 RETURNING *", | |
| 144 | ) | |
| 145 | .get(sha256(presented.code)); | |
| 146 | if (row === null) return err("invalid_grant"); | |
| 147 | if (row.expires_at <= now.toISOString()) return err("invalid_grant"); | |
| 148 | if (row.client_id !== presented.clientId) return err("invalid_grant"); | |
| 149 | if (row.redirect_uri !== presented.redirectUri) return err("invalid_grant"); | |
| 150 | if (!isVerifier(presented.verifier)) return err("invalid_grant"); | |
| 151 | const want = Buffer.from(row.challenge); | |
| 152 | const got = Buffer.from(challengeOf(presented.verifier)); | |
| 153 | if (want.length !== got.length || !timingSafeEqual(want, got)) | |
| 154 | return err("invalid_grant"); | |
| 155 | return ok({ | |
| 156 | clientId: row.client_id, | |
| 157 | userId: row.user_id, | |
| 158 | redirectUri: row.redirect_uri, | |
| 159 | scope: row.scope, | |
| 160 | claims: (row.claims === "" ? [] : row.claims.split(" ")) as OidcScope[], | |
| 161 | challenge: row.challenge, | |
| 162 | nonce: row.nonce, | |
| 163 | name: row.name, | |
| 164 | authTime: row.auth_time, | |
| 165 | }); | |
| 166 | } |
src/core/oidc.ts added +70
| @@ -0,0 +1,70 @@ | ||
| 1 | /** | |
| 2 | * What the forge says about a person as an OpenID provider (OpenID Connect | |
| 3 | * Core 1.0): the claims `userinfo` answers with, and the `id_token` a | |
| 4 | * relying party — a hosted app, another forge — signs a person in with. | |
| 5 | * | |
| 6 | * `sub` is the account's id, never its username: a username can be changed | |
| 7 | * or reused, and a relying party keys its accounts on `sub` (§5.7). | |
| 8 | * `email_verified` is false until the forge proves an address. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { Database } from "bun:sqlite"; | |
| 12 | import { signJwt } from "../kernel/jwt.ts"; | |
| 13 | import type { OidcScope } from "./oauth_codes.ts"; | |
| 14 | import { signingKey } from "./oidc_keys.ts"; | |
| 15 | import type { User } from "./users.ts"; | |
| 16 | ||
| 17 | /** How long an id_token vouches for a sign-in. */ | |
| 18 | export const ID_TOKEN_TTL_S = 10 * 60; | |
| 19 | ||
| 20 | /** The claims released for these scopes (§5.4). */ | |
| 21 | export function userClaims( | |
| 22 | user: User, | |
| 23 | scopes: readonly OidcScope[], | |
| 24 | issuer: string, | |
| 25 | ): Record<string, unknown> { | |
| 26 | const claims: Record<string, unknown> = { sub: user.id }; | |
| 27 | if (scopes.includes("profile")) { | |
| 28 | claims["preferred_username"] = user.username; | |
| 29 | claims["name"] = user.displayName || user.username; | |
| 30 | claims["profile"] = `${issuer}/${encodeURIComponent(user.username)}`; | |
| 31 | } | |
| 32 | if (scopes.includes("email") && user.email !== "") { | |
| 33 | claims["email"] = user.email; | |
| 34 | claims["email_verified"] = false; | |
| 35 | } | |
| 36 | return claims; | |
| 37 | } | |
| 38 | ||
| 39 | export interface IdTokenInput { | |
| 40 | readonly issuer: string; | |
| 41 | readonly clientId: string; | |
| 42 | readonly user: User; | |
| 43 | readonly scopes: readonly OidcScope[]; | |
| 44 | readonly nonce: string | null; | |
| 45 | readonly authTime: number; | |
| 46 | } | |
| 47 | ||
| 48 | /** Sign an id_token with the current key (§2, §3.1.3.6). */ | |
| 49 | export async function issueIdToken( | |
| 50 | db: Database, | |
| 51 | dataDir: string, | |
| 52 | input: IdTokenInput, | |
| 53 | now: Date = new Date(), | |
| 54 | ): Promise<string> { | |
| 55 | const key = await signingKey(db, dataDir, now); | |
| 56 | const iat = Math.floor(now.getTime() / 1000); | |
| 57 | return signJwt( | |
| 58 | { | |
| 59 | ...userClaims(input.user, input.scopes, input.issuer), | |
| 60 | iss: input.issuer, | |
| 61 | aud: input.clientId, | |
| 62 | iat, | |
| 63 | exp: iat + ID_TOKEN_TTL_S, | |
| 64 | auth_time: input.authTime, | |
| 65 | ...(input.nonce === null ? {} : { nonce: input.nonce }), | |
| 66 | }, | |
| 67 | key.privateJwk, | |
| 68 | key.kid, | |
| 69 | ); | |
| 70 | } |
src/core/oidc_keys.ts added +90
| @@ -0,0 +1,90 @@ | ||
| 1 | /** | |
| 2 | * The keys the forge signs OpenID `id_token`s with. One is current; it is | |
| 3 | * replaced once it is `ROTATE_MS` old, and every key stays published in the | |
| 4 | * JWKS for `PUBLISHED_MS` after it was made, so a token signed just before | |
| 5 | * a rotation still verifies for as long as it can live (minutes) and a | |
| 6 | * relying party's cached JWKS has a full rotation period to refresh. | |
| 7 | * | |
| 8 | * The private half is sealed under the data directory's key | |
| 9 | * (`kernel/secret.ts`) with the kid bound in, so a database copied without | |
| 10 | * that file signs nothing. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { Database } from "bun:sqlite"; | |
| 14 | import { id } from "../kernel/id.ts"; | |
| 15 | import { generateKeyPair, type Jwk } from "../kernel/jwt.ts"; | |
| 16 | import { open, seal } from "../kernel/secret.ts"; | |
| 17 | ||
| 18 | const DAY_MS = 24 * 60 * 60 * 1000; | |
| 19 | /** A key signs for this long before a new one replaces it. */ | |
| 20 | export const ROTATE_MS = 30 * DAY_MS; | |
| 21 | /** A key is published (and kept) for this long after it was made. */ | |
| 22 | export const PUBLISHED_MS = 2 * ROTATE_MS; | |
| 23 | ||
| 24 | export interface SigningKey { | |
| 25 | readonly kid: string; | |
| 26 | readonly privateJwk: Jwk; | |
| 27 | } | |
| 28 | ||
| 29 | interface Row { | |
| 30 | kid: string; | |
| 31 | private_enc: string; | |
| 32 | public_jwk: string; | |
| 33 | created_at: string; | |
| 34 | } | |
| 35 | ||
| 36 | /** Make a new current key now, whatever the age of the last one. */ | |
| 37 | export async function rotateKey( | |
| 38 | db: Database, | |
| 39 | dataDir: string, | |
| 40 | now: Date = new Date(), | |
| 41 | ): Promise<SigningKey> { | |
| 42 | const kid = id(); | |
| 43 | const { privateJwk, publicJwk } = await generateKeyPair(); | |
| 44 | db.query( | |
| 45 | "INSERT INTO oidc_key (kid, private_enc, public_jwk, created_at) VALUES (?1, ?2, ?3, ?4)", | |
| 46 | ).run( | |
| 47 | kid, | |
| 48 | seal(dataDir, JSON.stringify(privateJwk), `oidc_key:${kid}`), | |
| 49 | JSON.stringify(publicJwk), | |
| 50 | now.toISOString(), | |
| 51 | ); | |
| 52 | db.query("DELETE FROM oidc_key WHERE created_at <= ?1").run( | |
| 53 | new Date(now.getTime() - PUBLISHED_MS).toISOString(), | |
| 54 | ); | |
| 55 | return { kid, privateJwk }; | |
| 56 | } | |
| 57 | ||
| 58 | /** The key to sign with now: the newest, rotated first when it is due. */ | |
| 59 | export async function signingKey( | |
| 60 | db: Database, | |
| 61 | dataDir: string, | |
| 62 | now: Date = new Date(), | |
| 63 | ): Promise<SigningKey> { | |
| 64 | const row = db | |
| 65 | .query<Row, []>("SELECT * FROM oidc_key ORDER BY created_at DESC LIMIT 1") | |
| 66 | .get(); | |
| 67 | if (row !== null && Date.parse(row.created_at) > now.getTime() - ROTATE_MS) { | |
| 68 | const opened = open(dataDir, row.private_enc, `oidc_key:${row.kid}`); | |
| 69 | if (opened.ok) | |
| 70 | return { kid: row.kid, privateJwk: JSON.parse(opened.value) as Jwk }; | |
| 71 | // A key that no longer opens (the key file was replaced) is useless; | |
| 72 | // a fresh one is the only way to keep signing. | |
| 73 | } | |
| 74 | return rotateKey(db, dataDir, now); | |
| 75 | } | |
| 76 | ||
| 77 | /** The JWKS: every key a token in circulation may have been signed with. */ | |
| 78 | export function publishedKeys(db: Database, now: Date = new Date()): Jwk[] { | |
| 79 | return db | |
| 80 | .query<Row, [string]>( | |
| 81 | "SELECT * FROM oidc_key WHERE created_at > ?1 ORDER BY created_at DESC", | |
| 82 | ) | |
| 83 | .all(new Date(now.getTime() - PUBLISHED_MS).toISOString()) | |
| 84 | .map((row) => ({ | |
| 85 | ...(JSON.parse(row.public_jwk) as Jwk), | |
| 86 | kid: row.kid, | |
| 87 | alg: "ES256", | |
| 88 | use: "sig", | |
| 89 | })); | |
| 90 | } |
src/core/schema.ts +30
| @@ -1394,4 +1394,34 @@ export const migrations: readonly string[] = [ | ||
| 1394 | 1394 | ALTER TABLE look ADD COLUMN taken_as TEXT NOT NULL DEFAULT 'owner' |
| 1395 | 1395 | CHECK (taken_as IN ('owner','nobody')); |
| 1396 | 1396 | `, |
| 1397 | // 61 — one authorization server (#574, #666). A code is the one-use, | |
| 1398 | // hashed, minute-long step between a person's consent and a token; an | |
| 1399 | // OpenID signing key is sealed under the data directory's key and | |
| 1400 | // rotated by age. A token remembers the client it was minted for, the | |
| 1401 | // OpenID scopes it answers `userinfo` with, and whether it reaches the | |
| 1402 | // API at all — a hosted app's sign-in token does not. | |
| 1403 | ` | |
| 1404 | CREATE TABLE IF NOT EXISTS oauth_code ( | |
| 1405 | code_hash TEXT PRIMARY KEY, | |
| 1406 | client_id TEXT NOT NULL REFERENCES oauth_client(id) ON DELETE CASCADE, | |
| 1407 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 1408 | redirect_uri TEXT NOT NULL, | |
| 1409 | scope TEXT CHECK (scope IS NULL OR scope IN ('ro','rw','admin')), | |
| 1410 | claims TEXT NOT NULL, | |
| 1411 | challenge TEXT NOT NULL, | |
| 1412 | nonce TEXT, | |
| 1413 | name TEXT NOT NULL, | |
| 1414 | auth_time INTEGER NOT NULL, | |
| 1415 | expires_at TEXT NOT NULL | |
| 1416 | ); | |
| 1417 | CREATE TABLE IF NOT EXISTS oidc_key ( | |
| 1418 | kid TEXT PRIMARY KEY, | |
| 1419 | private_enc TEXT NOT NULL, | |
| 1420 | public_jwk TEXT NOT NULL, | |
| 1421 | created_at TEXT NOT NULL | |
| 1422 | ); | |
| 1423 | ALTER TABLE token ADD COLUMN client_id TEXT REFERENCES oauth_client(id) ON DELETE SET NULL; | |
| 1424 | ALTER TABLE token ADD COLUMN claims TEXT NOT NULL DEFAULT ''; | |
| 1425 | ALTER TABLE token ADD COLUMN api INTEGER NOT NULL DEFAULT 1; | |
| 1426 | `, | |
| 1397 | 1427 | ]; |
src/core/tokens.ts +74 −7
| @@ -26,6 +26,21 @@ export interface TokenInfo { | ||
| 26 | 26 | readonly lastUsedAt: string | null; |
| 27 | 27 | /** When the token stops working, or null for a token that does not. */ |
| 28 | 28 | readonly expiresAt: string | null; |
| 29 | /** The OAuth client it was minted for, or null for one made by hand. */ | |
| 30 | readonly client: string | null; | |
| 31 | /** False for a sign-in token: it answers `userinfo` and nothing else. */ | |
| 32 | readonly api: boolean; | |
| 33 | } | |
| 34 | ||
| 35 | /** What a token was minted for, beyond its owner, name and scope. */ | |
| 36 | export interface TokenOptions { | |
| 37 | readonly expiresAt?: string; | |
| 38 | /** The OAuth client that asked for it (`core/oauth.ts`). */ | |
| 39 | readonly clientId?: string; | |
| 40 | /** OpenID scopes it answers `userinfo` with: `openid profile email`. */ | |
| 41 | readonly claims?: readonly string[]; | |
| 42 | /** False mints a sign-in token the API refuses. Default true. */ | |
| 43 | readonly api?: boolean; | |
| 29 | 44 | } |
| 30 | 45 | |
| 31 | 46 | /** |
| @@ -38,13 +53,23 @@ export function createToken( | ||
| 38 | 53 | userId: string, |
| 39 | 54 | name: string, |
| 40 | 55 | scope: TokenScope, |
| 41 | options: { expiresAt?: string } = {}, | |
| 56 | options: TokenOptions = {}, | |
| 42 | 57 | ): { id: string; token: string } { |
| 43 | 58 | const tokenId = id(); |
| 44 | 59 | const token = `forge_${secret()}`; |
| 45 | 60 | db.query( |
| 46 | "INSERT INTO token (id, token_hash, user_id, name, scope, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | |
| 47 | ).run(tokenId, sha256(token), userId, name, scope, options.expiresAt ?? null); | |
| 61 | "INSERT INTO token (id, token_hash, user_id, name, scope, expires_at, client_id, claims, api) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | |
| 62 | ).run( | |
| 63 | tokenId, | |
| 64 | sha256(token), | |
| 65 | userId, | |
| 66 | name, | |
| 67 | scope, | |
| 68 | options.expiresAt ?? null, | |
| 69 | options.clientId ?? null, | |
| 70 | (options.claims ?? []).join(" "), | |
| 71 | options.api === false ? 0 : 1, | |
| 72 | ); | |
| 48 | 73 | return { id: tokenId, token }; |
| 49 | 74 | } |
| 50 | 75 | |
| @@ -62,10 +87,20 @@ export function createToken( | ||
| 62 | 87 | */ |
| 63 | 88 | const TOUCH_EVERY_MS = 60_000; |
| 64 | 89 | |
| 90 | /** | |
| 91 | * The account and scope behind a presented secret. Every use reads the | |
| 92 | * row, so a revoked token stops working on the next request — there is no | |
| 93 | * cache to outlive a DELETE. `userinfo` is the one caller that also takes | |
| 94 | * a sign-in token; everything else asks for `api`. | |
| 95 | */ | |
| 65 | 96 | export function verifyToken( |
| 66 | 97 | db: Database, |
| 67 | 98 | presented: string, |
| 68 | ): Result<{ user: User; scope: TokenScope }, "invalid_token"> { | |
| 99 | purpose: "api" | "userinfo" = "api", | |
| 100 | ): Result< | |
| 101 | { user: User; scope: TokenScope; claims: string[]; clientId: string | null }, | |
| 102 | "invalid_token" | |
| 103 | > { | |
| 69 | 104 | const row = db |
| 70 | 105 | .query< |
| 71 | 106 | { |
| @@ -74,13 +109,17 @@ export function verifyToken( | ||
| 74 | 109 | scope: TokenScope; |
| 75 | 110 | last_used_at: string | null; |
| 76 | 111 | expires_at: string | null; |
| 112 | client_id: string | null; | |
| 113 | claims: string; | |
| 114 | api: number; | |
| 77 | 115 | }, |
| 78 | 116 | [string] |
| 79 | 117 | >( |
| 80 | "SELECT id, user_id, scope, last_used_at, expires_at FROM token WHERE token_hash = ?1", | |
| 118 | "SELECT id, user_id, scope, last_used_at, expires_at, client_id, claims, api FROM token WHERE token_hash = ?1", | |
| 81 | 119 | ) |
| 82 | 120 | .get(sha256(presented)); |
| 83 | 121 | if (!row) return err("invalid_token"); |
| 122 | if (purpose === "api" && row.api !== 1) return err("invalid_token"); | |
| 84 | 123 | // Expiry is decided here, on every use, not by the sweep: a sweep that |
| 85 | 124 | // runs late must not be a token that works late. |
| 86 | 125 | if (row.expires_at !== null && Date.parse(row.expires_at) <= Date.now()) |
| @@ -96,7 +135,12 @@ export function verifyToken( | ||
| 96 | 135 | row.id, |
| 97 | 136 | ); |
| 98 | 137 | } |
| 99 | return ok({ user, scope: row.scope }); | |
| 138 | return ok({ | |
| 139 | user, | |
| 140 | scope: row.scope, | |
| 141 | claims: row.claims === "" ? [] : row.claims.split(" "), | |
| 142 | clientId: row.client_id, | |
| 143 | }); | |
| 100 | 144 | } |
| 101 | 145 | |
| 102 | 146 | export function listTokens(db: Database, userId: string): TokenInfo[] { |
| @@ -109,10 +153,15 @@ export function listTokens(db: Database, userId: string): TokenInfo[] { | ||
| 109 | 153 | created_at: string; |
| 110 | 154 | last_used_at: string | null; |
| 111 | 155 | expires_at: string | null; |
| 156 | client: string | null; | |
| 157 | api: number; | |
| 112 | 158 | }, |
| 113 | 159 | [string] |
| 114 | 160 | >( |
| 115 | "SELECT id, name, scope, created_at, last_used_at, expires_at FROM token WHERE user_id = ?1 ORDER BY id", | |
| 161 | `SELECT t.id, t.name, t.scope, t.created_at, t.last_used_at, t.expires_at, | |
| 162 | c.name AS client, t.api | |
| 163 | FROM token t LEFT JOIN oauth_client c ON c.id = t.client_id | |
| 164 | WHERE t.user_id = ?1 ORDER BY t.id`, | |
| 116 | 165 | ) |
| 117 | 166 | .all(userId); |
| 118 | 167 | return rows.map((r) => ({ |
| @@ -122,6 +171,8 @@ export function listTokens(db: Database, userId: string): TokenInfo[] { | ||
| 122 | 171 | createdAt: r.created_at, |
| 123 | 172 | lastUsedAt: r.last_used_at, |
| 124 | 173 | expiresAt: r.expires_at, |
| 174 | client: r.client, | |
| 175 | api: r.api === 1, | |
| 125 | 176 | })); |
| 126 | 177 | } |
| 127 | 178 | |
| @@ -155,6 +206,22 @@ export function revokeToken(db: Database, tokenId: string): boolean { | ||
| 155 | 206 | return db.query("DELETE FROM token WHERE id = ?1").run(tokenId).changes > 0; |
| 156 | 207 | } |
| 157 | 208 | |
| 209 | /** | |
| 210 | * Remove the token whose secret this is (RFC 7009). Holding the secret is | |
| 211 | * the authority: whoever could use it may also end it. | |
| 212 | */ | |
| 213 | export function revokePresented( | |
| 214 | db: Database, | |
| 215 | presented: string, | |
| 216 | ): { id: string; userId: string } | undefined { | |
| 217 | const row = db | |
| 218 | .query<{ id: string; user_id: string }, [string]>( | |
| 219 | "DELETE FROM token WHERE token_hash = ?1 RETURNING id, user_id", | |
| 220 | ) | |
| 221 | .get(sha256(presented)); | |
| 222 | return row === null ? undefined : { id: row.id, userId: row.user_id }; | |
| 223 | } | |
| 224 | ||
| 158 | 225 | /** |
| 159 | 226 | * Move an expiring token's expiry. A credential held by something that |
| 160 | 227 | * lives as long as it is wanted — a running app — is kept short and |
src/http/api.ts +17 −1
| @@ -8,7 +8,11 @@ | ||
| 8 | 8 | * back to continue); errors are `{ error, message }`. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { accountSignIns, endAccountSession } from "../actions/signins.ts"; | |
| 11 | import { | |
| 12 | accountSignIns, | |
| 13 | endAccountSession, | |
| 14 | revokeAccountToken, | |
| 15 | } from "../actions/signins.ts"; | |
| 12 | 16 | import { STRANGER_MAX } from "./limits.ts"; |
| 13 | 17 | import { |
| 14 | 18 | askedIn, |
| @@ -1281,6 +1285,18 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1281 | 1285 | return json({ tokens: seen.value.tokens, sessions: seen.value.sessions }); |
| 1282 | 1286 | }); |
| 1283 | 1287 | |
| 1288 | router.add("DELETE", "/api/v1/users/:username/tokens/:id", (ctx) => { | |
| 1289 | const denied = requireAccount(ctx, { adminToken: true }); | |
| 1290 | if (denied) return denied; | |
| 1291 | const done = revokeAccountToken( | |
| 1292 | ctx.app, | |
| 1293 | ctx.auth.user, | |
| 1294 | ctx.params.username!, | |
| 1295 | ctx.params.id!, | |
| 1296 | ); | |
| 1297 | return done.ok ? new Response(null, { status: 204 }) : notFound(); | |
| 1298 | }); | |
| 1299 | ||
| 1284 | 1300 | router.add("DELETE", "/api/v1/users/:username/sessions/:id", (ctx) => { |
| 1285 | 1301 | const denied = requireAccount(ctx, { adminToken: true }); |
| 1286 | 1302 | if (denied) return denied; |
src/http/oauth.ts +145 −22
| @@ -1,16 +1,27 @@ | ||
| 1 | 1 | /** |
| 2 | * OAuth discovery for the MCP, step one: the two well-known documents and | |
| 3 | * dynamic client registration. The authorize page and the token endpoint | |
| 4 | * the documents name come next; until then a client can find the forge and | |
| 5 | * register, and still signs in with a bearer token. | |
| 2 | * The forge's one authorization server, as HTTP: discovery (OAuth and | |
| 3 | * OpenID), dynamic client registration, the token endpoint, revocation, | |
| 4 | * `userinfo` and the JWKS. The consent page it sends people to is | |
| 5 | * `web/pages/oauth.ts`. Every caller — an MCP client, a hosted app signing | |
| 6 | * a person in, another forge — goes through the same endpoints and gets a | |
| 7 | * row in the same `token` table Settings lists. | |
| 6 | 8 | * |
| 7 | * Registration takes no cookie and grants nothing, so there is no ambient | |
| 8 | * authority for a cross-site page to ride; it is limited per address instead. | |
| 9 | * None of these endpoints reads a cookie, so there is no ambient authority | |
| 10 | * for a cross-site page to ride: they answer any origin. Registration is | |
| 11 | * limited per address; a code or token is a 256-bit secret, so guessing one | |
| 12 | * is not a thing a rate limit needs to stop. | |
| 9 | 13 | */ |
| 10 | 14 | import type { App } from "../app.ts"; |
| 15 | import { exchange, revokeHeld } from "../actions/oauth.ts"; | |
| 11 | 16 | import { createClient, parseRegistration } from "../core/oauth.ts"; |
| 17 | import { OIDC_SCOPES } from "../core/oauth_codes.ts"; | |
| 18 | import { userClaims } from "../core/oidc.ts"; | |
| 19 | import { publishedKeys, signingKey } from "../core/oidc_keys.ts"; | |
| 20 | import { verifyToken } from "../core/tokens.ts"; | |
| 21 | import { authorizePage, authorizeSubmit } from "../web/pages/oauth.ts"; | |
| 12 | 22 | import { RateLimiter } from "../core/ratelimit.ts"; |
| 13 | import type { Handler } from "./context.ts"; | |
| 23 | import type { Ctx, Handler } from "./context.ts"; | |
| 24 | import { readBounded } from "./limits.ts"; | |
| 14 | 25 | import { clientBucket } from "./peer.ts"; |
| 15 | 26 | import { boundedBody, json } from "./respond.ts"; |
| 16 | 27 | import type { Router } from "./router.ts"; |
| @@ -39,6 +50,61 @@ export const resourceMetadataUrl = (origin: string): string => | ||
| 39 | 50 | |
| 40 | 51 | const open = { "access-control-allow-origin": "*" }; |
| 41 | 52 | const docHeaders = { ...open, "cache-control": "public, max-age=300" }; |
| 53 | const noStore = { ...open, "cache-control": "no-store", pragma: "no-cache" }; | |
| 54 | ||
| 55 | /** Every scope the server grants: the forge's three and OpenID's. */ | |
| 56 | const SCOPES = ["ro", "rw", "admin", ...OIDC_SCOPES]; | |
| 57 | ||
| 58 | /** The authorization server's metadata (RFC 8414), shared by both documents. */ | |
| 59 | const serverMetadata = (origin: string) => ({ | |
| 60 | issuer: origin, | |
| 61 | authorization_endpoint: `${origin}/oauth/authorize`, | |
| 62 | token_endpoint: `${origin}/oauth/token`, | |
| 63 | registration_endpoint: `${origin}/oauth/register`, | |
| 64 | revocation_endpoint: `${origin}/oauth/revoke`, | |
| 65 | userinfo_endpoint: `${origin}/oauth/userinfo`, | |
| 66 | jwks_uri: `${origin}/oauth/jwks`, | |
| 67 | scopes_supported: SCOPES, | |
| 68 | response_types_supported: ["code"], | |
| 69 | response_modes_supported: ["query"], | |
| 70 | grant_types_supported: ["authorization_code"], | |
| 71 | code_challenge_methods_supported: ["S256"], | |
| 72 | token_endpoint_auth_methods_supported: ["none"], | |
| 73 | revocation_endpoint_auth_methods_supported: ["none"], | |
| 74 | subject_types_supported: ["public"], | |
| 75 | id_token_signing_alg_values_supported: ["ES256"], | |
| 76 | claims_supported: [ | |
| 77 | "sub", "iss", "aud", "exp", "iat", "auth_time", "nonce", | |
| 78 | "preferred_username", "name", "profile", "email", "email_verified", | |
| 79 | ], | |
| 80 | authorization_response_iss_parameter_supported: true, | |
| 81 | }); | |
| 82 | ||
| 83 | /** | |
| 84 | * A token or revocation request's parameters: a form body (what RFC 6749 | |
| 85 | * names), or JSON for the clients that send it anyway. Anything else, or | |
| 86 | * anything past the size cap, is no parameters at all. | |
| 87 | */ | |
| 88 | async function params(request: Request): Promise<(name: string) => string> { | |
| 89 | const type = request.headers.get("content-type") ?? ""; | |
| 90 | if (type.startsWith("application/x-www-form-urlencoded")) { | |
| 91 | const bytes = await readBounded(request, BODY_MAX); | |
outdated
High: |
||
| 92 | if (bytes === "too_large") return () => ""; | |
| 93 | const form = new URLSearchParams(new TextDecoder().decode(bytes)); | |
| 94 | return (name) => form.get(name) ?? ""; | |
| 95 | } | |
| 96 | const raw = await boundedBody(request, BODY_MAX); | |
| 97 | if (raw === "too_large") return () => ""; | |
| 98 | return (name) => { | |
| 99 | const value = raw[name]; | |
| 100 | return typeof value === "string" ? value : ""; | |
| 101 | }; | |
| 102 | } | |
| 103 | ||
| 104 | const bearer = (request: Request): string | undefined => { | |
| 105 | const header = request.headers.get("authorization") ?? ""; | |
| 106 | return header.startsWith("Bearer ") ? header.slice(7).trim() : undefined; | |
| 107 | }; | |
| 42 | 108 | |
| 43 | 109 | export function oauthRoutes(router: Router<Handler>): void { |
| 44 | 110 | router.add("GET", "/.well-known/oauth-protected-resource", (ctx) => |
| @@ -54,22 +120,79 @@ export function oauthRoutes(router: Router<Handler>): void { | ||
| 54 | 120 | ), |
| 55 | 121 | ); |
| 56 | 122 | router.add("GET", "/.well-known/oauth-authorization-server", (ctx) => |
| 57 | json( | |
| 58 | { | |
| 59 | issuer: ctx.url.origin, | |
| 60 | authorization_endpoint: `${ctx.url.origin}/oauth/authorize`, | |
| 61 | token_endpoint: `${ctx.url.origin}/oauth/token`, | |
| 62 | registration_endpoint: `${ctx.url.origin}/oauth/register`, | |
| 63 | scopes_supported: ["ro", "rw"], | |
| 64 | response_types_supported: ["code"], | |
| 65 | grant_types_supported: ["authorization_code"], | |
| 66 | code_challenge_methods_supported: ["S256"], | |
| 67 | token_endpoint_auth_methods_supported: ["none"], | |
| 68 | }, | |
| 69 | 200, | |
| 70 | docHeaders, | |
| 71 | ), | |
| 123 | json(serverMetadata(ctx.url.origin), 200, docHeaders), | |
| 72 | 124 | ); |
| 125 | router.add("GET", "/.well-known/openid-configuration", (ctx) => | |
| 126 | json(serverMetadata(ctx.url.origin), 200, docHeaders), | |
| 127 | ); | |
| 128 | router.add("GET", "/oauth/authorize", authorizePage); | |
| 129 | router.add("POST", "/oauth/authorize", authorizeSubmit); | |
| 130 | ||
| 131 | router.add("POST", "/oauth/token", async (ctx) => { | |
| 132 | const get = await params(ctx.request); | |
| 133 | const refuse = (error: string, error_description: string) => | |
| 134 | json({ error, error_description }, 400, noStore); | |
| 135 | if (get("grant_type") !== "authorization_code") | |
| 136 | return refuse("unsupported_grant_type", "only authorization_code is offered"); | |
| 137 | const presented = { | |
| 138 | code: get("code"), | |
| 139 | clientId: get("client_id"), | |
| 140 | redirectUri: get("redirect_uri"), | |
| 141 | verifier: get("code_verifier"), | |
| 142 | }; | |
| 143 | if (Object.values(presented).some((v) => v === "")) | |
| 144 | return refuse("invalid_request", "code, client_id, redirect_uri and code_verifier are required"); | |
| 145 | const issued = await exchange(ctx.app, ctx.url.origin, presented); | |
| 146 | if (!issued.ok) | |
| 147 | return refuse("invalid_grant", "the code is unknown, used, expired, or does not match"); | |
| 148 | return json(issued.value, 200, noStore); | |
| 149 | }); | |
| 150 | ||
| 151 | router.add("POST", "/oauth/revoke", async (ctx) => { | |
| 152 | const get = await params(ctx.request); | |
| 153 | const token = get("token"); | |
| 154 | if (token !== "") revokeHeld(ctx.app, token); | |
| 155 | return new Response(null, { status: 200, headers: noStore }); | |
| 156 | }); | |
| 157 | ||
| 158 | const userinfo = (ctx: Ctx): Response => { | |
| 159 | const presented = bearer(ctx.request); | |
| 160 | const verified = | |
| 161 | presented === undefined | |
| 162 | ? undefined | |
| 163 | : verifyToken(ctx.app.db, presented, "userinfo"); | |
| 164 | if (verified === undefined || !verified.ok) | |
| 165 | return json({ error: "invalid_token" }, 401, { | |
| 166 | ...noStore, | |
| 167 | "www-authenticate": 'Bearer error="invalid_token"', | |
| 168 | }); | |
| 169 | if (!verified.value.claims.includes("openid")) | |
| 170 | return json({ error: "insufficient_scope" }, 403, { | |
| 171 | ...noStore, | |
| 172 | "www-authenticate": 'Bearer error="insufficient_scope", scope="openid"', | |
| 173 | }); | |
| 174 | return json( | |
| 175 | userClaims( | |
| 176 | verified.value.user, | |
| 177 | verified.value.claims as (typeof OIDC_SCOPES)[number][], | |
| 178 | ctx.url.origin, | |
| 179 | ), | |
| 180 | 200, | |
| 181 | noStore, | |
| 182 | ); | |
| 183 | }; | |
| 184 | router.add("GET", "/oauth/userinfo", userinfo); | |
| 185 | router.add("POST", "/oauth/userinfo", userinfo); | |
| 186 | ||
| 187 | router.add("GET", "/oauth/jwks", async (ctx) => { | |
| 188 | let keys = publishedKeys(ctx.app.db); | |
| 189 | if (keys.length === 0) { | |
| 190 | await signingKey(ctx.app.db, ctx.app.config.dataDir); | |
| 191 | keys = publishedKeys(ctx.app.db); | |
| 192 | } | |
| 193 | return json({ keys }, 200, docHeaders); | |
| 194 | }); | |
| 195 | ||
| 73 | 196 | router.add("POST", "/oauth/register", async (ctx) => { |
| 74 | 197 | const verdict = limiterOf(ctx.app).take(clientBucket(ctx.request), "ro"); |
| 75 | 198 | if (!verdict.allowed) |
src/kernel/jwt.ts added +94
| @@ -0,0 +1,94 @@ | ||
| 1 | /** | |
| 2 | * JSON Web Tokens signed with ES256 (RFC 7515 + RFC 7518 §3.4), through | |
| 3 | * WebCrypto and nothing else. ES256 because it is the one algorithm every | |
| 4 | * OpenID Connect library verifies, its keys are small, and WebCrypto's | |
| 5 | * ECDSA signature is already the raw `r || s` form a JWS carries. | |
| 6 | * | |
| 7 | * Verification names the one algorithm it accepts: a header saying `none` | |
| 8 | * or `HS256` is refused, never obeyed. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { webcrypto } from "node:crypto"; | |
| 12 | ||
| 13 | export type Jwk = webcrypto.JsonWebKey & { kid?: string }; | |
| 14 | ||
| 15 | const ALG = { name: "ECDSA", namedCurve: "P-256" } as const; | |
| 16 | const SIGN = { name: "ECDSA", hash: "SHA-256" } as const; | |
| 17 | ||
| 18 | const b64url = (bytes: Uint8Array | string): string => | |
| 19 | Buffer.from(bytes).toString("base64url"); | |
| 20 | ||
| 21 | /** A fresh P-256 key pair, both halves as JWK. */ | |
| 22 | export async function generateKeyPair(): Promise<{ | |
| 23 | privateJwk: Jwk; | |
| 24 | publicJwk: Jwk; | |
| 25 | }> { | |
| 26 | const pair = (await crypto.subtle.generateKey(ALG, true, [ | |
| 27 | "sign", | |
| 28 | "verify", | |
| 29 | ])) as CryptoKeyPair; | |
| 30 | const privateJwk = (await crypto.subtle.exportKey( | |
| 31 | "jwk", | |
| 32 | pair.privateKey, | |
| 33 | )) as Jwk; | |
| 34 | const full = (await crypto.subtle.exportKey("jwk", pair.publicKey)) as Jwk; | |
| 35 | // Only the members a public JWK needs: nothing a verifier could misread. | |
| 36 | const publicJwk: Jwk = { kty: full.kty!, crv: full.crv!, x: full.x!, y: full.y! }; | |
| 37 | return { privateJwk, publicJwk }; | |
| 38 | } | |
| 39 | ||
| 40 | /** `header.payload.signature`, the header carrying `kid`. */ | |
| 41 | export async function signJwt( | |
| 42 | claims: Record<string, unknown>, | |
| 43 | privateJwk: Jwk, | |
| 44 | kid: string, | |
| 45 | ): Promise<string> { | |
| 46 | const key = await crypto.subtle.importKey("jwk", privateJwk, ALG, false, [ | |
| 47 | "sign", | |
| 48 | ]); | |
| 49 | const head = b64url(JSON.stringify({ alg: "ES256", typ: "JWT", kid })); | |
| 50 | const body = b64url(JSON.stringify(claims)); | |
| 51 | const signature = await crypto.subtle.sign( | |
| 52 | SIGN, | |
| 53 | key, | |
| 54 | new TextEncoder().encode(`${head}.${body}`), | |
| 55 | ); | |
| 56 | return `${head}.${body}.${b64url(new Uint8Array(signature))}`; | |
| 57 | } | |
| 58 | ||
| 59 | /** | |
| 60 | * The claims of a token one of `keys` signed with ES256, or undefined. | |
| 61 | * Checks the signature only; `exp`, `aud` and `iss` are the caller's. | |
| 62 | */ | |
| 63 | export async function verifyJwt( | |
| 64 | token: string, | |
| 65 | keys: readonly Jwk[], | |
| 66 | ): Promise<Record<string, unknown> | undefined> { | |
| 67 | const parts = token.split("."); | |
| 68 | if (parts.length !== 3) return undefined; | |
| 69 | const [head, body, signature] = parts as [string, string, string]; | |
| 70 | let header: { alg?: unknown; kid?: unknown }; | |
| 71 | let claims: unknown; | |
| 72 | try { | |
| 73 | header = JSON.parse(Buffer.from(head, "base64url").toString()); | |
| 74 | claims = JSON.parse(Buffer.from(body, "base64url").toString()); | |
| 75 | } catch { | |
| 76 | return undefined; | |
| 77 | } | |
| 78 | if (header.alg !== "ES256") return undefined; | |
| 79 | if (claims === null || typeof claims !== "object" || Array.isArray(claims)) | |
| 80 | return undefined; | |
| 81 | const jwk = keys.find((k) => k.kid === header.kid); | |
| 82 | if (jwk === undefined) return undefined; | |
| 83 | const { kid: _kid, alg: _alg, use: _use, ...bare } = jwk; | |
| 84 | const key = await crypto.subtle.importKey("jwk", bare, ALG, false, [ | |
| 85 | "verify", | |
| 86 | ]); | |
| 87 | const ok = await crypto.subtle.verify( | |
| 88 | SIGN, | |
| 89 | key, | |
| 90 | Buffer.from(signature, "base64url"), | |
| 91 | new TextEncoder().encode(`${head}.${body}`), | |
| 92 | ); | |
| 93 | return ok ? (claims as Record<string, unknown>) : undefined; | |
| 94 | } |
src/web/pages/account.ts +9 −2
| @@ -475,8 +475,15 @@ function tokensView(ctx: Ctx): Html { | ||
| 475 | 475 | ${tokens.map( |
| 476 | 476 | (t) => |
| 477 | 477 | html`<tr> |
| 478 | <td><strong>${t.name}</strong></td> | |
| 479 | <td>${badge(t.scope)}</td> | |
| 478 | <td> | |
| 479 | <strong>${t.name}</strong> | |
| 480 | ${when( | |
| 481 | t.client, | |
| 482 | (client) => | |
| 483 | html`<span class="muted small">via ${client}</span>`, | |
| 484 | )} | |
| 485 | </td> | |
| 486 | <td>${badge(t.api ? t.scope : "sign-in")}</td> | |
| 480 | 487 | <td class="muted">${time(t.createdAt)}</td> |
| 481 | 488 | <td class="muted"> |
| 482 | 489 | ${t.lastUsedAt ? time(t.lastUsedAt) : "never"} |
src/web/pages/oauth.ts added +296
| @@ -0,0 +1,296 @@ | ||
| 1 | /** | |
| 2 | * The consent page: `GET /oauth/authorize` asks a signed-in person whether | |
| 3 | * a client may act as them (or, for OpenID scopes alone, learn who they | |
| 4 | * are), and `POST` records the answer and sends them back with a code. | |
| 5 | * | |
| 6 | * Nothing redirects anywhere until the client and its redirect URI are | |
| 7 | * known to match a registration exactly; before that, a broken request is | |
| 8 | * a page here, never a hop to a URL someone wrote (RFC 6749 §4.1.2.1). | |
| 9 | * The POST is same-origin checked and takes only a cookie-signed-in | |
| 10 | * person — a token never mints another token. | |
| 11 | */ | |
| 12 | ||
| 13 | import { consent } from "../../actions/oauth.ts"; | |
| 14 | import { getClient, type OAuthClient } from "../../core/oauth.ts"; | |
| 15 | import { | |
| 16 | FORGE_SCOPES, | |
| 17 | parseScope, | |
| 18 | type Requested, | |
| 19 | } from "../../core/oauth_codes.ts"; | |
| 20 | import { scopeAllows, type TokenScope } from "../../core/tokens.ts"; | |
| 21 | import type { Ctx } from "../../http/context.ts"; | |
| 22 | import { signInFirst } from "../chrome.ts"; | |
| 23 | import { field, readForm } from "../form.ts"; | |
| 24 | import { html, when } from "../html.ts"; | |
| 25 | import { page, redirect } from "../layout.ts"; | |
| 26 | import { btn, card, selectField, field as uiField } from "../ui.ts"; | |
| 27 | ||
| 28 | const STATE_MAX = 1024; | |
| 29 | const NONCE_MAX = 256; | |
| 30 | const NAME_MAX = 100; | |
| 31 | ||
| 32 | export interface AuthorizeRequest { | |
| 33 | readonly client: OAuthClient; | |
| 34 | readonly redirectUri: string; | |
| 35 | readonly state: string | null; | |
| 36 | readonly requested: Requested; | |
| 37 | readonly challenge: string; | |
| 38 | readonly nonce: string | null; | |
| 39 | readonly prompt: string | null; | |
| 40 | } | |
| 41 | ||
| 42 | /** Why a request is refused, and whether the client may hear it. */ | |
| 43 | type Refused = | |
| 44 | | { readonly to: "page"; readonly message: string } | |
| 45 | | { | |
| 46 | readonly to: "client"; | |
| 47 | readonly redirectUri: string; | |
| 48 | readonly state: string | null; | |
| 49 | readonly error: string; | |
| 50 | readonly message: string; | |
| 51 | }; | |
| 52 | ||
| 53 | type Read = (name: string) => string | null; | |
| 54 | ||
| 55 | /** Read and check an authorization request from a query or a form. */ | |
| 56 | export function parseAuthorize( | |
| 57 | ctx: Ctx, | |
| 58 | get: Read, | |
| 59 | ): { ok: true; value: AuthorizeRequest } | { ok: false; error: Refused } { | |
| 60 | const client = getClient(ctx.app.db, get("client_id") ?? ""); | |
| 61 | if (client === null) | |
| 62 | return { ok: false, error: { to: "page", message: "This app is not registered with the forge." } }; | |
| 63 | const asked = get("redirect_uri"); | |
| 64 | const redirectUri = | |
| 65 | asked === null && client.redirectUris.length === 1 | |
| 66 | ? client.redirectUris[0]! | |
| 67 | : asked; | |
| 68 | if (redirectUri === null || !client.redirectUris.includes(redirectUri)) | |
| 69 | return { | |
| 70 | ok: false, | |
| 71 | error: { to: "page", message: "The address this app asked to return to is not one it registered." }, | |
| 72 | }; | |
| 73 | const state = get("state"); | |
| 74 | const back = (error: string, message: string) => ({ | |
| 75 | ok: false as const, | |
| 76 | error: { | |
| 77 | to: "client" as const, | |
| 78 | redirectUri, | |
| 79 | state: state !== null && state.length <= STATE_MAX ? state : null, | |
| 80 | error, | |
| 81 | message, | |
| 82 | }, | |
| 83 | }); | |
| 84 | if (state !== null && state.length > STATE_MAX) | |
| 85 | return back("invalid_request", "state is too long"); | |
| 86 | if (get("response_type") !== "code") | |
| 87 | return back("unsupported_response_type", "only response_type=code is offered"); | |
| 88 | const challenge = get("code_challenge") ?? ""; | |
| 89 | if (get("code_challenge_method") !== "S256" || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) | |
| 90 | return back("invalid_request", "PKCE with code_challenge_method=S256 is required"); | |
| 91 | const requested = parseScope(get("scope")); | |
| 92 | if (!requested.ok) return back("invalid_scope", requested.error); | |
| 93 | const nonce = get("nonce"); | |
| 94 | if (nonce !== null && nonce.length > NONCE_MAX) | |
| 95 | return back("invalid_request", "nonce is too long"); | |
| 96 | return { | |
| 97 | ok: true, | |
| 98 | value: { | |
| 99 | client, | |
| 100 | redirectUri, | |
| 101 | state, | |
| 102 | requested: requested.value, | |
| 103 | challenge, | |
| 104 | nonce, | |
| 105 | prompt: get("prompt"), | |
| 106 | }, | |
| 107 | }; | |
| 108 | } | |
| 109 | ||
| 110 | /** The client's redirect URI with these answers in its query. */ | |
| 111 | function backTo( | |
| 112 | redirectUri: string, | |
| 113 | params: Record<string, string | null>, | |
| 114 | issuer: string, | |
| 115 | ): Response { | |
| 116 | const url = new URL(redirectUri); | |
| 117 | for (const [key, value] of Object.entries(params)) | |
| 118 | if (value !== null) url.searchParams.set(key, value); | |
| 119 | // RFC 9207: the client learns which server answered, so a mix-up is caught. | |
| 120 | url.searchParams.set("iss", issuer); | |
| 121 | return redirect(url.toString()); | |
| 122 | } | |
| 123 | ||
| 124 | function refusedPage(ctx: Ctx, message: string): Response { | |
| 125 | return page( | |
| 126 | { | |
| 127 | ctx, | |
| 128 | title: "Sign-in link refused", | |
| 129 | body: card( | |
| 130 | html`<h2>This sign-in link cannot be used</h2> | |
| 131 | <p class="muted">${message}</p> | |
| 132 | <p class="muted small">Go back to the app and start again.</p>`, | |
| 133 | ), | |
| 134 | }, | |
| 135 | 400, | |
| 136 | ); | |
| 137 | } | |
| 138 | ||
| 139 | function refuse(ctx: Ctx, error: Refused): Response { | |
| 140 | if (error.to === "page") return refusedPage(ctx, error.message); | |
| 141 | return backTo( | |
| 142 | error.redirectUri, | |
| 143 | { error: error.error, error_description: error.message, state: error.state }, | |
| 144 | ctx.url.origin, | |
| 145 | ); | |
| 146 | } | |
| 147 | ||
| 148 | /** Only a person at a browser, with the forge's own cookie, may consent. */ | |
| 149 | const atBrowser = (ctx: Ctx): boolean => | |
| 150 | ctx.auth.user !== undefined && | |
| 151 | (ctx.auth.via === "session" || ctx.auth.via === "edge"); | |
| 152 | ||
| 153 | const SCOPE_WORDS: Record<TokenScope, string> = { | |
| 154 | ro: "read only — browse and clone what you can see", | |
| 155 | rw: "read + write — also push, open issues and pulls, tell the crew", | |
| 156 | admin: "admin — everything you can do, including settings", | |
| 157 | }; | |
| 158 | ||
| 159 | const CLAIM_WORDS: Record<string, string> = { | |
| 160 | openid: "who you are on this forge (an id that never changes)", | |
| 161 | profile: "your username and display name", | |
| 162 | email: "your email address", | |
| 163 | }; | |
| 164 | ||
| 165 | export function authorizePage(ctx: Ctx): Response { | |
| 166 | const parsed = parseAuthorize(ctx, (n) => ctx.url.searchParams.get(n)); | |
| 167 | if (!parsed.ok) return refuse(ctx, parsed.error); | |
| 168 | const req = parsed.value; | |
| 169 | if (!atBrowser(ctx)) { | |
| 170 | if (req.prompt === "none") | |
| 171 | return refuse(ctx, { | |
| 172 | to: "client", | |
| 173 | redirectUri: req.redirectUri, | |
| 174 | state: req.state, | |
| 175 | error: "login_required", | |
| 176 | message: "nobody is signed in", | |
| 177 | }); | |
| 178 | return signInFirst(ctx); | |
| 179 | } | |
| 180 | const user = ctx.auth.user!; | |
| 181 | if (user.kind !== "user") | |
| 182 | return refusedPage(ctx, "Only a person can allow an app."); | |
| 183 | const host = new URL(req.redirectUri).host; | |
| 184 | const asked = req.requested.scope; | |
| 185 | const hidden = ( | |
| 186 | <[string, string | null][]>[ | |
| 187 | ["client_id", req.client.id], | |
| 188 | ["redirect_uri", req.redirectUri], | |
| 189 | ["response_type", "code"], | |
| 190 | ["code_challenge", req.challenge], | |
| 191 | ["code_challenge_method", "S256"], | |
| 192 | ["scope", ctx.url.searchParams.get("scope") ?? ""], | |
| 193 | ["state", req.state], | |
| 194 | ["nonce", req.nonce], | |
| 195 | ] | |
| 196 | ).filter((p): p is [string, string] => p[1] !== null); | |
| 197 | const body = card( | |
| 198 | html`<form method="post" action="/oauth/authorize" class="stack"> | |
| 199 | <h2>${req.client.name} wants ${asked === null ? "you to sign in" : "to act as you"}</h2> | |
| 200 | <p class="muted"> | |
| 201 | Signed in as <strong>@${user.username}</strong>. After you answer you | |
| 202 | go back to <span class="mono">${host}</span>. | |
| 203 | </p> | |
| 204 | ${when( | |
| 205 | req.requested.claims.length > 0 ? req.requested.claims : undefined, | |
| 206 | (claims) => | |
| 207 | html`<p>It will learn:</p> | |
| 208 | <ul> | |
| 209 | ${claims.map((c) => html`<li>${CLAIM_WORDS[c] ?? c}</li>`)} | |
| 210 | </ul>`, | |
| 211 | )} | |
| 212 | ${hidden.map( | |
| 213 | ([name, value]) => html`<input type="hidden" name="${name}" value="${value}" />`, | |
| 214 | )} | |
| 215 | ${asked === null | |
| 216 | ? null | |
| 217 | : html`${selectField({ | |
| 218 | label: "Access", | |
| 219 | name: "access", | |
| 220 | options: FORGE_SCOPES.filter((s) => scopeAllows(asked, s)) | |
| 221 | .reverse() | |
| 222 | .map((s) => ({ value: s, label: SCOPE_WORDS[s], selected: s === asked })), | |
| 223 | hint: "You can give it less than it asked for, never more.", | |
| 224 | })} | |
| 225 | ${uiField({ | |
| 226 | label: "Token name", | |
| 227 | name: "name", | |
| 228 | value: req.client.name, | |
| 229 | required: true, | |
| 230 | hint: "How it is listed in Settings → Tokens, where you can revoke it.", | |
| 231 | })}`} | |
| 232 | <div class="form-actions"> | |
| 233 | ${btn(asked === null ? "Sign in" : "Allow", { | |
| 234 | variant: "primary", | |
| 235 | name: "decision", | |
| 236 | value: "allow", | |
| 237 | })} | |
| 238 | ${btn("Cancel", { name: "decision", value: "deny" })} | |
| 239 | </div> | |
| 240 | </form>`, | |
| 241 | ); | |
| 242 | const response = page({ ctx, title: `Allow ${req.client.name}?`, body }); | |
| 243 | // The answer is a redirect to the client; a page's CSP that allows forms | |
| 244 | // to post only here would stop the browser following it. | |
| 245 | const csp = response.headers.get("content-security-policy") ?? ""; | |
| 246 | response.headers.set( | |
| 247 | "content-security-policy", | |
| 248 | csp.replace( | |
| 249 | "form-action 'self'", | |
| 250 | `form-action 'self' ${new URL(req.redirectUri).origin}`, | |
| 251 | ), | |
| 252 | ); | |
| 253 | response.headers.set("cache-control", "no-store"); | |
| 254 | return response; | |
| 255 | } | |
| 256 | ||
| 257 | export async function authorizeSubmit(ctx: Ctx): Promise<Response> { | |
| 258 | const form = await readForm(ctx); | |
| 259 | if (form instanceof Response) return form; | |
| 260 | if (!atBrowser(ctx)) return new Response("forbidden", { status: 403 }); | |
| 261 | const parsed = parseAuthorize(ctx, (n) => { | |
| 262 | const value = form.get(n); | |
| 263 | return typeof value === "string" ? value : null; | |
| 264 | }); | |
| 265 | if (!parsed.ok) return refuse(ctx, parsed.error); | |
| 266 | const req = parsed.value; | |
| 267 | const answer = (error: string, message: string) => | |
| 268 | refuse(ctx, { | |
| 269 | to: "client", | |
| 270 | redirectUri: req.redirectUri, | |
| 271 | state: req.state, | |
| 272 | error, | |
| 273 | message, | |
| 274 | }); | |
| 275 | if (field(form, "decision") !== "allow") | |
| 276 | return answer("access_denied", "the person said no"); | |
| 277 | let scope = req.requested.scope; | |
| 278 | if (scope !== null) { | |
| 279 | const access = field(form, "access") as TokenScope; | |
| 280 | if (!FORGE_SCOPES.includes(access) || !scopeAllows(scope, access)) | |
| 281 | return answer("invalid_scope", "more access than was asked for"); | |
| 282 | scope = access; | |
| 283 | } | |
| 284 | // eslint-disable-next-line no-control-regex | |
| 285 | const name = field(form, "name").replace(/[\u0000-\u001f\u007f]/g, "").trim(); | |
| 286 | const code = consent(ctx.app, ctx.auth.user, { | |
| 287 | client: req.client, | |
| 288 | redirectUri: req.redirectUri, | |
| 289 | requested: { scope, claims: req.requested.claims }, | |
| 290 | challenge: req.challenge, | |
| 291 | nonce: req.nonce, | |
| 292 | name: (name === "" ? req.client.name : name).slice(0, NAME_MAX), | |
| 293 | }); | |
| 294 | if (!code.ok) return answer("access_denied", "this account cannot allow apps"); | |
| 295 | return backTo(req.redirectUri, { code: code.value, state: req.state }, ctx.url.origin); | |
| 296 | } |
test/authorization-server.test.ts added +322
| @@ -0,0 +1,322 @@ | ||
| 1 | /** | |
| 2 | * One authorization server (#574, #666): a private page signed in by the | |
| 3 | * forge alone, with no edge configured; the MCP's PKCE dance minting a | |
| 4 | * forge token; a hosted app signing a person in through OpenID Connect and | |
| 5 | * checking the id_token against the JWKS; key rotation; and revocation — | |
| 6 | * by the holder, the owner and the forge's owner — taking effect at once. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { signUp } from "../src/actions/users.ts"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { challengeOf, parseScope } from "../src/core/oauth_codes.ts"; | |
| 16 | import { rotateKey } from "../src/core/oidc_keys.ts"; | |
| 17 | import { verifyJwt, type Jwk } from "../src/kernel/jwt.ts"; | |
| 18 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 19 | ||
| 20 | const PASSWORD = "a-good-passphrase"; | |
| 21 | const VERIFIER = "v".repeat(20) + "-verifier-of-the-forty-three+chars".replace("+", "_"); | |
| 22 | const APP_CB = "http://notes.localhost:4000/auth/callback"; | |
| 23 | ||
| 24 | describe("one authorization server", () => { | |
| 25 | let dataDir: string; | |
| 26 | let app: App; | |
| 27 | let servers: Servers; | |
| 28 | let base: string; | |
| 29 | let owner: string; // cookie of the forge's owner (first account) | |
| 30 | let bob: string; // cookie of a second person | |
| 31 | ||
| 32 | const signIn = async (username: string): Promise<string> => { | |
| 33 | const res = await fetch(`${base}/signin`, { | |
| 34 | method: "POST", | |
| 35 | body: new URLSearchParams({ username, password: PASSWORD }), | |
| 36 | redirect: "manual", | |
| 37 | }); | |
| 38 | expect(res.status).toBe(303); | |
| 39 | return (res.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 40 | }; | |
| 41 | ||
| 42 | const register = async (redirect: string, name: string): Promise<string> => { | |
| 43 | const res = await fetch(`${base}/oauth/register`, { | |
| 44 | method: "POST", | |
| 45 | headers: { "content-type": "application/json" }, | |
| 46 | body: JSON.stringify({ client_name: name, redirect_uris: [redirect] }), | |
| 47 | }); | |
| 48 | expect(res.status).toBe(201); | |
| 49 | return ((await res.json()) as { client_id: string }).client_id; | |
| 50 | }; | |
| 51 | ||
| 52 | const authorizeQuery = (o: Record<string, string>) => | |
| 53 | new URLSearchParams({ | |
| 54 | response_type: "code", | |
| 55 | code_challenge: challengeOf(VERIFIER), | |
| 56 | code_challenge_method: "S256", | |
| 57 | state: "st-123", | |
| 58 | ...o, | |
| 59 | }); | |
| 60 | ||
| 61 | /** Consent as `cookie` and return the code the client is sent back with. */ | |
| 62 | const consentCode = async ( | |
| 63 | cookie: string, | |
| 64 | query: URLSearchParams, | |
| 65 | extra: Record<string, string> = {}, | |
| 66 | ): Promise<URL> => { | |
| 67 | const page = await fetch(`${base}/oauth/authorize?${query}`, { | |
| 68 | headers: { cookie }, | |
| 69 | redirect: "manual", | |
| 70 | }); | |
| 71 | expect(page.status).toBe(200); | |
| 72 | const form = new URLSearchParams(query); | |
| 73 | form.set("decision", "allow"); | |
| 74 | for (const [k, v] of Object.entries(extra)) form.set(k, v); | |
| 75 | const res = await fetch(`${base}/oauth/authorize`, { | |
| 76 | method: "POST", | |
| 77 | headers: { cookie, origin: base }, | |
| 78 | body: form, | |
| 79 | redirect: "manual", | |
| 80 | }); | |
| 81 | expect(res.status).toBe(303); | |
| 82 | return new URL(res.headers.get("location")!); | |
| 83 | }; | |
| 84 | ||
| 85 | const trade = (o: Record<string, string>) => | |
| 86 | fetch(`${base}/oauth/token`, { | |
| 87 | method: "POST", | |
| 88 | headers: { "content-type": "application/x-www-form-urlencoded" }, | |
| 89 | body: new URLSearchParams({ grant_type: "authorization_code", code_verifier: VERIFIER, ...o }), | |
| 90 | }); | |
| 91 | ||
| 92 | const me = (token: string) => | |
| 93 | fetch(`${base}/api/v1/user`, { headers: { authorization: `Bearer ${token}` } }); | |
| 94 | ||
| 95 | beforeAll(async () => { | |
| 96 | dataDir = await mkdtemp(join(tmpdir(), "forge-authz-")); | |
| 97 | // No edgeToken: the platform edge is off. | |
| 98 | app = createApp({ dataDir, port: 0 }); | |
| 99 | servers = await serve(app); | |
| 100 | base = servers.url; | |
| 101 | const alice = await signUp(app, { username: "alice", email: "[email protected]", password: PASSWORD }); | |
| 102 | const b = await signUp(app, { username: "bob", email: "[email protected]", password: PASSWORD }); | |
| 103 | expect(alice.ok && b.ok).toBe(true); | |
| 104 | if (!alice.ok) throw new Error("no alice"); | |
| 105 | const repo = await createRepo(app, alice.value, { name: "secret", visibility: "private" }); | |
| 106 | expect(repo.ok).toBe(true); | |
| 107 | owner = await signIn("alice"); | |
| 108 | bob = await signIn("bob"); | |
| 109 | }); | |
| 110 | afterAll(async () => { | |
| 111 | servers.stop(); | |
| 112 | await rm(dataDir, { recursive: true, force: true }); | |
| 113 | }); | |
| 114 | ||
| 115 | test("the verifier used here is a valid PKCE verifier", () => { | |
| 116 | expect(VERIFIER.length).toBeGreaterThanOrEqual(43); | |
| 117 | }); | |
| 118 | ||
| 119 | test("a private page works with no edge: the forge's own session opens it", async () => { | |
| 120 | expect(app.config.edgeToken).toBeUndefined(); | |
| 121 | const anonymous = await fetch(`${base}/alice/secret`, { redirect: "manual" }); | |
| 122 | expect(anonymous.status).toBe(404); | |
| 123 | const stranger = await fetch(`${base}/alice/secret`, { headers: { cookie: bob }, redirect: "manual" }); | |
| 124 | expect(stranger.status).toBe(404); | |
| 125 | const theirs = await fetch(`${base}/alice/secret`, { headers: { cookie: owner }, redirect: "manual" }); | |
| 126 | expect(theirs.status).toBe(200); | |
| 127 | // Edge headers with no edge configured are a claim nobody vouches for. | |
| 128 | const forged = await fetch(`${base}/alice/secret`, { | |
| 129 | headers: { "x-plat-user": "alice", "x-plat-edge-token": "" }, | |
| 130 | redirect: "manual", | |
| 131 | }); | |
| 132 | expect(forged.status).toBe(404); | |
| 133 | }); | |
| 134 | ||
| 135 | test("discovery: OpenID configuration names every endpoint and scope", async () => { | |
| 136 | const doc = (await (await fetch(`${base}/.well-known/openid-configuration`)).json()) as any; | |
| 137 | expect(doc.issuer).toBe(base); | |
| 138 | expect(doc.jwks_uri).toBe(`${base}/oauth/jwks`); | |
| 139 | expect(doc.userinfo_endpoint).toBe(`${base}/oauth/userinfo`); | |
| 140 | expect(doc.revocation_endpoint).toBe(`${base}/oauth/revoke`); | |
| 141 | expect(doc.scopes_supported).toEqual(["ro", "rw", "admin", "openid", "profile", "email"]); | |
| 142 | expect(doc.id_token_signing_alg_values_supported).toEqual(["ES256"]); | |
| 143 | }); | |
| 144 | ||
| 145 | test("scope parsing: one forge scope, OpenID words only with openid", () => { | |
| 146 | expect(parseScope(null)).toEqual({ ok: true, value: { scope: "ro", claims: [] } }); | |
| 147 | expect(parseScope("openid email")).toEqual({ ok: true, value: { scope: null, claims: ["openid", "email"] } }); | |
| 148 | expect(parseScope("rw profile")).toEqual({ ok: true, value: { scope: "rw", claims: [] } }); | |
| 149 | expect(parseScope("ro rw").ok).toBe(false); | |
| 150 | expect(parseScope("repo").ok).toBe(false); | |
| 151 | }); | |
| 152 | ||
| 153 | test("an unregistered redirect is a page here, never a redirect", async () => { | |
| 154 | const client = await register("https://client.example/cb", "Inspector"); | |
| 155 | const res = await fetch( | |
| 156 | `${base}/oauth/authorize?${authorizeQuery({ client_id: client, redirect_uri: "https://evil.example/cb" })}`, | |
| 157 | { headers: { cookie: owner }, redirect: "manual" }, | |
| 158 | ); | |
| 159 | expect(res.status).toBe(400); | |
| 160 | expect(res.headers.get("location")).toBeNull(); | |
| 161 | }); | |
| 162 | ||
| 163 | test("signed out, authorize sends the person to sign in and back", async () => { | |
| 164 | const client = await register("https://client.example/cb", "Inspector"); | |
| 165 | const res = await fetch(`${base}/oauth/authorize?${authorizeQuery({ client_id: client, redirect_uri: "https://client.example/cb" })}`, { | |
| 166 | redirect: "manual", | |
| 167 | }); | |
| 168 | expect(res.status).toBe(303); | |
| 169 | expect(res.headers.get("location")).toStartWith("/signin?next=%2Foauth%2Fauthorize"); | |
| 170 | }); | |
| 171 | ||
| 172 | test("a cross-origin consent is refused", async () => { | |
| 173 | const client = await register("https://client.example/cb", "Inspector"); | |
| 174 | const res = await fetch(`${base}/oauth/authorize`, { | |
| 175 | method: "POST", | |
| 176 | headers: { cookie: owner, origin: "https://evil.example" }, | |
| 177 | body: new URLSearchParams({ ...Object.fromEntries(authorizeQuery({ client_id: client, redirect_uri: "https://client.example/cb", scope: "rw" })), decision: "allow", access: "rw" }), | |
| 178 | redirect: "manual", | |
| 179 | }); | |
| 180 | expect(res.status).toBe(403); | |
| 181 | }); | |
| 182 | ||
| 183 | test("the MCP dance: rw consent mints a forge token; replay and wrong verifier fail", async () => { | |
| 184 | const cb = "https://client.example/cb"; | |
| 185 | const client = await register(cb, "Claude"); | |
| 186 | const back = await consentCode( | |
| 187 | owner, | |
| 188 | authorizeQuery({ client_id: client, redirect_uri: cb, scope: "rw" }), | |
| 189 | { access: "rw", name: "claude on laptop" }, | |
| 190 | ); | |
| 191 | expect(back.origin + back.pathname).toBe(cb); | |
| 192 | expect(back.searchParams.get("state")).toBe("st-123"); | |
| 193 | expect(back.searchParams.get("iss")).toBe(base); | |
| 194 | const code = back.searchParams.get("code")!; | |
| 195 | ||
| 196 | const wrong = await trade({ code, client_id: client, redirect_uri: cb, code_verifier: "x".repeat(43) }); | |
| 197 | expect(wrong.status).toBe(400); | |
| 198 | // The wrong verifier burned the code: the right one is now too late. | |
| 199 | const late = await trade({ code, client_id: client, redirect_uri: cb }); | |
| 200 | expect(late.status).toBe(400); | |
| 201 | ||
| 202 | const again = await consentCode(owner, authorizeQuery({ client_id: client, redirect_uri: cb, scope: "rw" }), { access: "rw" }); | |
| 203 | const fresh = again.searchParams.get("code")!; | |
| 204 | const ok = await trade({ code: fresh, client_id: client, redirect_uri: cb }); | |
| 205 | expect(ok.status).toBe(200); | |
| 206 | expect(ok.headers.get("cache-control")).toContain("no-store"); | |
| 207 | const issued = (await ok.json()) as any; | |
| 208 | expect(issued.token_type).toBe("Bearer"); | |
| 209 | expect(issued.scope).toBe("rw"); | |
| 210 | expect(issued.id_token).toBeUndefined(); | |
| 211 | expect((await me(issued.access_token)).status).toBe(200); | |
| 212 | const replay = await trade({ code: fresh, client_id: client, redirect_uri: cb }); | |
| 213 | expect(replay.status).toBe(400); | |
| 214 | ||
| 215 | // Listed with the owner's other tokens, naming its client. | |
| 216 | const listed = (await (await fetch(`${base}/api/v1/tokens`, { headers: { cookie: owner } })).json()) as any[]; | |
| 217 | expect(listed.some((t) => t.client === "Claude" && t.scope === "rw")).toBe(true); | |
| 218 | }); | |
| 219 | ||
| 220 | test("a person may give less than was asked, never more", async () => { | |
| 221 | const cb = "https://client.example/cb"; | |
| 222 | const client = await register(cb, "Inspector"); | |
| 223 | const back = await consentCode(owner, authorizeQuery({ client_id: client, redirect_uri: cb, scope: "rw" }), { access: "ro" }); | |
| 224 | const issued = (await (await trade({ code: back.searchParams.get("code")!, client_id: client, redirect_uri: cb })).json()) as any; | |
| 225 | expect(issued.scope).toBe("ro"); | |
| 226 | ||
| 227 | const more = await consentCode(owner, authorizeQuery({ client_id: client, redirect_uri: cb, scope: "ro" }), { access: "admin" }); | |
| 228 | expect(more.searchParams.get("error")).toBe("invalid_scope"); | |
| 229 | expect(more.searchParams.get("code")).toBeNull(); | |
| 230 | }); | |
| 231 | ||
| 232 | test("a hosted app signs a person in through OpenID Connect", async () => { | |
| 233 | const client = await register(APP_CB, "notes"); | |
| 234 | const back = await consentCode( | |
| 235 | bob, | |
| 236 | authorizeQuery({ client_id: client, redirect_uri: APP_CB, scope: "openid profile email", nonce: "n-0S6_WzA2Mj" }), | |
| 237 | ); | |
| 238 | const res = await trade({ code: back.searchParams.get("code")!, client_id: client, redirect_uri: APP_CB }); | |
| 239 | expect(res.status).toBe(200); | |
| 240 | const issued = (await res.json()) as any; | |
| 241 | expect(issued.scope).toBe("openid profile email"); | |
| 242 | expect(issued.expires_in).toBe(3600); | |
| 243 | ||
| 244 | // The relying party's check: signature by a published key, iss, aud, nonce, exp. | |
| 245 | const jwks = (await (await fetch(`${base}/oauth/jwks`)).json()) as { keys: Jwk[] }; | |
| 246 | const claims = (await verifyJwt(issued.id_token, jwks.keys))!; | |
| 247 | expect(claims).toBeDefined(); | |
| 248 | expect(claims.iss).toBe(base); | |
| 249 | expect(claims.aud).toBe(client); | |
| 250 | expect(claims.nonce).toBe("n-0S6_WzA2Mj"); | |
| 251 | expect(claims.preferred_username).toBe("bob"); | |
| 252 | expect(claims.email).toBe("[email protected]"); | |
| 253 | expect(Number(claims.exp)).toBeGreaterThan(Date.now() / 1000); | |
| 254 | // A forged signature is refused. | |
| 255 | const [h, p] = (issued.id_token as string).split("."); | |
| 256 | expect(await verifyJwt(`${h}.${p}.${"A".repeat(86)}`, jwks.keys)).toBeUndefined(); | |
| 257 | ||
| 258 | const info = await fetch(`${base}/oauth/userinfo`, { headers: { authorization: `Bearer ${issued.access_token}` } }); | |
| 259 | expect(info.status).toBe(200); | |
| 260 | const who = (await info.json()) as any; | |
| 261 | expect(who.sub).toBe(claims.sub); | |
| 262 | expect(who.preferred_username).toBe("bob"); | |
| 263 | ||
| 264 | // A sign-in reaches userinfo and nothing else: the API refuses it. | |
| 265 | expect((await me(issued.access_token)).status).toBe(401); | |
| 266 | }); | |
| 267 | ||
| 268 | test("key rotation: a new key signs, the old one still verifies", async () => { | |
| 269 | const client = await register(APP_CB, "notes"); | |
| 270 | const sign = async () => { | |
| 271 | const back = await consentCode(bob, authorizeQuery({ client_id: client, redirect_uri: APP_CB, scope: "openid" })); | |
| 272 | return ((await (await trade({ code: back.searchParams.get("code")!, client_id: client, redirect_uri: APP_CB })).json()) as any).id_token as string; | |
| 273 | }; | |
| 274 | const before = await sign(); | |
| 275 | await rotateKey(app.db, app.config.dataDir); | |
| 276 | const after = await sign(); | |
| 277 | const kid = (t: string) => JSON.parse(Buffer.from(t.split(".")[0]!, "base64url").toString()).kid; | |
| 278 | expect(kid(after)).not.toBe(kid(before)); | |
| 279 | const jwks = (await (await fetch(`${base}/oauth/jwks`)).json()) as { keys: Jwk[] }; | |
| 280 | expect(jwks.keys.length).toBeGreaterThanOrEqual(2); | |
| 281 | expect(jwks.keys.every((k) => k.d === undefined)).toBe(true); | |
| 282 | expect(await verifyJwt(before, jwks.keys)).toBeDefined(); | |
| 283 | expect(await verifyJwt(after, jwks.keys)).toBeDefined(); | |
| 284 | }); | |
| 285 | ||
| 286 | test("a revoked token stops working at once — by its holder, owner, or the forge's owner", async () => { | |
| 287 | const cb = "https://client.example/cb"; | |
| 288 | const client = await register(cb, "Claude"); | |
| 289 | const mint = async (cookie: string) => { | |
| 290 | const back = await consentCode(cookie, authorizeQuery({ client_id: client, redirect_uri: cb, scope: "ro" }), { access: "ro" }); | |
| 291 | return ((await (await trade({ code: back.searchParams.get("code")!, client_id: client, redirect_uri: cb })).json()) as any).access_token as string; | |
| 292 | }; | |
| 293 | ||
| 294 | // RFC 7009, by whoever holds it. | |
| 295 | const held = await mint(bob); | |
| 296 | expect((await me(held)).status).toBe(200); | |
| 297 | const revoked = await fetch(`${base}/oauth/revoke`, { | |
| 298 | method: "POST", | |
| 299 | headers: { "content-type": "application/x-www-form-urlencoded" }, | |
| 300 | body: new URLSearchParams({ token: held }), | |
| 301 | }); | |
| 302 | expect(revoked.status).toBe(200); | |
| 303 | expect((await me(held)).status).toBe(401); | |
| 304 | ||
| 305 | // By the forge's owner, for another account. | |
| 306 | const bobs = await mint(bob); | |
| 307 | expect((await me(bobs)).status).toBe(200); | |
| 308 | const list = (await (await fetch(`${base}/api/v1/users/bob/signins`, { headers: { cookie: owner } })).json()) as { tokens: any[] }; | |
| 309 | const target = list.tokens.find((t) => t.client === "Claude")!; | |
| 310 | expect(target).toBeDefined(); | |
| 311 | const gone = await fetch(`${base}/api/v1/users/bob/tokens/${target.id}`, { | |
| 312 | method: "DELETE", | |
| 313 | headers: { cookie: owner, origin: base }, | |
| 314 | }); | |
| 315 | expect(gone.status).toBe(204); | |
| 316 | expect((await me(bobs)).status).toBe(401); | |
| 317 | ||
| 318 | // Anyone else is told the account's tokens do not exist. | |
| 319 | const alices = await fetch(`${base}/api/v1/users/alice/signins`, { headers: { cookie: bob } }); | |
| 320 | expect(alices.status).toBe(404); | |
| 321 | }); | |
| 322 | }); |
test/oauth-discovery.test.ts +1 −1
| @@ -53,7 +53,7 @@ describe("oauth discovery and registration", () => { | ||
| 53 | 53 | expect(doc.token_endpoint).toBe(`${base}/oauth/token`); |
| 54 | 54 | expect(doc.registration_endpoint).toBe(`${base}/oauth/register`); |
| 55 | 55 | expect(doc.code_challenge_methods_supported).toEqual(["S256"]); |
| 56 | expect(doc.scopes_supported).toEqual(["ro", "rw"]); | |
| 56 | expect(doc.scopes_supported).toEqual(["ro", "rw", "admin", "openid", "profile", "email"]); | |
| 57 | 57 | }); |
| 58 | 58 | |
| 59 | 59 | test("a 401 from /mcp names the resource metadata", async () => { |
new above
offline
Hardcoded
false, but the forge proves emails now (emailVerified(db, user.id)incore/verify.ts). Relying parties will reject or re-verify addresses the forge has already proven. Pass the real value in.