From 75dbfa4185e404d6d5641034ddb4c93da0c13d87 Mon Sep 17 00:00:00 2001 From: Eric Bailey Date: Thu, 4 Jan 2024 12:52:05 -0600 Subject: [PATCH] Better handling of resumeSession errors --- packages/api/src/agent.ts | 23 +++++++++++++++-------- packages/api/src/types.ts | 7 ++++++- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/api/src/agent.ts b/packages/api/src/agent.ts index aea3cce9d4b..f9ac6c54ca3 100644 --- a/packages/api/src/agent.ts +++ b/packages/api/src/agent.ts @@ -1,5 +1,5 @@ import { ErrorResponseBody, errorResponseBody } from '@atproto/xrpc' -import { defaultFetchHandler } from '@atproto/xrpc' +import { defaultFetchHandler, XRPCError, ResponseType } from '@atproto/xrpc' import { isValidDidDoc, getPdsEndpoint } from '@atproto/common-web' import { AtpBaseClient, @@ -159,23 +159,30 @@ export class AtpAgent { try { this.session = session const res = await this.api.com.atproto.server.getSession() - if (!res.success || res.data.did !== this.session.did) { - throw new Error('Invalid session') + if (res.data.did !== this.session.did) { + throw new XRPCError(ResponseType.InvalidRequest, 'Invalid session', 'InvalidDID') } this.session.email = res.data.email this.session.handle = res.data.handle this.session.emailConfirmed = res.data.emailConfirmed this._updateApiEndpoint(res.data.didDoc) + this._persistSession?.('create', this.session) return res } catch (e) { this.session = undefined - throw e - } finally { - if (this.session) { - this._persistSession?.('create', this.session) + + if (e instanceof XRPCError && e.error) { + // `ExpiredToken` and `InvalidToken` are handled by the `this._refreshSession` + if (['AuthMissing', 'InvalidDID'].includes(e.error)) { + this._persistSession?.('expired', undefined) + } else { + this._persistSession?.('network-error', undefined) + } } else { - this._persistSession?.('create-failed', undefined) + this._persistSession?.('network-error', undefined) } + + throw e } } diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index c0f78bfaafc..7b462c0b7e8 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -3,7 +3,12 @@ import { LabelPreference } from './moderation/types' /** * Used by the PersistSessionHandler to indicate what change occurred */ -export type AtpSessionEvent = 'create' | 'create-failed' | 'update' | 'expired' +export type AtpSessionEvent = + | 'create' + | 'create-failed' + | 'update' + | 'expired' + | 'network-error' /** * Used by AtpAgent to store active sessions