[SDK] Migrate the account surface to the pds and service clients (#11367)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Samuel Newman
2026-08-13 22:26:17 +03:00
committed by GitHub
parent f5c166a055
commit 34d1c75756
16 changed files with 148 additions and 88 deletions
-6
View File
@@ -1099,12 +1099,6 @@
},
"typescript/no-misused-promises": {
"count": 2
},
"typescript/no-unsafe-call": {
"count": 2
},
"typescript/no-unsafe-member-access": {
"count": 2
}
},
"src/screens/Settings/components/CopyButton.tsx": {
@@ -1,13 +1,14 @@
import {useMutation} from '@tanstack/react-query'
import {useAgent} from '#/state/session'
import {usePdsClient} from '#/state/session'
import {com} from '#/lexicons'
export function useRequestEmailUpdate() {
const agent = useAgent()
const client = usePdsClient()
return useMutation({
mutationFn: async () => {
return (await agent.com.atproto.server.requestEmailUpdate()).data
return await client.call(com.atproto.server.requestEmailUpdate)
},
})
}
@@ -1,13 +1,14 @@
import {useMutation} from '@tanstack/react-query'
import {useAgent} from '#/state/session'
import {usePdsClient} from '#/state/session'
import {com} from '#/lexicons'
export function useRequestEmailVerification() {
const agent = useAgent()
const client = usePdsClient()
return useMutation({
mutationFn: async () => {
await agent.com.atproto.server.requestEmailConfirmation()
await client.call(com.atproto.server.requestEmailConfirmation)
},
})
}
@@ -4,7 +4,7 @@ import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro'
import {useAgent, useSession} from '#/state/session'
import {usePdsClient, useSession} from '#/state/session'
import {atoms as a, useBreakpoints, useTheme} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog'
@@ -16,6 +16,7 @@ import {useIntentDialogs} from '#/components/intents/IntentDialogs'
import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'
import {IS_NATIVE} from '#/env'
import {com} from '#/lexicons'
export function VerifyEmailIntentDialog() {
const {verifyEmailDialogControl: control} = useIntentDialogs()
@@ -37,7 +38,7 @@ function Inner({}: {control: DialogControlProps}) {
'loading' | 'success' | 'failure' | 'resent'
>('loading')
const [sending, setSending] = useState(false)
const agent = useAgent()
const client = usePdsClient()
const {currentAccount} = useSession()
const {mutate: confirmEmail} = useConfirmEmail({
onSuccess: () => setStatus('success'),
@@ -52,7 +53,7 @@ function Inner({}: {control: DialogControlProps}) {
const onPressResendEmail = async () => {
setSending(true)
await agent.com.atproto.server.requestEmailConfirmation()
await client.call(com.atproto.server.requestEmailConfirmation)
setSending(false)
setStatus('resent')
}
+20
View File
@@ -24,3 +24,23 @@ export function createLexClient(
): Client {
return new Client(agent, {strictResponseProcessing: false, ...options})
}
/**
* An unauthenticated {@link Client} pointed at an arbitrary service URL, for
* the PRE-AUTH flows that talk to a host the user typed or picked (hosting
* provider description, password reset, handle availability). Those requests
* cannot go through a session-scoped client, because there is no session yet.
*
* Deliberately NOT memoized: `service` is user-supplied and changes as the user
* edits it, so there is no stable key to cache on. Each call builds a fresh
* client, mirroring the ad-hoc agents these call sites constructed inline. That
* keeps client identity per-render, so callers must not put the returned client
* in a React Query key or a dependency array.
*
* Requests use PLAIN `fetch`, not `networkAwareFetch`: the host is untrusted
* input, and a typo'd or dead service must not be reported as the app losing
* network reachability.
*/
export function createServiceClient(service: string): Client {
return createLexClient({service})
}
+9 -5
View File
@@ -1,12 +1,11 @@
import {useCallback, useState} from 'react'
import {Keyboard, View} from 'react-native'
import {type ComAtprotoServerDescribeServer} from '@atproto/api'
import {Trans, useLingui} from '@lingui/react/macro'
import * as EmailValidator from 'email-validator'
import {createServiceClient} from '#/lib/lexClient'
import {cleanError, isNetworkError} from '#/lib/strings/errors'
import {logger} from '#/logger'
import {Agent} from '#/state/session/agent'
import {atoms as a, useTheme, web} from '#/alf'
import {Admonition} from '#/components/Admonition'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
@@ -16,9 +15,10 @@ import {At_Stroke2_Corner0_Rounded as At} from '#/components/icons/At'
import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'
import {IS_WEB} from '#/env'
import {com} from '#/lexicons'
import {FormContainer} from './FormContainer'
type ServiceDescription = ComAtprotoServerDescribeServer.OutputSchema
type ServiceDescription = com.atproto.server.describeServer.$OutputBody
export const ForgotPasswordForm = ({
error,
@@ -55,8 +55,12 @@ export const ForgotPasswordForm = ({
setIsProcessing(true)
try {
const agent = new Agent(null, {service: serviceUrl})
await agent.com.atproto.server.requestPasswordReset({email})
/*
* Pre-auth request against a user-chosen host, so it goes through a
* one-off service client rather than a session-scoped one.
*/
const client = createServiceClient(serviceUrl)
await client.call(com.atproto.server.requestPasswordReset, {email})
onEmailSent()
} catch (err) {
logger.warn('Failed to request password reset', {error: err})
+8 -3
View File
@@ -2,10 +2,10 @@ import {useState} from 'react'
import {View} from 'react-native'
import {Trans, useLingui} from '@lingui/react/macro'
import {createServiceClient} from '#/lib/lexClient'
import {cleanError, isNetworkError} from '#/lib/strings/errors'
import {checkAndFormatResetCode} from '#/lib/strings/password'
import {logger} from '#/logger'
import {Agent} from '#/state/session/agent'
import {atoms as a, web} from '#/alf'
import {Admonition} from '#/components/Admonition'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
@@ -16,6 +16,7 @@ import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'
import {useAnalytics} from '#/analytics'
import {IS_WEB} from '#/env'
import {com} from '#/lexicons'
import {FormContainer} from './FormContainer'
export const SetNewPasswordForm = ({
@@ -61,8 +62,12 @@ export const SetNewPasswordForm = ({
setIsProcessing(true)
try {
const agent = new Agent(null, {service: serviceUrl})
await agent.com.atproto.server.resetPassword({
/*
* Pre-auth request against a user-chosen host, so it goes through a
* one-off service client rather than a session-scoped one.
*/
const client = createServiceClient(serviceUrl)
await client.call(com.atproto.server.resetPassword, {
token: formattedCode,
password,
})
+2 -2
View File
@@ -6,7 +6,6 @@ import Animated, {
LayoutAnimationConfig,
LinearTransition,
} from 'react-native-reanimated'
import {type ComAtprotoServerListAppPasswords} from '@atproto/api'
import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro'
@@ -33,6 +32,7 @@ import {Loader} from '#/components/Loader'
import * as Prompt from '#/components/Prompt'
import * as Toast from '#/components/Toast'
import {Text} from '#/components/Typography'
import {type com} from '#/lexicons'
import {AddAppPasswordDialog} from './components/AddAppPasswordDialog'
import * as SettingsList from './components/SettingsList'
@@ -135,7 +135,7 @@ export function AppPasswordsScreen({}: Props) {
function AppPasswordCard({
appPassword,
}: {
appPassword: ComAtprotoServerListAppPasswords.AppPassword
appPassword: com.atproto.server.listAppPasswords.AppPassword
}) {
const t = useTheme()
const {i18n, _} = useLingui()
@@ -8,7 +8,6 @@ import Animated, {
SlideInRight,
SlideOutLeft,
} from 'react-native-reanimated'
import {type ComAtprotoServerCreateAppPassword} from '@atproto/api'
import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro'
@@ -25,6 +24,7 @@ import {ChevronRight_Stroke2_Corner0_Rounded as ChevronRight} from '#/components
import {SquareBehindSquare4_Stroke2_Corner0_Rounded as CopyIcon} from '#/components/icons/SquareBehindSquare4'
import {Text} from '#/components/Typography'
import {IS_WEB} from '#/env'
import {type com} from '#/lexicons'
import {CopyButton} from './CopyButton'
export function AddAppPasswordDialog({
@@ -70,7 +70,7 @@ function CreateDialogInner({passwords}: {passwords: string[]}) {
error: validationError,
isPending,
} = useMutation<
ComAtprotoServerCreateAppPassword.AppPassword,
com.atproto.server.createAppPassword.AppPassword,
Error | DisplayableError
>({
mutationFn: async () => {
@@ -7,8 +7,9 @@ import * as EmailValidator from 'email-validator'
import {cleanError, isNetworkError} from '#/lib/strings/errors'
import {checkAndFormatResetCode} from '#/lib/strings/password'
import {matchXrpcError} from '#/lib/xrpc-error'
import {logger} from '#/logger'
import {useAgent, useSession} from '#/state/session'
import {usePdsClient, useSession} from '#/state/session'
import {ErrorMessage} from '#/view/com/util/error/ErrorMessage'
import {android, atoms as a, web} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
@@ -17,6 +18,7 @@ import * as TextField from '#/components/forms/TextField'
import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'
import {IS_NATIVE} from '#/env'
import {com} from '#/lexicons'
enum Stages {
RequestCode = 'RequestCode',
@@ -44,7 +46,7 @@ export function ChangePasswordDialog({
function Inner() {
const {_} = useLingui()
const {currentAccount} = useSession()
const agent = useAgent()
const client = usePdsClient()
const control = Dialog.useDialogContext()
const [stage, setStage] = useState(Stages.RequestCode)
@@ -85,7 +87,7 @@ function Inner() {
setError('')
setIsProcessing(true)
try {
await agent.com.atproto.server.requestPasswordReset({
await client.call(com.atproto.server.requestPasswordReset, {
email: currentAccount.email,
})
setStage(Stages.ChangePassword)
@@ -129,7 +131,7 @@ function Inner() {
setError('')
setIsProcessing(true)
try {
await agent.com.atproto.server.resetPassword({
await client.call(com.atproto.server.resetPassword, {
token: formattedCode,
password: newPassword,
})
@@ -141,7 +143,9 @@ function Inner() {
msg`Unable to contact your service. Please check your internet connection and try again.`,
),
)
} else if (e?.toString().includes('Token is invalid')) {
} else if (
matchXrpcError(e, com.atproto.server.resetPassword) === 'InvalidToken'
) {
setError(_(msg`This confirmation code is not valid. Please try again.`))
} else {
logger.error('Failed to set new password', {safeMessage: e})
@@ -5,7 +5,7 @@ import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro'
import {logger} from '#/logger'
import {useAgent, useSessionApi} from '#/state/session'
import {usePdsClient, useSessionApi} from '#/state/session'
import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import {type DialogOuterProps} from '#/components/Dialog'
@@ -14,6 +14,7 @@ import {CircleInfo_Stroke2_Corner0_Rounded as CircleInfo} from '#/components/ico
import {Loader} from '#/components/Loader'
import * as Prompt from '#/components/Prompt'
import {Text} from '#/components/Typography'
import {com} from '#/lexicons'
export function DeactivateAccountDialog({
control,
@@ -34,7 +35,7 @@ function DeactivateAccountDialogInner({
}) {
const t = useTheme()
const {_} = useLingui()
const agent = useAgent()
const client = usePdsClient()
const {logoutCurrentAccount} = useSessionApi()
const [pending, setPending] = useState(false)
const [error, setError] = useState<string | undefined>()
@@ -42,7 +43,7 @@ function DeactivateAccountDialogInner({
const handleDeactivate = useCallback(async () => {
try {
setPending(true)
await agent.com.atproto.server.deactivateAccount({})
await client.call(com.atproto.server.deactivateAccount, {})
control.close(() => {
logoutCurrentAccount('Deactivated')
})
@@ -66,7 +67,7 @@ function DeactivateAccountDialogInner({
} finally {
setPending(false)
}
}, [agent, control, logoutCurrentAccount, _, setPending])
}, [client, control, logoutCurrentAccount, _, setPending])
return (
<>
@@ -1,14 +1,19 @@
import {useCallback, useRef, useState} from 'react'
import {type TextInput, View} from 'react-native'
import {type DidString} from '@atproto/syntax'
import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro'
import {DM_SERVICE_HEADERS} from '#/lib/constants'
import {useCleanError} from '#/lib/hooks/useCleanError'
import {sanitizeHandle} from '#/lib/strings/handles'
import {logger} from '#/logger'
import {useAgent, useSession, useSessionApi} from '#/state/session'
import {
useChatClient,
usePdsClient,
useSession,
useSessionApi,
} from '#/state/session'
import {atoms as a, useTheme} from '#/alf'
import {Admonition} from '#/components/Admonition'
import {type DialogOuterProps} from '#/components/Dialog'
@@ -24,6 +29,7 @@ import {Loader} from '#/components/Loader'
import * as Prompt from '#/components/Prompt'
import * as toast from '#/components/Toast'
import {Span, Text} from '#/components/Typography'
import {chat, com} from '#/lexicons'
import {resetToTab} from '#/Navigation'
const WHITESPACE_RE = /\s/gu
@@ -72,7 +78,8 @@ function DeleteAccountDialogInner({
const t = useTheme()
const {_} = useLingui()
const cleanError = useCleanError()
const agent = useAgent()
const client = usePdsClient()
const chatClient = useChatClient()
const {currentAccount} = useSession()
const {removeAccount} = useSessionApi()
@@ -89,7 +96,7 @@ function DeleteAccountDialogInner({
}
try {
setEmailState(EmailState.PENDING)
await agent.com.atproto.server.requestAccountDelete()
await client.call(com.atproto.server.requestAccountDelete)
setError('')
setEmailSentCount(prevCount => prevCount + 1)
setStep(Step.VERIFY_CODE)
@@ -103,7 +110,7 @@ function DeleteAccountDialogInner({
} finally {
setEmailState(EmailState.DEFAULT)
}
}, [agent, cleanError, emailState, setEmailState])
}, [client, cleanError, emailState, setEmailState])
const confirmDeletion = useCallback(async () => {
try {
@@ -112,15 +119,15 @@ function DeleteAccountDialogInner({
throw new Error('Invalid did')
}
const token = confirmCode.replace(WHITESPACE_RE, '')
// Inform chat service of intent to delete account.
const {success} = await agent.chat.bsky.actor.deleteAccount(undefined, {
headers: DM_SERVICE_HEADERS,
})
if (!success) {
throw new Error('Failed to inform chat service of account deletion')
}
await agent.com.atproto.server.deleteAccount({
did: currentAccount.did,
/*
* Inform chat service of intent to delete account. A non-2xx response
* throws, so reaching the next line means the chat service accepted it -
* the agent's `success` flag has no client-side equivalent.
*/
await chatClient.call(chat.bsky.actor.deleteAccount)
await client.call(com.atproto.server.deleteAccount, {
// the persisted account did is already resolved
did: currentAccount.did as DidString,
password,
token,
})
@@ -142,8 +149,9 @@ function DeleteAccountDialogInner({
}
}, [
_,
agent,
chatClient,
cleanError,
client,
confirmCode,
control,
currentAccount,
+13 -15
View File
@@ -1,39 +1,37 @@
import {type ComAtprotoServerCreateAppPassword} from '@atproto/api'
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
import {STALE} from '#/state/queries'
import {useAgent} from '../session'
import {com} from '#/lexicons'
import {usePdsClient} from '../session'
const RQKEY_ROOT = 'app-passwords'
export const RQKEY = () => [RQKEY_ROOT]
export function useAppPasswordsQuery() {
const agent = useAgent()
const client = usePdsClient()
return useQuery({
staleTime: STALE.MINUTES.FIVE,
queryKey: RQKEY(),
queryFn: async () => {
const res = await agent.com.atproto.server.listAppPasswords({})
return res.data.passwords
const data = await client.call(com.atproto.server.listAppPasswords)
return data.passwords
},
})
}
export function useAppPasswordCreateMutation() {
const queryClient = useQueryClient()
const agent = useAgent()
const client = usePdsClient()
return useMutation<
ComAtprotoServerCreateAppPassword.OutputSchema,
com.atproto.server.createAppPassword.$OutputBody,
Error,
{name: string; privileged: boolean}
>({
mutationFn: async ({name, privileged}) => {
return (
await agent.com.atproto.server.createAppPassword({
name,
privileged,
})
).data
return await client.call(com.atproto.server.createAppPassword, {
name,
privileged,
})
},
onSuccess() {
queryClient.invalidateQueries({
@@ -45,10 +43,10 @@ export function useAppPasswordCreateMutation() {
export function useAppPasswordDeleteMutation() {
const queryClient = useQueryClient()
const agent = useAgent()
const client = usePdsClient()
return useMutation<void, Error, {name: string}>({
mutationFn: async ({name}) => {
await agent.com.atproto.server.revokeAppPassword({
await client.call(com.atproto.server.revokeAppPassword, {
name,
})
},
+28 -15
View File
@@ -1,4 +1,4 @@
import {ComAtprotoTempCheckHandleAvailability} from '@atproto/api'
import {type DatetimeString, type HandleString} from '@atproto/syntax'
import {useQuery} from '@tanstack/react-query'
import {
@@ -7,10 +7,11 @@ import {
PUBLIC_BSKY_SERVICE,
} from '#/lib/constants'
import {useDebouncedValue} from '#/lib/hooks/useDebouncedValue'
import {createServiceClient} from '#/lib/lexClient'
import {createFullHandle} from '#/lib/strings/handles'
import {useAnalytics} from '#/analytics'
import {com} from '#/lexicons'
import * as bsky from '#/types/bsky'
import {Agent} from '../session/agent'
export const RQKEY_handleAvailability = (
handle: string,
@@ -79,25 +80,33 @@ export async function checkHandleAvailability(
},
) {
if (serviceDid === BSKY_SERVICE_DID) {
const agent = new Agent(null, {service: BSKY_SERVICE})
/*
* Runs pre-auth during signup, so it goes through a one-off service client
* rather than a session-scoped one. The target is the fixed entryway rather
* than a user-supplied host, but there is still no session to hang a client
* off.
*/
const client = createServiceClient(BSKY_SERVICE)
// entryway has a special API for handle availability
const {data} = await agent.com.atproto.temp.checkHandleAvailability({
handle,
birthDate,
const data = await client.call(com.atproto.temp.checkHandleAvailability, {
// the caller assembles this from a validated username and domain
handle: handle as HandleString,
// callers pass an ISO date string built from the birth-date picker
birthDate: birthDate as DatetimeString | undefined,
email,
})
if (
bsky.dangerousIsType<ComAtprotoTempCheckHandleAvailability.ResultAvailable>(
bsky.isType(
com.atproto.temp.checkHandleAvailability.resultAvailable,
data.result,
ComAtprotoTempCheckHandleAvailability.isResultAvailable,
)
) {
return {available: true} as const
} else if (
bsky.dangerousIsType<ComAtprotoTempCheckHandleAvailability.ResultUnavailable>(
bsky.isType(
com.atproto.temp.checkHandleAvailability.resultUnavailable,
data.result,
ComAtprotoTempCheckHandleAvailability.isResultUnavailable,
)
) {
return {
@@ -110,14 +119,18 @@ export async function checkHandleAvailability(
)
}
} else {
// 3rd party PDSes won't have this API so just try and resolve the handle
const agent = new Agent(null, {service: PUBLIC_BSKY_SERVICE})
/*
* 3rd party PDSes won't have this API so just try and resolve the handle.
* This is an unauthenticated public-appview read, not a call against the
* user's chosen host.
*/
const client = createServiceClient(PUBLIC_BSKY_SERVICE)
try {
const res = await agent.resolveHandle({
handle,
const data = await client.call(com.atproto.identity.resolveHandle, {
handle: handle as HandleString,
})
if (res.data.did) {
if (data.did) {
return {available: false} as const
}
} catch {}
+9 -3
View File
@@ -1,8 +1,10 @@
import {useCallback} from 'react'
import {type HandleString} from '@atproto/syntax'
import {useMutation, useQueryClient} from '@tanstack/react-query'
import {STALE} from '#/state/queries'
import {useAgent} from '#/state/session'
import {useAgent, usePdsClient} from '#/state/session'
import {com} from '#/lexicons'
const handleQueryKeyRoot = 'handle'
const fetchHandleQueryKey = (handleOrDid: string) => [
@@ -36,11 +38,15 @@ export function useUpdateHandleMutation(opts?: {
onSuccess?: (handle: string) => void
}) {
const queryClient = useQueryClient()
const agent = useAgent()
const client = usePdsClient()
return useMutation({
mutationFn: async ({handle}: {handle: string}) => {
await agent.updateHandle({handle})
// `agent.updateHandle` was a pure alias for this method
await client.call(com.atproto.identity.updateHandle, {
// callers validate the handle before submitting
handle: handle as HandleString,
})
},
onSuccess(_data, variables) {
opts?.onSuccess?.(variables.handle)
+8 -4
View File
@@ -1,6 +1,7 @@
import {useQuery} from '@tanstack/react-query'
import {Agent} from '../session/agent'
import {createServiceClient} from '#/lib/lexClient'
import {com} from '#/lexicons'
const RQKEY_ROOT = 'service'
export const RQKEY = (serviceUrl: string) => [RQKEY_ROOT, serviceUrl]
@@ -9,9 +10,12 @@ export function useServiceQuery(serviceUrl: string) {
return useQuery({
queryKey: RQKEY(serviceUrl),
queryFn: async () => {
const agent = new Agent(null, {service: serviceUrl})
const res = await agent.com.atproto.server.describeServer()
return res.data
/*
* The host is whatever the user typed or picked, so this describes it
* through a one-off service client rather than a session-scoped one.
*/
const client = createServiceClient(serviceUrl)
return await client.call(com.atproto.server.describeServer)
},
enabled: isValidUrl(serviceUrl),
})