[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": { "typescript/no-misused-promises": {
"count": 2 "count": 2
},
"typescript/no-unsafe-call": {
"count": 2
},
"typescript/no-unsafe-member-access": {
"count": 2
} }
}, },
"src/screens/Settings/components/CopyButton.tsx": { "src/screens/Settings/components/CopyButton.tsx": {
@@ -1,13 +1,14 @@
import {useMutation} from '@tanstack/react-query' import {useMutation} from '@tanstack/react-query'
import {useAgent} from '#/state/session' import {usePdsClient} from '#/state/session'
import {com} from '#/lexicons'
export function useRequestEmailUpdate() { export function useRequestEmailUpdate() {
const agent = useAgent() const client = usePdsClient()
return useMutation({ return useMutation({
mutationFn: async () => { 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 {useMutation} from '@tanstack/react-query'
import {useAgent} from '#/state/session' import {usePdsClient} from '#/state/session'
import {com} from '#/lexicons'
export function useRequestEmailVerification() { export function useRequestEmailVerification() {
const agent = useAgent() const client = usePdsClient()
return useMutation({ return useMutation({
mutationFn: async () => { 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 {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro' 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 {atoms as a, useBreakpoints, useTheme} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button' import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog' import * as Dialog from '#/components/Dialog'
@@ -16,6 +16,7 @@ import {useIntentDialogs} from '#/components/intents/IntentDialogs'
import {Loader} from '#/components/Loader' import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography' import {Text} from '#/components/Typography'
import {IS_NATIVE} from '#/env' import {IS_NATIVE} from '#/env'
import {com} from '#/lexicons'
export function VerifyEmailIntentDialog() { export function VerifyEmailIntentDialog() {
const {verifyEmailDialogControl: control} = useIntentDialogs() const {verifyEmailDialogControl: control} = useIntentDialogs()
@@ -37,7 +38,7 @@ function Inner({}: {control: DialogControlProps}) {
'loading' | 'success' | 'failure' | 'resent' 'loading' | 'success' | 'failure' | 'resent'
>('loading') >('loading')
const [sending, setSending] = useState(false) const [sending, setSending] = useState(false)
const agent = useAgent() const client = usePdsClient()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {mutate: confirmEmail} = useConfirmEmail({ const {mutate: confirmEmail} = useConfirmEmail({
onSuccess: () => setStatus('success'), onSuccess: () => setStatus('success'),
@@ -52,7 +53,7 @@ function Inner({}: {control: DialogControlProps}) {
const onPressResendEmail = async () => { const onPressResendEmail = async () => {
setSending(true) setSending(true)
await agent.com.atproto.server.requestEmailConfirmation() await client.call(com.atproto.server.requestEmailConfirmation)
setSending(false) setSending(false)
setStatus('resent') setStatus('resent')
} }
+20
View File
@@ -24,3 +24,23 @@ export function createLexClient(
): Client { ): Client {
return new Client(agent, {strictResponseProcessing: false, ...options}) 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 {useCallback, useState} from 'react'
import {Keyboard, View} from 'react-native' import {Keyboard, View} from 'react-native'
import {type ComAtprotoServerDescribeServer} from '@atproto/api'
import {Trans, useLingui} from '@lingui/react/macro' import {Trans, useLingui} from '@lingui/react/macro'
import * as EmailValidator from 'email-validator' import * as EmailValidator from 'email-validator'
import {createServiceClient} from '#/lib/lexClient'
import {cleanError, isNetworkError} from '#/lib/strings/errors' import {cleanError, isNetworkError} from '#/lib/strings/errors'
import {logger} from '#/logger' import {logger} from '#/logger'
import {Agent} from '#/state/session/agent'
import {atoms as a, useTheme, web} from '#/alf' import {atoms as a, useTheme, web} from '#/alf'
import {Admonition} from '#/components/Admonition' import {Admonition} from '#/components/Admonition'
import {Button, ButtonIcon, ButtonText} from '#/components/Button' 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 {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography' import {Text} from '#/components/Typography'
import {IS_WEB} from '#/env' import {IS_WEB} from '#/env'
import {com} from '#/lexicons'
import {FormContainer} from './FormContainer' import {FormContainer} from './FormContainer'
type ServiceDescription = ComAtprotoServerDescribeServer.OutputSchema type ServiceDescription = com.atproto.server.describeServer.$OutputBody
export const ForgotPasswordForm = ({ export const ForgotPasswordForm = ({
error, error,
@@ -55,8 +55,12 @@ export const ForgotPasswordForm = ({
setIsProcessing(true) setIsProcessing(true)
try { 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() onEmailSent()
} catch (err) { } catch (err) {
logger.warn('Failed to request password reset', {error: 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 {View} from 'react-native'
import {Trans, useLingui} from '@lingui/react/macro' import {Trans, useLingui} from '@lingui/react/macro'
import {createServiceClient} from '#/lib/lexClient'
import {cleanError, isNetworkError} from '#/lib/strings/errors' import {cleanError, isNetworkError} from '#/lib/strings/errors'
import {checkAndFormatResetCode} from '#/lib/strings/password' import {checkAndFormatResetCode} from '#/lib/strings/password'
import {logger} from '#/logger' import {logger} from '#/logger'
import {Agent} from '#/state/session/agent'
import {atoms as a, web} from '#/alf' import {atoms as a, web} from '#/alf'
import {Admonition} from '#/components/Admonition' import {Admonition} from '#/components/Admonition'
import {Button, ButtonIcon, ButtonText} from '#/components/Button' import {Button, ButtonIcon, ButtonText} from '#/components/Button'
@@ -16,6 +16,7 @@ import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography' import {Text} from '#/components/Typography'
import {useAnalytics} from '#/analytics' import {useAnalytics} from '#/analytics'
import {IS_WEB} from '#/env' import {IS_WEB} from '#/env'
import {com} from '#/lexicons'
import {FormContainer} from './FormContainer' import {FormContainer} from './FormContainer'
export const SetNewPasswordForm = ({ export const SetNewPasswordForm = ({
@@ -61,8 +62,12 @@ export const SetNewPasswordForm = ({
setIsProcessing(true) setIsProcessing(true)
try { 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, token: formattedCode,
password, password,
}) })
+2 -2
View File
@@ -6,7 +6,6 @@ import Animated, {
LayoutAnimationConfig, LayoutAnimationConfig,
LinearTransition, LinearTransition,
} from 'react-native-reanimated' } from 'react-native-reanimated'
import {type ComAtprotoServerListAppPasswords} from '@atproto/api'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro' import {Trans} from '@lingui/react/macro'
@@ -33,6 +32,7 @@ import {Loader} from '#/components/Loader'
import * as Prompt from '#/components/Prompt' import * as Prompt from '#/components/Prompt'
import * as Toast from '#/components/Toast' import * as Toast from '#/components/Toast'
import {Text} from '#/components/Typography' import {Text} from '#/components/Typography'
import {type com} from '#/lexicons'
import {AddAppPasswordDialog} from './components/AddAppPasswordDialog' import {AddAppPasswordDialog} from './components/AddAppPasswordDialog'
import * as SettingsList from './components/SettingsList' import * as SettingsList from './components/SettingsList'
@@ -135,7 +135,7 @@ export function AppPasswordsScreen({}: Props) {
function AppPasswordCard({ function AppPasswordCard({
appPassword, appPassword,
}: { }: {
appPassword: ComAtprotoServerListAppPasswords.AppPassword appPassword: com.atproto.server.listAppPasswords.AppPassword
}) { }) {
const t = useTheme() const t = useTheme()
const {i18n, _} = useLingui() const {i18n, _} = useLingui()
@@ -8,7 +8,6 @@ import Animated, {
SlideInRight, SlideInRight,
SlideOutLeft, SlideOutLeft,
} from 'react-native-reanimated' } from 'react-native-reanimated'
import {type ComAtprotoServerCreateAppPassword} from '@atproto/api'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro' 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 {SquareBehindSquare4_Stroke2_Corner0_Rounded as CopyIcon} from '#/components/icons/SquareBehindSquare4'
import {Text} from '#/components/Typography' import {Text} from '#/components/Typography'
import {IS_WEB} from '#/env' import {IS_WEB} from '#/env'
import {type com} from '#/lexicons'
import {CopyButton} from './CopyButton' import {CopyButton} from './CopyButton'
export function AddAppPasswordDialog({ export function AddAppPasswordDialog({
@@ -70,7 +70,7 @@ function CreateDialogInner({passwords}: {passwords: string[]}) {
error: validationError, error: validationError,
isPending, isPending,
} = useMutation< } = useMutation<
ComAtprotoServerCreateAppPassword.AppPassword, com.atproto.server.createAppPassword.AppPassword,
Error | DisplayableError Error | DisplayableError
>({ >({
mutationFn: async () => { mutationFn: async () => {
@@ -7,8 +7,9 @@ import * as EmailValidator from 'email-validator'
import {cleanError, isNetworkError} from '#/lib/strings/errors' import {cleanError, isNetworkError} from '#/lib/strings/errors'
import {checkAndFormatResetCode} from '#/lib/strings/password' import {checkAndFormatResetCode} from '#/lib/strings/password'
import {matchXrpcError} from '#/lib/xrpc-error'
import {logger} from '#/logger' 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 {ErrorMessage} from '#/view/com/util/error/ErrorMessage'
import {android, atoms as a, web} from '#/alf' import {android, atoms as a, web} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button' import {Button, ButtonIcon, ButtonText} from '#/components/Button'
@@ -17,6 +18,7 @@ import * as TextField from '#/components/forms/TextField'
import {Loader} from '#/components/Loader' import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography' import {Text} from '#/components/Typography'
import {IS_NATIVE} from '#/env' import {IS_NATIVE} from '#/env'
import {com} from '#/lexicons'
enum Stages { enum Stages {
RequestCode = 'RequestCode', RequestCode = 'RequestCode',
@@ -44,7 +46,7 @@ export function ChangePasswordDialog({
function Inner() { function Inner() {
const {_} = useLingui() const {_} = useLingui()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const agent = useAgent() const client = usePdsClient()
const control = Dialog.useDialogContext() const control = Dialog.useDialogContext()
const [stage, setStage] = useState(Stages.RequestCode) const [stage, setStage] = useState(Stages.RequestCode)
@@ -85,7 +87,7 @@ function Inner() {
setError('') setError('')
setIsProcessing(true) setIsProcessing(true)
try { try {
await agent.com.atproto.server.requestPasswordReset({ await client.call(com.atproto.server.requestPasswordReset, {
email: currentAccount.email, email: currentAccount.email,
}) })
setStage(Stages.ChangePassword) setStage(Stages.ChangePassword)
@@ -129,7 +131,7 @@ function Inner() {
setError('') setError('')
setIsProcessing(true) setIsProcessing(true)
try { try {
await agent.com.atproto.server.resetPassword({ await client.call(com.atproto.server.resetPassword, {
token: formattedCode, token: formattedCode,
password: newPassword, password: newPassword,
}) })
@@ -141,7 +143,9 @@ function Inner() {
msg`Unable to contact your service. Please check your internet connection and try again.`, 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.`)) setError(_(msg`This confirmation code is not valid. Please try again.`))
} else { } else {
logger.error('Failed to set new password', {safeMessage: e}) 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 {Trans} from '@lingui/react/macro'
import {logger} from '#/logger' import {logger} from '#/logger'
import {useAgent, useSessionApi} from '#/state/session' import {usePdsClient, useSessionApi} from '#/state/session'
import {atoms as a, useTheme} from '#/alf' import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button' import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import {type DialogOuterProps} from '#/components/Dialog' 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 {Loader} from '#/components/Loader'
import * as Prompt from '#/components/Prompt' import * as Prompt from '#/components/Prompt'
import {Text} from '#/components/Typography' import {Text} from '#/components/Typography'
import {com} from '#/lexicons'
export function DeactivateAccountDialog({ export function DeactivateAccountDialog({
control, control,
@@ -34,7 +35,7 @@ function DeactivateAccountDialogInner({
}) { }) {
const t = useTheme() const t = useTheme()
const {_} = useLingui() const {_} = useLingui()
const agent = useAgent() const client = usePdsClient()
const {logoutCurrentAccount} = useSessionApi() const {logoutCurrentAccount} = useSessionApi()
const [pending, setPending] = useState(false) const [pending, setPending] = useState(false)
const [error, setError] = useState<string | undefined>() const [error, setError] = useState<string | undefined>()
@@ -42,7 +43,7 @@ function DeactivateAccountDialogInner({
const handleDeactivate = useCallback(async () => { const handleDeactivate = useCallback(async () => {
try { try {
setPending(true) setPending(true)
await agent.com.atproto.server.deactivateAccount({}) await client.call(com.atproto.server.deactivateAccount, {})
control.close(() => { control.close(() => {
logoutCurrentAccount('Deactivated') logoutCurrentAccount('Deactivated')
}) })
@@ -66,7 +67,7 @@ function DeactivateAccountDialogInner({
} finally { } finally {
setPending(false) setPending(false)
} }
}, [agent, control, logoutCurrentAccount, _, setPending]) }, [client, control, logoutCurrentAccount, _, setPending])
return ( return (
<> <>
@@ -1,14 +1,19 @@
import {useCallback, useRef, useState} from 'react' import {useCallback, useRef, useState} from 'react'
import {type TextInput, View} from 'react-native' import {type TextInput, View} from 'react-native'
import {type DidString} from '@atproto/syntax'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro' import {Trans} from '@lingui/react/macro'
import {DM_SERVICE_HEADERS} from '#/lib/constants'
import {useCleanError} from '#/lib/hooks/useCleanError' import {useCleanError} from '#/lib/hooks/useCleanError'
import {sanitizeHandle} from '#/lib/strings/handles' import {sanitizeHandle} from '#/lib/strings/handles'
import {logger} from '#/logger' 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 {atoms as a, useTheme} from '#/alf'
import {Admonition} from '#/components/Admonition' import {Admonition} from '#/components/Admonition'
import {type DialogOuterProps} from '#/components/Dialog' import {type DialogOuterProps} from '#/components/Dialog'
@@ -24,6 +29,7 @@ import {Loader} from '#/components/Loader'
import * as Prompt from '#/components/Prompt' import * as Prompt from '#/components/Prompt'
import * as toast from '#/components/Toast' import * as toast from '#/components/Toast'
import {Span, Text} from '#/components/Typography' import {Span, Text} from '#/components/Typography'
import {chat, com} from '#/lexicons'
import {resetToTab} from '#/Navigation' import {resetToTab} from '#/Navigation'
const WHITESPACE_RE = /\s/gu const WHITESPACE_RE = /\s/gu
@@ -72,7 +78,8 @@ function DeleteAccountDialogInner({
const t = useTheme() const t = useTheme()
const {_} = useLingui() const {_} = useLingui()
const cleanError = useCleanError() const cleanError = useCleanError()
const agent = useAgent() const client = usePdsClient()
const chatClient = useChatClient()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {removeAccount} = useSessionApi() const {removeAccount} = useSessionApi()
@@ -89,7 +96,7 @@ function DeleteAccountDialogInner({
} }
try { try {
setEmailState(EmailState.PENDING) setEmailState(EmailState.PENDING)
await agent.com.atproto.server.requestAccountDelete() await client.call(com.atproto.server.requestAccountDelete)
setError('') setError('')
setEmailSentCount(prevCount => prevCount + 1) setEmailSentCount(prevCount => prevCount + 1)
setStep(Step.VERIFY_CODE) setStep(Step.VERIFY_CODE)
@@ -103,7 +110,7 @@ function DeleteAccountDialogInner({
} finally { } finally {
setEmailState(EmailState.DEFAULT) setEmailState(EmailState.DEFAULT)
} }
}, [agent, cleanError, emailState, setEmailState]) }, [client, cleanError, emailState, setEmailState])
const confirmDeletion = useCallback(async () => { const confirmDeletion = useCallback(async () => {
try { try {
@@ -112,15 +119,15 @@ function DeleteAccountDialogInner({
throw new Error('Invalid did') throw new Error('Invalid did')
} }
const token = confirmCode.replace(WHITESPACE_RE, '') const token = confirmCode.replace(WHITESPACE_RE, '')
// Inform chat service of intent to delete account. /*
const {success} = await agent.chat.bsky.actor.deleteAccount(undefined, { * Inform chat service of intent to delete account. A non-2xx response
headers: DM_SERVICE_HEADERS, * throws, so reaching the next line means the chat service accepted it -
}) * the agent's `success` flag has no client-side equivalent.
if (!success) { */
throw new Error('Failed to inform chat service of account deletion') await chatClient.call(chat.bsky.actor.deleteAccount)
} await client.call(com.atproto.server.deleteAccount, {
await agent.com.atproto.server.deleteAccount({ // the persisted account did is already resolved
did: currentAccount.did, did: currentAccount.did as DidString,
password, password,
token, token,
}) })
@@ -142,8 +149,9 @@ function DeleteAccountDialogInner({
} }
}, [ }, [
_, _,
agent, chatClient,
cleanError, cleanError,
client,
confirmCode, confirmCode,
control, control,
currentAccount, currentAccount,
+13 -15
View File
@@ -1,39 +1,37 @@
import {type ComAtprotoServerCreateAppPassword} from '@atproto/api'
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
import {STALE} from '#/state/queries' import {STALE} from '#/state/queries'
import {useAgent} from '../session' import {com} from '#/lexicons'
import {usePdsClient} from '../session'
const RQKEY_ROOT = 'app-passwords' const RQKEY_ROOT = 'app-passwords'
export const RQKEY = () => [RQKEY_ROOT] export const RQKEY = () => [RQKEY_ROOT]
export function useAppPasswordsQuery() { export function useAppPasswordsQuery() {
const agent = useAgent() const client = usePdsClient()
return useQuery({ return useQuery({
staleTime: STALE.MINUTES.FIVE, staleTime: STALE.MINUTES.FIVE,
queryKey: RQKEY(), queryKey: RQKEY(),
queryFn: async () => { queryFn: async () => {
const res = await agent.com.atproto.server.listAppPasswords({}) const data = await client.call(com.atproto.server.listAppPasswords)
return res.data.passwords return data.passwords
}, },
}) })
} }
export function useAppPasswordCreateMutation() { export function useAppPasswordCreateMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const agent = useAgent() const client = usePdsClient()
return useMutation< return useMutation<
ComAtprotoServerCreateAppPassword.OutputSchema, com.atproto.server.createAppPassword.$OutputBody,
Error, Error,
{name: string; privileged: boolean} {name: string; privileged: boolean}
>({ >({
mutationFn: async ({name, privileged}) => { mutationFn: async ({name, privileged}) => {
return ( return await client.call(com.atproto.server.createAppPassword, {
await agent.com.atproto.server.createAppPassword({ name,
name, privileged,
privileged, })
})
).data
}, },
onSuccess() { onSuccess() {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@@ -45,10 +43,10 @@ export function useAppPasswordCreateMutation() {
export function useAppPasswordDeleteMutation() { export function useAppPasswordDeleteMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const agent = useAgent() const client = usePdsClient()
return useMutation<void, Error, {name: string}>({ return useMutation<void, Error, {name: string}>({
mutationFn: async ({name}) => { mutationFn: async ({name}) => {
await agent.com.atproto.server.revokeAppPassword({ await client.call(com.atproto.server.revokeAppPassword, {
name, 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 {useQuery} from '@tanstack/react-query'
import { import {
@@ -7,10 +7,11 @@ import {
PUBLIC_BSKY_SERVICE, PUBLIC_BSKY_SERVICE,
} from '#/lib/constants' } from '#/lib/constants'
import {useDebouncedValue} from '#/lib/hooks/useDebouncedValue' import {useDebouncedValue} from '#/lib/hooks/useDebouncedValue'
import {createServiceClient} from '#/lib/lexClient'
import {createFullHandle} from '#/lib/strings/handles' import {createFullHandle} from '#/lib/strings/handles'
import {useAnalytics} from '#/analytics' import {useAnalytics} from '#/analytics'
import {com} from '#/lexicons'
import * as bsky from '#/types/bsky' import * as bsky from '#/types/bsky'
import {Agent} from '../session/agent'
export const RQKEY_handleAvailability = ( export const RQKEY_handleAvailability = (
handle: string, handle: string,
@@ -79,25 +80,33 @@ export async function checkHandleAvailability(
}, },
) { ) {
if (serviceDid === BSKY_SERVICE_DID) { 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 // entryway has a special API for handle availability
const {data} = await agent.com.atproto.temp.checkHandleAvailability({ const data = await client.call(com.atproto.temp.checkHandleAvailability, {
handle, // the caller assembles this from a validated username and domain
birthDate, handle: handle as HandleString,
// callers pass an ISO date string built from the birth-date picker
birthDate: birthDate as DatetimeString | undefined,
email, email,
}) })
if ( if (
bsky.dangerousIsType<ComAtprotoTempCheckHandleAvailability.ResultAvailable>( bsky.isType(
com.atproto.temp.checkHandleAvailability.resultAvailable,
data.result, data.result,
ComAtprotoTempCheckHandleAvailability.isResultAvailable,
) )
) { ) {
return {available: true} as const return {available: true} as const
} else if ( } else if (
bsky.dangerousIsType<ComAtprotoTempCheckHandleAvailability.ResultUnavailable>( bsky.isType(
com.atproto.temp.checkHandleAvailability.resultUnavailable,
data.result, data.result,
ComAtprotoTempCheckHandleAvailability.isResultUnavailable,
) )
) { ) {
return { return {
@@ -110,14 +119,18 @@ export async function checkHandleAvailability(
) )
} }
} else { } 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 { try {
const res = await agent.resolveHandle({ const data = await client.call(com.atproto.identity.resolveHandle, {
handle, handle: handle as HandleString,
}) })
if (res.data.did) { if (data.did) {
return {available: false} as const return {available: false} as const
} }
} catch {} } catch {}
+9 -3
View File
@@ -1,8 +1,10 @@
import {useCallback} from 'react' import {useCallback} from 'react'
import {type HandleString} from '@atproto/syntax'
import {useMutation, useQueryClient} from '@tanstack/react-query' import {useMutation, useQueryClient} from '@tanstack/react-query'
import {STALE} from '#/state/queries' import {STALE} from '#/state/queries'
import {useAgent} from '#/state/session' import {useAgent, usePdsClient} from '#/state/session'
import {com} from '#/lexicons'
const handleQueryKeyRoot = 'handle' const handleQueryKeyRoot = 'handle'
const fetchHandleQueryKey = (handleOrDid: string) => [ const fetchHandleQueryKey = (handleOrDid: string) => [
@@ -36,11 +38,15 @@ export function useUpdateHandleMutation(opts?: {
onSuccess?: (handle: string) => void onSuccess?: (handle: string) => void
}) { }) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const agent = useAgent() const client = usePdsClient()
return useMutation({ return useMutation({
mutationFn: async ({handle}: {handle: string}) => { 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) { onSuccess(_data, variables) {
opts?.onSuccess?.(variables.handle) opts?.onSuccess?.(variables.handle)
+8 -4
View File
@@ -1,6 +1,7 @@
import {useQuery} from '@tanstack/react-query' import {useQuery} from '@tanstack/react-query'
import {Agent} from '../session/agent' import {createServiceClient} from '#/lib/lexClient'
import {com} from '#/lexicons'
const RQKEY_ROOT = 'service' const RQKEY_ROOT = 'service'
export const RQKEY = (serviceUrl: string) => [RQKEY_ROOT, serviceUrl] export const RQKEY = (serviceUrl: string) => [RQKEY_ROOT, serviceUrl]
@@ -9,9 +10,12 @@ export function useServiceQuery(serviceUrl: string) {
return useQuery({ return useQuery({
queryKey: RQKEY(serviceUrl), queryKey: RQKEY(serviceUrl),
queryFn: async () => { queryFn: async () => {
const agent = new Agent(null, {service: serviceUrl}) /*
const res = await agent.com.atproto.server.describeServer() * The host is whatever the user typed or picked, so this describes it
return res.data * 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), enabled: isValidUrl(serviceUrl),
}) })