diff --git a/component/index.tsx b/component/index.tsx index c8ce7c757..5c56ff28a 100644 --- a/component/index.tsx +++ b/component/index.tsx @@ -190,24 +190,25 @@ export const ElementCall: FC = ({ [roomId, intent, stableConfig], ); - // Created in an effect so that the scope it lives in ends when the component - // is unmounted (or these options change), rather than keeping its device - // observers running for the rest of the page's life. Null until then, which - // is one render. const { controlledAudioDevices, callIntent } = params; const [vm, setVm] = useState(null); useEffect(() => { const scope = new ObservableScope(); - setVm(new AppViewModel(scope, { controlledAudioDevices, callIntent })); + setVm( + new AppViewModel( + scope, + { controlledAudioDevices, callIntent }, + // The host owns the client. We create a clientSession wrapping the host client. + hostClientSession(client), + // The host owns the session too, so there is nothing to manage here + null, + ), + ); return (): void => { setVm(null); scope.end(); }; - }, [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]); + }, [controlledAudioDevices, callIntent, client]); const room = client.getRoom(roomId); const rtcSession = useMemo( @@ -255,7 +256,7 @@ export const ElementCall: FC = ({ > - + = ({ vm, widget, clientSession }) => { +export const App: FC = ({ vm, widget }) => { // The standalone build has no host; the widget build's host is the client it // is a widget of. const hostBridge = useInitial(() => @@ -134,21 +131,23 @@ export const App: FC = ({ vm, widget, clientSession }) => { }); const content = loaded ? ( - - - - } - > - - } /> - } /> - } /> - } /> - - - - + + + + + } + > + + } /> + } /> + } /> + } /> + + + + + ) : ( diff --git a/src/ClientContext.test.tsx b/src/ClientContext.test.tsx index 3113b579a..9cf159a47 100644 --- a/src/ClientContext.test.tsx +++ b/src/ClientContext.test.tsx @@ -13,11 +13,14 @@ import { type FC } from "react"; import { BehaviorSubject } from "rxjs"; import { + ClientManagerProvider, ClientProvider, - useClientSession, + useClientManager, + useClientManagerIfAny, useClientSessionState, } from "./ClientContext"; import { + type ClientManager, type ClientSession, type ClientSessionState, hostClientSession, @@ -118,17 +121,28 @@ test("shows the session's error in place of its children", () => { expect(container.textContent).toContain("Something went wrong"); }); -test("hands the session itself to the context", () => { - const session: ClientSession = { - state$: new BehaviorSubject({ state: "signedOut" }), +test("hands the session's manager to views that need one", () => { + const manager: ClientManager = { + login: vi.fn(), register: vi.fn(), + logout: vi.fn(), }; - const { result } = renderHook(() => useClientSession(), { - wrapper: ({ children }) => ( - - <>{children} - - ), - }); - expect(result.current).toBe(session); + const { result } = renderHook( + () => [useClientManager(), useClientManagerIfAny()], + { + wrapper: ({ children }) => ( + + <>{children} + + ), + }, + ); + expect(result.current).toEqual([manager, manager]); +}); + +test("has no manager for a host's session", () => { + // The component and the widget provide none; a view that insists on one is + // in the wrong build + expect(renderHook(() => useClientManagerIfAny()).result.current).toBeNull(); + expect(() => renderHook(() => useClientManager())).toThrow(); }); diff --git a/src/ClientContext.tsx b/src/ClientContext.tsx index b8aad669d..4030d24c9 100644 --- a/src/ClientContext.tsx +++ b/src/ClientContext.tsx @@ -13,6 +13,7 @@ import { PosthogAnalytics } from "./analytics/PosthogAnalytics"; import { useBehavior } from "./useBehavior"; import { constant } from "./state/Behavior"; import { + type ClientManager, type ClientSession, type ClientSessionState, } from "./state/ClientSession"; @@ -33,22 +34,42 @@ const ClientContext = createContext(noClientSession); export const ClientContextProvider = ClientContext.Provider; -export const useClientSession = (): ClientSession => use(ClientContext); - export const useClientSessionState = (): ClientSessionState => - useBehavior(useClientSession().state$); + useBehavior(use(ClientContext).state$); export function useClient(): { client?: MatrixClient } { const state = useClientSessionState(); return { client: state.state === "signedIn" ? state.client : undefined }; } +// Null where the session is a host's: the component, and the widget +const ClientManagerContext = createContext(null); + +export const ClientManagerProvider = ClientManagerContext.Provider; + +/** + * The manager of a session that is Element Call's own, for views that only + * the standalone app mounts: the login and registration pages. Throws + * elsewhere, as those views have no business being there. + */ +export function useClientManager(): ClientManager { + const manager = use(ClientManagerContext); + if (manager === null) + throw new Error("This view needs a session of Element Call's own"); + return manager; +} + +/** + * The session's manager, or null where the session is a host's. For views + * shared with the widget, which can offer to sign out only when that is ours + * to do. + */ +export const useClientManagerIfAny = (): ClientManager | null => + use(ClientManagerContext); + interface Props { children: JSX.Element; - /** - * Where the client comes from: a session of Element Call's own, or one a - * host has supplied. - */ + /** a session from Element Call SPA, from a widget or the host (EW) */ session: ClientSession; } diff --git a/src/UserMenuContainer.test.tsx b/src/UserMenuContainer.test.tsx index 9ae3f5607..b199fcb93 100644 --- a/src/UserMenuContainer.test.tsx +++ b/src/UserMenuContainer.test.tsx @@ -13,9 +13,10 @@ import { type MatrixClient } from "matrix-js-sdk"; import { TooltipProvider } from "@vector-im/compound-web"; import { BehaviorSubject } from "rxjs"; -import { ClientProvider } from "./ClientContext"; +import { ClientManagerProvider, ClientProvider } from "./ClientContext"; import { LeaveToHomeProvider } from "./LeaveToHomeContext"; import { + type ClientManager, type ClientSession, type ClientSessionState, hostClientSession, @@ -49,8 +50,8 @@ test("leaves for home after logging out of the session", async () => { client: mockClient(), passwordlessUser: false, }), - logout, }, + { login: vi.fn(), register: vi.fn(), logout }, leaveToHome, ); @@ -61,7 +62,7 @@ test("leaves for home after logging out of the session", async () => { test("cannot end a session that is not ours", async () => { const leaveToHome = vi.fn(); - renderMenu(hostClientSession(mockClient()), leaveToHome); + renderMenu(hostClientSession(mockClient()), null, leaveToHome); await selectSignOut(); expect(leaveToHome).not.toHaveBeenCalled(); @@ -76,6 +77,7 @@ async function selectSignOut(): Promise { function renderMenu( session: ClientSession, + manager: ClientManager | null, leaveToHome: (() => void) | null = null, ): void { render( @@ -83,7 +85,9 @@ function renderMenu( - + + + diff --git a/src/UserMenuContainer.tsx b/src/UserMenuContainer.tsx index cd2423f14..01a33f399 100644 --- a/src/UserMenuContainer.tsx +++ b/src/UserMenuContainer.tsx @@ -9,12 +9,12 @@ import { type FC, useCallback, useState } from "react"; import { useNavigate, useLocation } from "react-router-dom"; import { logger } from "matrix-js-sdk/lib/logger"; -import { useClientSession, useClientSessionState } from "./ClientContext"; -import { useLeaveToHome } from "./LeaveToHomeContext"; import { - PosthogAnalytics, - RegistrationType, -} from "./analytics/PosthogAnalytics"; + useClient, + useClientManagerIfAny, + useClientSessionState, +} from "./ClientContext"; +import { useLeaveToHome } from "./LeaveToHomeContext"; import { useProfile } from "./profile/useProfile"; import { defaultSettingsTab, SettingsModal } from "./settings/SettingsModal"; import { UserMenu } from "./UserMenu"; @@ -26,12 +26,12 @@ interface Props { export const UserMenuContainer: FC = ({ preventNavigation = false }) => { const location = useLocation(); const navigate = useNavigate(); + const { client } = useClient(); const session = useClientSessionState(); - const client = session.state === "signedIn" ? session.client : undefined; const passwordlessUser = session.state === "signedIn" && session.passwordlessUser; // Absent when the session is a host's, which Element Call cannot end - const { logout } = useClientSession(); + const logout = useClientManagerIfAny()?.logout; const leaveToHome = useLeaveToHome(); const { displayName, avatarUrl } = useProfile(client); const [settingsModalOpen, setSettingsModalOpen] = useState(false); @@ -55,13 +55,7 @@ export const UserMenuContainer: FC = ({ preventNavigation = false }) => { break; case "logout": logout?.() - .then(() => { - leaveToHome?.(); - PosthogAnalytics.instance.logout(); - PosthogAnalytics.instance.setRegistrationType( - RegistrationType.Guest, - ); - }) + .then(() => leaveToHome?.()) .catch((e) => logger.error("Failed to log out", e)); break; case "login": diff --git a/src/auth/LoginPage.tsx b/src/auth/LoginPage.tsx index 64e3e9c70..07133a728 100644 --- a/src/auth/LoginPage.tsx +++ b/src/auth/LoginPage.tsx @@ -11,7 +11,7 @@ import { Trans, useTranslation } from "react-i18next"; import { Button } from "@vector-im/compound-web"; import Logo from "../icons/LogoLarge.svg?react"; -import { useClientSession } from "../ClientContext"; +import { useClientManager } from "../ClientContext"; import { FieldRow, InputField, ErrorMessage } from "../input/Input"; import styles from "./LoginPage.module.css"; import { usePageTitle } from "../usePageTitle"; @@ -23,7 +23,7 @@ export const LoginPage: FC = () => { const { t } = useTranslation(); usePageTitle(t("login_title")); - const { login } = useClientSession(); + const { login } = useClientManager(); const homeserver = Config.defaultHomeserverUrl(); // TODO: Make this configurable const usernameRef = useRef(null); const passwordRef = useRef(null); @@ -44,12 +44,6 @@ 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 () => { const locationState = location.state; diff --git a/src/auth/RegisterPage.tsx b/src/auth/RegisterPage.tsx index 36684c79b..ee25d897d 100644 --- a/src/auth/RegisterPage.tsx +++ b/src/auth/RegisterPage.tsx @@ -22,7 +22,11 @@ import { logger } from "matrix-js-sdk/lib/logger"; import { Button, Text } from "@vector-im/compound-web"; import { FieldRow, InputField, ErrorMessage } from "../input/Input"; -import { useClientSession, useClientSessionState } from "../ClientContext"; +import { + useClient, + useClientManager, + useClientSessionState, +} from "../ClientContext"; import { useRegistrationTerms } from "./useRegistrationTerms"; import styles from "./LoginPage.module.css"; import Logo from "../icons/LogoLarge.svg?react"; @@ -39,11 +43,11 @@ export const RegisterPage: FC = () => { const session = useClientSessionState(); const loading = session.state === "loading"; - const client = session.state === "signedIn" ? session.client : undefined; - const authenticated = client !== undefined; const passwordlessUser = session.state === "signedIn" && session.passwordlessUser; - const { register } = useClientSession(); + const { client } = useClient(); + const authenticated = client !== undefined; + const { register } = useClientManager(); const confirmPasswordRef = useRef(null); const navigate = useNavigate(); @@ -67,7 +71,6 @@ export const RegisterPage: FC = () => { const submit = async (): Promise => { setRegistering(true); - if (!register) throw new Error("This session cannot register"); const recaptchaResponse = await execute(); const { client: newClient, setSignedIn } = await register( diff --git a/src/auth/useRegisterPasswordlessUser.ts b/src/auth/useRegisterPasswordlessUser.ts index 22a2e6791..0a648cc16 100644 --- a/src/auth/useRegisterPasswordlessUser.ts +++ b/src/auth/useRegisterPasswordlessUser.ts @@ -8,7 +8,7 @@ Please see LICENSE in the repository root for full details. import { useCallback } from "react"; import { secureRandomString } from "matrix-js-sdk/lib/randomstring"; -import { useClientSession } from "../ClientContext"; +import { useClientManagerIfAny } from "../ClientContext"; import { useRegistrationTerms } from "../auth/useRegistrationTerms"; import { generateRandomName } from "../auth/generateRandomName"; import { useRecaptcha } from "../auth/useRecaptcha"; @@ -21,7 +21,8 @@ interface UseRegisterPasswordlessUserType { } export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType { - const { register } = useClientSession(); + // Null in the widget, which never registers anyone + const register = useClientManagerIfAny()?.register; const { isWidget } = useUrlParams(); const { privacyPolicyUrl, recaptchaKey } = useRegistrationTerms(); const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey); diff --git a/src/home/UnauthenticatedView.tsx b/src/home/UnauthenticatedView.tsx index 2639dc4cf..37a68fc64 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 { useClientSession } from "../ClientContext"; +import { useClientManager } from "../ClientContext"; import { Header, HeaderLogo, LeftNav, RightNav } from "../Header"; import { UserMenuContainer } from "../UserMenuContainer"; import { FieldRow, InputField, ErrorMessage } from "../input/Input"; @@ -37,7 +37,7 @@ import { ExternalLink, Link } from "../button/Link"; import { useUrlParams } from "../UrlParams"; export const UnauthenticatedView: FC = () => { - const { register } = useClientSession(); + const { register } = useClientManager(); const { header } = useUrlParams(); const [loading, setLoading] = useState(false); const [error, setError] = useState(); @@ -65,7 +65,6 @@ 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(); // Signed in only once the call exists too: this view is replaced the diff --git a/src/main.tsx b/src/main.tsx index 2d3124a69..d5ee9601e 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -53,24 +53,25 @@ 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); + // As a widget, the client comes from the host over the widget API, and + // the session is the host's. Standalone, Element Call restores or creates + // a session of its own, which it also manages. + const options = { controlledAudioDevices, callIntent }; + let vm: AppViewModel; + if (widget === null) { + const session = new StandaloneClientSession(globalScope); + vm = new AppViewModel(globalScope, options, session, session); + } else { + vm = new AppViewModel( + globalScope, + options, + pendingHostClientSession(globalScope, widget.client), + null, + ); + } root.render( - + , ); }) diff --git a/src/room/RoomPage.tsx b/src/room/RoomPage.tsx index 2d7455fa3..ed98de29a 100644 --- a/src/room/RoomPage.tsx +++ b/src/room/RoomPage.tsx @@ -12,7 +12,7 @@ import { logger } from "matrix-js-sdk/lib/logger"; import { Trans, useTranslation } from "react-i18next"; import { UnknownSolidIcon } from "@vector-im/compound-design-tokens/assets/web/icons"; -import { useClientSessionState } from "../ClientContext"; +import { useClient, useClientSessionState } from "../ClientContext"; import { ErrorPage, FullScreenView, LoadingPage } from "../FullScreenView"; import { RoomAuthView } from "./RoomAuthView"; import { CallView } from "./CallView"; @@ -42,12 +42,12 @@ export const RoomPage: FC = (): ReactNode => { const { registerPasswordlessUser } = useRegisterPasswordlessUser(); const [isRegistering, setIsRegistering] = useState(false); + const { client } = useClient(); const session = useClientSessionState(); const loading = session.state === "loading"; - const client = session.state === "signedIn" ? session.client : undefined; - const authenticated = client !== undefined; const passwordlessUser = session.state === "signedIn" && session.passwordlessUser; + const authenticated = client !== undefined; const { avatarUrl, displayName: userDisplayName } = useProfile(client); const groupCallState = useLoadGroupCall(client, roomIdOrAlias, viaServers); diff --git a/src/state/AppViewModel.ts b/src/state/AppViewModel.ts index e8882b8c1..02ad25de5 100644 --- a/src/state/AppViewModel.ts +++ b/src/state/AppViewModel.ts @@ -5,6 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial Please see LICENSE in the repository root for full details. */ +import { type ClientManager, type ClientSession } from "./ClientSession"; import { type AudioOutputOptions, MediaDevices } from "./MediaDevices"; import { type ObservableScope } from "./ObservableScope"; import { createAppBackgroundEffects } from "../tracks/BackgroundEffectsContext"; @@ -22,8 +23,14 @@ export class AppViewModel { // TODO: Move more application logic here. The CallViewModel, at the very // least, ought to be accessible from this object. + /** + * @param clientSession Where the client comes from. SPA js-sdk, EW host, widget + */ public constructor( private readonly scope: ObservableScope, private readonly audioOutputOptions: AudioOutputOptions, + public readonly clientSession: ClientSession, + /** Null where the session is a host's and not ours to manage. */ + public readonly clientManager: ClientManager | null, ) {} } diff --git a/src/state/ClientSession.test.ts b/src/state/ClientSession.test.ts index d8dbfecb1..82a36166b 100644 --- a/src/state/ClientSession.test.ts +++ b/src/state/ClientSession.test.ts @@ -20,11 +20,6 @@ test("a host's client is signed in from the start", () => { client, passwordlessUser: false, }); - // The host owns the session, so there is nothing for Element Call to do to it - expect(session.login).toBeUndefined(); - expect(session.register).toBeUndefined(); - expect(session.logout).toBeUndefined(); - expect(session.changePassword).toBeUndefined(); }); test("a pending host client is loading until it arrives", async () => { @@ -41,11 +36,10 @@ test("a pending host client is loading until it arrives", async () => { }); }); -test("a pending host client that never arrives stays loading", async () => { - const session = pendingHostClientSession( - testScope(), - Promise.reject(new Error("no widget API")), - ); +test("a pending host client that never arrives is an error", async () => { + const error = new Error("no widget API"); + const session = pendingHostClientSession(testScope(), Promise.reject(error)); await flushPromises(); - expect(session.state$.value).toEqual({ state: "loading" }); + // An error page rather than a spinner that never ends + expect(session.state$.value).toEqual({ state: "error", error }); }); diff --git a/src/state/ClientSession.ts b/src/state/ClientSession.ts index 01a4b0ec3..de0c005cc 100644 --- a/src/state/ClientSession.ts +++ b/src/state/ClientSession.ts @@ -7,7 +7,7 @@ Please see LICENSE in the repository root for full details. import { type MatrixClient } from "matrix-js-sdk"; import { logger } from "matrix-js-sdk/lib/logger"; -import { catchError, EMPTY, from, map } from "rxjs"; +import { catchError, from, map, of } from "rxjs"; import { type Behavior, constant } from "./Behavior"; import { type ObservableScope } from "./ObservableScope"; @@ -20,7 +20,6 @@ export interface StoredSession { device_id: string; access_token: string; passwordlessUser: boolean; - tempPassword?: string; } export type ClientSessionState = @@ -41,28 +40,33 @@ export interface Registration { } /** - * Where Element Call's client comes from, and what can be done with the - * session behind it. Actions are absent when the session is not Element Call's - * to manage, as with a client supplied by a host. + * Where Element Call's client comes from. Every build has one: a session of + * Element Call's own, or one a host has supplied. */ export interface ClientSession { state$: Behavior; +} + +/** + * What can be done with a client created in EC (SPA). Widget and host client + * wont have this, see useClientManager and useClientManagerIfAny + */ +export interface ClientManager { /** Signs in to the homeserver with a password, ending any current session. */ - login?: ( + login: ( homeserver: string, username: string, password: string, ) => Promise; /** Registers an account on the default homeserver. */ - register?: ( + register: ( username: string, password: string, displayName: string, recaptchaResponse: string, passwordlessUser: boolean, ) => Promise; - changePassword?: (password: string) => Promise; - logout?: () => Promise; + logout: () => Promise; } /** @@ -87,7 +91,7 @@ export function pendingHostClientSession( map(signedIn), catchError((e) => { logger.error("Failed to obtain the host's client", e); - return EMPTY; + return of({ state: "error", error: e }); }), ), { state: "loading" }, diff --git a/src/state/StandaloneClientSession.test.ts b/src/state/StandaloneClientSession.test.ts index 47762891e..2ec1049fc 100644 --- a/src/state/StandaloneClientSession.test.ts +++ b/src/state/StandaloneClientSession.test.ts @@ -15,6 +15,7 @@ import { loginWithPassword, registerWithPassword, } from "../auth/interactiveAuth"; +import { PosthogAnalytics } from "../analytics/PosthogAnalytics"; import { Config } from "../config/Config"; import { OpenElsewhereError } from "../RichError"; import { flushPromises, testScope } from "../utils/test"; @@ -32,14 +33,12 @@ const session: StoredSession = { device_id: "AAAA", access_token: "secret", passwordlessUser: true, - tempPassword: "temporary", }; const user = { setRawDisplayName: vi.fn(), setDisplayName: vi.fn() }; const mockClient = (): MatrixClient => ({ stopClient: vi.fn(), - setPassword: vi.fn().mockResolvedValue(undefined), logout: vi.fn().mockResolvedValue(undefined), clearStores: vi.fn().mockResolvedValue(undefined), setDisplayName: vi.fn().mockResolvedValue(undefined), @@ -115,13 +114,15 @@ test("drops a session the homeserver no longer knows", async () => { expect(clientSession.state$.value).toEqual({ state: "signedOut" }); }); -test("drops the session and stays loading on any other error", async () => { +test("drops the session and reports any other error", async () => { storeSession(); - vi.mocked(initClient).mockRejectedValue(new Error("offline")); + const error = new Error("offline"); + vi.mocked(initClient).mockRejectedValue(error); const clientSession = new StandaloneClientSession(testScope()); await flushPromises(); expect(storedSession()).toBeNull(); - expect(clientSession.state$.value).toEqual({ state: "loading" }); + // An error page rather than a spinner that never ends + expect(clientSession.state$.value).toEqual({ state: "error", error }); }); test("logs in with a password, ending the session it had", async () => { @@ -197,12 +198,7 @@ test("registers a passwordless account, signing in only when asked", async () => client, passwordlessUser: true, }); - // A passwordless user keeps the generated password, to set a real one later - expect(storedSession()).toEqual({ - ...credentials, - passwordlessUser: true, - tempPassword: "temporary", - }); + expect(storedSession()).toEqual({ ...credentials, passwordlessUser: true }); }); test("registers an account with a password of its own", async () => { @@ -223,27 +219,6 @@ test("registers an account with a password of its own", async () => { expect(storedSession()).toEqual({ ...credentials, passwordlessUser: false }); }); -test("turns a passwordless user into one with a password", async () => { - storeSession(); - const client = mockClient(); - vi.mocked(initClient).mockResolvedValue(client); - const clientSession = new StandaloneClientSession(testScope()); - await flushPromises(); - - await clientSession.changePassword("hunter2"); - - expect(client.setPassword).toHaveBeenCalledWith( - expect.objectContaining({ user: session.user_id, password: "temporary" }), - "hunter2", - ); - expect(clientSession.state$.value).toEqual({ - state: "signedIn", - client, - passwordlessUser: false, - }); - expect(storedSession()).toEqual({ ...session, passwordlessUser: false }); -}); - test("logs out, clearing the client's stores and the stored session", async () => { storeSession(); const client = mockClient(); @@ -251,12 +226,16 @@ test("logs out, clearing the client's stores and the stored session", async () = const clientSession = new StandaloneClientSession(testScope()); await flushPromises(); + const analyticsLogout = vi.spyOn(PosthogAnalytics.instance, "logout"); + await clientSession.logout(); expect(client.logout).toHaveBeenCalledWith(true); expect(client.clearStores).toHaveBeenCalled(); expect(storedSession()).toBeNull(); expect(clientSession.state$.value).toEqual({ state: "signedOut" }); + // Analytics forget the user along with the session + expect(analyticsLogout).toHaveBeenCalled(); }); test("claims exclusive use of storage from other instances of the app", () => { diff --git a/src/state/StandaloneClientSession.ts b/src/state/StandaloneClientSession.ts index 2da352eaf..08ad7eae1 100644 --- a/src/state/StandaloneClientSession.ts +++ b/src/state/StandaloneClientSession.ts @@ -9,6 +9,10 @@ import { type MatrixClient, MatrixError } from "matrix-js-sdk"; import { logger } from "matrix-js-sdk/lib/logger"; import { BehaviorSubject } from "rxjs"; +import { + PosthogAnalytics, + RegistrationType, +} from "../analytics/PosthogAnalytics"; import { Config } from "../config/Config"; import { OpenElsewhereError } from "../RichError"; import { @@ -19,6 +23,7 @@ import { initClient } from "../utils/initClient"; import { fallbackICEServerAllowed } from "../utils/matrix"; import { type Behavior } from "./Behavior"; import { + type ClientManager, type ClientSession, type ClientSessionState, type Registration, @@ -40,7 +45,7 @@ const SESSION_KEY = "matrix-auth-store"; * and therefore the client store worker, so it may only be imported by the * standalone app's entry point. */ -export class StandaloneClientSession implements ClientSession { +export class StandaloneClientSession implements ClientSession, ClientManager { private readonly state = new BehaviorSubject({ state: "loading", }); @@ -65,7 +70,10 @@ export class StandaloneClientSession implements ClientSession { this.loadChannel?.removeEventListener("message", onOpenedElsewhere), ); - this.restore().catch((e) => logger.error(e)); + this.restore().catch((e) => { + logger.error("Failed to restore the session", e); + this.state.next({ state: "error", error: e }); + }); } private get client(): MatrixClient | undefined { @@ -146,7 +154,6 @@ export class StandaloneClientSession implements ClientSession { recaptchaResponse, )), passwordlessUser, - ...(passwordlessUser ? { tempPassword: password } : {}), }; const client = await this.createClient(homeserver, session); @@ -188,28 +195,6 @@ export class StandaloneClientSession implements ClientSession { }); } - public readonly changePassword = async (password: string): Promise => { - const client = this.client; - const session = loadSession(); - if (!client || !session) return; - - await 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 }); - this.state.next({ state: "signedIn", client, passwordlessUser: false }); - }; - public readonly logout = async (): Promise => { const client = this.client; if (!client) return; @@ -218,6 +203,8 @@ export class StandaloneClientSession implements ClientSession { await client.clearStores(); clearSession(); this.state.next({ state: "signedOut" }); + PosthogAnalytics.instance.logout(); + PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest); }; }