diff --git a/patches/@atproto__oauth-client@0.6.1.patch b/patches/@atproto__oauth-client@0.6.1.patch new file mode 100644 index 000000000..a93a9d2e1 --- /dev/null +++ b/patches/@atproto__oauth-client@0.6.1.patch @@ -0,0 +1,63 @@ +diff --git a/dist/oauth-session.js b/dist/oauth-session.js +index 02882b2..11e0e0b 100644 +--- a/dist/oauth-session.js ++++ b/dist/oauth-session.js +@@ -6,6 +6,18 @@ const token_invalid_error_js_1 = require("./errors/token-invalid-error.js"); + const token_revoked_error_js_1 = require("./errors/token-revoked-error.js"); + const fetch_dpop_js_1 = require("./fetch-dpop.js"); + const ReadableStream = globalThis.ReadableStream; ++function isSameDpopKey(a, b) { ++ const x = a?.bareJwk; ++ const y = b?.bareJwk; ++ if (!x || !y) ++ return false; ++ return (x.kty === y.kty && ++ x.crv === y.crv && ++ x.x === y.x && ++ x.y === y.y && ++ x.n === y.n && ++ x.e === y.e); ++} + class OAuthSession { + constructor(server, sub, sessionGetter, fetch = globalThis.fetch) { + Object.defineProperty(this, "server", { +@@ -47,6 +59,17 @@ class OAuthSession { + get serverMetadata() { + return this.server.serverMetadata; + } ++ /** ++ * The DPoP key lives on this instance while the token set is re-read from ++ * the shared store on every call. When the store holds a different key, ++ * another instance re-authenticated this sub and now owns the session. ++ */ ++ async ownsStoredSession() { ++ const stored = await this.sessionGetter.getStored(this.sub); ++ if (stored?.dpopKey == null) ++ return true; ++ return isSameDpopKey(stored.dpopKey, this.server.dpopKey); ++ } + /** + * @param refresh When `true`, the credentials will be refreshed even if they + * are not expired. When `false`, the credentials will not be refreshed even +@@ -97,6 +120,11 @@ class OAuthSession { + if (!isInvalidTokenResponse(initialResponse)) { + return initialResponse; + } ++ // A stale instance must neither refresh nor delete a session it no ++ // longer owns; doing so logs out the instance that does own it. ++ if (!(await this.ownsStoredSession())) { ++ return initialResponse; ++ } + let tokenSetFresh; + try { + // Force a refresh +@@ -120,7 +148,8 @@ class OAuthSession { + // resource server. This might be due to the resource server not accepting + // credentials from the authorization server (e.g. because some migration + // occurred). Any ways, there is no point in keeping the session. +- if (isInvalidTokenResponse(finalResponse)) { ++ if (isInvalidTokenResponse(finalResponse) && ++ (await this.ownsStoredSession())) { + // @TODO Is there a "softer" way to handle this, e.g. by marking the + // session as "expired" in the session store, allowing the user to trigger + // a new login (using login_hint)? diff --git a/patches/@atproto__oauth-client@0.6.1.patch.md b/patches/@atproto__oauth-client@0.6.1.patch.md new file mode 100644 index 000000000..916dc9fb1 --- /dev/null +++ b/patches/@atproto__oauth-client@0.6.1.patch.md @@ -0,0 +1,21 @@ +# @atproto/oauth-client stale-instance DPoP guard + +`OAuthSession` keeps its DPoP key in memory but re-reads the token set from the shared session +store (IndexedDB on web, keyed by DID) on every request. Logging in again for the same DID +replaces the stored token set and key. Any session object that is still alive from before that +login (a second tab or window, or a leftover agent in the same tab) then signs the new token with +its old key. The PDS answers 401 `invalid_token` ("DPoP key does not match the token binding"). + +Upstream `fetchHandler` treats that 401 as an expired token: it forces a refresh (which succeeds, +because the refresh token in the store is valid), retries with the old key, gets 401 again, and +calls `delStored`, deleting the shared session. The tab the user is actually using is then logged +out with "The session was deleted by another process". Each re-login repeats the loop. + +This patch adds `ownsStoredSession()`, which compares the instance's key with the key currently in +the store. When they differ, `fetchHandler` returns the 401 without refreshing or deleting. When +nothing is stored, or the keys match, behavior is unchanged. + +Applies to 0.6.1, which both `@atproto/oauth-client-browser@0.3.42` (web) and +`@atproto/oauth-client-expo` (native) resolve to. The bug only shows on web; native runs one +instance per app process, so the guard is a no-op there. Drop the patch once upstream ships an +equivalent guard. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 22cb2c1eb..444e00b6e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -224,6 +224,7 @@ overrides: eslint-plugin-react-hooks>zod: ^3.25.76 patchedDependencies: + '@atproto/oauth-client@0.6.1': 634e026f45f4f312f21d5ad51c0c6431b176b7f35c9cf47e668210b4cd00a40b '@sentry/expo-upload-sourcemaps@8.18.0': 2368e1e1986165e7ead3c60017b78b2f9ade1b6a6b2f5ad27cd428608c6f12ae core-js@3.49.0: b14d6dc69d8b2ee39f04ff532bcb886f363b381a493cc59074f0f569f7844a38 expo-age-range@0.2.18: c325225749993424461eeece1d97a99b19c00da2ebc958a73c12e4eca0c39306 @@ -260,7 +261,7 @@ importers: version: 0.5.7 '@atproto/oauth-client': specifier: 0.6.1 - version: 0.6.1 + version: 0.6.1(patch_hash=634e026f45f4f312f21d5ad51c0c6431b176b7f35c9cf47e668210b4cd00a40b) '@atproto/oauth-client-browser': specifier: 0.3.42 version: 0.3.42 @@ -10245,14 +10246,14 @@ snapshots: '@atproto/did': 0.3.0 '@atproto/jwk': 0.6.0 '@atproto/jwk-webcrypto': 0.2.0 - '@atproto/oauth-client': 0.6.1 + '@atproto/oauth-client': 0.6.1(patch_hash=634e026f45f4f312f21d5ad51c0c6431b176b7f35c9cf47e668210b4cd00a40b) '@atproto/oauth-types': 0.6.3 core-js: 3.49.0(patch_hash=b14d6dc69d8b2ee39f04ff532bcb886f363b381a493cc59074f0f569f7844a38) '@atproto/oauth-client-expo@0.0.10(edfeffc83f5dbe9dff3f743027bf8992)': dependencies: '@atproto-labs/simple-store': 0.3.0 - '@atproto/oauth-client': 0.6.1 + '@atproto/oauth-client': 0.6.1(patch_hash=634e026f45f4f312f21d5ad51c0c6431b176b7f35c9cf47e668210b4cd00a40b) '@atproto/oauth-client-browser': 0.3.42 core-js: 3.49.0(patch_hash=b14d6dc69d8b2ee39f04ff532bcb886f363b381a493cc59074f0f569f7844a38) expo: 54.0.35(@babel/core@7.29.0(supports-color@8.1.1))(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.81.5(patch_hash=7f480a2c0ace258e2553e1ff23e39618d12b433dbb38fa4f6080943d6060be74)(@babel/core@7.29.0(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.0(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.1.17)(react@19.1.0)(supports-color@8.1.1))(react@19.1.0))(react-native@0.81.5(patch_hash=7f480a2c0ace258e2553e1ff23e39618d12b433dbb38fa4f6080943d6060be74)(@babel/core@7.29.0(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.0(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.1.17)(react@19.1.0)(supports-color@8.1.1))(react@19.1.0)(supports-color@8.1.1) @@ -10263,7 +10264,7 @@ snapshots: transitivePeerDependencies: - react - '@atproto/oauth-client@0.6.1': + '@atproto/oauth-client@0.6.1(patch_hash=634e026f45f4f312f21d5ad51c0c6431b176b7f35c9cf47e668210b4cd00a40b)': dependencies: '@atproto-labs/did-resolver': 0.2.6 '@atproto-labs/fetch': 0.2.3 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index b5d61f0c4..e9f9a326f 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -42,6 +42,7 @@ allowBuilds: 'esbuild': true 'unrs-resolver': true patchedDependencies: + '@atproto/oauth-client@0.6.1': patches/@atproto__oauth-client@0.6.1.patch '@sentry/expo-upload-sourcemaps@8.18.0': patches/@sentry__expo-upload-sourcemaps@8.18.0.patch 'core-js@3.49.0': patches/core-js@3.49.0.patch 'expo-age-range@0.2.18': patches/expo-age-range@0.2.18.patch diff --git a/src/state/session/__tests__/oauth-session-stale-instance-test.ts b/src/state/session/__tests__/oauth-session-stale-instance-test.ts new file mode 100644 index 000000000..cbe57e89e --- /dev/null +++ b/src/state/session/__tests__/oauth-session-stale-instance-test.ts @@ -0,0 +1,132 @@ +import {OAuthSession} from '@atproto/oauth-client' +import {describe, expect, it, jest} from '@jest/globals' + +const SUB = 'did:plc:test' + +function fakeKey(x: string) { + return {bareJwk: {kty: 'EC', crv: 'P-256', x, y: 'y'}} +} + +function tokenSet(accessToken: string) { + return { + sub: SUB, + iss: 'https://pds.test', + aud: 'https://pds.test', + token_type: 'DPoP', + access_token: accessToken, + refresh_token: 'refresh', + scope: 'atproto', + } +} + +function invalidTokenResponse() { + return new Response(null, { + status: 401, + headers: { + 'WWW-Authenticate': + 'DPoP error="invalid_token", error_description="DPoP key does not match the token binding"', + }, + }) +} + +function okResponse() { + return new Response('{}', {status: 200}) +} + +function makeSession({ + instanceKey, + storedKey, + responses, +}: { + instanceKey: ReturnType + storedKey: ReturnType | undefined + responses: Response[] +}) { + const refresh = jest.fn(() => Promise.resolve({tokenSet: tokenSet('fresh')})) + const sessionGetter = { + getSession: jest.fn((_sub: string, force?: boolean | 'auto') => + force === true + ? refresh() + : Promise.resolve({tokenSet: tokenSet('current')}), + ), + getStored: jest.fn(() => + Promise.resolve( + storedKey + ? {dpopKey: storedKey, tokenSet: tokenSet('current')} + : undefined, + ), + ), + delStored: jest.fn(() => Promise.resolve()), + } + const session = Object.create(OAuthSession.prototype) as OAuthSession + Object.assign(session, { + server: {dpopKey: instanceKey}, + sub: SUB, + sessionGetter, + dpopFetch: jest.fn(() => Promise.resolve(responses.shift()!)), + }) + return {session, sessionGetter, refresh} +} + +describe('OAuthSession stale-instance guard', () => { + it('does not refresh or delete when the store holds a different DPoP key', async () => { + const {session, sessionGetter, refresh} = makeSession({ + instanceKey: fakeKey('old'), + storedKey: fakeKey('new'), + responses: [invalidTokenResponse()], + }) + + const res = await session.fetchHandler('/xrpc/chat.bsky.convo.getLog', {}) + + expect(res.status).toBe(401) + expect(refresh).not.toHaveBeenCalled() + expect(sessionGetter.delStored).not.toHaveBeenCalled() + }) + + it('still deletes the session when the owning instance is rejected twice', async () => { + const {session, sessionGetter, refresh} = makeSession({ + instanceKey: fakeKey('same'), + storedKey: fakeKey('same'), + responses: [invalidTokenResponse(), invalidTokenResponse()], + }) + + const res = await session.fetchHandler( + '/xrpc/app.bsky.actor.getPreferences', + {}, + ) + + expect(res.status).toBe(401) + expect(refresh).toHaveBeenCalledTimes(1) + expect(sessionGetter.delStored).toHaveBeenCalledTimes(1) + }) + + it('refreshes and retries when the owning instance holds an expired token', async () => { + const {session, sessionGetter, refresh} = makeSession({ + instanceKey: fakeKey('same'), + storedKey: fakeKey('same'), + responses: [invalidTokenResponse(), okResponse()], + }) + + const res = await session.fetchHandler( + '/xrpc/app.bsky.actor.getPreferences', + {}, + ) + + expect(res.status).toBe(200) + expect(refresh).toHaveBeenCalledTimes(1) + expect(sessionGetter.delStored).not.toHaveBeenCalled() + }) + + it('keeps the upstream behavior when nothing is stored', async () => { + const {session, sessionGetter, refresh} = makeSession({ + instanceKey: fakeKey('same'), + storedKey: undefined, + responses: [invalidTokenResponse(), invalidTokenResponse()], + }) + + await session.fetchHandler('/xrpc/app.bsky.actor.getPreferences', {}) + + expect(refresh).toHaveBeenCalledTimes(1) + expect(sessionGetter.delStored).toHaveBeenCalledTimes(1) + }) +})