A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(app): explain passkey prompt failures
Hampusc7eb3b397210
diff --git a/fluxer_app/src/features/auth/components/modals/PasskeyNameModal.tsx b/fluxer_app/src/features/auth/components/modals/PasskeyNameModal.tsxindex 7aa44ae34..01cf574b7 100644--- a/fluxer_app/src/features/auth/components/modals/PasskeyNameModal.tsx+++ b/fluxer_app/src/features/auth/components/modals/PasskeyNameModal.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport * as Modal from '@app/features/app/components/dialogs/Modal';+import {describePasskeyError} from '@app/features/auth/utils/PasskeyErrorMessages';import {HttpError} from '@app/features/platform/types/EndpointError';import {Button} from '@app/features/ui/button/Button';import * as ModalCommands from '@app/features/ui/commands/ModalCommands';@@ -33,7 +34,12 @@ interface FormInputs {name: string;}-export const PasskeyNameModal = observer(({onSubmit}: {onSubmit: (name: string) => void | Promise<void>}) => {+interface PasskeyNameModalProps {+ onSubmit: (name: string) => void | Promise<void>;+ rpId?: string | null;+}++export const PasskeyNameModal = observer(({onSubmit, rpId = null}: PasskeyNameModalProps) => {const {i18n} = useLingui();const form = useForm<FormInputs>();const handleSubmit = async (data: FormInputs) => {@@ -44,7 +50,10 @@ export const PasskeyNameModal = observer(({onSubmit}: {onSubmit: (name: string)if (error instanceof HttpError) {FormUtils.handleError(i18n, form, error, 'name');} else {- form.setError('name', {type: 'server', message: FormUtils.extractErrorMessage(i18n, error)});+ form.setError('name', {+ type: 'server',+ message: describePasskeyError(i18n, error, rpId) ?? FormUtils.extractErrorMessage(i18n, error),+ });}}};diff --git a/fluxer_app/src/features/auth/hooks/useLoginFlow.ts b/fluxer_app/src/features/auth/hooks/useLoginFlow.tsindex a0c67952a..d34bc2c49 100644--- a/fluxer_app/src/features/auth/hooks/useLoginFlow.ts+++ b/fluxer_app/src/features/auth/hooks/useLoginFlow.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {Routes} from '@app/app/Routes';import {type RuntimeConfigSnapshot, runtimeInstanceKey} from '@app/features/app/state/InstanceSnapshotStore';import RuntimeConfig from '@app/features/app/state/RuntimeConfig';import {resolveSnapshotInstanceDomain} from '@app/features/auth/AccountDisplayUtils';@@ -33,7 +34,9 @@ import {type MfaChallenge,toLoginSuccessPayload,} from '@app/features/auth/state/AuthFlow';-import {accountSignInIdentifier, loginIdentifierField} from '@app/features/auth/utils/AccountSignInIdentifier';+import {loginIdentifierField} from '@app/features/auth/utils/AccountSignInIdentifier';+import {describePasskeyError, describePasskeyPromptEnded} from '@app/features/auth/utils/PasskeyErrorMessages';+import {classifyPasskeyFailure} from '@app/features/auth/utils/PasskeyFailure';import * as WebAuthnUtils from '@app/features/auth/utils/WebAuthnUtils';import {ForegroundGatewayConnectionRecoverableError,@@ -47,7 +50,6 @@ import {Platform} from '@app/features/platform/types/Platform';import {Logger} from '@app/features/platform/utils/AppLogger';import * as ToastCommands from '@app/features/ui/commands/ToastCommands';import {isDesktop} from '@app/features/ui/utils/NativeUtils';-import type {I18n} from '@lingui/core';import {msg} from '@lingui/core/macro';import {useLingui} from '@lingui/react/macro';import {useCallback, useEffect, useMemo, useRef, useState} from 'react';@@ -56,11 +58,6 @@ const logger = Logger.create('useLoginFlow');const LOGIN_CONNECTING_STATUS_DELAY_MS = 1500;-export const SESSION_EXPIRED_SIGN_IN_AGAIN_DESCRIPTOR = msg({- message: 'Session expired for {identifier}. Sign in again.',- comment:- 'Login layout banner shown when the session for a specific account has expired. Account identifier is interpolated.',-});const PASSKEY_UNAVAILABLE_DESCRIPTOR = msg({message: 'Passkey sign-in is unavailable here.',comment: 'Auth error shown when passkey sign-in cannot run in the current authentication environment.',@@ -135,7 +132,7 @@ const handleLoginOutcome = async (}};-export function isLoginConnectionFailure(error: unknown): boolean {+function isLoginConnectionFailure(error: unknown): boolean {if (error instanceof AccountReplacementRecoveryFailedError) {return isLoginConnectionFailure(error.errors[0]);}@@ -257,6 +254,7 @@ export function useLoginFormController({});if (outcome === 'cancelled') {writePasskeyLoginRoute('native');+ ToastCommands.error(describePasskeyPromptEnded(i18n));}}navigating = outcome === 'navigating';@@ -272,10 +270,14 @@ export function useLoginFormController({if (AuthenticationCommands.showAccountRestriction(err)) {return;}- const userCancelled =- err instanceof DOMException && (err.name === 'NotAllowedError' || err.name === 'AbortError');- if (isDesktop() && !userCancelled) {+ const failure = classifyPasskeyFailure(err, isDesktop() ? 'browser_handoff' : 'show_error');+ if (failure === 'aborted') {+ return;+ }+ if (failure === 'browser_handoff') {onDesktopPasskeyHandoff();+ } else {+ ToastCommands.error(describePasskeyError(i18n, err, null) ?? i18n._(COULDN_T_VERIFY_WITH_PASSKEY_DESCRIPTOR));}} finally {if (!navigating) {@@ -309,22 +311,15 @@ export interface StoredAccountLoginPayload {readonly runtimeSnapshot: RuntimeConfigSnapshot;}-function accountIdentifier(account: Account): string {- return accountSignInIdentifier(account) ?? account.userData?.username ?? account.userId;-}--export function sessionExpiredMessage(i18n: I18n, account: Account): string {- return i18n._(SESSION_EXPIRED_SIGN_IN_AGAIN_DESCRIPTOR, {identifier: accountIdentifier(account)});-}--export interface StoredAccountSelectionHandlers {+interface StoredAccountSelectionHandlers {+ readonly redirectPath: string | null;readonly onLoginWithStoredAccount: (payload: StoredAccountLoginPayload) => Promise<void>;readonly onSessionExpired: (account: Account) => void;}async function selectStoredAccount(account: Account,- {onLoginWithStoredAccount, onSessionExpired}: StoredAccountSelectionHandlers,+ {redirectPath, onLoginWithStoredAccount, onSessionExpired}: StoredAccountSelectionHandlers,): Promise<void> {if (account.isValid === false) {onSessionExpired(account);@@ -333,7 +328,10 @@ async function selectStoredAccount(const accountKey = getAccountKey(account);try {if (Accounts.canSwitchAccounts) {- await Accounts.switchToAccount(accountKey);+ await Accounts.switchToAccount(+ accountKey,+ redirectPath == null || redirectPath === '' ? Routes.ME : redirectPath,+ );return;}const {token, userId, runtimeSnapshot} = await Accounts.prepareAccountCredentials(accountKey);@@ -349,12 +347,14 @@ async function selectStoredAccount(}interface AccountSwitchControllerOptions {+ redirectPath: string | null;onError: (message: string) => void;- onSessionExpired: (account: Account, message: string) => void;+ onSessionExpired: (account: Account) => void;onLoginWithStoredAccount: (payload: StoredAccountLoginPayload) => Promise<void>;}export function useAccountSwitchController({+ redirectPath,onError,onSessionExpired,onLoginWithStoredAccount,@@ -363,23 +363,20 @@ export function useAccountSwitchController({const [isSwitching, setIsSwitching] = useState(false);const switchToAccount = useCallback(async (account: Account) => {- const handleSessionExpired = (expiredAccount: Account) => {- onSessionExpired(expiredAccount, sessionExpiredMessage(i18n, expiredAccount));- };if (account.isValid === false) {- handleSessionExpired(account);+ onSessionExpired(account);return;}setIsSwitching(true);try {- await selectStoredAccount(account, {onLoginWithStoredAccount, onSessionExpired: handleSessionExpired});+ await selectStoredAccount(account, {redirectPath, onLoginWithStoredAccount, onSessionExpired});} catch (error) {onError(getAuthErrorMessage(error, i18n));} finally {setIsSwitching(false);}},- [i18n, onError, onLoginWithStoredAccount, onSessionExpired],+ [i18n, onError, onLoginWithStoredAccount, onSessionExpired, redirectPath],);return {isSwitching, switchToAccount};}@@ -452,6 +449,7 @@ export function useMfaController({ticket, methods, inviteCode, onLoginSuccess}:navigating = outcome === 'navigating';if (outcome === 'cancelled') {preferLegacyRef.current = false;+ ToastCommands.error(describePasskeyPromptEnded(i18n));}if (typeof outcome === 'string') {return;@@ -464,10 +462,8 @@ export function useMfaController({ticket, methods, inviteCode, onLoginSuccess}:if (AuthenticationCommands.showAccountRestriction(error)) {return;}- const userCancelled =- error instanceof DOMException && (error.name === 'NotAllowedError' || error.name === 'AbortError');- if (!userCancelled) {- ToastCommands.error(i18n._(COULDN_T_VERIFY_WITH_PASSKEY_DESCRIPTOR));+ if (classifyPasskeyFailure(error, 'show_error') !== 'aborted') {+ ToastCommands.error(describePasskeyError(i18n, error, null) ?? i18n._(COULDN_T_VERIFY_WITH_PASSKEY_DESCRIPTOR));}} finally {if (!navigating) {diff --git a/fluxer_app/src/features/auth/passkey_migration/PasskeyBridgePage.tsx b/fluxer_app/src/features/auth/passkey_migration/PasskeyBridgePage.tsxindex 5359839c7..cb44dc8aa 100644--- a/fluxer_app/src/features/auth/passkey_migration/PasskeyBridgePage.tsx+++ b/fluxer_app/src/features/auth/passkey_migration/PasskeyBridgePage.tsx@@ -163,6 +163,59 @@ const LegacyPasskeyBridgePage: React.FC<PasskeyBridgePageProps> = ({side, hash,}, [side.target]);const expired = state.status === 'expired';const failed = state.status === 'failed';+ let description = PRESS_CONTINUE_DESCRIPTOR;+ let actions: React.ReactNode;+ if (expired) {+ description = REQUEST_EXPIRED_DESCRIPTOR;+ actions = (+ <Button onClick={handleBack} autoFocus data-flx="auth.passkey-bridge-page.button.back">+ {i18n._(BACK_TO_PRODUCT_DESCRIPTOR, {productName: RuntimeConfig.productName})}+ </Button>+ );+ } else if (failed) {+ description = THAT_DIDN_T_WORK_DESCRIPTOR;+ actions = (+ <>+ <Button+ variant={opensInOwnTab ? 'secondary' : 'primary'}+ onClick={loadOptions}+ autoFocus={!opensInOwnTab}+ data-flx="auth.passkey-bridge-page.button.try-again"+ >+ {i18n._(TRY_AGAIN_DESCRIPTOR)}+ </Button>+ <Button+ variant={opensInOwnTab ? 'primary' : 'ghost'}+ onClick={cancel}+ autoFocus={opensInOwnTab}+ data-flx="auth.passkey-bridge-page.button.cancel"+ >+ {i18n._(CANCEL_DESCRIPTOR)}+ </Button>+ </>+ );+ } else {+ actions = (+ <>+ <Button+ onClick={handleContinue}+ submitting={state.status !== 'ready'}+ autoFocus+ data-flx="auth.passkey-bridge-page.button.continue"+ >+ {i18n._(CONTINUE_DESCRIPTOR)}+ </Button>+ <Button+ variant="ghost"+ onClick={cancel}+ disabled={state.status === 'running'}+ data-flx="auth.passkey-bridge-page.button.cancel"+ >+ {i18n._(CANCEL_DESCRIPTOR)}+ </Button>+ </>+ );+ }return (<main className={styles.errorFallbackContainer} data-flx="auth.passkey-bridge-page.container"><FluxerIcon className={styles.errorFallbackIcon} data-flx="auth.passkey-bridge-page.icon" />@@ -175,55 +228,11 @@ const LegacyPasskeyBridgePage: React.FC<PasskeyBridgePageProps> = ({side, hash,role={expired || failed ? 'alert' : undefined}data-flx="auth.passkey-bridge-page.description">- {i18n._(- expired ? REQUEST_EXPIRED_DESCRIPTOR : failed ? THAT_DIDN_T_WORK_DESCRIPTOR : PRESS_CONTINUE_DESCRIPTOR,- )}+ {i18n._(description)}</p></div><div className={styles.errorFallbackActions} data-flx="auth.passkey-bridge-page.actions">- {expired ? (- <Button onClick={handleBack} autoFocus data-flx="auth.passkey-bridge-page.button.back">- {i18n._(BACK_TO_PRODUCT_DESCRIPTOR, {productName: RuntimeConfig.productName})}- </Button>- ) : failed ? (- <>- <Button- variant={opensInOwnTab ? 'secondary' : 'primary'}- onClick={loadOptions}- autoFocus={!opensInOwnTab}- data-flx="auth.passkey-bridge-page.button.try-again"- >- {i18n._(TRY_AGAIN_DESCRIPTOR)}- </Button>- <Button- variant={opensInOwnTab ? 'primary' : 'ghost'}- onClick={cancel}- autoFocus={opensInOwnTab}- data-flx="auth.passkey-bridge-page.button.cancel"- >- {i18n._(CANCEL_DESCRIPTOR)}- </Button>- </>- ) : (- <>- <Button- onClick={handleContinue}- submitting={state.status !== 'ready'}- autoFocus- data-flx="auth.passkey-bridge-page.button.continue"- >- {i18n._(CONTINUE_DESCRIPTOR)}- </Button>- <Button- variant="ghost"- onClick={cancel}- disabled={state.status === 'running'}- data-flx="auth.passkey-bridge-page.button.cancel"- >- {i18n._(CANCEL_DESCRIPTOR)}- </Button>- </>- )}+ {actions}</div></main>);diff --git a/fluxer_app/src/features/auth/passkey_migration/usePasskeyBridgeReturn.ts b/fluxer_app/src/features/auth/passkey_migration/usePasskeyBridgeReturn.tsindex cb85221aa..9b12d78a7 100644--- a/fluxer_app/src/features/auth/passkey_migration/usePasskeyBridgeReturn.ts+++ b/fluxer_app/src/features/auth/passkey_migration/usePasskeyBridgeReturn.ts@@ -20,6 +20,7 @@ interface PasskeyBridgeReturnOptions {redirectPath?: string;onLoginSuccess: (payload: LoginSuccessPayload) => Promise<void> | void;onRequireMfa: (challenge: MfaChallenge) => void;+ onCancelled: () => void;onFailure: () => void;}@@ -55,6 +56,7 @@ export function usePasskeyBridgeReturn(options: PasskeyBridgeReturnOptions): booif (result.status === 'cancelled') {writePasskeyLoginRoute('native');restoreMfa();+ optionsRef.current.onCancelled();return;}await optionsRef.current.onLoginSuccess(toLoginSuccessPayload(result));diff --git a/fluxer_app/src/features/auth/utils/PasskeyErrorMessages.ts b/fluxer_app/src/features/auth/utils/PasskeyErrorMessages.tsnew file mode 100644index 000000000..e3ae2eab0--- /dev/null+++ b/fluxer_app/src/features/auth/utils/PasskeyErrorMessages.ts@@ -0,0 +1,84 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {I18n} from '@lingui/core';+import {msg} from '@lingui/core/macro';++const PASSKEYS_UNAVAILABLE_DESCRIPTOR = msg({+ message:+ 'Passkeys are not available on this device. On a computer, connect a security key and try again, or use another sign-in method.',+ comment: 'Error shown when adding or using a passkey on a device or app build that cannot run passkeys.',+});+const PASSKEY_NOT_ALLOWED_DESCRIPTOR = msg({+ message:+ 'The passkey prompt was cancelled, timed out or was blocked by your browser. Try again and finish the prompt on your device.',+ comment: 'Error shown when the browser passkey prompt ends without a passkey.',+});+const PASSKEY_ALREADY_REGISTERED_DESCRIPTOR = msg({+ message: 'This device or security key already has a passkey for your account.',+ comment: 'Error shown when adding a passkey with an authenticator that already holds one for this account.',+});+const PASSKEY_DOMAIN_MISMATCH_DESCRIPTOR = msg({+ message:+ 'Your browser blocked the passkey because this page is not on {rpId}, the passkey domain of this instance. Ask the instance owner to check the passkey domain setting.',+ comment:+ 'Error shown when the browser refuses a passkey because the page address does not match the domain the passkey belongs to. {rpId} is a domain name such as example.com.',+});+const PASSKEY_SECURITY_ERROR_DESCRIPTOR = msg({+ message:+ 'Your browser blocked the passkey because this page address does not match the passkey domain of this instance. Ask the instance owner to check the passkey domain setting.',+ comment: 'Error shown when the browser refuses a passkey because the page address does not match its domain.',+});+const PASSKEY_NOT_SUPPORTED_DESCRIPTOR = msg({+ message: 'This browser or authenticator cannot create the kind of passkey this instance asks for.',+ comment: 'Error shown when the browser or security key does not support the requested passkey type.',+});++export class PasskeysUnsupportedError extends Error {+ constructor() {+ super('WebAuthn is not supported in this environment.');+ this.name = 'PasskeysUnsupportedError';+ }+}++const DOMAIN_ERROR_CODES = new Set(['ERROR_INVALID_DOMAIN', 'ERROR_INVALID_RP_ID']);++function errorCode(error: Error): string | null {+ const code = (error as {code?: unknown}).code;+ return typeof code === 'string' ? code : null;+}++function withErrorName(message: string, name: string): string {+ return `${message} (${name})`;+}++export function describePasskeyPromptEnded(i18n: I18n): string {+ return i18n._(PASSKEY_NOT_ALLOWED_DESCRIPTOR);+}++export function describePasskeyError(i18n: I18n, error: unknown, rpId: string | null): string | null {+ if (error instanceof PasskeysUnsupportedError) {+ return i18n._(PASSKEYS_UNAVAILABLE_DESCRIPTOR);+ }+ if (!(error instanceof Error)) {+ return null;+ }+ const code = errorCode(error);+ switch (error.name) {+ case 'NotAllowedError':+ case 'AbortError':+ return withErrorName(describePasskeyPromptEnded(i18n), error.name);+ case 'InvalidStateError':+ return withErrorName(i18n._(PASSKEY_ALREADY_REGISTERED_DESCRIPTOR), error.name);+ case 'SecurityError':+ return withErrorName(+ rpId !== null && (code === null || DOMAIN_ERROR_CODES.has(code))+ ? i18n._(PASSKEY_DOMAIN_MISMATCH_DESCRIPTOR, {rpId})+ : i18n._(PASSKEY_SECURITY_ERROR_DESCRIPTOR),+ error.name,+ );+ case 'NotSupportedError':+ return withErrorName(i18n._(PASSKEY_NOT_SUPPORTED_DESCRIPTOR), error.name);+ default:+ return null;+ }+}diff --git a/fluxer_app/src/features/auth/utils/PasskeyFailure.ts b/fluxer_app/src/features/auth/utils/PasskeyFailure.tsnew file mode 100644index 000000000..0acd7bc44--- /dev/null+++ b/fluxer_app/src/features/auth/utils/PasskeyFailure.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++type PasskeyFailureFallback = 'show_error' | 'browser_handoff';+type PasskeyFailure = 'aborted' | PasskeyFailureFallback;++export function classifyPasskeyFailure(error: unknown, fallback: PasskeyFailureFallback): PasskeyFailure {+ if (!(error instanceof Error)) {+ return fallback;+ }+ if (error.name === 'AbortError') {+ return 'aborted';+ }+ if (error.name === 'NotAllowedError') {+ return 'show_error';+ }+ return fallback;+}diff --git a/fluxer_app/src/features/auth/utils/PasskeyPinErrors.ts b/fluxer_app/src/features/auth/utils/PasskeyPinErrors.tsindex c98647059..1087a6ffe 100644--- a/fluxer_app/src/features/auth/utils/PasskeyPinErrors.ts+++ b/fluxer_app/src/features/auth/utils/PasskeyPinErrors.ts@@ -8,7 +8,12 @@ export type PasskeyPinFailure =| {kind: 'not-set'};export function parsePasskeyPinFailure(error: unknown): PasskeyPinFailure | null {- const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';+ let message = '';+ if (error instanceof Error) {+ message = error.message;+ } else if (typeof error === 'string') {+ message = error;+ }if (!message) {return null;}diff --git a/fluxer_app/src/features/auth/utils/WebAuthnUtils.ts b/fluxer_app/src/features/auth/utils/WebAuthnUtils.tsindex 677b2085d..051603422 100644--- a/fluxer_app/src/features/auth/utils/WebAuthnUtils.ts+++ b/fluxer_app/src/features/auth/utils/WebAuthnUtils.ts@@ -2,6 +2,7 @@import {promptForSecurityKeyPin} from '@app/features/auth/components/modals/PasskeyPinModal';import {writePasskeyLoginRoute} from '@app/features/auth/passkey_migration/PasskeyLoginRoute';+import {PasskeysUnsupportedError} from '@app/features/auth/utils/PasskeyErrorMessages';import {parsePasskeyPinFailure} from '@app/features/auth/utils/PasskeyPinErrors';import {Platform} from '@app/features/platform/types/Platform';import {getElectronAPI} from '@app/features/ui/utils/NativeUtils';@@ -21,10 +22,24 @@ interface NativeCeremonyRequestContext {instanceKey?: string;}+const NATIVE_CEREMONY_ERROR_NAME = /\b(NotAllowedError|InvalidStateError): /u;++function withNativeCeremonyErrorName(error: unknown): unknown {+ const name = error instanceof Error ? NATIVE_CEREMONY_ERROR_NAME.exec(error.message)?.[1] : undefined;+ if (name !== undefined) {+ (error as Error).name = name;+ }+ return error;+}+async function runNativeCeremonyWithPinSupport<T>(instanceKey: string | null,- run: (requestContext?: NativeCeremonyRequestContext) => Promise<T>,+ ceremony: (requestContext?: NativeCeremonyRequestContext) => Promise<T>,): Promise<T> {+ const run = (requestContext?: NativeCeremonyRequestContext) =>+ ceremony(requestContext).catch((error: unknown) => {+ throw withNativeCeremonyErrorName(error);+ });const baseContext = instanceKey == null ? undefined : {instanceKey};try {return await run(baseContext);@@ -44,10 +59,6 @@ async function rememberMigratedPasskeyUse<T>(rpId: string | undefined, ceremony:return result;}-export function isBrowserWebAuthnSupported(): boolean {- return browserSupportsWebAuthn();-}-export async function isWebAuthnSupported(): Promise<boolean> {if (Platform.isElectron) {const electronApi = getElectronAPI();@@ -58,7 +69,7 @@ export async function isWebAuthnSupported(): Promise<boolean> {export async function assertWebAuthnSupported(): Promise<void> {if (!(await isWebAuthnSupported())) {- throw new Error('WebAuthn is not supported in this environment.');+ throw new PasskeysUnsupportedError();}}