A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): sign in with one-time links, add a purchase heading
Hampus969b71327873
diff --git a/fluxer_app/src/features/auth/commands/AuthenticationCommands.ts b/fluxer_app/src/features/auth/commands/AuthenticationCommands.tsindex f47883067..174b368cb 100644--- a/fluxer_app/src/features/auth/commands/AuthenticationCommands.ts+++ b/fluxer_app/src/features/auth/commands/AuthenticationCommands.ts@@ -2,6 +2,7 @@import {Endpoints} from '@app/features/app/constants/Endpoints';import type {RuntimeConfigSnapshot} from '@app/features/app/state/InstanceSnapshotStore';+import {markSsoAutoStartSpent} from '@app/features/auth/flow/SsoAutoStart';import {parseAccountRestriction} from '@app/features/auth/state/AccountRestriction';import type {UserData} from '@app/features/auth/state/AccountStorageContract';import Accounts from '@app/features/auth/state/Accounts';@@ -10,6 +11,7 @@ import {type InstanceHTTPTarget, instanceRequest} from '@app/features/platform/timport {HttpError} from '@app/features/platform/types/EndpointError';import {Logger} from '@app/features/platform/utils/AppLogger';import {failureCode, ipAuthorizationRequiredResponseFromError} from '@app/features/platform/utils/ResponseInspection';+import {forgetPurchaseIntent} from '@app/features/premium/state/PurchaseIntent';import {getCurrentOrDetectedLocale} from '@app/features/user/utils/LocaleUtils';import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';import type {ValueOf} from '@fluxer/constants/src/ValueOf';@@ -23,6 +25,7 @@ import type {UsernameAvailabilityResponse,UsernameSuggestionsResponse,} from '@fluxer/schema/src/domains/auth/AuthSchemas';+import type {GuildEntryResult} from '@fluxer/schema/src/domains/user/AccountSchemas';import type {UserPartial} from '@fluxer/schema/src/domains/user/UserResponseSchemas';import type {AuthenticationResponseJSON, PublicKeyCredentialRequestOptionsJSON} from '@simplewebauthn/browser';@@ -102,7 +105,9 @@ export function authResponseUserToUserData(user?: AuthResponseUserIdentity | nulexport type TokenResponse = AuthTokenResponse;export type RegistrationPendingApprovalResponse = AuthRegistrationPendingApprovalResponse;-export type RegisterResponse = TokenResponse | RegistrationPendingApprovalResponse;+export type RegisterResponse =+ | (TokenResponse & {entry?: GuildEntryResult | null})+ | RegistrationPendingApprovalResponse;export function isIpAuthorizationRequiredResponse(response: LoginResponse | IpAuthorizationRequiredResponse,@@ -613,8 +618,21 @@ export async function resendVerificationEmail(target: InstanceHTTPTarget): Promi}}-export async function logout(): Promise<void> {- await Accounts.logout();+export async function logout(options: {notifyServer?: boolean} = {}): Promise<void> {+ forgetPurchaseIntent();+ markSsoAutoStartSpent();+ await Accounts.logout(options);+}++export async function redeemSignInLink(token: string, target: InstanceHTTPTarget): Promise<AuthTokenResponse> {+ const response = await instanceRequest<AuthTokenResponse>({+ method: 'POST',+ path: Endpoints.AUTH_SIGN_IN_LINK,+ target,+ body: tokenBody(token),+ headers: withAuthLocaleHeader(),+ });+ return response.body;}export async function authorizeIp(token: string, target: InstanceHTTPTarget): Promise<VerificationResult> {@@ -781,7 +799,7 @@ interface CompleteLoginPayload {runtimeSnapshot: RuntimeConfigSnapshot;}-export class InvalidLoginCredentialsError extends Error {+class InvalidLoginCredentialsError extends Error {constructor(field: 'token' | 'userId') {super(`Login response ${field} must be a non-empty string`);this.name = 'InvalidLoginCredentialsError';diff --git a/fluxer_app/src/features/auth/components/pages/LoginPage.tsx b/fluxer_app/src/features/auth/components/pages/LoginPage.tsxindex 40752c157..f2a990f47 100644--- a/fluxer_app/src/features/auth/components/pages/LoginPage.tsx+++ b/fluxer_app/src/features/auth/components/pages/LoginPage.tsx@@ -1,6 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {Routes} from '@app/app/Routes';+import {readHashParam} from '@app/features/app/hooks/useHashParam';+import {runtimeInstanceKey} from '@app/features/app/state/InstanceSnapshotStore';+import {SignInLinkPage} from '@app/features/auth/components/pages/SignInLinkPage';import {AuthFloatingBackButton} from '@app/features/auth/flow/AuthFloatingBackButton';import {AuthLoginLayout} from '@app/features/auth/flow/AuthLoginLayout';import {AuthRouterLink} from '@app/features/auth/flow/AuthRouterLink';@@ -8,27 +11,46 @@ import {AUTH_LOGIN_METHOD_QUERY_PARAM} from '@app/features/auth/flow/auth_login_import {isHandoffRequest} from '@app/features/auth/flow/auth_login_core/useDesktopHandoffFlow';import {DesktopHandoffMfaStep} from '@app/features/auth/flow/DesktopHandoffMfaStep';import Authentication, {LoginState} from '@app/features/auth/state/Authentication';-import {useAuthRuntimeTarget} from '@app/features/auth/state/AuthRuntimeTarget';+import {type AuthRuntimeTarget, useAuthRuntimeTarget} from '@app/features/auth/state/AuthRuntimeTarget';import {safeRedirectTarget} from '@app/features/auth/utils/SafeRedirect';import {GO_BACK_DESCRIPTOR,REGISTER_DESCRIPTOR,SIGN_IN_DESCRIPTOR,} from '@app/features/i18n/utils/CommonMessageDescriptors';+import * as RouterUtils from '@app/features/navigation/utils/RouterUtils';import {useLocation} from '@app/features/platform/components/router/RouterReact';+import {hasPurchaseIntent} from '@app/features/premium/state/PurchaseIntent';+import {getPremiumProductName} from '@app/features/premium/utils/PremiumUtils';import {SteppedCarousel} from '@app/features/ui/stepped_carousel/SteppedCarousel';import {useFluxerDocumentTitle} from '@app/features/window/hooks/useFluxerDocumentTitle';+import {msg} from '@lingui/core/macro';import {useLingui} from '@lingui/react/macro';import {observer} from 'mobx-react-lite';-import {useCallback, useMemo, useState} from 'react';+import {useCallback, useEffect, useMemo, useState} from 'react';++const GET_PREMIUM_HEADING_DESCRIPTOR = msg({+ message: 'Sign in or create an account to get {premiumProductName}',+ comment:+ 'Heading of the sign-in screen when someone came from a purchase button. premiumProductName is the subscription name.',+});++const SIGN_IN_LINK_HASH_PARAM = 'sign_in_link';const LOGIN_PAGE_STEP_ORDER: ReadonlyArray<LoginState> = [LoginState.DEFAULT, LoginState.MFA];-function resolveLoginRedirectPath(isHandoff: boolean, safeRedirect: string | null): string | null {+function resolveLoginRedirectPath(+ isHandoff: boolean,+ safeRedirect: string | null,+ runtimeTarget: AuthRuntimeTarget,+): string | null {if (isHandoff) {return null;}- return safeRedirect ?? Routes.ME;+ const {initialSnapshot, snapshot} = runtimeTarget;+ const changedInstance =+ initialSnapshot != null && snapshot != null && runtimeInstanceKey(initialSnapshot) !== runtimeInstanceKey(snapshot);+ return changedInstance ? Routes.ME : (safeRedirect ?? Routes.ME);}function resolveRegisterSearch(safeRedirect: string | null): Record<string, string> {@@ -54,14 +76,18 @@ const LoginPage = observer(function LoginPage({onBackActionChange}: LoginPageProconst isHandoff = isHandoffRequest(params);return (<AuthLoginLayout- redirectPath={resolveLoginRedirectPath(isHandoff, safeRedirect)}+ redirectPath={resolveLoginRedirectPath(isHandoff, safeRedirect, runtimeTarget)}inviteCode={null}desktopHandoff={isHandoff}excludeCurrentUser={false}extraTopContent={null}forgotPasswordAction={null}showTitle={true}- title={null}+ title={+ hasPurchaseIntent()+ ? i18n._(GET_PREMIUM_HEADING_DESCRIPTOR, {premiumProductName: getPremiumProductName()})+ : null+ }onLoginComplete={runtimeTarget.reset}onBackActionChange={onBackActionChange}completeLoginRedirectPath={Routes.ME}@@ -89,10 +115,24 @@ const LoginPageContainer = observer(() => {const runtimeTarget = useAuthRuntimeTarget();const loginState = Authentication.loginState;const [backAction, setBackAction] = useState<(() => void) | null>(null);+ const [signInLink, setSignInLink] = useState(() => readHashParam(window.location.hash, SIGN_IN_LINK_HASH_PARAM));const handleBackActionChange = useCallback((action: (() => void) | null) => {setBackAction(() => action);}, []);+ const handleSignInLinkBack = useCallback(() => setSignInLink(null), []);+ useEffect(() => {+ if (signInLink != null) RouterUtils.replaceWith(Routes.LOGIN);+ }, [signInLink]);useFluxerDocumentTitle(i18n._(SIGN_IN_DESCRIPTOR));+ if (signInLink != null) {+ return (+ <SignInLinkPage+ token={signInLink}+ onBack={handleSignInLinkBack}+ data-flx="auth.login-page.login-page-container.sign-in-link-page"+ />+ );+ }return (<>{backAction == null ? null : (diff --git a/fluxer_app/src/features/auth/components/pages/SignInLinkPage.tsx b/fluxer_app/src/features/auth/components/pages/SignInLinkPage.tsxnew file mode 100644index 000000000..139d7c91d--- /dev/null+++ b/fluxer_app/src/features/auth/components/pages/SignInLinkPage.tsx@@ -0,0 +1,140 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {Routes} from '@app/app/Routes';+import type {RuntimeConfigSnapshot} from '@app/features/app/state/InstanceSnapshotStore';+import * as AuthenticationCommands from '@app/features/auth/commands/AuthenticationCommands';+import styles from '@app/features/auth/components/pages/LoginPage.module.css';+import {AuthRuntimeTargetGate} from '@app/features/auth/flow/AuthRuntimeTargetGate';+import {useAuthSingleUseRequest} from '@app/features/auth/flow/AuthSingleUseRequest';+import {useAuthPresentation} from '@app/features/auth/flow/useAuthPresentation';+import {toLoginSuccessPayload} from '@app/features/auth/state/AuthFlow';+import {AuthCardVariant} from '@app/features/auth/state/AuthLayoutContext';+import {useAuthRuntimeTarget} from '@app/features/auth/state/AuthRuntimeTarget';+import {BACK_TO_SIGN_IN_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';+import {instanceTargetFromSnapshot} from '@app/features/platform/transport/InstanceHTTP';+import {failureValidationErrors} from '@app/features/platform/utils/ResponseInspection';+import {Spinner} from '@app/features/ui/components/Spinner';+import * as FormUtils from '@app/lib/forms';+import {flxElementClassName} from '@app/lib/react';+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';+import {msg} from '@lingui/core/macro';+import {Trans, useLingui} from '@lingui/react/macro';+import {observer} from 'mobx-react-lite';+import {useState} from 'react';++const SIGN_IN_LINK_EXPIRED_DESCRIPTOR = msg({+ message: 'This sign-in link expired or was already used.',+ comment: 'Shown when someone opens a one-time sign-in link that no longer works.',+});++function isExpiredLink(error: unknown): boolean {+ return (+ failureValidationErrors(error)?.some(+ (fault) => fault.code === ValidationErrorCodes.INVALID_OR_EXPIRED_AUTHORIZATION_TOKEN,+ ) === true+ );+}++interface SignInLinkContentProps {+ readonly token: string;+ readonly runtimeSnapshot: RuntimeConfigSnapshot;+ readonly onBack: () => void;+}++const SignInLinkContent = observer(function SignInLinkContent({+ token,+ runtimeSnapshot,+ onBack,+}: SignInLinkContentProps) {+ const {i18n} = useLingui();+ const runtimeTarget = useAuthRuntimeTarget();+ const [error, setError] = useState<string | null>(null);+ useAuthSingleUseRequest(token, async (request) => {+ try {+ const response = await AuthenticationCommands.redeemSignInLink(+ token,+ instanceTargetFromSnapshot(runtimeSnapshot),+ );+ await AuthenticationCommands.completeLogin(+ {...toLoginSuccessPayload(response), runtimeSnapshot},+ {redirectPath: Routes.ME},+ );+ runtimeTarget.reset();+ } catch (failure) {+ if (AuthenticationCommands.showAccountRestriction(failure) || !request.isCurrent()) {+ return;+ }+ setError(+ isExpiredLink(failure) ? i18n._(SIGN_IN_LINK_EXPIRED_DESCRIPTOR) : FormUtils.extractErrorMessage(i18n, failure),+ );+ }+ });+ if (error != null) {+ return (+ <flx-auth-sign-in-link-page+ className={flxElementClassName(styles.loginContainer)}+ data-flx="auth.sign-in-link-page.login-container"+ >+ <h1 className={styles.title} data-flx="auth.sign-in-link-page.title">+ <Trans comment="Heading when a one-time sign-in link could not sign the person in.">+ Couldn't sign you in+ </Trans>+ </h1>+ <flx-auth-sign-in-link-page-notice+ aria-live="assertive"+ className={flxElementClassName(styles.loginNotice)}+ data-flx="auth.sign-in-link-page.login-notice"+ >+ {error}+ </flx-auth-sign-in-link-page-notice>+ <flx-auth-sign-in-link-page-actions+ className={flxElementClassName(styles.ssoCallbackActions)}+ data-flx="auth.sign-in-link-page.actions"+ >+ <button+ type="button"+ onClick={onBack}+ className={styles.ssoBackButton}+ data-flx="auth.sign-in-link-page.back-button"+ >+ {i18n._(BACK_TO_SIGN_IN_DESCRIPTOR)}+ </button>+ </flx-auth-sign-in-link-page-actions>+ </flx-auth-sign-in-link-page>+ );+ }+ return (+ <flx-auth-sign-in-link-page+ className={flxElementClassName(styles.loginContainer)}+ data-flx="auth.sign-in-link-page.login-container--2"+ >+ <h1 className={styles.title} data-flx="auth.sign-in-link-page.title--2">+ <Trans>Completing sign-in…</Trans>+ </h1>+ <p className={styles.ssoProcessingHint} role="status" data-flx="auth.sign-in-link-page.processing-hint">+ <Spinner data-flx="auth.sign-in-link-page.spinner" />+ </p>+ </flx-auth-sign-in-link-page>+ );+});++interface SignInLinkPageProps {+ readonly token: string;+ readonly onBack: () => void;+}++export const SignInLinkPage = observer(function SignInLinkPage({token, onBack}: SignInLinkPageProps) {+ useAuthPresentation({variant: AuthCardVariant.COMPACT});+ return (+ <AuthRuntimeTargetGate data-flx="auth.sign-in-link-page.runtime-target-gate">+ {(runtimeSnapshot) => (+ <SignInLinkContent+ token={token}+ runtimeSnapshot={runtimeSnapshot}+ onBack={onBack}+ data-flx="auth.sign-in-link-page.content"+ />+ )}+ </AuthRuntimeTargetGate>+ );+});