diff --git a/component/index.tsx b/component/index.tsx index 2b96272e3..c8ce7c757 100644 --- a/component/index.tsx +++ b/component/index.tsx @@ -73,6 +73,7 @@ import { } from "../src/UrlParams"; import { MediaDevicesContext } from "../src/MediaDevicesContext"; import { AppViewModel } from "../src/state/AppViewModel"; +import { hostClientSession } from "../src/state/ClientSession"; import { ObservableScope } from "../src/state/ObservableScope"; import { BackgroundEffectsProvider } from "../src/tracks/BackgroundEffectsContext"; import { Config } from "../src/config/Config"; @@ -204,6 +205,10 @@ export const ElementCall: FC = ({ }; }, [controlledAudioDevices, callIntent]); + // The host owns the user's session, so Element Call neither authenticates + // anyone nor manages it; it follows whichever client the host hands it. + const clientSession = useMemo(() => hostClientSession(client), [client]); + const room = client.getRoom(roomId); const rtcSession = useMemo( () => (room === null ? null : client.matrixRTC.getRoomSession(room)), @@ -250,7 +255,7 @@ export const ElementCall: FC = ({ > - + - (await import("./utils/spa")).initSPA(...args); - interface SimpleProviderProps { children: JSX.Element; } @@ -122,9 +112,11 @@ interface Props { vm: AppViewModel; /** A point of access to the widget API, if running as a widget. */ widget: WidgetHelpers | null; + /** Where the client comes from. It abstracts: widget, from the host, SPA managed client. */ + clientSession: ClientSession; } -export const App: FC = ({ vm, widget }) => { +export const App: FC = ({ vm, widget, clientSession }) => { // The standalone build has no host; the widget build's host is the client it // is a widget of. const hostBridge = useInitial(() => @@ -141,40 +133,26 @@ export const App: FC = ({ vm, widget }) => { .catch(logger.error); }); - // As a widget, the client comes from the host over the widget API. Standalone, - // Element Call finds one itself, so there is nothing to wait for here. - const [widgetClient, setWidgetClient] = useState( - undefined, + const content = loaded ? ( + + + + } + > + + } /> + } /> + } /> + } /> + + + + + + ) : ( + ); - useEffect(() => { - if (widget === null) return; - widget.client - .then(setWidgetClient) - .catch((e) => logger.error("Failed to obtain the host's client", e)); - }, [widget]); - const clientReady = widget === null || widgetClient !== undefined; - - const content = - loaded && clientReady ? ( - - - - } - > - - } /> - } /> - } /> - } /> - - - - - - ) : ( - - ); return ( diff --git a/src/Avatar.test.tsx b/src/Avatar.test.tsx index 3d1cb9862..4e48be915 100644 --- a/src/Avatar.test.tsx +++ b/src/Avatar.test.tsx @@ -12,6 +12,7 @@ import { type FC, type PropsWithChildren } from "react"; import { ClientContextProvider } from "./ClientContext"; import { Avatar } from "./Avatar"; +import { hostClientSession } from "./state/ClientSession"; import { mockMatrixRoomMember, mockRtcMembership } from "./utils/test"; import { type HostBridge, @@ -26,18 +27,7 @@ const TestComponent: FC< }> > = ({ client, hostBridge = nullHostBridge, children }) => { return ( - + {children} ); diff --git a/src/ClientContext.test.tsx b/src/ClientContext.test.tsx index a64f850e9..6c1015e9d 100644 --- a/src/ClientContext.test.tsx +++ b/src/ClientContext.test.tsx @@ -6,17 +6,26 @@ Please see LICENSE in the repository root for full details. */ import { expect, test, vi } from "vitest"; -import { act, render, renderHook, waitFor } from "@testing-library/react"; +import { act, render, renderHook } from "@testing-library/react"; import { BrowserRouter } from "react-router-dom"; import { type MatrixClient } from "matrix-js-sdk"; import { type FC } from "react"; +import { BehaviorSubject } from "rxjs"; import { - type ClientLoader, ClientProvider, useClientDisconnected, - useClientState, + useClientLegacy, + useClientSession, + useClientSessionState, } from "./ClientContext"; +import { + type ClientSession, + type ClientSessionState, + hostClientSession, +} from "./state/ClientSession"; +import { LeaveToHomeProvider } from "./LeaveToHomeContext"; +import { flushPromises } from "./utils/test"; const mockClient = (userId = "@alice:example.org"): MatrixClient => ({ @@ -29,67 +38,47 @@ const mockClient = (userId = "@alice:example.org"): MatrixClient => /** Reports what the context says, so a test can assert on it. */ const ShowClientState: FC = () => { - const state = useClientState(); - if (state === undefined) return loading; - if (state.state === "error") return error; - return ( - {state.authenticated?.client.getUserId() ?? "unauthenticated"} - ); + const state = useClientSessionState(); + switch (state.state) { + case "signedIn": + return {state.client.getUserId()}; + case "signedOut": + return unauthenticated; + default: + return {state.state}; + } }; -test("uses a client supplied by the host without waiting", () => { - const client = mockClient(); - - const { container } = render( +const renderProvider = ( + session: ClientSession, + children = , +): ReturnType => + render( - - - + {children} , ); +test("uses a client supplied by the host without waiting", () => { + const { container } = renderProvider(hostClientSession(mockClient())); + // Available on the very first render: a supplied client needs no session // restoring, so there is no loading state to pass through. expect(container.textContent).toBe("@alice:example.org"); }); -test("does not claim exclusive use of storage when given a client", () => { - // The channel is created when the module loads, so spy on the prototype - // rather than trying to replace the global. - const postMessage = vi.spyOn(BroadcastChannel.prototype, "postMessage"); - - render( - - - - - , - ); - - // The broadcast shuts down other instances to protect Element Call's own - // stores. A host's client brings its own, so there is nothing to protect. - expect(postMessage).not.toHaveBeenCalled(); - - postMessage.mockRestore(); -}); - test("follows the client when the host swaps it", () => { - const first = mockClient(); - const second = mockClient("@bob:example.org"); - - const { container, rerender } = render( - - - - - , + const { container, rerender } = renderProvider( + hostClientSession(mockClient()), ); expect(container.textContent).toBe("@alice:example.org"); // A host that re-authenticates hands us a new client on a mounted component rerender( - + , @@ -98,47 +87,89 @@ test("follows the client when the host swaps it", () => { expect(container.textContent).toBe("@bob:example.org"); }); -test("finds a client of its own when the host supplies none", async () => { - const client = mockClient(); - const loadClient = vi - .fn() - .mockResolvedValue({ client, passwordlessUser: true }); - - const { container } = render( - - - - - , - ); +test("follows a session of its own as it is restored", () => { + const state$ = new BehaviorSubject({ state: "loading" }); + const { container } = renderProvider({ state$ }); // Nothing to show until a session has been restored or created expect(container.textContent).toBe("loading"); - await waitFor(() => expect(container.textContent).toBe("@alice:example.org")); - // Given the session store to restore from and to clear on a stale session - expect(loadClient).toHaveBeenCalledWith( - expect.any(Function), - expect.any(Function), + act(() => + state$.next({ + state: "signedIn", + client: mockClient(), + passwordlessUser: true, + }), ); + expect(container.textContent).toBe("@alice:example.org"); }); -test("has no one signed in when given neither a client nor a way to load one", async () => { - const { container } = render( - - - +test("has no one signed in when the session says so", () => { + const { container } = renderProvider({ + state$: new BehaviorSubject({ state: "signedOut" }), + }); + expect(container.textContent).toBe("unauthenticated"); +}); + +test("shows the session's error in place of its children", () => { + const { container } = renderProvider({ + state$: new BehaviorSubject({ + state: "error", + error: new Error("Opened elsewhere"), + }), + }); + // The error page, not the children + expect(container.textContent).not.toContain("error"); + expect(container.textContent).toContain("Something went wrong"); +}); + +test("hands the session itself to the context", () => { + const session: ClientSession = { + state$: new BehaviorSubject({ state: "signedOut" }), + register: vi.fn(), + }; + const { result } = renderHook(() => useClientSession(), { + wrapper: ({ children }) => ( + + <>{children} - , + ), + }); + expect(result.current).toBe(session); +}); + +test("leaves for home after logging out of the session", async () => { + const logout = vi.fn().mockResolvedValue(undefined); + const leaveToHome = vi.fn(); + const { result } = renderClientLegacy( + { + state$: new BehaviorSubject({ + state: "signedIn", + client: mockClient(), + passwordlessUser: false, + }), + logout, + }, + leaveToHome, ); - await waitFor(() => expect(container.textContent).toBe("unauthenticated")); + await act(async () => { + result.current.logout?.(); + await flushPromises(); + }); + expect(logout).toHaveBeenCalled(); + expect(leaveToHome).toHaveBeenCalled(); +}); + +test("offers no logout when the session is not ours to end", () => { + const { result } = renderClientLegacy(hostClientSession(mockClient())); + expect(result.current.logout).toBeUndefined(); }); test("reports the client as disconnected while its sync fails to connect", () => { const client = mockClient(); const { result } = renderHook(() => useClientDisconnected(), { wrapper: ({ children }) => ( - + <>{children} ), @@ -160,3 +191,20 @@ test("reports the client as disconnected while its sync fails to connect", () => act(() => onSync("SYNCING", null)); expect(result.current).toBe(false); }); + +function renderClientLegacy( + session: ClientSession, + leaveToHome: (() => void) | null = null, +): ReturnType, never>> { + return renderHook(() => useClientLegacy(), { + wrapper: ({ children }) => ( + + + + <>{children} + + + + ), + }); +} diff --git a/src/ClientContext.tsx b/src/ClientContext.tsx index 97ee1f2e1..b0b2d6dc7 100644 --- a/src/ClientContext.tsx +++ b/src/ClientContext.tsx @@ -7,12 +7,10 @@ Please see LICENSE in the repository root for full details. import { type FC, - useCallback, useEffect, useState, createContext, use, - useRef, useMemo, type JSX, } from "react"; @@ -26,8 +24,12 @@ import { PosthogAnalytics, RegistrationType, } from "./analytics/PosthogAnalytics"; -import { useEventTarget } from "./useEvents"; -import { OpenElsewhereError } from "./RichError"; +import { useBehavior } from "./useBehavior"; +import { constant } from "./state/Behavior"; +import { + type ClientSession, + type ClientSessionState, +} from "./state/ClientSession"; declare global { interface Window { @@ -36,96 +38,74 @@ declare global { } } -export type ClientState = ValidClientState | ErrorState; - -export type ValidClientState = { - state: "valid"; - authenticated?: AuthenticatedClient; - setClient: (client: MatrixClient, session: Session) => void; +// Without a provider, no one is signed in and there is no session to act on +const noClientSession: ClientSession = { + state$: constant({ state: "signedOut" }), }; -export type AuthenticatedClient = { - client: MatrixClient; - isPasswordlessUser: boolean; - changePassword: (password: string) => Promise; - logout: () => void; -}; - -export type ErrorState = { - state: "error"; - error: Error; -}; - -const ClientContext = createContext(undefined); +const ClientContext = createContext(noClientSession); export const ClientContextProvider = ClientContext.Provider; -export const useClientState = (): ClientState | undefined => use(ClientContext); +export const useClientSession = (): ClientSession => use(ClientContext); -export function useClient(): { - client?: MatrixClient; - setClient?: (client: MatrixClient, session: Session) => void; -} { - let client; - let setClient; +export const useClientSessionState = (): ClientSessionState => + useBehavior(useClientSession().state$); - const clientState = useClientState(); - if (clientState?.state === "valid") { - client = clientState.authenticated?.client; - setClient = clientState.setClient; - } - - return { client, setClient }; +export function useClient(): { client?: MatrixClient } { + const state = useClientSessionState(); + return { client: state.state === "signedIn" ? state.client : undefined }; } // Plain representation of the `ClientContext` as a helper for old components that expected an object with multiple fields. export function useClientLegacy(): { client?: MatrixClient; - setClient?: (client: MatrixClient, session: Session) => void; passwordlessUser: boolean; loading: boolean; authenticated: boolean; logout?: () => void; error?: Error; } { - const clientState = useClientState(); - - let client; - let setClient; - let passwordlessUser = false; - let loading = true; - let error; - let authenticated = false; - let logout; - - if (clientState?.state === "valid") { - client = clientState.authenticated?.client; - setClient = clientState.setClient; - passwordlessUser = clientState.authenticated?.isPasswordlessUser ?? false; - loading = false; - authenticated = client !== undefined; - logout = clientState.authenticated?.logout; - } else if (clientState?.state === "error") { - error = clientState.error; - loading = false; - } + const state = useClientSessionState(); + const logout = useLogout(); + const client = state.state === "signedIn" ? state.client : undefined; return { client, - setClient, - passwordlessUser, - loading, - authenticated, + passwordlessUser: state.state === "signedIn" && state.passwordlessUser, + loading: state.state === "loading", + authenticated: client !== undefined, logout, - error, + error: state.state === "error" ? state.error : undefined, }; } +/** + * Ends the session, where it is ours to end, and leaves for home. + */ +function useLogout(): (() => void) | undefined { + const { logout } = useClientSession(); + const leaveToHome = useLeaveToHome(); + return useMemo(() => { + if (logout === undefined) return undefined; + return (): void => { + logout() + .then(() => { + leaveToHome?.(); + PosthogAnalytics.instance.logout(); + PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest); + }) + .catch((e) => logger.error("Failed to log out", e)); + }; + }, [logout, leaveToHome]); +} + /** * Whether the signed-in client is supposed to be connected but is not. */ export function useClientDisconnected(): boolean { - const { client } = useClient(); + const state = useClientSessionState(); + const client = state.state === "signedIn" ? state.client : undefined; // Tagged with the client it describes, so that a swapped client does not // inherit the old one's verdict before its first sync const [disconnected, setDisconnected] = useState< @@ -148,248 +128,33 @@ export function useClientDisconnected(): boolean { return disconnected !== null && disconnected[0] === client && disconnected[1]; } -const loadChannel = - "BroadcastChannel" in window ? new BroadcastChannel("load") : null; - interface Props { children: JSX.Element; /** - * The client Element Call should use. - * - * An application hosting Element Call as a component already has a client, - * and owns the user's session; supplying it here means Element Call neither - * authenticates anyone nor manages their session. Left out, Element Call finds a client - * itself — from the widget API, or by restoring or creating a session of its - * own. + * Where the client comes from: a session of Element Call's own, or one a + * host has supplied. */ - client?: MatrixClient; - /** - * How Element Call finds a client when none is supplied: the standalone app - * restores or creates a session of its own. Stable, as a hook dependency. - * Left out along with the client, no one is signed in. - * - * A prop, rather than this module importing `utils/spa` itself, because: - * - This module is in the component build, and so is everything it imports, - * dynamically or not: a dynamic import becomes a chunk in the package, - * not a module left out of it. - * - Behind `utils/spa` sits `utils/initClient` and the client store worker, - * which the bundler emits as soon as it loads the import (see there). - * - `App.tsx`, which the component never imports, is where the standalone - * app passes the loader in; the component passes nothing, having the - * host's client. - */ - loadClient?: ClientLoader; + session: ClientSession; } -/** - * Restores or creates a session of Element Call's own, kept where the given - * functions keep it. Resolves to null when no one is signed in. - */ -export type ClientLoader = ( - loadSession: () => Session | undefined, - clearSession: () => void, -) => Promise; - -export const ClientProvider: FC = ({ children, client, loadClient }) => { - const leaveToHome = useLeaveToHome(); - - // null = signed out, undefined = loading - const [initClientState, setInitClientState] = useState< - InitResult | null | undefined - >( - client === undefined - ? undefined - : // A supplied client belongs to the host, so there is no session of ours - // to restore and nothing to wait for. - { client, passwordlessUser: false }, - ); - - const initializing = useRef(false); - useEffect(() => { - if (client !== undefined) { - // Nothing to load, but a host may hand us a different client later — on - // re-authenticating, say — so follow whichever one it has given us. - setInitClientState((current) => - current?.client === client - ? current - : { client, passwordlessUser: false }, - ); - // Analytics still need to follow the user's choices. - if (PosthogAnalytics.instance.isEnabled()) - PosthogAnalytics.instance.startListeningToSettingsChanges(); - return; - } - // In case the component is mounted, unmounted, and remounted quickly (as - // React does in strict mode), we need to make sure not to doubly initialize - // the client. - if (initializing.current) return; - if (loadClient === undefined) { - setInitClientState(null); - return; - } - initializing.current = true; - - loadClient(loadSession, clearSession) - .then((initResult) => { - setInitClientState(initResult); - if (PosthogAnalytics.instance.isEnabled()) - PosthogAnalytics.instance.startListeningToSettingsChanges(); - }) - .catch((err) => logger.error(err)) - .finally(() => (initializing.current = false)); - }, [client, loadClient]); - - const changePassword = useCallback( - async (password: string) => { - const session = loadSession(); - if (!initClientState?.client || !session) { - return; - } - - await initClientState.client.setPassword( - { - type: "m.login.password", - identifier: { - type: "m.id.user", - user: session.user_id, - }, - user: session.user_id, - password: session.tempPassword, - }, - password, - ); - - saveSession({ ...session, passwordlessUser: false }); - - setInitClientState({ - ...initClientState, - passwordlessUser: false, - }); - }, - [initClientState], - ); - - const setClient = useCallback( - (client: MatrixClient, session: Session) => { - const oldClient = initClientState?.client; - if (oldClient && oldClient !== client) { - oldClient.stopClient(); - } - - saveSession(session); - setInitClientState({ - client, - passwordlessUser: session.passwordlessUser, - }); - if (PosthogAnalytics.instance.isEnabled()) - PosthogAnalytics.instance.startListeningToSettingsChanges(); - }, - [initClientState?.client], - ); - - const logout = useCallback(async () => { - const client = initClientState?.client; - if (!client) { - return; - } - - await client.logout(true); - await client.clearStores(); - clearSession(); - setInitClientState(null); - leaveToHome?.(); - PosthogAnalytics.instance.logout(); - PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest); - }, [leaveToHome, initClientState?.client]); - - // To protect against multiple sessions writing to the same storage - // simultaneously, we send a broadcast message that shuts down all other - // running instances of the app. Element Call only has storage of its own to - // protect when it created the session itself; given a client — by a host, or - // over the widget API — it is mostly stateless. - const ownsSession = client === undefined; - useEffect(() => { - if (ownsSession) loadChannel?.postMessage({}); - }, [ownsSession]); - - const [alreadyOpenedErr, setAlreadyOpenedErr] = useState( - undefined, - ); - useEventTarget( - loadChannel, - "message", - useCallback(() => { - initClientState?.client.stopClient(); - setAlreadyOpenedErr(new OpenElsewhereError()); - }, [initClientState?.client, setAlreadyOpenedErr]), - ); - - const state: ClientState | undefined = useMemo(() => { - if (alreadyOpenedErr) { - return { state: "error", error: alreadyOpenedErr }; - } - - if (initClientState === undefined) return undefined; - - const authenticated = - initClientState === null - ? undefined - : { - client: initClientState.client, - isPasswordlessUser: initClientState.passwordlessUser, - changePassword, - logout, - }; - - return { - state: "valid", - authenticated, - setClient, - }; - }, [alreadyOpenedErr, changePassword, initClientState, logout, setClient]); +export const ClientProvider: FC = ({ children, session }) => { + const state = useBehavior(session.state$); useEffect(() => { - if (!initClientState) { - return; - } - - window.matrixclient = initClientState.client; - window.passwordlessUser = initClientState.passwordlessUser; + if (state.state !== "signedIn") return; + window.matrixclient = state.client; + window.passwordlessUser = state.passwordlessUser; if (PosthogAnalytics.hasInstance()) PosthogAnalytics.instance.onLoginStatusChanged(); - }, [initClientState]); + // Analytics follow the user's choices whoever the client belongs to + if (PosthogAnalytics.instance.isEnabled()) + PosthogAnalytics.instance.startListeningToSettingsChanges(); + }, [state]); - if (alreadyOpenedErr) { - return ; - } + if (state.state === "error") return ; - return {children}; -}; - -export type InitResult = { - client: MatrixClient; - passwordlessUser: boolean; -}; - -export interface Session { - user_id: string; - device_id: string; - access_token: string; - passwordlessUser: boolean; - tempPassword?: string; -} - -const clearSession = (): void => localStorage.removeItem("matrix-auth-store"); -const saveSession = (s: Session): void => - localStorage.setItem("matrix-auth-store", JSON.stringify(s)); -const loadSession = (): Session | undefined => { - const data = localStorage.getItem("matrix-auth-store"); - if (!data) { - return undefined; - } - - return JSON.parse(data); + return {children}; }; const clientIsDisconnected = ( diff --git a/src/auth/LoginPage.tsx b/src/auth/LoginPage.tsx index da20a86be..64e3e9c70 100644 --- a/src/auth/LoginPage.tsx +++ b/src/auth/LoginPage.tsx @@ -11,10 +11,9 @@ import { Trans, useTranslation } from "react-i18next"; import { Button } from "@vector-im/compound-web"; import Logo from "../icons/LogoLarge.svg?react"; -import { useClient } from "../ClientContext"; +import { useClientSession } from "../ClientContext"; import { FieldRow, InputField, ErrorMessage } from "../input/Input"; import styles from "./LoginPage.module.css"; -import { useInteractiveLogin } from "./useInteractiveLogin"; import { usePageTitle } from "../usePageTitle"; import { PosthogAnalytics } from "../analytics/PosthogAnalytics"; import { Config } from "../config/Config"; @@ -24,8 +23,7 @@ export const LoginPage: FC = () => { const { t } = useTranslation(); usePageTitle(t("login_title")); - const { client, setClient } = useClient(); - const login = useInteractiveLogin(client); + const { login } = useClientSession(); const homeserver = Config.defaultHomeserverUrl(); // TODO: Make this configurable const usernameRef = useRef(null); const passwordRef = useRef(null); @@ -46,15 +44,14 @@ export const LoginPage: FC = () => { setLoading(false); return; } + if (!login) { + setError(Error("This session cannot be logged in to")); + setLoading(false); + return; + } login(homeserver, usernameRef.current.value, passwordRef.current.value) - .then(async ([client, session]) => { - if (!setClient) { - return; - } - - setClient(client, session); - + .then(async () => { const locationState = location.state; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore @@ -72,7 +69,7 @@ export const LoginPage: FC = () => { setLoading(false); }); }, - [login, location, navigate, homeserver, setClient], + [login, location, navigate, homeserver], ); // we need to limit the length of the homserver name to not cover the whole loginview input with the string. let shortendHomeserverName = Config.defaultServerName()?.slice(0, 25); diff --git a/src/auth/RegisterPage.tsx b/src/auth/RegisterPage.tsx index c89bf06e2..a2a676bac 100644 --- a/src/auth/RegisterPage.tsx +++ b/src/auth/RegisterPage.tsx @@ -22,8 +22,8 @@ import { logger } from "matrix-js-sdk/lib/logger"; import { Button, Text } from "@vector-im/compound-web"; import { FieldRow, InputField, ErrorMessage } from "../input/Input"; -import { useClientLegacy } from "../ClientContext"; -import { useInteractiveRegistration } from "./useInteractiveRegistration"; +import { useClientLegacy, useClientSession } from "../ClientContext"; +import { useRegistrationTerms } from "./useRegistrationTerms"; import styles from "./LoginPage.module.css"; import Logo from "../icons/LogoLarge.svg?react"; import { LoadingPage } from "../FullScreenView"; @@ -37,8 +37,9 @@ export const RegisterPage: FC = () => { const { t } = useTranslation(); usePageTitle(t("action.register")); - const { loading, authenticated, passwordlessUser, client, setClient } = + const { loading, authenticated, passwordlessUser, client } = useClientLegacy(); + const { register } = useClientSession(); const confirmPasswordRef = useRef(null); const navigate = useNavigate(); @@ -47,7 +48,7 @@ export const RegisterPage: FC = () => { const [error, setError] = useState(); const [password, setPassword] = useState(""); const [passwordConfirmation, setPasswordConfirmation] = useState(""); - const { recaptchaKey, register } = useInteractiveRegistration(client); + const { recaptchaKey } = useRegistrationTerms(); const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey); const onSubmitRegisterForm = useCallback( @@ -62,9 +63,10 @@ export const RegisterPage: FC = () => { const submit = async (): Promise => { setRegistering(true); + if (!register) throw new Error("This session cannot register"); const recaptchaResponse = await execute(); - const [newClient, session] = await register( + const { client: newClient, setSignedIn } = await register( userName, password, userName, @@ -95,7 +97,7 @@ export const RegisterPage: FC = () => { } } - setClient?.(newClient, session); + setSignedIn(); PosthogAnalytics.instance.eventSignup.cacheSignupEnd(new Date()); }; @@ -117,16 +119,7 @@ export const RegisterPage: FC = () => { reset(); }); }, - [ - register, - location, - navigate, - passwordlessUser, - reset, - execute, - client, - setClient, - ], + [register, location, navigate, passwordlessUser, reset, execute, client], ); useEffect(() => { diff --git a/src/auth/interactiveAuth.ts b/src/auth/interactiveAuth.ts index 0b5813311..0540e16fc 100644 --- a/src/auth/interactiveAuth.ts +++ b/src/auth/interactiveAuth.ts @@ -13,11 +13,11 @@ import { } from "matrix-js-sdk"; import { logger } from "matrix-js-sdk/lib/logger"; -import { type Session } from "../ClientContext"; +import { type StoredSession } from "../state/ClientSession"; /** What the homeserver hands out for a new session. */ export type Credentials = Pick< - Session, + StoredSession, "user_id" | "device_id" | "access_token" >; diff --git a/src/auth/useInteractiveLogin.ts b/src/auth/useInteractiveLogin.ts deleted file mode 100644 index 3b4ceb66d..000000000 --- a/src/auth/useInteractiveLogin.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2022-2024 New Vector Ltd. - -SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial -Please see LICENSE in the repository root for full details. -*/ - -import { useCallback } from "react"; -import { type MatrixClient } from "matrix-js-sdk"; - -import { initClient } from "../utils/initClient"; -import { type Session } from "../ClientContext"; -import { loginWithPassword } from "./interactiveAuth"; - -/** - * This provides the login method to login using user credentials. - * @param oldClient If there is an already authenticated client it should be passed to this hook - * this allows the interactive login to sign out the client before logging in. - * @returns A async method that can be called/awaited to log in with the provided credentials. - */ -export function useInteractiveLogin( - oldClient?: MatrixClient, -): ( - homeserver: string, - username: string, - password: string, -) => Promise<[MatrixClient, Session]> { - return useCallback< - ( - homeserver: string, - username: string, - password: string, - ) => Promise<[MatrixClient, Session]> - >( - async (homeserver: string, username: string, password: string) => { - const session: Session = { - ...(await loginWithPassword(homeserver, username, password)), - passwordlessUser: false, - }; - - // To not confuse the rust crypto sessions we need to logout the old client before initializing the new one. - await oldClient?.logout(true); - const client = await initClient( - { - baseUrl: homeserver, - accessToken: session.access_token, - userId: session.user_id, - deviceId: session.device_id, - }, - false, - ); - return [client, session]; - }, - [oldClient], - ); -} diff --git a/src/auth/useInteractiveRegistration.ts b/src/auth/useInteractiveRegistration.ts deleted file mode 100644 index 97f813f7f..000000000 --- a/src/auth/useInteractiveRegistration.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2022-2024 New Vector Ltd. - -SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial -Please see LICENSE in the repository root for full details. -*/ - -import { useCallback } from "react"; -import { type MatrixClient } from "matrix-js-sdk"; - -import { initClient } from "../utils/initClient"; -import { type Session } from "../ClientContext"; -import { Config } from "../config/Config"; -import { registerWithPassword } from "./interactiveAuth"; -import { useRegistrationTerms } from "./useRegistrationTerms"; - -export const useInteractiveRegistration = ( - oldClient?: MatrixClient, -): { - privacyPolicyUrl?: string; - recaptchaKey?: string; - register: ( - username: string, - password: string, - displayName: string, - recaptchaResponse: string, - passwordlessUser: boolean, - ) => Promise<[MatrixClient, Session]>; -} => { - const { privacyPolicyUrl, recaptchaKey } = useRegistrationTerms(); - - const register = useCallback( - async ( - username: string, - password: string, - displayName: string, - recaptchaResponse: string, - passwordlessUser: boolean, - ): Promise<[MatrixClient, Session]> => { - const homeserver = Config.defaultHomeserverUrl()!; - const session: Session = { - ...(await registerWithPassword( - homeserver, - username, - password, - recaptchaResponse, - )), - passwordlessUser, - ...(passwordlessUser ? { tempPassword: password } : {}), - }; - - await oldClient?.logout(true); - const client = await initClient( - { - baseUrl: homeserver, - accessToken: session.access_token, - userId: session.user_id, - deviceId: session.device_id, - }, - false, - ); - - await client.setDisplayName(displayName); - const user = client.getUser(client.getUserId()!)!; - user.setRawDisplayName(displayName); - user.setDisplayName(displayName); - - return [client, session]; - }, - [oldClient], - ); - - return { privacyPolicyUrl, recaptchaKey, register }; -}; diff --git a/src/auth/useRegisterPasswordlessUser.ts b/src/auth/useRegisterPasswordlessUser.ts index 27674c623..22a2e6791 100644 --- a/src/auth/useRegisterPasswordlessUser.ts +++ b/src/auth/useRegisterPasswordlessUser.ts @@ -8,8 +8,8 @@ Please see LICENSE in the repository root for full details. import { useCallback } from "react"; import { secureRandomString } from "matrix-js-sdk/lib/randomstring"; -import { useClient } from "../ClientContext"; -import { useInteractiveRegistration } from "../auth/useInteractiveRegistration"; +import { useClientSession } from "../ClientContext"; +import { useRegistrationTerms } from "../auth/useRegistrationTerms"; import { generateRandomName } from "../auth/generateRandomName"; import { useRecaptcha } from "../auth/useRecaptcha"; import { useUrlParams } from "../UrlParams"; @@ -21,16 +21,15 @@ interface UseRegisterPasswordlessUserType { } export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType { - const { setClient } = useClient(); + const { register } = useClientSession(); const { isWidget } = useUrlParams(); - const { privacyPolicyUrl, recaptchaKey, register } = - useInteractiveRegistration(); + const { privacyPolicyUrl, recaptchaKey } = useRegistrationTerms(); const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey); const registerPasswordlessUser = useCallback( async (displayName: string) => { - if (!setClient) { - throw new Error("No client context"); + if (!register) { + throw new Error("This session cannot register"); } if (isWidget) { throw new Error( @@ -41,20 +40,20 @@ export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType { try { const recaptchaResponse = await execute(); const userName = generateRandomName(); - const [client, session] = await register( + const { setSignedIn } = await register( userName, secureRandomString(16), displayName, recaptchaResponse, true, ); - setClient(client, session); + setSignedIn(); } catch (e) { reset(); throw e; } }, - [execute, reset, register, setClient, isWidget], + [execute, reset, register, isWidget], ); return { privacyPolicyUrl, registerPasswordlessUser, recaptchaId }; diff --git a/src/home/HomePage.tsx b/src/home/HomePage.tsx index e61368559..2b26e0808 100644 --- a/src/home/HomePage.tsx +++ b/src/home/HomePage.tsx @@ -8,7 +8,7 @@ Please see LICENSE in the repository root for full details. import { useTranslation } from "react-i18next"; import { type FC } from "react"; -import { useClientState } from "../ClientContext"; +import { useClientSessionState } from "../ClientContext"; import { ErrorPage, LoadingPage } from "../FullScreenView"; import { UnauthenticatedView } from "./UnauthenticatedView"; import { RegisteredView } from "./RegisteredView"; @@ -18,17 +18,16 @@ export const HomePage: FC = () => { const { t } = useTranslation(); usePageTitle(t("common.home")); - const clientState = useClientState(); + const session = useClientSessionState(); - if (!clientState) { - return ; - } else if (clientState.state === "error") { - return ; - } else { - return clientState.authenticated ? ( - - ) : ( - - ); + switch (session.state) { + case "loading": + return ; + case "error": + return ; + case "signedIn": + return ; + case "signedOut": + return ; } }; diff --git a/src/home/UnauthenticatedView.tsx b/src/home/UnauthenticatedView.tsx index 6e05bc347..2639dc4cf 100644 --- a/src/home/UnauthenticatedView.tsx +++ b/src/home/UnauthenticatedView.tsx @@ -12,7 +12,7 @@ import { Button, Heading, Text } from "@vector-im/compound-web"; import { logger } from "matrix-js-sdk/lib/logger"; import { useNavigate } from "react-router-dom"; -import { useClient } from "../ClientContext"; +import { useClientSession } from "../ClientContext"; import { Header, HeaderLogo, LeftNav, RightNav } from "../Header"; import { UserMenuContainer } from "../UserMenuContainer"; import { FieldRow, InputField, ErrorMessage } from "../input/Input"; @@ -22,7 +22,7 @@ import { roomAliasLocalpartFromRoomName, sanitiseRoomNameInput, } from "../utils/matrix"; -import { useInteractiveRegistration } from "../auth/useInteractiveRegistration"; +import { useRegistrationTerms } from "../auth/useRegistrationTerms"; import { JoinExistingCallModal } from "./JoinExistingCallModal"; import { useRecaptcha } from "../auth/useRecaptcha"; import { Form } from "../form/Form"; @@ -37,12 +37,12 @@ import { ExternalLink, Link } from "../button/Link"; import { useUrlParams } from "../UrlParams"; export const UnauthenticatedView: FC = () => { - const { setClient } = useClient(); + const { register } = useClientSession(); const { header } = useUrlParams(); const [loading, setLoading] = useState(false); const [error, setError] = useState(); const [optInAnalytics] = useOptInAnalytics(); - const { recaptchaKey, register } = useInteractiveRegistration(); + const { recaptchaKey } = useRegistrationTerms(); const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey); const [joinExistingCallModalOpen, setJoinExistingCallModalOpen] = @@ -65,9 +65,12 @@ export const UnauthenticatedView: FC = () => { async function submit(): Promise { setError(undefined); setLoading(true); + if (!register) throw new Error("This session cannot register"); const recaptchaResponse = await execute(); const userName = generateRandomName(); - const [client, session] = await register( + // Signed in only once the call exists too: this view is replaced the + // moment the session has a user, and the call is what they came for + const { client, setSignedIn } = await register( userName, secureRandomString(16), displayName, @@ -83,15 +86,11 @@ export const UnauthenticatedView: FC = () => { E2eeType.SHARED_KEY, ); } catch (error) { - if (!setClient) { - throw error; - } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore if (error.errcode === "M_ROOM_IN_USE") { setOnFinished(() => { - setClient(client, session); + setSignedIn(); const aliasLocalpart = roomAliasLocalpartFromRoomName(roomName); navigate(`/${aliasLocalpart}`)?.catch((error) => { logger.error("Failed to navigate to alias localpart", error); @@ -106,14 +105,10 @@ export const UnauthenticatedView: FC = () => { } } - // Only consider the registration successful if we managed to create the room, too - if (!setClient) { - throw new Error("setClient is undefined"); - } if (!createRoomResult.password) throw new Error("Failed to create room with shared secret"); - setClient(client, session); + setSignedIn(); await navigate( getRelativeRoomUrl( createRoomResult.roomId, @@ -130,14 +125,7 @@ export const UnauthenticatedView: FC = () => { reset(); }); }, - [ - register, - reset, - execute, - navigate, - setJoinExistingCallModalOpen, - setClient, - ], + [register, reset, execute, navigate, setJoinExistingCallModalOpen], ); return ( diff --git a/src/main.tsx b/src/main.tsx index b2f79f34e..2d3124a69 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -20,7 +20,9 @@ import { App } from "./App"; import { init as initRageshake } from "./settings/rageshake"; import { Initializer } from "./initializer"; import { AppViewModel } from "./state/AppViewModel"; +import { pendingHostClientSession } from "./state/ClientSession"; import { globalScope } from "./state/ObservableScope"; +import { StandaloneClientSession } from "./state/StandaloneClientSession"; import { getUrlParams } from "./UrlParams"; initRageshake().catch((e) => { @@ -51,6 +53,12 @@ if (fatalError !== null) { Initializer.initBeforeReact() .then((widget) => { const { controlledAudioDevices, callIntent } = getUrlParams(); + // As a widget, the client comes from the host over the widget API. + // Standalone, Element Call restores or creates a session of its own. + const clientSession = + widget === null + ? new StandaloneClientSession(globalScope) + : pendingHostClientSession(globalScope, widget.client); root.render( , ); diff --git a/src/settings/useSubmitRageshake.test.tsx b/src/settings/useSubmitRageshake.test.tsx index a53398d39..0b05bc0bf 100644 --- a/src/settings/useSubmitRageshake.test.tsx +++ b/src/settings/useSubmitRageshake.test.tsx @@ -20,6 +20,7 @@ import { type MatrixClient } from "matrix-js-sdk/lib/client"; import { useSubmitRageshake, getRageshakeSubmitUrl } from "./submit-rageshake"; import { ClientContextProvider } from "../ClientContext"; +import { hostClientSession } from "../state/ClientSession"; import { getUrlParams } from "../UrlParams"; import { mockConfig } from "../utils/test"; import { DEFAULT_CONFIG } from "../config/ConfigOptions"; @@ -74,18 +75,7 @@ function renderWithMockClient( } as unknown as MatrixClient); render( - + ({ initClient: vi.fn() })); - -const session: Session = { - user_id: "@alice:example.org", - device_id: "AAAA", - access_token: "secret", - passwordlessUser: true, -}; -const client = {} as MatrixClient; - -describe("initSPA", () => { - const clearSession = vi.fn(); - - beforeEach(() => { - vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue( - "https://hs.example.org", - ); - }); - afterEach(() => { - vi.restoreAllMocks(); - vi.clearAllMocks(); - }); - - it("continues without a client when no session is stored", async () => { - await expect(initSPA(() => undefined, clearSession)).resolves.toBeNull(); - - expect(initClient).not.toHaveBeenCalled(); - expect(clearSession).not.toHaveBeenCalled(); - }); - - it("restores the stored session into a client", async () => { - vi.mocked(initClient).mockResolvedValue(client); - - await expect(initSPA(() => session, clearSession)).resolves.toEqual({ - client, - passwordlessUser: true, - }); - - expect(initClient).toHaveBeenCalledWith( - expect.objectContaining({ - baseUrl: "https://hs.example.org", - accessToken: "secret", - userId: "@alice:example.org", - deviceId: "AAAA", - }), - // Restoring: the crypto store is the session's, not to be wiped - true, - ); - }); - - it("drops a session the homeserver no longer knows", async () => { - vi.mocked(initClient).mockRejectedValue( - new MatrixError({ errcode: "M_UNKNOWN_TOKEN", error: "Unknown token" }), - ); - - await expect(initSPA(() => session, clearSession)).resolves.toBeNull(); - expect(clearSession).toHaveBeenCalled(); - }); - - it("drops the session and fails on any other error", async () => { - vi.mocked(initClient).mockRejectedValue(new Error("offline")); - - await expect(initSPA(() => session, clearSession)).rejects.toThrow( - "offline", - ); - expect(clearSession).toHaveBeenCalled(); - }); -}); diff --git a/src/utils/spa.ts b/src/utils/spa.ts deleted file mode 100644 index 613981c16..000000000 --- a/src/utils/spa.ts +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2024 New Vector Ltd. - -SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial -Please see LICENSE in the repository root for full details. -*/ - -import { type ICreateClientOpts, MatrixError } from "matrix-js-sdk"; -import { logger } from "matrix-js-sdk/lib/logger"; - -import { Config } from "../config/Config"; -import { fallbackICEServerAllowed } from "./matrix"; -import { initClient } from "./initClient"; -import type { InitResult, Session } from "../ClientContext"; - -export async function initSPA( - loadSession: () => Session | undefined, - clearSession: () => void, -): Promise { - // We're running as a standalone application - try { - const session = loadSession(); - if (!session) { - logger.log("No session stored; continuing without a client"); - return null; - } - - logger.log("Using a standalone client"); - - /* eslint-disable camelcase */ - const { user_id, device_id, access_token, passwordlessUser } = session; - const initClientParams: ICreateClientOpts = { - baseUrl: Config.defaultHomeserverUrl()!, - accessToken: access_token, - userId: user_id, - deviceId: device_id, - fallbackICEServerAllowed, - livekitServiceURL: Config.get().livekit?.livekit_service_url, - }; - - try { - const client = await initClient(initClientParams, true); - return { - client, - passwordlessUser, - }; - } catch (err) { - if (err instanceof MatrixError && err.errcode === "M_UNKNOWN_TOKEN") { - // We can't use this session anymore, so let's log it out - logger.log( - "The session from local store is invalid; continuing without a client", - ); - clearSession(); - // returning null = "no client` pls register" (undefined = "loading" which is the current value when reaching this line) - return null; - } - throw err; - } - } catch (err) { - clearSession(); - throw err; - } -}