diff --git a/eslint-suppressions.json b/eslint-suppressions.json index d83567e42..e58b949eb 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -1026,10 +1026,10 @@ "count": 1 }, "@typescript-eslint/no-unsafe-call": { - "count": 30 + "count": 28 }, "@typescript-eslint/no-unsafe-member-access": { - "count": 30 + "count": 28 } }, "src/lib/translation/index.tsx": { diff --git a/src/lib/strings/__tests__/errors.test.ts b/src/lib/strings/__tests__/errors.test.ts new file mode 100644 index 000000000..d487e9b0f --- /dev/null +++ b/src/lib/strings/__tests__/errors.test.ts @@ -0,0 +1,27 @@ +import {cleanError} from '../errors' + +const INTERRUPTED = 'Connection was interrupted. Please try again.' + +it.each([ + 'XRPCError: DPoP proof is too old', + 'Failed to verify DPoP proof: "iat" claim timestamp check failed (too far in the past)', +])('maps "%s" to a connection-interrupted message', error => { + expect(cleanError(error)).toBe(INTERRUPTED) +}) + +it.each([ + 'XRPCError: DPoP proof replayed', + 'XRPCError: DPoP proof "jti" replayed', +])('does not invite a resubmit for "%s"', error => { + expect(cleanError(error)).not.toBe(INTERRUPTED) +}) + +it('no longer blames the device clock', () => { + expect(cleanError('invalid_dpop_proof: iat claim')).not.toMatch(/clock/i) +}) + +it('keeps the generic message for other DPoP proof errors', () => { + expect(cleanError('invalid_dpop_proof: DPoP "htm" mismatch')).toBe( + 'Authentication error. Please try signing in again.', + ) +}) diff --git a/src/lib/strings/errors.ts b/src/lib/strings/errors.ts index 65e6fec60..101614ecb 100644 --- a/src/lib/strings/errors.ts +++ b/src/lib/strings/errors.ts @@ -52,8 +52,8 @@ export function cleanError(str: any): string { ) { return t`Session storage is unavailable. Please sign in again.` } - if (str.includes('invalid_dpop_proof') && str.includes('iat claim')) { - return t`Your device clock appears to be incorrect. Please check your system time settings and try again.` + if (isDelayedDpopProofError(str)) { + return t`Connection was interrupted. Please try again.` } if (str.includes('invalid_dpop_proof')) { return t`Authentication error. Please try signing in again.` @@ -91,6 +91,13 @@ export function cleanError(str: any): string { return str } +function isDelayedDpopProofError(str: string) { + return ( + str.includes('DPoP proof is too old') || + str.includes('"iat" claim timestamp check failed (too far in the past)') + ) +} + const NETWORK_ERRORS = [ 'Abort', 'Network request failed', diff --git a/src/state/session/__tests__/oauth-dpop-recovery-test.ts b/src/state/session/__tests__/oauth-dpop-recovery-test.ts new file mode 100644 index 000000000..cf6372466 --- /dev/null +++ b/src/state/session/__tests__/oauth-dpop-recovery-test.ts @@ -0,0 +1,123 @@ +import {describe, expect, it, jest} from '@jest/globals' + +import {fetchWithDpopRetry} from '../oauth-dpop-recovery' + +const URL = 'https://pds.example.com/xrpc/app.bsky.feed.getTimeline' + +function jsonResponse(status: number, body: unknown) { + return new Response(JSON.stringify(body), { + status, + headers: {'Content-Type': 'application/json'}, + }) +} + +function dpopError(message: string) { + return jsonResponse(401, {error: 'invalid_dpop_proof', message}) +} + +function mockHandler(...responses: Response[]) { + const handler = + jest.fn<(url: string, init: RequestInit) => Promise>() + for (const res of responses) handler.mockResolvedValueOnce(res) + return handler +} + +describe('fetchWithDpopRetry', () => { + it.each([ + 'DPoP proof is too old', + 'DPoP proof "jti" replayed', + 'DPoP proof replayed', + 'Failed to verify DPoP proof: "iat" claim timestamp check failed (too far in the past)', + ])('retries a GET once after "%s" and returns the retry', async message => { + const handler = mockHandler(dpopError(message), jsonResponse(200, {ok: 1})) + const init = {method: 'GET', headers: {'atproto-proxy': 'x'}} + + const res = await fetchWithDpopRetry(handler, URL, init) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ok: 1}) + expect(handler).toHaveBeenCalledTimes(2) + expect(handler).toHaveBeenNthCalledWith(2, URL, init) + }) + + it('treats an omitted method as GET and retries HEAD', async () => { + const omitted = mockHandler( + dpopError('DPoP proof is too old'), + jsonResponse(200, {}), + ) + await fetchWithDpopRetry(omitted, URL, {}) + expect(omitted).toHaveBeenCalledTimes(2) + + const head = mockHandler( + dpopError('DPoP proof is too old'), + jsonResponse(200, {}), + ) + await fetchWithDpopRetry(head, URL, {method: 'head'}) + expect(head).toHaveBeenCalledTimes(2) + }) + + it.each(['POST', 'PUT', 'PATCH', 'DELETE'])( + 'never retries %s', + async method => { + const handler = mockHandler(dpopError('DPoP proof is too old')) + + const res = await fetchWithDpopRetry(handler, URL, {method}) + + expect(res.status).toBe(401) + expect(handler).toHaveBeenCalledTimes(1) + }, + ) + + it('surfaces a second failure without a third attempt', async () => { + const handler = mockHandler( + dpopError('DPoP proof is too old'), + dpopError('DPoP proof is too old'), + jsonResponse(200, {}), + ) + + const res = await fetchWithDpopRetry(handler, URL, {method: 'GET'}) + + expect(res.status).toBe(401) + expect(await res.json()).toEqual({ + error: 'invalid_dpop_proof', + message: 'DPoP proof is too old', + }) + expect(handler).toHaveBeenCalledTimes(2) + }) + + it.each([ + ['another DPoP error', dpopError('DPoP "htm" mismatch')], + [ + 'invalid_token', + jsonResponse(401, {error: 'invalid_token', message: 'expired'}), + ], + ['a non-JSON body', new Response('nope', {status: 401})], + ])('does not retry %s and leaves the body readable', async (_, first) => { + const handler = mockHandler(first) + + const res = await fetchWithDpopRetry(handler, URL, {method: 'GET'}) + + expect(res.status).toBe(401) + await expect(res.text()).resolves.toBeTruthy() + expect(handler).toHaveBeenCalledTimes(1) + }) + + it('does not retry an aborted request', async () => { + const controller = new AbortController() + controller.abort() + const handler = mockHandler(dpopError('DPoP proof is too old')) + + await fetchWithDpopRetry(handler, URL, {signal: controller.signal}) + + expect(handler).toHaveBeenCalledTimes(1) + }) + + it('passes non-401 responses through untouched', async () => { + const handler = mockHandler(jsonResponse(500, {error: 'InternalError'})) + + const res = await fetchWithDpopRetry(handler, URL, {method: 'GET'}) + + expect(res.status).toBe(500) + expect(handler).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/state/session/oauth-agent.ts b/src/state/session/oauth-agent.ts index 3b0ddeb6c..3f15477f6 100644 --- a/src/state/session/oauth-agent.ts +++ b/src/state/session/oauth-agent.ts @@ -15,6 +15,7 @@ import { } from './agent' import {configureModerationForAccount} from './moderation' import {getOAuthClient} from './oauth-client' +import {fetchWithDpopRetry} from './oauth-dpop-recovery' import {type SessionAccount} from './types' export async function oauthCreateAgent(session: OAuthSession) { @@ -130,7 +131,11 @@ export class OauthBskyAppAgent extends Agent { }, fetchHandler(url, init) { const finalInit = stripAppviewProxyForPdsLocalMethods(url, init) ?? init - return session.fetchHandler(url, finalInit).then( + return fetchWithDpopRetry( + (u, i) => session.fetchHandler(u, i), + url, + finalInit, + ).then( res => { reportProxiedFetch(finalInit, res.status) return res diff --git a/src/state/session/oauth-dpop-recovery.ts b/src/state/session/oauth-dpop-recovery.ts new file mode 100644 index 000000000..fcac88039 --- /dev/null +++ b/src/state/session/oauth-dpop-recovery.ts @@ -0,0 +1,41 @@ +const RETRYABLE_METHODS = new Set(['GET', 'HEAD']) + +const RETRYABLE_DPOP_MESSAGES = new Set([ + 'DPoP proof is too old', + 'DPoP proof "jti" replayed', + 'DPoP proof replayed', + 'Failed to verify DPoP proof: "iat" claim timestamp check failed (too far in the past)', +]) + +// A proof can be rejected as stale or replayed when the OS delays or resends a +// request. Reads are retried once with a fresh proof; writes never are, since +// the original may have already been applied. +export async function fetchWithDpopRetry( + fetchHandler: (url: string, init: RequestInit) => Promise, + url: string, + init: RequestInit, +): Promise { + const res = await fetchHandler(url, init) + if (res.status !== 401) return res + const method = (init.method ?? 'GET').toUpperCase() + if (!RETRYABLE_METHODS.has(method) || init.signal?.aborted) return res + if (!(await isRetryableDpopError(res))) return res + res.body?.cancel().catch(() => {}) + return fetchHandler(url, init) +} + +async function isRetryableDpopError(res: Response): Promise { + try { + const body = (await res.clone().json()) as { + error?: unknown + message?: unknown + } | null + return ( + body?.error === 'invalid_dpop_proof' && + typeof body.message === 'string' && + RETRYABLE_DPOP_MESSAGES.has(body.message) + ) + } catch { + return false + } +}