A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): add identifier-first email and code steps
Hampus5093f4bd31c9
diff --git a/fluxer_app/src/features/auth/flow/identifier_first/AuthIdentifierCodeStep.tsx b/fluxer_app/src/features/auth/flow/identifier_first/AuthIdentifierCodeStep.tsxnew file mode 100644index 000000000..cbb0c2ad2--- /dev/null+++ b/fluxer_app/src/features/auth/flow/identifier_first/AuthIdentifierCodeStep.tsx@@ -0,0 +1,188 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ NEW_CODE_SENT_DESCRIPTOR,+ SIGN_IN_WITH_A_PASSKEY_DESCRIPTOR,+ USE_A_DIFFERENT_EMAIL_DESCRIPTOR,+} from '@app/features/auth/AuthMessageDescriptors';+import type {AccountEntryResult} from '@app/features/auth/commands/AccountEntryCommands';+import * as AccountEntryCommands from '@app/features/auth/commands/AccountEntryCommands';+import {EmailCodeField} from '@app/features/auth/flow/EmailCodeField';+import type {AuthIdentifierFirstStepProps} from '@app/features/auth/flow/identifier_first/AuthIdentifierFirstStep';+import styles from '@app/features/auth/flow/identifier_first/AuthIdentifierFirstStep.module.css';+import {type IdentifierStep, isCompleteEmailCode} from '@app/features/auth/flow/identifier_first/IdentifierFirstState';+import {QuietButton} from '@app/features/auth/flow/QuietButton';+import {+ type RegistrationLegalConsentConfig,+ RegistrationLegalNotice,+} from '@app/features/auth/flow/RegistrationLegalNotice';+import {CREATE_ACCOUNT_DESCRIPTOR, SIGN_IN_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';+import {Button} from '@app/features/ui/button/Button';+import {msg} from '@lingui/core/macro';+import {useLingui} from '@lingui/react/macro';+import {makeAutoObservable} from 'mobx';+import {observer} from 'mobx-react-lite';+import type {ReactNode} from 'react';++const SEND_NEW_CODE_DESCRIPTOR = msg({+ message: 'Send a new code',+ comment: 'Quiet text button that emails a fresh sign-in code.',+});+const SEND_NEW_CODE_IN_DESCRIPTOR = msg({+ message: 'Send a new code in {seconds}s',+ comment: 'Disabled text button while a new sign-in code cannot be sent yet. seconds counts down.',+});++export type CodeDeliveryRequest = Pick<Extract<IdentifierStep, {kind: 'code'}>, 'email' | 'ticket' | 'existingAccount'>;++export class IdentifierCodeDraft {+ code = '';+ status: string | null = null;++ constructor() {+ makeAutoObservable(this, {}, {autoBind: true});+ }++ setCode(value: string): void {+ this.code = value;+ }++ setStatus(value: string | null): void {+ this.status = value;+ }+}++interface AuthIdentifierCodeStepProps+ extends Pick<+ AuthIdentifierFirstStepProps,+ 'runtimeSnapshot' | 'inviteCode' | 'passkeyAvailable' | 'passkeyDisabled' | 'onPasskeyLogin'+ > {+ readonly step: Extract<IdentifierStep, {kind: 'code'}>;+ readonly draft: IdentifierCodeDraft;+ readonly registrationUrlCode: string | null;+ readonly heading: ReactNode;+ readonly consentConfig: RegistrationLegalConsentConfig;+ readonly error: string | null;+ readonly submitting: boolean;+ readonly resendSeconds: number;+ readonly run: (work: () => Promise<void>) => Promise<void>;+ readonly finishEntry: (result: AccountEntryResult) => Promise<void>;+ readonly sendCode: (request: CodeDeliveryRequest) => Promise<void>;+ readonly onBack: () => void;+}++export const AuthIdentifierCodeStep = observer(function AuthIdentifierCodeStep({+ runtimeSnapshot,+ inviteCode,+ passkeyAvailable,+ passkeyDisabled,+ onPasskeyLogin,+ step,+ draft,+ registrationUrlCode,+ heading,+ consentConfig,+ error,+ submitting,+ resendSeconds,+ run,+ finishEntry,+ sendCode,+ onBack,+}: AuthIdentifierCodeStepProps) {+ const {i18n} = useLingui();+ const {code, status, setCode, setStatus} = draft;+ const signingUp = step.purpose === 'sign_up';+ const handleCodeSubmit = (value: string) => {+ if (!isCompleteEmailCode(value)) return;+ const {ticket, purpose} = step;+ void run(async () => {+ const result = await AccountEntryCommands.verifyEmailCode({+ ticket,+ code: value,+ consent: purpose === 'sign_up',+ inviteCode,+ registrationUrlCode,+ snapshot: runtimeSnapshot,+ });+ await finishEntry(result);+ });+ };++ const handleResend = () => {+ const {email: address, ticket, existingAccount} = step;+ void run(async () => {+ await sendCode({email: address, ticket, existingAccount});+ setStatus(i18n._(NEW_CODE_SENT_DESCRIPTOR));+ });+ };++ return (+ <flx-auth-identifier-first className="flx-element" data-flx="auth.flow.identifier-first.code-step">+ {heading}+ <form+ className={styles.form}+ onSubmit={(event) => {+ event.preventDefault();+ handleCodeSubmit(code);+ }}+ data-flx="auth.flow.identifier-first.code-form"+ >+ <EmailCodeField+ value={code}+ error={error}+ disabled={submitting}+ onChange={setCode}+ onComplete={signingUp ? undefined : handleCodeSubmit}+ data-flx="auth.flow.identifier-first.email-code-field"+ />+ {status === null ? null : (+ <p className={styles.hint} role="status" data-flx="auth.flow.identifier-first.status">+ {status}+ </p>+ )}+ {signingUp ? (+ <RegistrationLegalNotice+ config={consentConfig}+ data-flx="auth.flow.identifier-first.auth-identifier-first-step.registration-legal-notice"+ />+ ) : null}+ <Button+ type="submit"+ fitContainer+ submitting={submitting}+ disabled={!isCompleteEmailCode(code)}+ data-flx="auth.flow.identifier-first.button.verify-code"+ >+ {i18n._(signingUp ? CREATE_ACCOUNT_DESCRIPTOR : SIGN_IN_DESCRIPTOR)}+ </Button>+ </form>+ <div className={styles.quietActions} data-flx="auth.flow.identifier-first.code-actions">+ <QuietButton+ onClick={handleResend}+ disabled={submitting || resendSeconds > 0}+ data-flx="auth.flow.identifier-first.auth-identifier-first-step.quiet-button.resend"+ >+ {resendSeconds > 0+ ? i18n._(SEND_NEW_CODE_IN_DESCRIPTOR, {seconds: resendSeconds})+ : i18n._(SEND_NEW_CODE_DESCRIPTOR)}+ </QuietButton>+ {step.existingAccount && passkeyAvailable ? (+ <QuietButton+ onClick={onPasskeyLogin}+ disabled={passkeyDisabled}+ data-flx="auth.flow.identifier-first.auth-identifier-first-step.quiet-button.passkey-login"+ >+ {i18n._(SIGN_IN_WITH_A_PASSKEY_DESCRIPTOR)}+ </QuietButton>+ ) : null}+ <QuietButton+ onClick={onBack}+ data-flx="auth.flow.identifier-first.auth-identifier-first-step.quiet-button.go-to"+ >+ {i18n._(USE_A_DIFFERENT_EMAIL_DESCRIPTOR)}+ </QuietButton>+ </div>+ </flx-auth-identifier-first>+ );+});diff --git a/fluxer_app/src/features/auth/flow/identifier_first/AuthIdentifierEmailStep.tsx b/fluxer_app/src/features/auth/flow/identifier_first/AuthIdentifierEmailStep.tsxnew file mode 100644index 000000000..18a278cd2--- /dev/null+++ b/fluxer_app/src/features/auth/flow/identifier_first/AuthIdentifierEmailStep.tsx@@ -0,0 +1,200 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {SIGN_IN_WITH_A_PASSKEY_DESCRIPTOR} from '@app/features/auth/AuthMessageDescriptors';+import * as AccountEntryCommands from '@app/features/auth/commands/AccountEntryCommands';+import loginStyles from '@app/features/auth/components/pages/LoginPage.module.css';+import FormField from '@app/features/auth/flow/AuthFormField';+import type {CodeDeliveryRequest} from '@app/features/auth/flow/identifier_first/AuthIdentifierCodeStep';+import type {AuthIdentifierFirstStepProps} from '@app/features/auth/flow/identifier_first/AuthIdentifierFirstStep';+import styles from '@app/features/auth/flow/identifier_first/AuthIdentifierFirstStep.module.css';+import {+ decideAfterIdentify,+ type IdentifierStep,+ needsPasswordStep,+} from '@app/features/auth/flow/identifier_first/IdentifierFirstState';+import {QuietButton} from '@app/features/auth/flow/QuietButton';+import {isAgeBlocked} from '@app/features/auth/state/AccountEntryStorage';+import {CONTINUE_DESCRIPTOR, EMAIL_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';+import {Button} from '@app/features/ui/button/Button';+import {msg} from '@lingui/core/macro';+import {useLingui} from '@lingui/react/macro';+import clsx from 'clsx';+import type {ReactNode, RefObject} from 'react';++const CONTINUE_WITHOUT_EMAIL_DESCRIPTOR = msg({+ message: 'Continue without email',+ comment: 'Quiet text button on the sign-in screen that creates an account without an email address.',+});+const REGISTRATION_CLOSED_DESCRIPTOR = msg({+ message: "No account uses this email, and this instance isn't taking new accounts right now.",+ comment: 'Error under the email field when the address is new and the instance does not allow sign-ups.',+});++interface AuthIdentifierEmailStepProps+ extends Pick<+ AuthIdentifierFirstStepProps,+ | 'runtimeSnapshot'+ | 'showTitle'+ | 'extraTopContent'+ | 'notice'+ | 'passkeyAvailable'+ | 'passkeyDisabled'+ | 'onPasskeyLogin'+ | 'alternativeActions'+ > {+ readonly heading: ReactNode;+ readonly email: string;+ readonly setEmail: (value: string) => void;+ readonly error: string | null;+ readonly setError: (value: string | null) => void;+ readonly submitting: boolean;+ readonly fieldId: string;+ readonly fieldRef: RefObject<HTMLInputElement | null>;+ readonly emailCodes: boolean;+ readonly instantAccounts: boolean;+ readonly registrationUrlCode: string | null;+ readonly run: (work: () => Promise<void>) => Promise<void>;+ readonly goTo: (step: IdentifierStep) => void;+ readonly sendCode: (request: CodeDeliveryRequest) => Promise<void>;+ readonly onAgeBlocked: () => void;+}++export function AuthIdentifierEmailStep({+ runtimeSnapshot,+ showTitle,+ extraTopContent,+ notice,+ passkeyAvailable,+ passkeyDisabled,+ onPasskeyLogin,+ alternativeActions,+ heading,+ email,+ setEmail,+ error,+ setError,+ submitting,+ fieldId,+ fieldRef,+ emailCodes,+ instantAccounts,+ registrationUrlCode,+ run,+ goTo,+ sendCode,+ onAgeBlocked,+}: AuthIdentifierEmailStepProps) {+ const {i18n} = useLingui();+ const handleEmailSubmit = () =>+ run(async () => {+ const address = email.trim();+ const response = await AccountEntryCommands.identify(address, runtimeSnapshot);+ const decision = decideAfterIdentify(response, emailCodes, registrationUrlCode !== null);+ if (decision.kind === 'registration_closed') {+ setError(i18n._(REGISTRATION_CLOSED_DESCRIPTOR));+ return;+ }+ if (decision.kind === 'password') {+ goTo({kind: 'password', email: address, ticket: response.ticket});+ return;+ }+ if (isAgeBlocked() && response.account === 'new') {+ onAgeBlocked();+ return;+ }+ if (decision.kind === 'create_password') {+ goTo({kind: 'create_password', email: address});+ return;+ }+ try {+ await sendCode({email: address, ticket: response.ticket, existingAccount: response.account === 'existing'});+ } catch (caught) {+ if (!needsPasswordStep(caught)) throw caught;+ goTo({kind: 'password', email: address, ticket: response.ticket});+ }+ });++ return (+ <flx-auth-identifier-first className="flx-element" data-flx="auth.flow.identifier-first.email-step">+ {extraTopContent}+ {heading}+ {notice === null ? null : (+ <div className={loginStyles.loginNotice} role="alert" dir="auto" data-flx="auth.flow.identifier-first.notice">+ {notice}+ </div>+ )}+ <form+ className={clsx(styles.form, !showTitle && styles.formAfterHeader)}+ onSubmit={(event) => {+ event.preventDefault();+ void handleEmailSubmit();+ }}+ autoComplete="on"+ name="login"+ data-flx="auth.flow.identifier-first.email-form"+ >+ <FormField+ id={`${fieldId}-email`}+ name="email"+ type="email"+ autoComplete="username webauthn"+ autoCapitalize="none"+ autoCorrect="off"+ spellCheck={false}+ enterKeyHint="go"+ autoFocus+ data-step-focus="true"+ required+ label={i18n._(EMAIL_DESCRIPTOR)}+ value={email}+ onChange={(value) => {+ setError(null);+ setEmail(value);+ }}+ error={error ?? undefined}+ inputRef={fieldRef}+ data-flx="auth.flow.identifier-first.form-field.email"+ />+ <Button+ type="submit"+ fitContainer+ submitting={submitting}+ disabled={email.trim().length === 0}+ data-flx="auth.flow.identifier-first.button.continue"+ >+ {i18n._(CONTINUE_DESCRIPTOR)}+ </Button>+ </form>+ <div className={styles.quietActions} data-flx="auth.flow.identifier-first.email-actions">+ {instantAccounts ? (+ <QuietButton+ onClick={() => {+ if (isAgeBlocked()) {+ onAgeBlocked();+ return;+ }+ goTo({kind: 'name'});+ }}+ data-flx="auth.flow.identifier-first.auth-identifier-first-step.quiet-button.go-to--4"+ >+ {i18n._(CONTINUE_WITHOUT_EMAIL_DESCRIPTOR)}+ </QuietButton>+ ) : null}+ {passkeyAvailable ? (+ <QuietButton+ onClick={onPasskeyLogin}+ disabled={passkeyDisabled}+ data-flx="auth.flow.identifier-first.auth-identifier-first-step.quiet-button.passkey-login--2"+ >+ {i18n._(SIGN_IN_WITH_A_PASSKEY_DESCRIPTOR)}+ </QuietButton>+ ) : null}+ </div>+ {alternativeActions === null ? null : (+ <div className={styles.alternatives} data-flx="auth.flow.identifier-first.alternatives">+ {alternativeActions}+ </div>+ )}+ </flx-auth-identifier-first>+ );+}diff --git a/fluxer_app/src/features/auth/flow/identifier_first/AuthIdentifierFirstStep.module.css b/fluxer_app/src/features/auth/flow/identifier_first/AuthIdentifierFirstStep.module.cssnew file mode 100644index 000000000..e29a26527--- /dev/null+++ b/fluxer_app/src/features/auth/flow/identifier_first/AuthIdentifierFirstStep.module.css@@ -0,0 +1,67 @@+/* SPDX-License-Identifier: AGPL-3.0-or-later */++.form {+ display: flex;+ flex-direction: column;+ gap: 1.125rem;+}++.formAfterHeader {+ margin-top: 1.75rem;+}++.description {+ margin: -0.75rem 0 1.25rem;+ text-align: center;+ font-size: 0.875rem;+ line-height: 1.25rem;+ color: var(--text-secondary);+ overflow-wrap: anywhere;+}++.quietActions {+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: 0.25rem 1rem;+ margin-top: 1rem;+}++.textButton {+ padding: 0.125rem 0.25rem;+ border: none;+ border-radius: 0.25rem;+ background: none;+ color: var(--text-link);+ font: inherit;+ font-size: 0.875rem;+ font-weight: 600;+ cursor: pointer;+}++.textButton:hover:not(:disabled) {+ text-decoration: underline;+}++.textButton:disabled {+ color: var(--text-tertiary);+ cursor: default;+}++.hint {+ margin: 0;+ font-size: 0.875rem;+ line-height: 1.25rem;+ color: var(--text-tertiary);+}++.hintError {+ color: var(--status-danger);+}++.alternatives {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ margin-top: 1rem;+}diff --git a/fluxer_app/src/features/auth/flow/identifier_first/IdentifierFirstState.ts b/fluxer_app/src/features/auth/flow/identifier_first/IdentifierFirstState.tsnew file mode 100644index 000000000..9f86ee697--- /dev/null+++ b/fluxer_app/src/features/auth/flow/identifier_first/IdentifierFirstState.ts@@ -0,0 +1,84 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {failureCode} from '@app/features/platform/utils/ResponseInspection';+import {InstantAccountAvailability} from '@fluxer/constants/src/AccountConfigConstants';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import type {IdentifyResponse} from '@fluxer/schema/src/domains/auth/AuthSchemas';+import type {InstanceFeatures} from '@fluxer/schema/src/domains/instance/InstanceSchemas';++const EMAIL_CODE_LENGTH = 6;++type EmailCodePurpose = 'sign_in' | 'sign_up';++export type IdentifierStep =+ | {readonly kind: 'email'}+ | {readonly kind: 'name'}+ | {+ readonly kind: 'code';+ readonly email: string;+ readonly ticket: string;+ readonly purpose: EmailCodePurpose;+ readonly existingAccount: boolean;+ readonly resendAvailableAt: number;+ }+ | {readonly kind: 'password'; readonly email: string; readonly ticket: string | null}+ | {readonly kind: 'create_password'; readonly email: string};++export type IdentifyDecision =+ | {readonly kind: 'send_code'}+ | {readonly kind: 'password'}+ | {readonly kind: 'create_password'}+ | {readonly kind: 'registration_closed'};++export function decideAfterIdentify(+ response: IdentifyResponse,+ emailCodes: boolean,+ hasRegistrationLink = false,+): IdentifyDecision {+ if (response.account === 'existing') {+ return emailCodes && response.sign_in_method === 'code' ? {kind: 'send_code'} : {kind: 'password'};+ }+ if (response.registration?.mode === 'closed' && !hasRegistrationLink) {+ return {kind: 'registration_closed'};+ }+ if (!emailCodes || response.registration?.requires_password === true) {+ return {kind: 'create_password'};+ }+ return {kind: 'send_code'};+}++export function needsPasswordStep(error: unknown): boolean {+ return failureCode(error) === APIErrorCodes.PASSWORD_SIGN_IN_REQUIRED;+}++export function normalizeEmailCode(value: string): string {+ return value.replace(/\D/g, '').slice(0, EMAIL_CODE_LENGTH);+}++export function isCompleteEmailCode(value: string): boolean {+ return value.length === EMAIL_CODE_LENGTH;+}++export function secondsUntil(timestamp: number, now: number): number {+ return Math.max(0, Math.ceil((timestamp - now) / 1000));+}++export function parseIsoTimestamp(value: string, fallback: number): number {+ const parsed = Date.parse(value);+ return Number.isNaN(parsed) ? fallback : parsed;+}++export function offersInstantAccount(+ features: Pick<InstanceFeatures, 'instant_accounts' | 'instant_account_availability'>,+ registrationUrlCode: string | null,+): boolean {+ const availability =+ features.instant_account_availability ??+ (features.instant_accounts === true ? InstantAccountAvailability.AVAILABLE : InstantAccountAvailability.DISABLED);+ if (availability === InstantAccountAvailability.AVAILABLE) return true;+ return (+ registrationUrlCode !== null &&+ (availability === InstantAccountAvailability.REGISTRATION_CLOSED ||+ availability === InstantAccountAvailability.APPROVAL_REQUIRED)+ );+}diff --git a/fluxer_app/src/features/auth/flow/identifier_first/usePasskeyAutofill.ts b/fluxer_app/src/features/auth/flow/identifier_first/usePasskeyAutofill.tsnew file mode 100644index 000000000..0fc62e031--- /dev/null+++ b/fluxer_app/src/features/auth/flow/identifier_first/usePasskeyAutofill.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {RuntimeConfigSnapshot} from '@app/features/app/state/InstanceSnapshotStore';+import {rpIdMatchesPage} from '@app/features/auth/passkey_migration/PasskeyMigrationOrigin';+import {+ authenticateWithWebAuthn,+ getWebAuthnAuthenticationOptions,+ type LoginSuccessPayload,+} from '@app/features/auth/state/AuthFlow';+import {Platform} from '@app/features/platform/types/Platform';+import {Logger} from '@app/features/platform/utils/AppLogger';+import {browserSupportsWebAuthnAutofill, startAuthentication, WebAuthnAbortService} from '@simplewebauthn/browser';+import {useEffect, useRef} from 'react';++const logger = new Logger('PasskeyAutofill');++export function usePasskeyAutofill(+ enabled: boolean,+ runtimeSnapshot: RuntimeConfigSnapshot,+ inviteCode: string | null,+ onSignedIn: (payload: LoginSuccessPayload) => Promise<void>,+): void {+ const onSignedInRef = useRef(onSignedIn);+ onSignedInRef.current = onSignedIn;+ useEffect(() => {+ if (!enabled || Platform.isElectron) return;+ let active = true;+ let pending = false;+ const start = async () => {+ if (!(await browserSupportsWebAuthnAutofill())) return;+ const options = await getWebAuthnAuthenticationOptions(runtimeSnapshot);+ if (!active || (options.rpId !== undefined && !rpIdMatchesPage(options.rpId))) return;+ pending = true;+ const credential = await startAuthentication({optionsJSON: options, useBrowserAutofill: true}).finally(() => {+ pending = false;+ });+ if (!active) return;+ const payload = await authenticateWithWebAuthn({+ response: credential,+ challenge: options.challenge,+ inviteCode: inviteCode ?? undefined,+ runtimeSnapshot,+ });+ await onSignedInRef.current(payload);+ };+ start().catch((error: unknown) => {+ if (active) logger.debug('Passkey autofill ended', error);+ });+ return () => {+ active = false;+ if (pending) WebAuthnAbortService.cancelCeremony();+ };+ }, [enabled, inviteCode, runtimeSnapshot]);+}