A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): offer passkeys after sign-in and on dotless hosts
Hampusea12c413da0d
diff --git a/fluxer_app/src/features/auth/PasskeyAvailability.ts b/fluxer_app/src/features/auth/PasskeyAvailability.tsindex 1c2447d95..17598a57d 100644--- a/fluxer_app/src/features/auth/PasskeyAvailability.ts+++ b/fluxer_app/src/features/auth/PasskeyAvailability.ts@@ -3,7 +3,7 @@import type {RuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfig';import {isDesktop} from '@app/features/ui/utils/NativeUtils';-export const DESKTOP_PASSKEY_RELYING_PARTIES: ReadonlyArray<string> = Object.freeze(['fluxer.app']);+const DESKTOP_PASSKEY_RELYING_PARTIES: ReadonlyArray<string> = Object.freeze(['fluxer.app']);function hostFromEndpoint(endpoint: string | undefined): string | null {if (endpoint == null || endpoint.length === 0) {@@ -16,31 +16,34 @@ function hostFromEndpoint(endpoint: string | undefined): string | null {}}-export function resolvePasskeyRelyingPartyId(snapshot: RuntimeConfigSnapshot | null | undefined): string | null {+function resolvePasskeyRelyingPartyId(snapshot: RuntimeConfigSnapshot | null | undefined): string | null {const host = hostFromEndpoint(snapshot?.webAppEndpoint);if (host == null) {return null;}+ if (host.includes(':') || /^\d+(\.\d+){3}$/.test(host)) {+ return null;+ }const labels = host.split('.');if (labels.length < 2) {- return null;+ return host;}return labels.slice(-2).join('.');}-export function isRelyingPartyAssertableFromHost(relyingPartyId: string, host: string): boolean {+function isRelyingPartyAssertableFromHost(relyingPartyId: string, host: string): boolean {const rp = relyingPartyId.toLowerCase();const origin = host.toLowerCase();return origin === rp || origin.endsWith(`.${rp}`);}-export interface PasskeyAvailabilityRequest {+interface PasskeyAvailabilityRequest {readonly snapshot: RuntimeConfigSnapshot | null | undefined;readonly currentHost: string;readonly desktop: boolean;}-export function isPasskeyAvailableForInstance({snapshot, currentHost, desktop}: PasskeyAvailabilityRequest): boolean {+function isPasskeyAvailableForInstance({snapshot, currentHost, desktop}: PasskeyAvailabilityRequest): boolean {const relyingPartyId = resolvePasskeyRelyingPartyId(snapshot);if (relyingPartyId == null) {return false;diff --git a/fluxer_app/src/features/auth/components/modals/AuthenticatorOfferModal.tsx b/fluxer_app/src/features/auth/components/modals/AuthenticatorOfferModal.tsxnew file mode 100644index 000000000..805b3aa59--- /dev/null+++ b/fluxer_app/src/features/auth/components/modals/AuthenticatorOfferModal.tsx@@ -0,0 +1,84 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {ConfirmModal} from '@app/features/app/components/dialogs/ConfirmModal';+import {startPasskeyRegistration} from '@app/features/auth/utils/PasskeyRegistrationFlow';+import * as WebAuthnUtils from '@app/features/auth/utils/WebAuthnUtils';+import {getProtectedLocalStorage} from '@app/features/platform/state/ProtectedWebStorage';+import * as ModalCommands from '@app/features/ui/commands/ModalCommands';+import {modal} from '@app/features/ui/commands/ModalCommands';+import Users from '@app/features/user/state/Users';+import {UserAuthenticatorTypes} from '@fluxer/constants/src/UserConstants';+import {msg} from '@lingui/core/macro';+import {useLingui} from '@lingui/react/macro';+import {observer} from 'mobx-react-lite';++const OFFER_DISMISSED_KEY_PREFIX = 'fluxer.authenticator_offer_dismissed';++function offerDismissedKey(userId: string): string {+ return `${OFFER_DISMISSED_KEY_PREFIX}:${userId}`;+}++const SIGN_IN_FASTER_DESCRIPTOR = msg({+ message: 'Sign in faster next time',+ comment: 'Title of the optional, dismissible offer to add a passkey.',+});+const SIGN_IN_FASTER_BODY_DESCRIPTOR = msg({+ message:+ 'Add a passkey to sign in with your fingerprint, face or screen lock. You can also do this later in settings.',+ comment: 'Body of the optional, dismissible offer to add a passkey.',+});+const ADD_PASSKEY_DESCRIPTOR = msg({+ message: 'Add passkey',+ comment: 'Button in the optional passkey offer.',+});+const NOT_NOW_DESCRIPTOR = msg({+ message: 'Not now',+ comment: 'Button that dismisses the optional passkey offer.',+});++function rememberDismissed(userId: string): void {+ try {+ getProtectedLocalStorage()?.setItem(offerDismissedKey(userId), '1');+ } catch {}+}++function wasAuthenticatorOfferDismissed(userId: string): boolean {+ try {+ return getProtectedLocalStorage()?.getItem(offerDismissedKey(userId)) === '1';+ } catch {+ return true;+ }+}++const AuthenticatorOfferModal = observer(() => {+ const {i18n} = useLingui();+ return (+ <ConfirmModal+ title={i18n._(SIGN_IN_FASTER_DESCRIPTOR)}+ description={i18n._(SIGN_IN_FASTER_BODY_DESCRIPTOR)}+ primaryText={i18n._(ADD_PASSKEY_DESCRIPTOR)}+ primaryVariant="primary"+ secondaryText={i18n._(NOT_NOW_DESCRIPTOR)}+ onPrimary={() => {+ void startPasskeyRegistration(i18n);+ }}+ data-flx="auth.authenticator-offer-modal.confirm-modal"+ />+ );+});++export async function offerAuthenticatorCalmly(): Promise<void> {+ const user = Users.currentUser;+ if (+ user == null ||+ wasAuthenticatorOfferDismissed(user.id) ||+ user.authenticatorTypes?.includes(UserAuthenticatorTypes.WEBAUTHN)+ ) {+ return;+ }+ if (!(await WebAuthnUtils.isWebAuthnSupported())) {+ return;+ }+ rememberDismissed(user.id);+ ModalCommands.push(modal(() => <AuthenticatorOfferModal data-flx="auth.authenticator-offer-modal" />));+}diff --git a/fluxer_app/src/features/auth/components/modals/BackupCodesModal.tsx b/fluxer_app/src/features/auth/components/modals/BackupCodesModal.tsxindex 0923f8fd5..7beba56cb 100644--- a/fluxer_app/src/features/auth/components/modals/BackupCodesModal.tsx+++ b/fluxer_app/src/features/auth/components/modals/BackupCodesModal.tsx@@ -35,7 +35,7 @@ export const BackupCodesModal = observer(({backupCodes, user, challenge}: Backup<Modal.Content data-flx="auth.backup-codes-modal.modal-content"><Modal.ContentLayout data-flx="auth.backup-codes-modal.modal-content-layout"><Modal.Description data-flx="auth.backup-codes-modal.description">- <Trans>Use these codes to access your account if you lose your authenticator app.</Trans>+ <Trans>Use these codes to sign in if you lose your authenticator app or passkey.</Trans></Modal.Description><Modal.Description data-flx="auth.backup-codes-modal.description--2"><Trans>We recommend saving these codes now so that you don't get locked out of your account.</Trans>diff --git a/fluxer_app/src/features/auth/utils/PasskeyRegistration.ts b/fluxer_app/src/features/auth/utils/PasskeyRegistration.tsnew file mode 100644index 000000000..0f1397f87--- /dev/null+++ b/fluxer_app/src/features/auth/utils/PasskeyRegistration.ts@@ -0,0 +1,29 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import * as WebAuthnUtils from '@app/features/auth/utils/WebAuthnUtils';+import * as UserCommands from '@app/features/user/commands/UserCommands';+import type {PublicKeyCredentialCreationOptionsJSON} from '@simplewebauthn/browser';++const PREFETCHED_OPTIONS_MAX_AGE_MS = 4 * 60 * 1000;++export async function preparePasskeyRegistration(): Promise<PublicKeyCredentialCreationOptionsJSON> {+ await WebAuthnUtils.assertWebAuthnSupported();+ return UserCommands.getWebAuthnRegistrationOptions();+}++export function createPasskeyRegistration(+ prefetched: PublicKeyCredentialCreationOptionsJSON,+ now: () => number = Date.now,+): (name: string) => Promise<void> {+ let unused: PublicKeyCredentialCreationOptionsJSON | null = prefetched;+ const fetchedAt = now();+ return async (name) => {+ const options =+ unused !== null && now() - fetchedAt < PREFETCHED_OPTIONS_MAX_AGE_MS+ ? unused+ : await preparePasskeyRegistration();+ const credential = await WebAuthnUtils.performRegistration(options);+ unused = null;+ await UserCommands.registerWebAuthnCredential(credential, options.challenge, name);+ };+}diff --git a/fluxer_app/src/features/auth/utils/PasskeyRegistrationFlow.tsx b/fluxer_app/src/features/auth/utils/PasskeyRegistrationFlow.tsxnew file mode 100644index 000000000..b177515b6--- /dev/null+++ b/fluxer_app/src/features/auth/utils/PasskeyRegistrationFlow.tsx@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {GenericErrorModal} from '@app/features/app/components/alerts/GenericErrorModal';+import {PasskeyNameModal} from '@app/features/auth/components/modals/PasskeyNameModal';+import {describePasskeyError} from '@app/features/auth/utils/PasskeyErrorMessages';+import {createPasskeyRegistration, preparePasskeyRegistration} from '@app/features/auth/utils/PasskeyRegistration';+import {SOMETHING_WENT_WRONG_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';+import {isAbortError} from '@app/features/platform/utils/PlatformHelpers';+import * as ModalCommands from '@app/features/ui/commands/ModalCommands';+import {modal} from '@app/features/ui/commands/ModalCommands';+import * as FormUtils from '@app/lib/forms';+import type {I18n} from '@lingui/core';++export async function startPasskeyRegistration(i18n: I18n): Promise<void> {+ let options: Awaited<ReturnType<typeof preparePasskeyRegistration>>;+ try {+ options = await preparePasskeyRegistration();+ } catch (error) {+ if (isAbortError(error)) return;+ const message = describePasskeyError(i18n, error, null);+ if (message === null) {+ FormUtils.pushApiErrorModal(i18n, error);+ return;+ }+ ModalCommands.push(+ modal(() => (+ <GenericErrorModal+ title={i18n._(SOMETHING_WENT_WRONG_DESCRIPTOR)}+ message={message}+ data-flx="auth.passkey-registration-flow.generic-error-modal"+ />+ )),+ );+ return;+ }+ ModalCommands.push(+ modal(() => (+ <PasskeyNameModal+ rpId={options.rp.id ?? null}+ onSubmit={createPasskeyRegistration(options)}+ data-flx="auth.passkey-registration-flow.passkey-name-modal"+ />+ )),+ );+}