A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): auto-start single sign-on and show the provider
Hampus1b19a3532912
diff --git a/fluxer_app/src/features/auth/components/pages/LoginPage.module.css b/fluxer_app/src/features/auth/components/pages/LoginPage.module.cssindex 40d2b1535..f1aa9aef0 100644--- a/fluxer_app/src/features/auth/components/pages/LoginPage.module.css+++ b/fluxer_app/src/features/auth/components/pages/LoginPage.module.css@@ -75,13 +75,15 @@text-align: center;}-@keyframes handoffSpin {- from {- transform: rotate(0deg);- }- to {- transform: rotate(360deg);- }+.ssoButtonLabel {+ display: -webkit-box;+ min-width: 0;+ overflow: hidden;+ overflow-wrap: anywhere;+ white-space: normal;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 1;+ line-clamp: 1;}.ssoCallbackActions {diff --git a/fluxer_app/src/features/auth/flow/AuthSsoPanel.tsx b/fluxer_app/src/features/auth/flow/AuthSsoPanel.tsxindex e7c0425e4..ac5c4c9f7 100644--- a/fluxer_app/src/features/auth/flow/AuthSsoPanel.tsx+++ b/fluxer_app/src/features/auth/flow/AuthSsoPanel.tsx@@ -6,28 +6,66 @@ import {SIGN_IN_WITH_BROWSER_DESCRIPTOR} from '@app/features/auth/AuthMessageDesimport * as AuthenticationCommands from '@app/features/auth/commands/AuthenticationCommands';import styles from '@app/features/auth/components/pages/LoginPage.module.css';import {AuthLoginBrowserStep} from '@app/features/auth/flow/auth_login_core/AuthLoginBrowserStep';+import {markSsoAutoStartSpent} from '@app/features/auth/flow/SsoAutoStart';+import {type StepTitleChangeHandler, useReportStepTitle} from '@app/features/auth/flow/useReportStepTitle';import {getAuthErrorMessage} from '@app/features/auth/hooks/useAuthForm';import {type LoginSuccessPayload, startSsoLogin} from '@app/features/auth/state/AuthFlow';+import {isolateBidi} from '@app/features/i18n/utils/BidiIsolate';import {Button} from '@app/features/ui/button/Button';import {isDesktop, navigateToExternalURL} 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 {observer} from 'mobx-react-lite';import {type ReactNode, useCallback, useState} from 'react';-export const ORGANIZATION_SSO_PROVIDER_DESCRIPTOR = msg({+const ORGANIZATION_SSO_PROVIDER_DESCRIPTOR = msg({message: "Sign in with your organization's single sign-on provider.",comment: 'Description shown when sign-in is restricted to the configured SSO provider.',});-export const CONTINUE_WITH_SSO_DESCRIPTOR = msg({+const CONTINUE_WITH_SSO_DESCRIPTOR = msg({message: 'Continue with SSO',comment: 'Button label that starts single sign-on.',});+const CONTINUE_WITH_PROVIDER_DESCRIPTOR = msg({+ message: 'Continue with {providerName}',+ comment:+ "Button label that starts single sign-on. providerName is the name of the organisation's sign-in provider, shown as typed by the admin, never translated.",+});+const SINGLE_SIGN_ON_TITLE_DESCRIPTOR = msg({+ message: 'Single sign-on',+ comment: 'Heading of the single sign-on panel when the admin has not named the sign-in provider.',+});const SSO_NOT_CONFIGURED_DESCRIPTOR = msg({message: 'This instance has not finished setting up single sign-on. Ask an administrator to enable it.',comment: 'Explanation shown in place of the single sign-on description when the instance offers no SSO provider.',});+interface SsoButtonLabelProps {+ readonly ssoConfig: InstanceSsoConfig | null;+ readonly 'data-flx': string;+}++function resolveSsoButtonLabel(ssoConfig: InstanceSsoConfig | null, i18n: I18n): string | null {+ if (ssoConfig?.button_label != null) {+ return ssoConfig.button_label;+ }+ if (ssoConfig?.display_name != null) {+ return i18n._(CONTINUE_WITH_PROVIDER_DESCRIPTOR, {providerName: isolateBidi(ssoConfig.display_name)});+ }+ return null;+}++export function SsoButtonLabel({ssoConfig, 'data-flx': dataFlx}: SsoButtonLabelProps) {+ const {i18n} = useLingui();+ const label = resolveSsoButtonLabel(ssoConfig, i18n);+ return (+ <bdi className={styles.ssoButtonLabel} title={label ?? undefined} data-flx={dataFlx}>+ {label ?? i18n._(CONTINUE_WITH_SSO_DESCRIPTOR)}+ </bdi>+ );+}+export function isInstanceSsoAvailable(ssoConfig: InstanceSsoConfig | null): boolean {return ssoConfig?.enabled === true;}@@ -44,25 +82,29 @@ interface AuthSsoPanelProps {dataFlx?: string;onStart?: () => void;onBrowserLoginSuccess?: (payload: LoginSuccessPayload) => Promise<void> | void;+ onStepTitleChange?: StepTitleChangeHandler | null;}export const AuthSsoPanel = observer(function AuthSsoPanel({redirectPath,extraTopContent,runtimeSnapshot,- showTitle = true,+ showTitle: showTitleProp = true,dataFlx = 'auth.flow.auth-sso-panel',onStart,onBrowserLoginSuccess,+ onStepTitleChange = null,}: AuthSsoPanelProps) {const {i18n} = useLingui();const panelSnapshot = runtimeSnapshot ?? RuntimeConfig.getSnapshot();const ssoConfig = resolveAuthPanelSso(panelSnapshot);const isAvailable = isInstanceSsoAvailable(ssoConfig);- const ssoDisplayName = ssoConfig?.display_name ?? 'Single Sign-On';+ const ssoDisplayName = ssoConfig?.display_name ?? i18n._(SINGLE_SIGN_ON_TITLE_DESCRIPTOR);const [error, setError] = useState<string | null>(null);const [isStartingSso, setIsStartingSso] = useState(false);const [showBrowserHandoff, setShowBrowserHandoff] = useState(false);+ const showTitle = showTitleProp && onStepTitleChange == null;+ useReportStepTitle(onStepTitleChange, showBrowserHandoff ? i18n._(SIGN_IN_WITH_BROWSER_DESCRIPTOR) : ssoDisplayName);const handleStartSso = useCallback(async () => {if (!isAvailable) return;if (onStart != null) {@@ -77,6 +119,7 @@ export const AuthSsoPanel = observer(function AuthSsoPanel({try {setError(null);setIsStartingSso(true);+ markSsoAutoStartSpent();const {authorizationUrl} = await startSsoLogin({redirectTo: redirectPath,runtimeSnapshot: panelSnapshot,@@ -111,6 +154,7 @@ export const AuthSsoPanel = observer(function AuthSsoPanel({onBack={handleBackFromBrowserHandoff}onChangeInstance={null}onSuccess={handleBrowserLoginSuccess}+ startSsodata-flx={`${dataFlx}.browser-step`}/>);@@ -134,7 +178,7 @@ export const AuthSsoPanel = observer(function AuthSsoPanel({disabled={!isAvailable || isStartingSso}data-flx={`${dataFlx}.button.start-sso`}>- {i18n._(CONTINUE_WITH_SSO_DESCRIPTOR)}+ <SsoButtonLabel ssoConfig={ssoConfig} data-flx={`${dataFlx}.sso-button-label`} /></Button>{error && (<div className={styles.loginNotice} role="alert" data-flx={`${dataFlx}.login-notice`}>diff --git a/fluxer_app/src/features/auth/flow/SsoAutoStart.ts b/fluxer_app/src/features/auth/flow/SsoAutoStart.tsnew file mode 100644index 000000000..36298d20b--- /dev/null+++ b/fluxer_app/src/features/auth/flow/SsoAutoStart.ts@@ -0,0 +1,116 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {getProtectedSessionStorage} from '@app/features/platform/state/ProtectedWebStorage';+import {Logger} from '@app/features/platform/utils/AppLogger';+import {useEffect, useRef} from 'react';++const logger = new Logger('SsoAutoStart');++const SSO_AUTO_START_SPENT_KEY = 'fluxer.sso.auto_start_spent';++export const SSO_START_QUERY_PARAM = 'sso';++interface SsoAutoStartRequest {+ readonly allowed: boolean;+ readonly desktopApp: boolean;+ readonly desktopHandoff: boolean;+ readonly onSignInStep: boolean;+ readonly ssoAvailable: boolean;+ readonly ssoEnforced: boolean;+ readonly startRequested: boolean;+ readonly spent: boolean;+}++function isSsoStartRequested(search: string): boolean {+ return new URLSearchParams(search).get(SSO_START_QUERY_PARAM) === '1';+}++export function withoutSsoStartRequest(pathWithSearch: string): string {+ const queryStart = pathWithSearch.indexOf('?');+ if (queryStart === -1) {+ return pathWithSearch;+ }+ const params = new URLSearchParams(pathWithSearch.slice(queryStart + 1));+ params.delete(SSO_START_QUERY_PARAM);+ const query = params.toString();+ const path = pathWithSearch.slice(0, queryStart);+ return query === '' ? path : `${path}?${query}`;+}++function shouldAutoStartSso(request: SsoAutoStartRequest): boolean {+ if (!request.allowed || request.desktopApp || !request.ssoAvailable || !request.onSignInStep) {+ return false;+ }+ if (request.startRequested) {+ return true;+ }+ return request.ssoEnforced && !request.desktopHandoff && !request.spent;+}++function isSsoAutoStartSpent(): boolean {+ try {+ const storage = getProtectedSessionStorage();+ return storage == null || storage.getItem(SSO_AUTO_START_SPENT_KEY) != null;+ } catch (error) {+ logger.warn('Failed to read the SSO auto-start state', error);+ return true;+ }+}++export function markSsoAutoStartSpent(): void {+ try {+ getProtectedSessionStorage()?.setItem(SSO_AUTO_START_SPENT_KEY, '1');+ } catch (error) {+ logger.warn('Failed to persist the SSO auto-start state', error);+ }+}++interface UseSsoAutoStartOptions {+ readonly allowed: boolean;+ readonly desktopApp: boolean;+ readonly desktopHandoff: boolean;+ readonly onSignInStep: (startRequested: boolean) => boolean;+ readonly ssoAvailable: boolean;+ readonly ssoEnforced: boolean;+ readonly pathname: string;+ readonly search: string;+ readonly start: () => Promise<void>;+}++export function useSsoAutoStart({+ allowed,+ desktopApp,+ desktopHandoff,+ onSignInStep,+ ssoAvailable,+ ssoEnforced,+ pathname,+ search,+ start,+}: UseSsoAutoStartOptions): void {+ const attemptedRef = useRef(false);+ useEffect(() => {+ if (attemptedRef.current) {+ return;+ }+ const startRequested = isSsoStartRequested(search);+ const shouldStart = shouldAutoStartSso({+ allowed,+ desktopApp,+ desktopHandoff,+ onSignInStep: onSignInStep(startRequested),+ ssoAvailable,+ ssoEnforced,+ startRequested,+ spent: isSsoAutoStartSpent(),+ });+ if (!shouldStart) {+ return;+ }+ attemptedRef.current = true;+ if (startRequested) {+ window.history.replaceState(window.history.state, '', withoutSsoStartRequest(`${pathname}${search}`));+ }+ void start();+ }, [allowed, desktopApp, desktopHandoff, onSignInStep, ssoAvailable, ssoEnforced, pathname, search, start]);+}diff --git a/fluxer_app/src/features/auth/flow/browser_handoff/useBrowserLoginHandoff.ts b/fluxer_app/src/features/auth/flow/browser_handoff/useBrowserLoginHandoff.tsindex 0ee2fd8f2..a0c35c0e7 100644--- a/fluxer_app/src/features/auth/flow/browser_handoff/useBrowserLoginHandoff.ts+++ b/fluxer_app/src/features/auth/flow/browser_handoff/useBrowserLoginHandoff.ts@@ -11,6 +11,7 @@ import type {BrowserLoginHandoffTarget,} from '@app/features/auth/flow/browser_handoff/BrowserLoginHandoffTransport';import {resolveBrowserLoginHandoffTransport} from '@app/features/auth/flow/browser_handoff/BrowserLoginHandoffTransport';+import {SSO_START_QUERY_PARAM} from '@app/features/auth/flow/SsoAutoStart';import {getAuthErrorMessage} from '@app/features/auth/hooks/useAuthForm';import type {LoginSuccessPayload} from '@app/features/auth/state/AuthFlow';import {type LoginIdentifierField, loginIdentifierField} from '@app/features/auth/utils/AccountSignInIdentifier';@@ -36,11 +37,12 @@ export const BrowserLoginHandoffAction = Object.freeze({} as const);export type BrowserLoginHandoffAction = (typeof BrowserLoginHandoffAction)[keyof typeof BrowserLoginHandoffAction];-export type BrowserLoginHandoffPendingAction = BrowserLoginHandoffAction | null;+type BrowserLoginHandoffPendingAction = BrowserLoginHandoffAction | null;export interface UseBrowserLoginHandoffOptions {readonly runtimeSnapshot: RuntimeConfigSnapshot;readonly prefillIdentifier?: string | null;+ readonly startSso?: boolean;readonly onEnded: () => void;readonly onSuccess: (payload: LoginSuccessPayload) => Promise<void> | void;}@@ -83,12 +85,14 @@ interface BrowserLoginHandoffURLRequest {readonly session: BrowserLoginHandoffSession;readonly prefillIdentifier: string | null | undefined;readonly prefillField: LoginIdentifierField;+ readonly startSso: boolean;}function buildBrowserLoginHandoffURL({session,prefillIdentifier,prefillField,+ startSso,}: BrowserLoginHandoffURLRequest): string {const params = new URLSearchParams({handoff: '1',@@ -98,6 +102,9 @@ function buildBrowserLoginHandoffURL({if (prefillIdentifier != null && prefillIdentifier.length > 0) {params.set(prefillField, prefillIdentifier);}+ if (startSso) {+ params.set(SSO_START_QUERY_PARAM, '1');+ }return `${session.target.webAppEndpoint}/login?${params.toString()}`;}@@ -131,6 +138,7 @@ function useBrowserLoginHandoffCountdown(expiresAt: string | null): number | nulexport function useBrowserLoginHandoff({runtimeSnapshot,prefillIdentifier,+ startSso = false,onEnded,onSuccess,}: UseBrowserLoginHandoffOptions): BrowserLoginHandoffController {@@ -247,6 +255,7 @@ export function useBrowserLoginHandoff({session: currentSession,prefillIdentifier,prefillField: loginIdentifierField(runtimeSnapshot),+ startSso,}),);return true;@@ -256,7 +265,7 @@ export function useBrowserLoginHandoff({} finally {setPendingAction(null);}- }, [getCurrentSession, i18n, prefillIdentifier, runtimeSnapshot]);+ }, [getCurrentSession, i18n, prefillIdentifier, runtimeSnapshot, startSso]);const showManualCode = useCallback(async (): Promise<boolean> => {setPendingAction(BrowserLoginHandoffAction.SHOW_CODE);try {