From 19f7953becb2ba2143e3b7ab08df0ff2426b91da Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Tue, 4 Aug 2026 11:19:24 -0400 Subject: [PATCH] fix(auth): normalize login handle input and offer sign-in when handle is taken (#157) --- __tests__/lib/strings/handles.test.ts | 88 ++++++++++++- eslint-suppressions.json | 5 - src/lib/strings/handles.ts | 35 ++++++ src/locale/locales/en/messages.po | 134 ++++++++++++-------- src/screens/Login/LoginForm.tsx | 161 +++++++++++++++++++++--- src/screens/Login/index.tsx | 13 +- src/screens/Signup/StepHandle/index.tsx | 43 ++++++- src/screens/Signup/index.tsx | 10 +- src/state/session/resolveForLogin.ts | 24 ++++ src/view/com/auth/LoggedOut.tsx | 11 +- 10 files changed, 445 insertions(+), 79 deletions(-) diff --git a/__tests__/lib/strings/handles.test.ts b/__tests__/lib/strings/handles.test.ts index f3b289afd..7246ecff4 100644 --- a/__tests__/lib/strings/handles.test.ts +++ b/__tests__/lib/strings/handles.test.ts @@ -1,4 +1,10 @@ -import {type IsValidHandle, validateServiceHandle} from '#/lib/strings/handles' +import { + buildHandleCandidates, + isCorrectedLoginIdentifier, + type IsValidHandle, + normalizeLoginIdentifier, + validateServiceHandle, +} from '#/lib/strings/handles' describe('handle validation', () => { const valid = [ @@ -40,3 +46,83 @@ describe('handle validation', () => { }, ) }) + +describe('normalizeLoginIdentifier', () => { + const cases: [string, string][] = [ + ['maria.bsky.social', 'maria.bsky.social'], + ['maria.blacksky.app', 'maria.blacksky.app'], + [' Maria.Bsky.Social ', 'maria.bsky.social'], + ['@maria.bsky.social', 'maria.bsky.social'], + ['maria@bsky.app', 'maria.bsky.app'], + ['@maria@bsky.social', 'maria.bsky.social'], + ['bigdocenergy23', 'bigdocenergy23'], + ['@BigDocEnergy23', 'bigdocenergy23'], + ['maria.bsky.social.', 'maria.bsky.social'], + ] + it.each(cases)(`normalizes %s to %s`, (input, expected) => { + expect(normalizeLoginIdentifier(input)).toEqual(expected) + }) + + it('leaves DIDs untouched apart from trimming', () => { + expect(normalizeLoginIdentifier(' did:plc:abc123 ')).toEqual( + 'did:plc:abc123', + ) + expect(normalizeLoginIdentifier('did:web:Example.com')).toEqual( + 'did:web:Example.com', + ) + expect(normalizeLoginIdentifier('DID:web:Example.com')).toEqual( + 'DID:web:Example.com', + ) + }) + + it('returns empty string for empty input', () => { + expect(normalizeLoginIdentifier(' ')).toEqual('') + }) +}) + +describe('isCorrectedLoginIdentifier', () => { + const notCorrections: string[] = [ + 'maria.bsky.social', + ' Maria.Bsky.Social ', + '@maria.bsky.social', + 'bigdocenergy23', + ' did:plc:abc123 ', + ] + it.each(notCorrections)(`%s is not a correction`, input => { + expect( + isCorrectedLoginIdentifier(input, normalizeLoginIdentifier(input)), + ).toEqual(false) + }) + + const corrections: string[] = ['maria@bsky.app', 'maria.bsky.social.'] + it.each(corrections)(`%s is a correction`, input => { + expect( + isCorrectedLoginIdentifier(input, normalizeLoginIdentifier(input)), + ).toEqual(true) + }) +}) + +describe('buildHandleCandidates', () => { + it('builds one candidate per service domain plus bsky.social', () => { + expect( + buildHandleCandidates('maria', ['.myatproto.social', '.blacksky.app']), + ).toEqual([ + 'maria.myatproto.social', + 'maria.blacksky.app', + 'maria.bsky.social', + ]) + }) + + it('handles domains without a leading dot and dedupes', () => { + expect(buildHandleCandidates('maria', ['bsky.social'])).toEqual([ + 'maria.bsky.social', + ]) + }) + + it('falls back to bsky.social when no domains are known', () => { + expect(buildHandleCandidates('maria', undefined)).toEqual([ + 'maria.bsky.social', + ]) + expect(buildHandleCandidates('maria', [])).toEqual(['maria.bsky.social']) + }) +}) diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 60238cd39..68dfa075a 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -1151,11 +1151,6 @@ "count": 1 } }, - "src/screens/Login/LoginForm.tsx": { - "@typescript-eslint/no-misused-promises": { - "count": 2 - } - }, "src/screens/Login/SetNewPasswordForm.tsx": { "@typescript-eslint/no-explicit-any": { "count": 1 diff --git a/src/lib/strings/handles.ts b/src/lib/strings/handles.ts index bdac50a56..b44f8bf1c 100644 --- a/src/lib/strings/handles.ts +++ b/src/lib/strings/handles.ts @@ -21,6 +21,41 @@ export function createFullHandle(name: string, domain: string): string { return `${name}.${domain}` } +export function normalizeLoginIdentifier(input: string): string { + const identifier = input.trim() + if (/^did:/i.test(identifier)) { + return identifier + } + return identifier + .toLowerCase() + .replace(/^@+/, '') + .replace(/@/g, '.') + .replace(/\.+$/, '') +} + +// case/whitespace/leading-@ changes are habits, not mistakes — only +// separator rewrites should pause sign-in for user confirmation +export function isCorrectedLoginIdentifier( + input: string, + normalized: string, +): boolean { + const identifier = input.trim() + if (/^did:/i.test(identifier)) { + return false + } + return normalized !== identifier.toLowerCase().replace(/^@+/, '') +} + +export function buildHandleCandidates( + name: string, + availableUserDomains?: string[], +): string[] { + const domains = [...(availableUserDomains ?? []), 'bsky.social'].map(d => + d.replace(/^\.+/, ''), + ) + return [...new Set(domains)].map(domain => createFullHandle(name, domain)) +} + export function isInvalidHandle(handle: string): boolean { return handle === 'handle.invalid' } diff --git a/src/locale/locales/en/messages.po b/src/locale/locales/en/messages.po index 2e93d8e32..133c347d3 100644 --- a/src/locale/locales/en/messages.po +++ b/src/locale/locales/en/messages.po @@ -233,7 +233,7 @@ msgid "{0} is live" msgstr "" #. placeholder {0}: createFullHandle(draftValue, selectedDomain) -#: src/screens/Signup/StepHandle/index.tsx:283 +#: src/screens/Signup/StepHandle/index.tsx:299 msgid "{0} is not available" msgstr "" @@ -983,7 +983,7 @@ msgid "Accessibility Settings" msgstr "" #: src/Navigation.tsx:431 -#: src/screens/Login/LoginForm.tsx:120 +#: src/screens/Login/LoginForm.tsx:218 #: src/screens/Settings/AccountSettings.tsx:69 #: src/screens/Settings/Settings.tsx:167 #: src/screens/Settings/Settings.tsx:170 @@ -1924,8 +1924,8 @@ msgstr "" #: src/screens/Login/ChooseAccountForm.tsx:113 #: src/screens/Login/ForgotPasswordForm.tsx:124 #: src/screens/Login/ForgotPasswordForm.tsx:130 -#: src/screens/Login/LoginForm.tsx:157 -#: src/screens/Login/LoginForm.tsx:163 +#: src/screens/Login/LoginForm.tsx:290 +#: src/screens/Login/LoginForm.tsx:296 #: src/screens/Login/SetNewPasswordForm.tsx:170 #: src/screens/Login/SetNewPasswordForm.tsx:176 #: src/screens/Messages/components/ChatDisabled.tsx:166 @@ -2326,8 +2326,8 @@ msgstr "Camera access needed" #: src/features/liveNow/components/GoLiveDialog.tsx:254 #: src/lib/media/picker.tsx:38 #: src/screens/Deactivated.tsx:288 -#: src/screens/Login/LoginForm.tsx:170 -#: src/screens/Login/LoginForm.tsx:177 +#: src/screens/Login/LoginForm.tsx:303 +#: src/screens/Login/LoginForm.tsx:310 #: src/screens/Messages/components/InviteLinkDialog.tsx:502 #: src/screens/Messages/components/InviteLinkDialog.tsx:506 #: src/screens/Messages/ConversationSettings/prompts.tsx:108 @@ -2370,7 +2370,7 @@ msgstr "Cancel reply" msgid "Cancel search" msgstr "" -#: src/screens/Login/LoginForm.tsx:171 +#: src/screens/Login/LoginForm.tsx:304 msgid "Cancels the sign-in process" msgstr "Cancels the sign-in process" @@ -2635,7 +2635,7 @@ msgstr "" msgid "Choose your account provider" msgstr "" -#: src/screens/Signup/index.tsx:227 +#: src/screens/Signup/index.tsx:233 msgid "Choose your community" msgstr "Choose your community" @@ -2647,7 +2647,7 @@ msgstr "" msgid "Choose your password" msgstr "" -#: src/screens/Signup/index.tsx:231 +#: src/screens/Signup/index.tsx:237 msgid "Choose your username" msgstr "" @@ -2872,7 +2872,7 @@ msgstr "" msgid "Complete onboarding and start using your account" msgstr "" -#: src/screens/Signup/index.tsx:233 +#: src/screens/Signup/index.tsx:239 msgid "Complete the challenge" msgstr "" @@ -2940,8 +2940,8 @@ msgstr "Confirm with your account password" msgid "Confirmation code" msgstr "" -#: src/screens/Signup/index.tsx:278 -#: src/screens/Signup/index.tsx:281 +#: src/screens/Signup/index.tsx:284 +#: src/screens/Signup/index.tsx:287 msgid "Contact support" msgstr "" @@ -3354,7 +3354,7 @@ msgstr "" msgid "Create account" msgstr "" -#: src/screens/Signup/index.tsx:176 +#: src/screens/Signup/index.tsx:182 msgid "Create Account" msgstr "Create Account" @@ -3532,8 +3532,8 @@ msgstr "" #: src/screens/Settings/AppearanceSettings.tsx:156 #: src/screens/Settings/components/ChangeHandleDialog.tsx:273 #: src/screens/Settings/components/ChangeHandleDialog.tsx:298 -#: src/screens/Signup/StepHandle/index.tsx:229 -#: src/screens/Signup/StepHandle/index.tsx:254 +#: src/screens/Signup/StepHandle/index.tsx:242 +#: src/screens/Signup/StepHandle/index.tsx:270 msgid "Default" msgstr "" @@ -3889,7 +3889,7 @@ msgid "Does not include nudity." msgstr "" #: src/screens/Settings/components/ChangeHandleDialog.tsx:249 -#: src/screens/Signup/StepHandle/index.tsx:205 +#: src/screens/Signup/StepHandle/index.tsx:218 msgid "Domain" msgstr "Domain" @@ -4359,11 +4359,11 @@ msgstr "Enter your birthdate" msgid "Enter your email address" msgstr "" -#: src/screens/Login/LoginForm.tsx:141 +#: src/screens/Login/LoginForm.tsx:245 msgid "Enter your handle (e.g. alice.bsky.social)" msgstr "Enter your handle (e.g. alice.bsky.social)" -#: src/screens/Login/index.tsx:122 +#: src/screens/Login/index.tsx:128 msgid "Enter your handle to sign in" msgstr "Enter your handle to sign in" @@ -5070,7 +5070,7 @@ msgstr "" msgid "Finish" msgstr "" -#: src/screens/Login/LoginForm.tsx:150 +#: src/screens/Login/LoginForm.tsx:283 msgid "Finishing sign-in… complete it in your browser, or cancel." msgstr "Finishing sign-in… complete it in your browser, or cancel." @@ -5288,8 +5288,8 @@ msgstr "" msgid "Forget the noise" msgstr "" -#: src/screens/Login/index.tsx:146 -#: src/screens/Login/index.tsx:162 +#: src/screens/Login/index.tsx:153 +#: src/screens/Login/index.tsx:169 msgid "Forgot Password" msgstr "" @@ -5449,7 +5449,7 @@ msgstr "" #: src/screens/VideoFeed/components/Header.tsx:163 #: src/screens/VideoFeed/index.tsx:1168 #: src/screens/VideoFeed/index.tsx:1172 -#: src/view/com/auth/LoggedOut.tsx:103 +#: src/view/com/auth/LoggedOut.tsx:104 #: src/view/com/profile/ProfileFollowers.tsx:211 #: src/view/com/profile/ProfileFollowers.tsx:212 #: src/view/screens/NotFound.tsx:51 @@ -5707,7 +5707,7 @@ msgstr "" msgid "Have a code? <0>Click here." msgstr "" -#: src/screens/Signup/index.tsx:276 +#: src/screens/Signup/index.tsx:282 msgid "Having trouble?" msgstr "" @@ -6275,6 +6275,10 @@ msgstr "" msgid "iOS 26 Crash Regression" msgstr "iOS 26 Crash Regression" +#: src/screens/Signup/StepHandle/index.tsx:364 +msgid "Is this your account?" +msgstr "Is this your account?" + #: src/components/contacts/components/InviteInfo.tsx:47 msgid "It looks like some of your contacts have not tried to find you here yet. You can personally invite them by customizing a draft message we will provide." msgstr "" @@ -6508,8 +6512,8 @@ msgstr "" msgid "Let me choose" msgstr "" -#: src/screens/Login/index.tsx:147 -#: src/screens/Login/index.tsx:163 +#: src/screens/Login/index.tsx:154 +#: src/screens/Login/index.tsx:170 msgid "Let's get your password reset!" msgstr "" @@ -6818,8 +6822,8 @@ msgstr "" msgid "Logged-out visibility" msgstr "" -#: src/screens/Login/LoginForm.tsx:183 -#: src/screens/Login/LoginForm.tsx:190 +#: src/screens/Login/LoginForm.tsx:316 +#: src/screens/Login/LoginForm.tsx:323 msgid "Login" msgstr "Login" @@ -8337,7 +8341,7 @@ msgstr "" msgid "Password must be at least 8 characters long." msgstr "" -#: src/screens/Login/index.tsx:176 +#: src/screens/Login/index.tsx:183 msgid "Password updated" msgstr "" @@ -8631,7 +8635,7 @@ msgstr "Please enter your password to continue." msgid "Please enter your password." msgstr "Please enter your password." -#: src/screens/Login/LoginForm.tsx:52 +#: src/screens/Login/LoginForm.tsx:70 msgid "Please enter your username or handle" msgstr "Please enter your username or handle" @@ -10169,8 +10173,8 @@ msgstr "" #: src/screens/Settings/components/ChangeHandleDialog.tsx:252 #: src/screens/Settings/components/ChangeHandleDialog.tsx:256 -#: src/screens/Signup/StepHandle/index.tsx:208 -#: src/screens/Signup/StepHandle/index.tsx:212 +#: src/screens/Signup/StepHandle/index.tsx:221 +#: src/screens/Signup/StepHandle/index.tsx:225 msgid "Select domain" msgstr "Select domain" @@ -10178,7 +10182,7 @@ msgstr "Select domain" msgid "Select duration" msgstr "" -#: src/screens/Login/index.tsx:136 +#: src/screens/Login/index.tsx:143 msgid "Select from an existing account" msgstr "" @@ -10678,9 +10682,9 @@ msgstr "" #: src/components/WelcomeModal.tsx:197 #: src/components/WelcomeModal.tsx:209 #: src/screens/Hashtag.tsx:228 -#: src/screens/Login/index.tsx:121 -#: src/screens/Login/index.tsx:135 -#: src/screens/Login/LoginForm.tsx:117 +#: src/screens/Login/index.tsx:127 +#: src/screens/Login/index.tsx:142 +#: src/screens/Login/LoginForm.tsx:215 #: src/screens/Messages/JoinRequest.tsx:290 #: src/screens/Messages/JoinRequest.tsx:296 #: src/screens/Search/SearchResults.tsx:303 @@ -10702,6 +10706,14 @@ msgstr "" msgid "Sign in as {0}" msgstr "" +#: src/screens/Signup/StepHandle/index.tsx:375 +msgid "Sign in as {fullDraftHandle}" +msgstr "Sign in as {fullDraftHandle}" + +#: src/screens/Login/LoginForm.tsx:263 +msgid "Sign in as {handle}" +msgstr "Sign in as {handle}" + #: src/screens/Login/ChooseAccountForm.tsx:97 msgid "Sign in as..." msgstr "" @@ -10714,6 +10726,10 @@ msgstr "Sign in code" msgid "Sign in failed. Please try again." msgstr "Sign in failed. Please try again." +#: src/screens/Signup/StepHandle/index.tsx:368 +msgid "Sign in instead" +msgstr "Sign in instead" + #: src/lib/strings/errors.ts:62 msgid "Sign in is taking too long. Please try again." msgstr "Sign in is taking too long. Please try again." @@ -11051,7 +11067,7 @@ msgstr "" msgid "Starter Packs let you share your favorite feeds and people with your friends." msgstr "" -#: src/screens/Login/LoginForm.tsx:184 +#: src/screens/Login/LoginForm.tsx:317 msgid "Starts the sign-in process" msgstr "Starts the sign-in process" @@ -11061,7 +11077,7 @@ msgstr "Starts the sign-in process" msgid "Step {0} of {1}" msgstr "" -#: src/screens/Signup/index.tsx:221 +#: src/screens/Signup/index.tsx:227 msgid "Step {displayStep} of {displayTotal}" msgstr "Step {displayStep} of {displayTotal}" @@ -11413,7 +11429,7 @@ msgstr "" msgid "That contains the following:" msgstr "" -#: src/screens/Signup/StepHandle/index.tsx:124 +#: src/screens/Signup/StepHandle/index.tsx:136 msgid "That handle is already taken." msgstr "That handle is already taken." @@ -12285,10 +12301,12 @@ msgstr "" #: src/screens/Deactivated.tsx:130 #: src/screens/Login/ForgotPasswordForm.tsx:69 -#: src/screens/Login/index.tsx:94 -#: src/screens/Login/LoginForm.tsx:102 +#: src/screens/Login/index.tsx:100 +#: src/screens/Login/LoginForm.tsx:84 +#: src/screens/Login/LoginForm.tsx:122 +#: src/screens/Login/LoginForm.tsx:191 #: src/screens/Login/SetNewPasswordForm.tsx:83 -#: src/screens/Signup/index.tsx:113 +#: src/screens/Signup/index.tsx:119 msgid "Unable to contact your service. Please check your Internet connection." msgstr "" @@ -12759,23 +12777,23 @@ msgctxt "toast" msgid "User list updated" msgstr "" -#: src/screens/Signup/StepHandle/index.tsx:331 +#: src/screens/Signup/StepHandle/index.tsx:347 msgid "Username cannot be longer than {MAX_SERVICE_HANDLE_LENGTH, plural, other {# characters}}" msgstr "" -#: src/screens/Signup/StepHandle/index.tsx:314 +#: src/screens/Signup/StepHandle/index.tsx:330 msgid "Username cannot begin or end with a hyphen" msgstr "" -#: src/screens/Signup/StepHandle/index.tsx:339 +#: src/screens/Signup/StepHandle/index.tsx:355 msgid "Username must be at least 3 characters" msgstr "Username must be at least 3 characters" -#: src/screens/Signup/StepHandle/index.tsx:318 +#: src/screens/Signup/StepHandle/index.tsx:334 msgid "Username must only contain letters (a-z), numbers, and hyphens" msgstr "" -#: src/screens/Login/LoginForm.tsx:127 +#: src/screens/Login/LoginForm.tsx:225 msgid "Username or handle" msgstr "Username or handle" @@ -13158,6 +13176,14 @@ msgstr "" msgid "We couldn't find an account at {didOrHandle}." msgstr "We couldn't find an account at {didOrHandle}." +#: src/screens/Login/LoginForm.tsx:104 +msgid "We couldn't find an account for \"{identifier}\". Enter your full handle including its domain (like {examples})" +msgstr "We couldn't find an account for \"{identifier}\". Enter your full handle including its domain (like {examples})" + +#: src/screens/Login/LoginForm.tsx:200 +msgid "We couldn't find an account with the handle \"{identifier}\". Check the spelling, or create a new account if you don't have one yet." +msgstr "We couldn't find an account with the handle \"{identifier}\". Check the spelling, or create a new account if you don't have one yet." + #: src/screens/Hashtag.tsx:259 msgid "We couldn't find any results for that tag." msgstr "" @@ -13191,6 +13217,14 @@ msgstr "" msgid "We estimate {estimatedTime} until your account is ready." msgstr "" +#: src/screens/Login/LoginForm.tsx:275 +msgid "We filled in our best guess at your full handle. If it looks right, press Login to continue" +msgstr "We filled in our best guess at your full handle. If it looks right, press Login to continue" + +#: src/screens/Login/LoginForm.tsx:255 +msgid "We found more than one account with that name. Which one is yours?" +msgstr "We found more than one account with that name. Which one is yours?" + #. placeholder {0}: currentAccount?.email #: src/components/intents/VerifyEmailIntentDialog.tsx:102 msgid "We have sent another verification email to <0>{0}." @@ -13538,7 +13572,7 @@ msgstr "" msgid "You can continue ongoing conversations regardless of which setting you choose." msgstr "" -#: src/screens/Login/index.tsx:177 +#: src/screens/Login/index.tsx:184 #: src/screens/Login/PasswordUpdatedForm.tsx:27 msgid "You can now sign in with your new password." msgstr "" @@ -13838,11 +13872,11 @@ msgstr "You won’t be able to rejoin unless you’re invited." msgid "You: {message}" msgstr "You: {message}" -#: src/screens/Signup/index.tsx:193 +#: src/screens/Signup/index.tsx:199 msgid "You'll follow the suggested users and feeds once you finish creating your account!" msgstr "" -#: src/screens/Signup/index.tsx:198 +#: src/screens/Signup/index.tsx:204 msgid "You'll follow the suggested users once you finish creating your account!" msgstr "" @@ -13925,7 +13959,7 @@ msgstr "" msgid "You've run out of videos to watch. Maybe it's a good time to take a break?" msgstr "" -#: src/screens/Signup/index.tsx:229 +#: src/screens/Signup/index.tsx:235 msgid "Your account" msgstr "" diff --git a/src/screens/Login/LoginForm.tsx b/src/screens/Login/LoginForm.tsx index ceb52540b..18a26767e 100644 --- a/src/screens/Login/LoginForm.tsx +++ b/src/screens/Login/LoginForm.tsx @@ -1,15 +1,22 @@ import {useRef, useState} from 'react' import {Keyboard, LayoutAnimation, Platform, View} from 'react-native' +import {type ComAtprotoServerDescribeServer} from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {Trans} from '@lingui/react/macro' import {cleanError, isNetworkError} from '#/lib/strings/errors' +import { + buildHandleCandidates, + isCorrectedLoginIdentifier, + normalizeLoginIdentifier, +} from '#/lib/strings/handles' import {logger} from '#/logger' import {useSessionApi} from '#/state/session' import {getOAuthClient, signInNativeAndroid} from '#/state/session/oauth-client' import { isHandleResolutionError, + resolveBareNameToHandles, resolveDeactivatedHandle, } from '#/state/session/resolveForLogin' import {atoms as a, useTheme} from '#/alf' @@ -23,11 +30,13 @@ import {FormContainer} from './FormContainer' export const LoginForm = ({ error, + serviceDescription, initialHandle, setError, onPressBack, }: { error: string + serviceDescription: ComAtprotoServerDescribeServer.OutputSchema | undefined initialHandle: string setError: (v: string) => void onPressBack: () => void @@ -35,26 +44,106 @@ export const LoginForm = ({ const [isProcessing, setIsProcessing] = useState(false) const [awaitingRedirect, setAwaitingRedirect] = useState(false) const abortRef = useRef(null) - const identifierValueRef = useRef(initialHandle || '') + const processingRef = useRef(false) + const [identifierValue, setIdentifierValue] = useState( + initialHandle || '', + ) + const [handleOptions, setHandleOptions] = useState(null) + const [showGuessConfirm, setShowGuessConfirm] = useState(false) const t = useTheme() const {_} = useLingui() const {login} = useSessionApi() const onPressNext = async () => { - if (isProcessing) return - Keyboard.dismiss() - LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) - setError('') + if (isProcessing || processingRef.current) return + processingRef.current = true + try { + Keyboard.dismiss() + LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) + setError('') + setHandleOptions(null) + setShowGuessConfirm(false) - const identifier = identifierValueRef.current.trim() + const identifier = normalizeLoginIdentifier(identifierValue) + + if (!identifier) { + setError(_(msg`Please enter your username or handle`)) + return + } - if (!identifier) { - setError(_(msg`Please enter your username or handle`)) - return + if (isCorrectedLoginIdentifier(identifierValue, identifier)) { + setIdentifierValue(identifier) + setShowGuessConfirm(true) + return + } + + if (!identifier.startsWith('did:') && !identifier.includes('.')) { + if (!serviceDescription) { + setError( + _( + msg`Unable to contact your service. Please check your Internet connection.`, + ), + ) + return + } + setIsProcessing(true) + try { + const matches = await resolveBareNameToHandles( + identifier, + serviceDescription.availableUserDomains, + ) + if (matches.length === 0) { + const examples = buildHandleCandidates( + identifier, + serviceDescription.availableUserDomains, + ) + .slice(0, 2) + .join(' or ') + setError( + _( + msg`We couldn't find an account for "${identifier}". Enter your full handle including its domain (like ${examples})`, + ), + ) + return + } + if (matches.length > 1) { + setHandleOptions(matches) + return + } + setIdentifierValue(matches[0]) + setShowGuessConfirm(true) + return + } catch (e) { + logger.warn('Failed to resolve bare name during sign-in', { + error: String(e), + }) + setError( + _( + msg`Unable to contact your service. Please check your Internet connection.`, + ), + ) + return + } finally { + setIsProcessing(false) + } + } + + setIdentifierValue(identifier) + await signInWithIdentifier(identifier) + } finally { + processingRef.current = false } + } - setIsProcessing(true) + const onPressHandleOption = (handle: string) => { + if (isProcessing) return + setHandleOptions(null) + setError('') + setIdentifierValue(handle) + setShowGuessConfirm(true) + } + const signInWithIdentifier = async (identifier: string) => { const client = getOAuthClient() const controller = Platform.OS === 'android' ? new AbortController() : null if (controller) { @@ -102,6 +191,15 @@ export const LoginForm = ({ msg`Unable to contact your service. Please check your Internet connection.`, ), ) + } else if (isHandleResolutionError(e)) { + logger.warn('Failed to resolve handle during sign-in', { + error: errMsg, + }) + setError( + _( + msg`We couldn't find an account with the handle "${identifier}". Check the spelling, or create a new account if you don't have one yet.`, + ), + ) } else { logger.warn('Failed to start OAuth sign-in', {error: errMsg}) setError(cleanError(errMsg)) @@ -131,11 +229,17 @@ export const LoginForm = ({ autoComplete="username" returnKeyType="done" textContentType="username" - defaultValue={initialHandle || ''} + value={identifierValue} onChangeText={v => { - identifierValueRef.current = v + setIdentifierValue(v) + if (handleOptions) { + setHandleOptions(null) + } + if (showGuessConfirm) { + setShowGuessConfirm(false) + } }} - onSubmitEditing={onPressNext} + onSubmitEditing={() => void onPressNext()} editable={!isProcessing} accessibilityHint={_( msg`Enter your handle (e.g. alice.bsky.social)`, @@ -145,6 +249,35 @@ export const LoginForm = ({ + {handleOptions && ( + + + + We found more than one account with that name. Which one is yours? + + + {handleOptions.map(handle => ( + + ))} + + )} + {showGuessConfirm && ( + + + We filled in our best guess at your full handle. If it looks right, + press Login to continue + + + )} {awaitingRedirect && ( @@ -185,7 +318,7 @@ export const LoginForm = ({ variant="solid" color="primary" size="large" - onPress={onPressNext}> + onPress={() => void onPressNext()}> Login diff --git a/src/screens/Login/index.tsx b/src/screens/Login/index.tsx index 8fde80eec..6456a8704 100644 --- a/src/screens/Login/index.tsx +++ b/src/screens/Login/index.tsx @@ -38,7 +38,13 @@ const OrderedForms = [ Forms.PasswordUpdated, ] as const -export const Login = ({onPressBack}: {onPressBack: () => void}) => { +export const Login = ({ + onPressBack, + prefillHandle, +}: { + onPressBack: () => void + prefillHandle?: string +}) => { const {_} = useLingui() const brand = useBrand() const failedAttemptCountRef = useRef(0) @@ -54,10 +60,10 @@ export const Login = ({onPressBack}: {onPressBack: () => void}) => { requestedAccount?.service || brand.services.pds.url || DEFAULT_SERVICE, ) const [initialHandle, setInitialHandle] = useState( - requestedAccount?.handle || '', + prefillHandle || requestedAccount?.handle || '', ) const [currentForm, setCurrentForm] = useState( - requestedAccount + requestedAccount || prefillHandle ? Forms.Login : accounts.length ? Forms.ChooseAccount @@ -123,6 +129,7 @@ export const Login = ({onPressBack}: {onPressBack: () => void}) => { content = ( diff --git a/src/screens/Signup/StepHandle/index.tsx b/src/screens/Signup/StepHandle/index.tsx index b5cebcb64..c209ceb2f 100644 --- a/src/screens/Signup/StepHandle/index.tsx +++ b/src/screens/Signup/StepHandle/index.tsx @@ -1,4 +1,4 @@ -import {ReactNode, useMemo, useState} from 'react' +import {type ReactNode, useMemo, useState} from 'react' import {View} from 'react-native' import Animated, { FadeIn, @@ -35,12 +35,17 @@ import {useAnalytics} from '#/analytics' import {BackNextButtons} from '../BackNextButtons' import {HandleSuggestions} from './HandleSuggestions' -export function StepHandle() { +export function StepHandle({ + onPressSignIn, +}: { + onPressSignIn?: (handle: string) => void +}) { const {_} = useLingui() const ax = useAnalytics() const t = useTheme() const {state, dispatch} = useSignupContext() const [draftValue, setDraftValue] = useState(state.handle) + const [submitFoundTaken, setSubmitFoundTaken] = useState(false) const [selectedDomain, setSelectedDomain] = useState( state.userDomain || state.serviceDescription?.availableUserDomains?.[0] || @@ -85,6 +90,12 @@ export function StepHandle() { const isNextDisabled = !validCheck.overall || !!state.error || isNotReady ? true : isHandleTaken + const showSignInInstead = + !!onPressSignIn && + draftValue.length > 0 && + ((isHandleTaken && hasDebounceSettled) || submitFoundTaken) + const fullDraftHandle = createFullHandle(draftValue.trim(), selectedDomain) + const textFieldInvalid = isHandleTaken || !validCheck.frontLengthNotTooLong || @@ -119,6 +130,7 @@ export function StepHandle() { ) if (!handleAvailable) { + setSubmitFoundTaken(true) dispatch({ type: 'setError', value: _(msg`That handle is already taken.`), @@ -178,6 +190,7 @@ export function StepHandle() { if (state.error) { dispatch({type: 'setError', value: ''}) } + setSubmitFoundTaken(false) setDraftValue(val.toLowerCase()) }} label={selectedDomain} @@ -241,7 +254,10 @@ export function StepHandle() { setSelectedDomain(domain)}> + onPress={() => { + setSubmitFoundTaken(false) + setSelectedDomain(domain) + }}> {domain} @@ -341,6 +357,27 @@ export function StepHandle() { )} + {showSignInInstead && ( + + + + Is this your account? + + + + + )} diff --git a/src/screens/Signup/index.tsx b/src/screens/Signup/index.tsx index be2ac171c..011c26442 100644 --- a/src/screens/Signup/index.tsx +++ b/src/screens/Signup/index.tsx @@ -36,7 +36,13 @@ import {useAnalytics} from '#/analytics' import {GCP_PROJECT_ID, IS_ANDROID} from '#/env' import * as bsky from '#/types/bsky' -export function Signup({onPressBack}: {onPressBack: () => void}) { +export function Signup({ + onPressBack, + onPressSignIn, +}: { + onPressBack: () => void + onPressSignIn?: (handle: string) => void +}) { const ax = useAnalytics() const {_} = useLingui() const brand = useBrand() @@ -251,7 +257,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) { refetchServer={refetch} /> ) : state.activeStep === SignupStep.HANDLE ? ( - + ) : ( )} diff --git a/src/state/session/resolveForLogin.ts b/src/state/session/resolveForLogin.ts index 30b0866c2..b8a2d8006 100644 --- a/src/state/session/resolveForLogin.ts +++ b/src/state/session/resolveForLogin.ts @@ -2,6 +2,7 @@ import {AtpAgent, XRPCError} from '@atproto/api' import {BSKY_SERVICE, PUBLIC_BSKY_SERVICE} from '#/lib/constants' import {isNetworkError} from '#/lib/strings/errors' +import {buildHandleCandidates} from '#/lib/strings/handles' export function isHandleResolutionError(e: unknown): boolean { if (e && typeof e === 'object' && 'name' in e) { @@ -18,6 +19,29 @@ export function isHandleResolutionError(e: unknown): boolean { ) } +export async function resolveBareNameToHandles( + name: string, + availableUserDomains?: string[], +): Promise { + const candidates = buildHandleCandidates(name, availableUserDomains) + const appview = new AtpAgent({service: PUBLIC_BSKY_SERVICE}) + const results = await Promise.allSettled( + candidates.map(handle => + appview.com.atproto.identity.resolveHandle({handle}), + ), + ) + const matches = candidates.filter((_, i) => results[i].status === 'fulfilled') + // only a definite not-found proves a candidate doesn't exist; a transient + // failure on the user's real domain must not let a lookalike domain win + const retryableFailure = results.find( + r => r.status === 'rejected' && !isHandleResolutionError(r.reason), + ) + if (retryableFailure?.status === 'rejected') { + throw retryableFailure.reason + } + return matches +} + export async function resolveDeactivatedHandle( identifier: string, ): Promise { diff --git a/src/view/com/auth/LoggedOut.tsx b/src/view/com/auth/LoggedOut.tsx index 91c0b9afc..05340d0d2 100644 --- a/src/view/com/auth/LoggedOut.tsx +++ b/src/view/com/auth/LoggedOut.tsx @@ -61,6 +61,7 @@ export function LoggedOut({onDismiss}: {onDismiss?: () => void}) { const initialScreenState = getInitialScreenState(requestedAccountSwitchTo) const [screenState, setScreenState] = useState(initialScreenState) + const [loginHandlePrefill, setLoginHandlePrefill] = useState('') const {clearRequestedAccount} = useLoggedOutViewControls() const setActiveLanding = useSetActiveLanding() @@ -137,13 +138,21 @@ export function LoggedOut({onDismiss}: {onDismiss?: () => void}) { ) : undefined} {screenState === ScreenState.S_Login ? ( { + setLoginHandlePrefill('') setScreenState(initialScreenState) }} /> ) : undefined} {screenState === ScreenState.S_CreateAccount ? ( - setScreenState(initialScreenState)} /> + setScreenState(initialScreenState)} + onPressSignIn={handle => { + setLoginHandlePrefill(handle) + setScreenState(ScreenState.S_Login) + }} + /> ) : undefined} -- knotmirror 0.0.1