This commit is contained in:
Timo K.
2026-11-12 13:25:45 +01:00
parent 8d5d482771
commit a2e3a2c13f
17 changed files with 185 additions and 183 deletions
+12 -11
View File
@@ -190,24 +190,25 @@ export const ElementCall: FC<ElementCallProps> = ({
[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<AppViewModel | null>(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<ElementCallProps> = ({
>
<Decoration>
<TooltipProvider>
<ClientProvider session={clientSession}>
<ClientProvider session={vm.clientSession}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider
effects={vm.backgroundEffects}
+19 -20
View File
@@ -29,14 +29,13 @@ import { HomePage } from "./home/HomePage";
import { LoginPage } from "./auth/LoginPage";
import { RegisterPage } from "./auth/RegisterPage";
import { RoomPage } from "./room/RoomPage";
import { ClientProvider } from "./ClientContext";
import { ClientManagerProvider, ClientProvider } from "./ClientContext";
import { ErrorPage, LoadingPage } from "./FullScreenView";
import { Initializer } from "./initializer";
import { type WidgetHelpers } from "./widget";
import { useTheme } from "./useTheme";
import { BackgroundEffectsProvider } from "./tracks/BackgroundEffectsContext";
import { type AppViewModel } from "./state/AppViewModel";
import { type ClientSession } from "./state/ClientSession";
import { MediaDevicesContext } from "./MediaDevicesContext";
import {
HeaderStyle,
@@ -112,11 +111,9 @@ 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<Props> = ({ vm, widget, clientSession }) => {
export const App: FC<Props> = ({ 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<Props> = ({ vm, widget, clientSession }) => {
});
const content = loaded ? (
<ClientProvider session={clientSession}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider effects={vm.backgroundEffects}>
<Sentry.ErrorBoundary
fallback={(error) => <ErrorPage error={error} />}
>
<Routes>
<SentryRoute path="/" element={<HomePage />} />
<SentryRoute path="/login" element={<LoginPage />} />
<SentryRoute path="/register" element={<RegisterPage />} />
<SentryRoute path="*" element={<RoomPage />} />
</Routes>
</Sentry.ErrorBoundary>
</BackgroundEffectsProvider>
</MediaDevicesContext>
<ClientProvider session={vm.clientSession}>
<ClientManagerProvider value={vm.clientManager}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider effects={vm.backgroundEffects}>
<Sentry.ErrorBoundary
fallback={(error) => <ErrorPage error={error} />}
>
<Routes>
<SentryRoute path="/" element={<HomePage />} />
<SentryRoute path="/login" element={<LoginPage />} />
<SentryRoute path="/register" element={<RegisterPage />} />
<SentryRoute path="*" element={<RoomPage />} />
</Routes>
</Sentry.ErrorBoundary>
</BackgroundEffectsProvider>
</MediaDevicesContext>
</ClientManagerProvider>
</ClientProvider>
) : (
<LoadingPage />
+26 -12
View File
@@ -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<ClientSessionState>({ 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 }) => (
<ClientProvider session={session}>
<>{children}</>
</ClientProvider>
),
});
expect(result.current).toBe(session);
const { result } = renderHook(
() => [useClientManager(), useClientManagerIfAny()],
{
wrapper: ({ children }) => (
<ClientManagerProvider value={manager}>
<>{children}</>
</ClientManagerProvider>
),
},
);
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();
});
+28 -7
View File
@@ -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<ClientSession>(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<ClientManager | null>(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;
}
+8 -4
View File
@@ -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<void> {
function renderMenu(
session: ClientSession,
manager: ClientManager | null,
leaveToHome: (() => void) | null = null,
): void {
render(
@@ -83,7 +85,9 @@ function renderMenu(
<TooltipProvider>
<LeaveToHomeProvider value={leaveToHome}>
<ClientProvider session={session}>
<UserMenuContainer />
<ClientManagerProvider value={manager}>
<UserMenuContainer />
</ClientManagerProvider>
</ClientProvider>
</LeaveToHomeProvider>
</TooltipProvider>
+8 -14
View File
@@ -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<Props> = ({ 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<Props> = ({ 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":
+2 -8
View File
@@ -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<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(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;
+8 -5
View File
@@ -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<HTMLInputElement>(null);
const navigate = useNavigate();
@@ -67,7 +71,6 @@ export const RegisterPage: FC = () => {
const submit = async (): Promise<void> => {
setRegistering(true);
if (!register) throw new Error("This session cannot register");
const recaptchaResponse = await execute();
const { client: newClient, setSignedIn } = await register(
+3 -2
View File
@@ -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);
+2 -3
View File
@@ -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<Error>();
@@ -65,7 +65,6 @@ export const UnauthenticatedView: FC = () => {
async function submit(): Promise<void> {
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
+17 -16
View File
@@ -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(
<StrictMode>
<App
vm={
new AppViewModel(globalScope, {
controlledAudioDevices,
callIntent,
})
}
widget={widget}
clientSession={clientSession}
/>
<App vm={vm} widget={widget} />
</StrictMode>,
);
})
+3 -3
View File
@@ -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);
+7
View File
@@ -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,
) {}
}
+5 -11
View File
@@ -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 });
});
+14 -10
View File
@@ -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<ClientSessionState>;
}
/**
* 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<MatrixClient>;
/** Registers an account on the default homeserver. */
register?: (
register: (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
) => Promise<Registration>;
changePassword?: (password: string) => Promise<void>;
logout?: () => Promise<void>;
logout: () => Promise<void>;
}
/**
@@ -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<ClientSessionState>({ state: "error", error: e });
}),
),
{ state: "loading" },
+11 -32
View File
@@ -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", () => {
+12 -25
View File
@@ -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<ClientSessionState>({
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<void> => {
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<void> => {
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);
};
}