diff --git a/packages/hatk/src/database/db.ts b/packages/hatk/src/database/db.ts index 8e557e6..0244d9d 100644 --- a/packages/hatk/src/database/db.ts +++ b/packages/hatk/src/database/db.ts @@ -240,6 +240,17 @@ export async function initDatabase( try { await run(`ALTER TABLE _oauth_requests ADD COLUMN pds_token_endpoint TEXT`) } catch {} + // What a session asked for and was granted. NULL on sessions that predate + // this, which are treated as they were before: a scope refusal ends them. + try { + await run(`ALTER TABLE _oauth_sessions ADD COLUMN requested_scope TEXT`) + } catch {} + try { + await run(`ALTER TABLE _oauth_sessions ADD COLUMN granted_scope TEXT`) + } catch {} + try { + await run(`ALTER TABLE _oauth_requests ADD COLUMN pds_scope TEXT`) + } catch {} // Now the columns the indexes below name are all present, on a database of // any age. A new collection's table was created above and needs nothing; an diff --git a/packages/hatk/src/oauth/db.ts b/packages/hatk/src/oauth/db.ts index 874fb80..a2cef26 100644 --- a/packages/hatk/src/oauth/db.ts +++ b/packages/hatk/src/oauth/db.ts @@ -21,6 +21,8 @@ CREATE TABLE IF NOT EXISTS _oauth_sessions ( refresh_token TEXT, dpop_jkt TEXT NOT NULL, token_expires_at INTEGER, + requested_scope TEXT, + granted_scope TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); @@ -43,6 +45,7 @@ CREATE TABLE IF NOT EXISTS _oauth_requests ( pds_state TEXT, did TEXT, login_hint TEXT, + pds_scope TEXT, expires_at INTEGER NOT NULL ); @@ -112,12 +115,14 @@ export async function storeOAuthRequest( pdsState?: string did?: string loginHint?: string + /** What was asked of the PDS, which is not always `scope`: see negotiateScope. */ + pdsScope?: string expiresAt: number }, ): Promise { await runSQL( - `INSERT INTO _oauth_requests (request_uri, client_id, redirect_uri, scope, state, code_challenge, code_challenge_method, dpop_jkt, pds_request_uri, pds_auth_server, pds_authorization_endpoint, pds_token_endpoint, pds_endpoint, pds_code_verifier, pds_state, did, login_hint, expires_at) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)`, + `INSERT INTO _oauth_requests (request_uri, client_id, redirect_uri, scope, state, code_challenge, code_challenge_method, dpop_jkt, pds_request_uri, pds_auth_server, pds_authorization_endpoint, pds_token_endpoint, pds_endpoint, pds_code_verifier, pds_state, did, login_hint, expires_at, pds_scope) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)`, [ requestUri, data.clientId, @@ -137,6 +142,7 @@ export async function storeOAuthRequest( data.did || null, data.loginHint || null, data.expiresAt, + data.pdsScope || null, ], ) } @@ -185,11 +191,20 @@ export async function storeSession( refreshToken?: string dpopJkt: string tokenExpiresAt?: number + /** + * The scope asked of the PDS for this session, and the scope it granted. + * A server may grant less than it was asked for, on purpose — a group's + * host narrows a sign-in as the group to what the person's roles allow — + * and the difference is what tells a refusal it can do nothing about from + * one a new sign-in would fix. See withheldByServer in pds-proxy.ts. + */ + requestedScope?: string + grantedScope?: string }, ): Promise { await runSQL( - `INSERT OR REPLACE INTO _oauth_sessions (did, pds_endpoint, pds_auth_server, pds_token_endpoint, access_token, refresh_token, dpop_jkt, token_expires_at, updated_at) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,CURRENT_TIMESTAMP)`, + `INSERT OR REPLACE INTO _oauth_sessions (did, pds_endpoint, pds_auth_server, pds_token_endpoint, access_token, refresh_token, dpop_jkt, token_expires_at, requested_scope, granted_scope, updated_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,CURRENT_TIMESTAMP)`, [ did, data.pdsEndpoint, @@ -199,6 +214,8 @@ export async function storeSession( data.refreshToken || null, data.dpopJkt, data.tokenExpiresAt || null, + data.requestedScope || null, + data.grantedScope || null, ], ) } diff --git a/packages/hatk/src/oauth/server.ts b/packages/hatk/src/oauth/server.ts index 4a96bea..a67c534 100644 --- a/packages/hatk/src/oauth/server.ts +++ b/packages/hatk/src/oauth/server.ts @@ -391,6 +391,7 @@ export async function handlePar( let pdsTokenEndpoint: string | undefined let pdsCodeVerifier: string | undefined let pdsState: string | undefined + let pdsScope: string | undefined let pdsEndpoint: string | undefined if (prompt === 'create' && body.login_hint) { @@ -440,7 +441,7 @@ export async function handlePar( const parEndpoint = endpoints.parEndpoint const serverDpopProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', parEndpoint) - const pdsScope = await negotiateScope( + pdsScope = await negotiateScope( config, body.scope || 'atproto transition:generic', pdsEndpoint, @@ -541,6 +542,7 @@ export async function handlePar( pdsState, did, loginHint: body.login_hint, + pdsScope, expiresAt, }) @@ -702,6 +704,7 @@ export async function serverLogin( pdsState, did, loginHint: handle, + pdsScope: scope, expiresAt, }) @@ -831,6 +834,8 @@ export async function handleCallback( refreshToken: tokenData.refresh_token, dpopJkt: serverJkt, tokenExpiresAt: tokenData.expires_in ? Math.floor(Date.now() / 1000) + tokenData.expires_in : undefined, + requestedScope: request.pds_scope ?? undefined, + grantedScope: typeof tokenData.scope === 'string' ? tokenData.scope : undefined, }) await fireOnLoginHook(did, config) @@ -1153,6 +1158,8 @@ export async function obtainSession( refreshToken: typeof token.refresh_token === 'string' ? token.refresh_token : undefined, dpopJkt: serverJkt, tokenExpiresAt: typeof token.expires_in === 'number' ? Math.floor(Date.now() / 1000) + token.expires_in : undefined, + requestedScope: typeof body.scope === 'string' ? body.scope : undefined, + grantedScope: typeof token.scope === 'string' ? token.scope : undefined, }) emit('oauth', 'session_obtained', { did, from: origin }) return { did, response: out } @@ -1169,6 +1176,8 @@ export async function refreshPdsSession( pds_token_endpoint?: string refresh_token: string dpop_jkt: string + requested_scope?: string | null + granted_scope?: string | null }, ): Promise<{ accessToken: string; refreshToken?: string; expiresAt?: number } | null> { if (!session.refresh_token) return null @@ -1247,6 +1256,9 @@ export async function refreshPdsSession( refreshToken: tokenData.refresh_token || session.refresh_token, dpopJkt: session.dpop_jkt, tokenExpiresAt: tokenData.expires_in ? Math.floor(Date.now() / 1000) + tokenData.expires_in : undefined, + // A refresh renews the grant, it does not renegotiate it. + requestedScope: session.requested_scope ?? undefined, + grantedScope: typeof tokenData.scope === 'string' ? tokenData.scope : (session.granted_scope ?? undefined), }) return { diff --git a/packages/hatk/src/pds-proxy.ts b/packages/hatk/src/pds-proxy.ts index 43be3e2..4694906 100644 --- a/packages/hatk/src/pds-proxy.ts +++ b/packages/hatk/src/pds-proxy.ts @@ -25,6 +25,61 @@ export class ScopeMissingProxyError extends ProxyError { } } +/** + * A call the session's grant does not cover, where signing in again would not + * change that: the server granted less than it was asked for, on purpose. The + * session is kept and only this call fails, as a 403 — the answer is no, not + * "authorize again". Named apart from ScopeMissingError on purpose: the browser + * client and the admin page answer that name by starting a new sign-in. + */ +export class ScopeWithheldProxyError extends ProxyError { + constructor() { + super(403, 'ScopeWithheld') + } +} + +type ProxySession = { + access_token: string + pds_endpoint: string + did: string + refresh_token: string + dpop_jkt: string + requested_scope?: string | null + granted_scope?: string | null +} + +/** + * Did the server grant this session less than it was asked for? + * + * A scope refusal means one of two things. Either the session predates a + * scope the app has since added, and a new sign-in asks for it — or the server + * chose not to grant it, as a group's host does when someone signs in as the + * group, and a new sign-in gets the same answer. Ending the session is the + * fix for the first and, for the second, signs the account out on every page + * that makes a call it may not. + * + * Narrower is counted, not compared: a server reports its grant in its own + * words — the reference PDS drops default parameters, sorts collections and + * fills them in from a space's declaration — so a full grant rarely matches the + * request string for string. It does keep one scope for each one asked for, + * and narrowing takes whole scopes away, so fewer scopes granted than asked + * for is the sign. + * + * A session that predates recording either keeps the old answer. + */ +function withheldByServer(session: ProxySession): boolean { + if (!session.requested_scope || !session.granted_scope) return false + const count = (scope: string) => new Set(scope.split(/\s+/).filter(Boolean)).size + return count(session.granted_scope) < count(session.requested_scope) +} + +/** End the session so the user authorizes again — unless that could not help. */ +async function refuseForScope(session: ProxySession): Promise { + if (withheldByServer(session)) throw new ScopeWithheldProxyError() + await deleteSession(session.did) + throw new ScopeMissingProxyError() +} + // --- Low-level PDS proxy with DPoP + nonce retry + token refresh --- interface PdsProxyResult { @@ -39,7 +94,7 @@ type FetchFn = (token: string, nonce?: string) => Promise /** Shared retry logic: DPoP nonce handling + token refresh. */ async function withDpopRetry( oauthConfig: OAuthConfig, - session: { access_token: string; pds_endpoint: string; did: string; refresh_token: string; dpop_jkt: string }, + session: ProxySession, doFetch: FetchFn, ): Promise { let accessToken = session.access_token @@ -58,11 +113,8 @@ async function withDpopRetry( } } - // Step 2: handle insufficient scope — clear session so user re-authenticates with updated scopes - if (result.body.error === 'ScopeMissingError') { - await deleteSession(session.did) - throw new ScopeMissingProxyError() - } + // Step 2: handle insufficient scope — see refuseForScope + if (result.body.error === 'ScopeMissingError') await refuseForScope(session) // Step 3: handle expired PDS token — refresh and retry if (isTokenError(result.body.error)) { @@ -86,10 +138,7 @@ async function withDpopRetry( // handled above; pds.js answers InvalidToken for a scope its permissioned // space endpoints refuse, which is indistinguishable from expiry until // the refresh rules expiry out. - if (!result.ok && isTokenError(result.body.error)) { - await deleteSession(session.did) - throw new ScopeMissingProxyError() - } + if (!result.ok && isTokenError(result.body.error)) await refuseForScope(session) } } @@ -131,7 +180,7 @@ function isTokenError(error: unknown): boolean { async function proxyToPds( oauthConfig: OAuthConfig, - session: { access_token: string; pds_endpoint: string; did: string; refresh_token: string; dpop_jkt: string }, + session: ProxySession, method: string, pdsUrl: string, body: unknown, diff --git a/packages/hatk/test/obtain-session.test.ts b/packages/hatk/test/obtain-session.test.ts index 9b4dc68..626987c 100644 --- a/packages/hatk/test/obtain-session.test.ts +++ b/packages/hatk/test/obtain-session.test.ts @@ -119,6 +119,20 @@ test('calls the endpoint as the OAuth client, with DPoP, and stores the session }) }) +test('remembers the scope it asked for and the scope it was granted', async () => { + // A host may grant less than was asked; what tells a later refusal apart + // from an outdated session is having both. + answers = [{ status: 200, body: session({ scope: 'atproto repo:app.example.profile' }) }] + await obtainSession(config, ENDPOINT, { + handle: 'club.test', + scope: 'atproto repo:app.example.profile repo:app.example.item', + }) + expect(await getSession(GROUP)).toMatchObject({ + requested_scope: 'atproto repo:app.example.profile repo:app.example.item', + granted_scope: 'atproto repo:app.example.profile', + }) +}) + test('answers a nonce challenge once', async () => { answers = [ { status: 400, body: { error: 'use_dpop_nonce' }, headers: { 'DPoP-Nonce': 'n1' } }, diff --git a/packages/hatk/test/scope-refusal.test.ts b/packages/hatk/test/scope-refusal.test.ts index 671c7a3..f190b6e 100644 --- a/packages/hatk/test/scope-refusal.test.ts +++ b/packages/hatk/test/scope-refusal.test.ts @@ -1,5 +1,5 @@ -import { afterEach, beforeAll, beforeEach, expect, test, vi } from 'vitest' -import { pdsXrpc, ScopeMissingProxyError } from '../src/pds-proxy.ts' +import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest' +import { pdsXrpc, ScopeMissingProxyError, ScopeWithheldProxyError } from '../src/pds-proxy.ts' import { initOAuth } from '../src/oauth/server.ts' import { OAUTH_DDL, getSession, storeSession } from '../src/oauth/db.ts' import { runSQL } from '../src/database/db.ts' @@ -114,3 +114,74 @@ test('an unrelated failure is left alone', async () => { }) expect(await getSession(DID)).not.toBeNull() }) + +// A server may grant less than it was asked for, on purpose: a group's host +// narrows a sign-in as the group to what the person's roles allow. A refusal +// then is the server's answer, not an old session, and a new sign-in would get +// the same grant — so ending the session only signs the account out on every +// page that makes a call it may not. +describe('a session the server granted less than it asked for', () => { + const asked = 'atproto repo:app.example.post space:app.example.pool?action=read space:app.example.members?action=read' + const narrowed = 'atproto repo:app.example.post space:app.example.pool?action=read' + + async function storeNarrowed(granted = narrowed) { + await storeSession(DID, { + pdsEndpoint: PDS, + pdsAuthServer: PDS, + accessToken: 'stale-token', + refreshToken: 'a-refresh-token', + dpopJkt: 'jkt', + requestedScope: asked, + grantedScope: granted, + }) + } + + test('keeps the session and fails only the call', async () => { + await storeNarrowed() + stubFetchSequence([{ status: 403, body: { error: 'ScopeMissingError' } }]) + + const err = await pdsXrpc(config, { did: DID }, 'com.atproto.space.listSpaces').catch((e) => e) + expect(err).toBeInstanceOf(ScopeWithheldProxyError) + expect(err).not.toBeInstanceOf(ScopeMissingProxyError) + // Not the name the browser client answers by signing in again. + expect(err).toMatchObject({ status: 403, message: 'ScopeWithheld' }) + expect(await getSession(DID)).not.toBeNull() + }) + + test('keeps it through the refusal pds.js spells as an expired token', async () => { + await storeNarrowed() + stubFetchSequence([refused, refreshed, refused]) + + await expect(pdsXrpc(config, { did: DID }, 'com.atproto.space.listSpaces')).rejects.toBeInstanceOf( + ScopeWithheldProxyError, + ) + const session = await getSession(DID) + // Refreshed, and still knowing what it was granted. + expect(session).toMatchObject({ access_token: 'fresh-token', requested_scope: asked, granted_scope: narrowed }) + }) + + test("a full grant in the server's own words still ends the session", async () => { + // The reference PDS rewrites a space scope it grants — default parameters + // dropped, collections filled in — so the grant does not match the request + // string for string. Nothing was withheld; the app has asked for more since. + await storeNarrowed( + 'atproto repo:app.example.post space:app.example.pool?collection=app.example.photo&action=read space:app.example.members?action=read', + ) + stubFetchSequence([{ status: 403, body: { error: 'ScopeMissingError' } }]) + + await expect(pdsXrpc(config, { did: DID }, 'com.atproto.space.listSpaces')).rejects.toBeInstanceOf( + ScopeMissingProxyError, + ) + expect(await getSession(DID)).toBeNull() + }) + + test('a full grant still ends the session: the app has asked for more since', async () => { + await storeNarrowed(asked) + stubFetchSequence([{ status: 403, body: { error: 'ScopeMissingError' } }]) + + await expect(pdsXrpc(config, { did: DID }, 'com.atproto.space.listSpaces')).rejects.toBeInstanceOf( + ScopeMissingProxyError, + ) + expect(await getSession(DID)).toBeNull() + }) +})