From 839c0a720c62a26c7e11d714a214be692510b0d1 Mon Sep 17 00:00:00 2001 From: Richard van der Hoff <1389908+richvdh@users.noreply.github.com> Date: Thu, 24 Aug 2023 09:28:43 +0100 Subject: [PATCH] Lock out the first tab if Element is opened in a second tab. (#11425) * Implement session lock dialogs * Bump analytics-events package * clean up resetJsDomAfterEach * fix types * update snapshot * update i18n strings --- package.json | 2 +- res/css/_components.pcss | 2 + .../auth/_ConfirmSessionLockTheftView.pcss | 30 +++ .../auth/_SessionLockStolenView.pcss | 30 +++ src/Lifecycle.ts | 50 +++++ src/PosthogTrackers.ts | 2 + src/Views.ts | 6 + src/components/structures/MatrixChat.tsx | 52 ++++- .../auth/ConfirmSessionLockTheftView.tsx | 51 +++++ .../structures/auth/SessionLockStolenView.tsx | 35 ++++ src/i18n/strings/en_EN.json | 2 + src/utils/SessionLock.ts | 4 +- .../components/structures/MatrixChat-test.tsx | 179 ++++++++++++++++-- .../__snapshots__/MatrixChat-test.tsx.snap | 171 +++++++++++++++++ test/test-utils/utilities.ts | 60 ++++++ test/utils/SessionLock-test.ts | 29 +-- yarn.lock | 8 +- 17 files changed, 663 insertions(+), 50 deletions(-) create mode 100644 res/css/structures/auth/_ConfirmSessionLockTheftView.pcss create mode 100644 res/css/structures/auth/_SessionLockStolenView.pcss create mode 100644 src/components/structures/auth/ConfirmSessionLockTheftView.tsx create mode 100644 src/components/structures/auth/SessionLockStolenView.tsx diff --git a/package.json b/package.json index 3074fe96d6..1a8c0e7174 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,7 @@ }, "dependencies": { "@babel/runtime": "^7.12.5", - "@matrix-org/analytics-events": "^0.6.0", + "@matrix-org/analytics-events": "^0.7.0", "@matrix-org/emojibase-bindings": "^1.1.2", "@matrix-org/matrix-wysiwyg": "^2.4.1", "@matrix-org/react-sdk-module-api": "^2.1.0", diff --git a/res/css/_components.pcss b/res/css/_components.pcss index fcebafcfcc..0e01b34cd9 100644 --- a/res/css/_components.pcss +++ b/res/css/_components.pcss @@ -90,8 +90,10 @@ @import "./structures/_UserMenu.pcss"; @import "./structures/_ViewSource.pcss"; @import "./structures/auth/_CompleteSecurity.pcss"; +@import "./structures/auth/_ConfirmSessionLockTheftView.pcss"; @import "./structures/auth/_Login.pcss"; @import "./structures/auth/_Registration.pcss"; +@import "./structures/auth/_SessionLockStolenView.pcss"; @import "./structures/auth/_SetupEncryptionBody.pcss"; @import "./views/audio_messages/_AudioPlayer.pcss"; @import "./views/audio_messages/_PlayPauseButton.pcss"; diff --git a/res/css/structures/auth/_ConfirmSessionLockTheftView.pcss b/res/css/structures/auth/_ConfirmSessionLockTheftView.pcss new file mode 100644 index 0000000000..14b92daaa8 --- /dev/null +++ b/res/css/structures/auth/_ConfirmSessionLockTheftView.pcss @@ -0,0 +1,30 @@ +/* +Copyright 2019-2023 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +.mx_ConfirmSessionLockTheftView { + width: 100%; + height: 100%; + display: flex; + align-items: center; + justify-content: center; +} + +.mx_ConfirmSessionLockTheftView_body { + display: flex; + flex-direction: column; + max-width: 400px; + align-items: center; +} diff --git a/res/css/structures/auth/_SessionLockStolenView.pcss b/res/css/structures/auth/_SessionLockStolenView.pcss new file mode 100644 index 0000000000..e9ab0d95ff --- /dev/null +++ b/res/css/structures/auth/_SessionLockStolenView.pcss @@ -0,0 +1,30 @@ +/* +Copyright 2023 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +.mx_SessionLockStolenView { + h1 { + font-weight: var(--cpd-font-weight-semibold); + font-size: $font-32px; + text-align: center; + } + + h2 { + margin: 0; + font-weight: 500; + font-size: $font-24px; + text-align: center; + } +} diff --git a/src/Lifecycle.ts b/src/Lifecycle.ts index 6ca7055078..34c27c6a21 100644 --- a/src/Lifecycle.ts +++ b/src/Lifecycle.ts @@ -82,6 +82,41 @@ dis.register((payload) => { } }); +/** + * This is set to true by {@link #onSessionLockStolen}. + * + * It is used in various of the async functions to prevent races where we initialise a client after the lock is stolen. + */ +let sessionLockStolen = false; + +// this is exposed solely for unit tests. +// ts-prune-ignore-next +export function setSessionLockNotStolen(): void { + sessionLockStolen = false; +} + +/** + * Handle the session lock being stolen. Stops any active Matrix Client, and aborts any ongoing client initialisation. + */ +export async function onSessionLockStolen(): Promise { + sessionLockStolen = true; + stopMatrixClient(); +} + +/** + * Check if we still hold the session lock. + * + * If not, raises a {@link SessionLockStolenError}. + */ +function checkSessionLock(): void { + if (sessionLockStolen) { + throw new SessionLockStolenError("session lock has been released"); + } +} + +/** Error type raised by various functions in the Lifecycle workflow if session lock is stolen during execution */ +class SessionLockStolenError extends Error {} + interface ILoadSessionOpts { enableGuest?: boolean; guestHsUrl?: string; @@ -153,6 +188,9 @@ export async function loadSession(opts: ILoadSessionOpts = {}): Promise if (success) { return true; } + if (sessionLockStolen) { + return false; + } if (enableGuest && guestHsUrl) { return registerAsGuest(guestHsUrl, guestIsUrl, defaultDeviceDisplayName); @@ -166,6 +204,12 @@ export async function loadSession(opts: ILoadSessionOpts = {}): Promise // need to show the general failure dialog. Instead, just go back to welcome. return false; } + + // likewise, if the session lock has been stolen while we've been trying to start + if (sessionLockStolen) { + return false; + } + return handleLoadSessionFailure(e); } } @@ -719,6 +763,7 @@ export async function hydrateSession(credentials: IMatrixClientCreds): Promise { + checkSessionLock(); credentials.guest = Boolean(credentials.guest); const softLogout = isSoftLogout(); @@ -749,6 +794,8 @@ async function doSetLoggedIn(credentials: IMatrixClientCreds, clearStorageEnable await abortLogin(); } + // check the session lock just before creating the new client + checkSessionLock(); MatrixClientPeg.replaceUsingCreds(credentials); const client = MatrixClientPeg.safeGet(); @@ -781,6 +828,7 @@ async function doSetLoggedIn(credentials: IMatrixClientCreds, clearStorageEnable } else { logger.warn("No local storage available: can't persist session!"); } + checkSessionLock(); dis.fire(Action.OnLoggedIn); await startMatrixClient(client, /*startSyncing=*/ !softLogout); @@ -976,6 +1024,8 @@ async function startMatrixClient(client: MatrixClient, startSyncing = true): Pro await MatrixClientPeg.assign(); } + checkSessionLock(); + // Run the migrations after the MatrixClientPeg has been assigned SettingsStore.runMigrations(); diff --git a/src/PosthogTrackers.ts b/src/PosthogTrackers.ts index c03a20216c..14bd8426de 100644 --- a/src/PosthogTrackers.ts +++ b/src/PosthogTrackers.ts @@ -27,6 +27,7 @@ export type InteractionName = InteractionEvent["name"]; const notLoggedInMap: Record, ScreenName> = { [Views.LOADING]: "Loading", + [Views.CONFIRM_LOCK_THEFT]: "ConfirmStartup", [Views.WELCOME]: "Welcome", [Views.LOGIN]: "Login", [Views.REGISTER]: "Register", @@ -35,6 +36,7 @@ const notLoggedInMap: Record, ScreenName> = { [Views.COMPLETE_SECURITY]: "CompleteSecurity", [Views.E2E_SETUP]: "E2ESetup", [Views.SOFT_LOGOUT]: "SoftLogout", + [Views.LOCK_STOLEN]: "SessionLockStolen", }; const loggedInPageTypeMap: Record = { diff --git a/src/Views.ts b/src/Views.ts index 447dbeab84..4c7f002d50 100644 --- a/src/Views.ts +++ b/src/Views.ts @@ -20,6 +20,9 @@ enum Views { // trying to re-animate a matrix client or register as a guest. LOADING, + // Another tab holds the lock. + CONFIRM_LOCK_THEFT, + // we are showing the welcome view WELCOME, @@ -48,6 +51,9 @@ enum Views { // We are logged out (invalid token) but have our local state again. The user // should log back in to rehydrate the client. SOFT_LOGOUT, + + // Another instance of the application has started up. We just show an error page. + LOCK_STOLEN, } export default Views; diff --git a/src/components/structures/MatrixChat.tsx b/src/components/structures/MatrixChat.tsx index 9d99f3e39f..401dfc712f 100644 --- a/src/components/structures/MatrixChat.tsx +++ b/src/components/structures/MatrixChat.tsx @@ -147,6 +147,9 @@ import { NotificationColor } from "../../stores/notifications/NotificationColor" import { UserTab } from "../views/dialogs/UserTab"; import { shouldSkipSetupEncryption } from "../../utils/crypto/shouldSkipSetupEncryption"; import { Filter } from "../views/dialogs/spotlight/Filter"; +import { checkSessionLockFree, getSessionLock } from "../../utils/SessionLock"; +import { SessionLockStolenView } from "./auth/SessionLockStolenView"; +import { ConfirmSessionLockTheftView } from "./auth/ConfirmSessionLockTheftView"; // legacy export export { default as Views } from "../../Views"; @@ -307,11 +310,23 @@ export default class MatrixChat extends React.PureComponent { initSentry(SdkConfig.get("sentry")); + if (!checkSessionLockFree()) { + // another instance holds the lock; confirm its theft before proceeding + setTimeout(() => this.setState({ view: Views.CONFIRM_LOCK_THEFT }), 0); + } else { + this.startInitSession(); + } + } + + /** + * Kick off a call to {@link initSession}, and handle any errors + */ + private startInitSession = (): void => { this.initSession().catch((err) => { // TODO: show an error screen, rather than a spinner of doom logger.error("Error initialising Matrix session", err); }); - } + }; /** * Do what we can to establish a Matrix session. @@ -324,6 +339,13 @@ export default class MatrixChat extends React.PureComponent { * * If all else fails, present a login screen. */ private async initSession(): Promise { + // The Rust Crypto SDK will break if two Element instances try to use the same datastore at once, so + // make sure we are the only Element instance in town (on this browser/domain). + if (!(await getSessionLock(() => this.onSessionLockStolen()))) { + // we failed to get the lock. onSessionLockStolen should already have been called, so nothing left to do. + return; + } + // If the user was soft-logged-out, we want to make the SoftLogout component responsible for doing any // token auth (rather than Lifecycle.attemptDelegatedAuthLogin), since SoftLogout knows about submitting the // device ID and preserving the session. @@ -378,6 +400,18 @@ export default class MatrixChat extends React.PureComponent { } } + private async onSessionLockStolen(): Promise { + // switch to the LockStolenView. We deliberately do this immediately, rather than going through the dispatcher, + // because there can be a substantial queue in the dispatcher, and some of the events in it might require an + // active MatrixClient. + await new Promise((resolve) => { + this.setState({ view: Views.LOCK_STOLEN }, resolve); + }); + + // now we can tell the Lifecycle routines to abort any active startup, and to stop the active client. + await Lifecycle.onSessionLockStolen(); + } + private async postLoginSetup(): Promise { const cli = MatrixClientPeg.safeGet(); const cryptoEnabled = cli.isCryptoEnabled(); @@ -574,6 +608,11 @@ export default class MatrixChat extends React.PureComponent { } private onAction = (payload: ActionPayload): void => { + // once the session lock has been stolen, don't try to do anything. + if (this.state.view === Views.LOCK_STOLEN) { + return; + } + // Start the onboarding process for certain actions if (MatrixClientPeg.get()?.isGuest() && ONBOARDING_FLOW_STARTERS.includes(payload.action)) { // This will cause `payload` to be dispatched later, once a @@ -2051,6 +2090,15 @@ export default class MatrixChat extends React.PureComponent { ); + } else if (this.state.view === Views.CONFIRM_LOCK_THEFT) { + view = ( + { + this.setState({ view: Views.LOADING }); + this.startInitSession(); + }} + /> + ); } else if (this.state.view === Views.COMPLETE_SECURITY) { view = ; } else if (this.state.view === Views.E2E_SETUP) { @@ -2157,6 +2205,8 @@ export default class MatrixChat extends React.PureComponent { ); } else if (this.state.view === Views.USE_CASE_SELECTION) { view = => this.onShowPostLoginScreen(useCase)} />; + } else if (this.state.view === Views.LOCK_STOLEN) { + view = ; } else { logger.error(`Unknown view ${this.state.view}`); return null; diff --git a/src/components/structures/auth/ConfirmSessionLockTheftView.tsx b/src/components/structures/auth/ConfirmSessionLockTheftView.tsx new file mode 100644 index 0000000000..36d612d21b --- /dev/null +++ b/src/components/structures/auth/ConfirmSessionLockTheftView.tsx @@ -0,0 +1,51 @@ +/* +Copyright 2023 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +import React from "react"; + +import { _t } from "../../../languageHandler"; +import SdkConfig from "../../../SdkConfig"; +import AccessibleButton from "../../views/elements/AccessibleButton"; + +interface Props { + /** Callback which the view will call if the user confirms they want to use this window */ + onConfirm: () => void; +} + +/** + * Component shown by {@link MatrixChat} when another session is already active in the same browser and we need to + * confirm if we should steal its lock + */ +export function ConfirmSessionLockTheftView(props: Props): JSX.Element { + const brand = SdkConfig.get().brand; + + return ( +
+
+

+ {_t( + '%(brand)s is open in another window. Click "%(label)s" to use %(brand)s here and disconnect the other window.', + { brand, label: _t("action|continue") }, + )} +

+ + + {_t("action|continue")} + +
+
+ ); +} diff --git a/src/components/structures/auth/SessionLockStolenView.tsx b/src/components/structures/auth/SessionLockStolenView.tsx new file mode 100644 index 0000000000..0c0bc01849 --- /dev/null +++ b/src/components/structures/auth/SessionLockStolenView.tsx @@ -0,0 +1,35 @@ +/* +Copyright 2023 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +import React from "react"; + +import SplashPage from "../SplashPage"; +import { _t } from "../../../languageHandler"; +import SdkConfig from "../../../SdkConfig"; + +/** + * Component shown by {@link MatrixChat} when another session is started in the same browser. + */ +export function SessionLockStolenView(): JSX.Element { + const brand = SdkConfig.get().brand; + + return ( + +

{_t("common|error")}

+

{_t("%(brand)s has been opened in another tab.", { brand })}

+
+ ); +} diff --git a/src/i18n/strings/en_EN.json b/src/i18n/strings/en_EN.json index e1bc2ee44e..23f763824f 100644 --- a/src/i18n/strings/en_EN.json +++ b/src/i18n/strings/en_EN.json @@ -3406,6 +3406,7 @@ "Device verified": "Device verified", "Really reset verification keys?": "Really reset verification keys?", "Skip verification for now": "Skip verification for now", + "%(brand)s is open in another window. Click \"%(label)s\" to use %(brand)s here and disconnect the other window.": "%(brand)s is open in another window. Click \"%(label)s\" to use %(brand)s here and disconnect the other window.", "Too many attempts in a short time. Wait some time before trying again.": "Too many attempts in a short time. Wait some time before trying again.", "Too many attempts in a short time. Retry after %(timeout)s.": "Too many attempts in a short time. Retry after %(timeout)s.", "Signing out your devices will delete the message encryption keys stored on them, making encrypted chat history unreadable.": "Signing out your devices will delete the message encryption keys stored on them, making encrypted chat history unreadable.", @@ -3448,6 +3449,7 @@ "Registration Successful": "Registration Successful", "Host account on": "Host account on", "Decide where your account is hosted": "Decide where your account is hosted", + "%(brand)s has been opened in another tab.": "%(brand)s has been opened in another tab.", "It looks like you don't have a Security Key or any other devices you can verify against. This device will not be able to access old encrypted messages. In order to verify your identity on this device, you'll need to reset your verification keys.": "It looks like you don't have a Security Key or any other devices you can verify against. This device will not be able to access old encrypted messages. In order to verify your identity on this device, you'll need to reset your verification keys.", "Proceed with reset": "Proceed with reset", "Verify with Security Key or Phrase": "Verify with Security Key or Phrase", diff --git a/src/utils/SessionLock.ts b/src/utils/SessionLock.ts index ce1a9ced84..76780b543c 100644 --- a/src/utils/SessionLock.ts +++ b/src/utils/SessionLock.ts @@ -177,7 +177,7 @@ export async function getSessionLock(onNewInstance: () => Promise): Promis // and, once it has done so, stop pinging the lock. if (lockServicer !== null) { - clearInterval(lockServicer); + window.clearInterval(lockServicer); } window.localStorage.removeItem(SESSION_LOCK_CONSTANTS.STORAGE_ITEM_PING); window.localStorage.removeItem(SESSION_LOCK_CONSTANTS.STORAGE_ITEM_OWNER); @@ -233,7 +233,7 @@ export async function getSessionLock(onNewInstance: () => Promise): Promis // claim the lock, and kick off a background process to service it every 5 seconds serviceLock(); - lockServicer = setInterval(serviceLock, 5000); + lockServicer = window.setInterval(serviceLock, 5000); // Now add a listener for other claimants to the lock. window.addEventListener("storage", onStorageEvent); diff --git a/test/components/structures/MatrixChat-test.tsx b/test/components/structures/MatrixChat-test.tsx index 233814019c..c01b0025ab 100644 --- a/test/components/structures/MatrixChat-test.tsx +++ b/test/components/structures/MatrixChat-test.tsx @@ -25,6 +25,7 @@ import { completeAuthorizationCodeGrant } from "matrix-js-sdk/src/oidc/authorize import { logger } from "matrix-js-sdk/src/logger"; import { OidcError } from "matrix-js-sdk/src/oidc/error"; import { BearerTokenResponse } from "matrix-js-sdk/src/oidc/validate"; +import { defer, sleep } from "matrix-js-sdk/src/utils"; import MatrixChat from "../../../src/components/structures/MatrixChat"; import * as StorageManager from "../../../src/utils/StorageManager"; @@ -37,7 +38,9 @@ import { flushPromises, getMockClientWithEventEmitter, mockClientMethodsUser, + MockClientWithEventEmitter, mockPlatformPeg, + resetJsDomAfterEach, } from "../../test-utils"; import * as leaveRoomUtils from "../../../src/utils/leave-behaviour"; import * as voiceBroadcastUtils from "../../../src/voice-broadcast/utils/cleanUpBroadcasts"; @@ -47,6 +50,7 @@ import { Call } from "../../../src/models/Call"; import { PosthogAnalytics } from "../../../src/PosthogAnalytics"; import PlatformPeg from "../../../src/PlatformPeg"; import EventIndexPeg from "../../../src/indexing/EventIndexPeg"; +import * as Lifecycle from "../../../src/Lifecycle"; jest.mock("matrix-js-sdk/src/oidc/authorize", () => ({ completeAuthorizationCodeGrant: jest.fn(), @@ -137,7 +141,23 @@ describe("", () => { render(); // make test results readable - filterConsole("Failed to parse localStorage object"); + filterConsole( + "Failed to parse localStorage object", + "Sync store cannot be used on this browser", + "Crypto store cannot be used on this browser", + "Storage consistency checks failed", + "LegacyCallHandler: missing ", () => { await clearAllModals(); }); + resetJsDomAfterEach(); + afterEach(() => { jest.restoreAllMocks(); - localStorage.clear(); - sessionStorage.clear(); // emit a loggedOut event so that all of the Store singletons forget about their references to the mock client defaultDispatcher.dispatch({ action: Action.OnLoggedOut }); @@ -206,13 +226,8 @@ describe("", () => { }, }; - beforeEach(() => { - localStorage.setItem("mx_hs_url", serverConfig.hsUrl); - localStorage.setItem("mx_is_url", serverConfig.isUrl); - localStorage.setItem("mx_access_token", accessToken); - localStorage.setItem("mx_user_id", userId); - localStorage.setItem("mx_device_id", deviceId); - + beforeEach(async () => { + await populateStorageForSession(); jest.spyOn(StorageManager, "idbLoad").mockImplementation(async (table, key) => { const safeKey = Array.isArray(key) ? key[0] : key; return mockidb[table]?.[safeKey]; @@ -516,12 +531,8 @@ describe("", () => { describe("with a soft-logged-out session", () => { const mockidb: Record> = {}; - beforeEach(() => { - localStorage.setItem("mx_hs_url", serverConfig.hsUrl); - localStorage.setItem("mx_is_url", serverConfig.isUrl); - localStorage.setItem("mx_access_token", accessToken); - localStorage.setItem("mx_user_id", userId); - localStorage.setItem("mx_device_id", deviceId); + beforeEach(async () => { + await populateStorageForSession(); localStorage.setItem("mx_soft_logout", "true"); mockClient.loginFlows.mockResolvedValue({ flows: [{ type: "m.login.password" }] }); @@ -742,6 +753,7 @@ describe("", () => { localStorage.removeItem("mx_sso_hs_url"); const localStorageGetSpy = jest.spyOn(localStorage.__proto__, "getItem"); getComponent({ realQueryParams }); + await flushPromises(); expect(localStorageGetSpy).toHaveBeenCalledWith("mx_sso_hs_url"); expect(localStorageGetSpy).toHaveBeenCalledWith("mx_sso_is_url"); @@ -759,6 +771,7 @@ describe("", () => { it("should attempt token login", async () => { getComponent({ realQueryParams }); + await flushPromises(); expect(loginClient.login).toHaveBeenCalledWith("m.login.token", { initial_device_display_name: undefined, @@ -1093,4 +1106,138 @@ describe("", () => { }); }); }); + + describe("Multi-tab lockout", () => { + afterEach(() => { + Lifecycle.setSessionLockNotStolen(); + }); + + it("waits for other tab to stop during startup", async () => { + fetchMock.get("/welcome.html", { body: "

Hello

" }); + jest.spyOn(Lifecycle, "attemptDelegatedAuthLogin"); + + // simulate an active window + localStorage.setItem("react_sdk_session_lock_ping", String(Date.now())); + + const rendered = getComponent({}); + await flushPromises(); + expect(rendered.container).toMatchSnapshot(); + + // user confirms + rendered.getByRole("button", { name: "Continue" }).click(); + await flushPromises(); + + // we should have claimed the session, but gone no further + expect(Lifecycle.attemptDelegatedAuthLogin).not.toHaveBeenCalled(); + const sessionId = localStorage.getItem("react_sdk_session_lock_claimant"); + expect(sessionId).toEqual(expect.stringMatching(/./)); + expect(rendered.container).toMatchSnapshot(); + + // the other tab shuts down + localStorage.removeItem("react_sdk_session_lock_ping"); + // fire the storage event manually, because writes to localStorage from the same javascript context don't + // fire it automatically + window.dispatchEvent(new StorageEvent("storage", { key: "react_sdk_session_lock_ping" })); + + // startup continues + await flushPromises(); + expect(Lifecycle.attemptDelegatedAuthLogin).toHaveBeenCalled(); + + // should just show the welcome screen + await rendered.findByText("Hello"); + expect(rendered.container).toMatchSnapshot(); + }); + + describe("shows the lockout page when a second tab opens", () => { + beforeEach(() => { + // make sure we start from a clean DOM for each of these tests + document.body.replaceChildren(); + }); + + function simulateSessionLockClaim() { + localStorage.setItem("react_sdk_session_lock_claimant", "testtest"); + window.dispatchEvent(new StorageEvent("storage", { key: "react_sdk_session_lock_claimant" })); + } + + it("after a session is restored", async () => { + await populateStorageForSession(); + + const client = getMockClientWithEventEmitter(getMockClientMethods()); + jest.spyOn(MatrixJs, "createClient").mockReturnValue(client); + client.getProfileInfo.mockResolvedValue({ displayname: "Ernie" }); + + const rendered = getComponent({}); + await waitForSyncAndLoad(client, true); + rendered.getByText("Welcome Ernie"); + + // we're now at the welcome page. Another session wants the lock... + simulateSessionLockClaim(); + await flushPromises(); + expect(rendered.container).toMatchSnapshot(); + }); + + it("while we were waiting for the lock ourselves", async () => { + // simulate there already being one session + localStorage.setItem("react_sdk_session_lock_ping", String(Date.now())); + + const rendered = getComponent({}); + await flushPromises(); + + // user confirms continue + rendered.getByRole("button", { name: "Continue" }).click(); + await flushPromises(); + expect(rendered.getByTestId("spinner")).toBeInTheDocument(); + + // now a third session starts + simulateSessionLockClaim(); + await flushPromises(); + expect(rendered.container).toMatchSnapshot(); + }); + + it("while we are checking the sync store", async () => { + const rendered = getComponent({}); + await flushPromises(); + expect(rendered.getByTestId("spinner")).toBeInTheDocument(); + + // now a third session starts + simulateSessionLockClaim(); + await flushPromises(); + expect(rendered.container).toMatchSnapshot(); + }); + + it("during crypto init", async () => { + await populateStorageForSession(); + + const client = new MockClientWithEventEmitter({ + initCrypto: jest.fn(), + ...getMockClientMethods(), + }) as unknown as Mocked; + jest.spyOn(MatrixJs, "createClient").mockReturnValue(client); + + // intercept initCrypto and have it block until we complete the deferred + const initCryptoCompleteDefer = defer(); + const initCryptoCalled = new Promise((resolve) => { + client.initCrypto.mockImplementation(() => { + resolve(); + return initCryptoCompleteDefer.promise; + }); + }); + + const rendered = getComponent({}); + await initCryptoCalled; + console.log("initCrypto called"); + + simulateSessionLockClaim(); + await flushPromises(); + + // now we should see the error page + rendered.getByText("Test has been opened in another tab."); + + // let initCrypto complete, and check we don't get a modal + initCryptoCompleteDefer.resolve(); + await sleep(10); // Modals take a few ms to appear + expect(document.body).toMatchSnapshot(); + }); + }); + }); }); diff --git a/test/components/structures/__snapshots__/MatrixChat-test.tsx.snap b/test/components/structures/__snapshots__/MatrixChat-test.tsx.snap index a2ca722e2c..baf1a33410 100644 --- a/test/components/structures/__snapshots__/MatrixChat-test.tsx.snap +++ b/test/components/structures/__snapshots__/MatrixChat-test.tsx.snap @@ -1,5 +1,176 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[` Multi-tab lockout shows the lockout page when a second tab opens after a session is restored 1`] = ` +
+
+

+ Error +

+

+ Test has been opened in another tab. +

+
+
+`; + +exports[` Multi-tab lockout shows the lockout page when a second tab opens during crypto init 1`] = ` + +
+
+

+ Error +

+

+ Test has been opened in another tab. +

+
+
+ +`; + +exports[` Multi-tab lockout shows the lockout page when a second tab opens while we are checking the sync store 1`] = ` +
+
+

+ Error +

+

+ Test has been opened in another tab. +

+
+
+`; + +exports[` Multi-tab lockout shows the lockout page when a second tab opens while we were waiting for the lock ourselves 1`] = ` +
+
+

+ Error +

+

+ Test has been opened in another tab. +

+
+
+`; + +exports[` Multi-tab lockout waits for other tab to stop during startup 1`] = ` +
+
+
+

+ Test is open in another window. Click "Continue" to use Test here and disconnect the other window. +

+
+ Continue +
+
+
+
+`; + +exports[` Multi-tab lockout waits for other tab to stop during startup 2`] = ` +
+
+
+
+
+
+
+`; + +exports[` Multi-tab lockout waits for other tab to stop during startup 3`] = ` +
+
+
+
+
+
+

+ Hello +

+
+
+
+ +
+
+
+ +
+
+`; + exports[` should render spinner while app is loading 1`] = `
void)[] = []; + + beforeEach(() => { + // intercept `window.addEventListener` and `document.addEventListener`, and register 'removeEventListener' calls + // for `afterEach`. + for (const obj of [window, document]) { + const originalFn = obj.addEventListener; + obj.addEventListener = (...args: Parameters) => { + originalFn.apply(obj, args); + resetCalls.push(() => obj.removeEventListener(...args)); + }; + + // also reset the intercept after the test + resetCalls.push(() => { + obj.addEventListener = originalFn; + }); + } + + // intercept setTimeout and setInterval, and clear them at the end. + // + // *Don't* use jest.spyOn for this because it makes the DOM testing library think we are using fake timers. + // + ["setTimeout", "setInterval"].forEach((name) => { + const originalFn = window[name as keyof Window]; + // @ts-ignore assignment to read-only property + window[name] = (...args) => { + const result = originalFn.apply(window, args); + resetCalls.push(() => window.clearTimeout(result)); + return result; + }; + resetCalls.push(() => { + // @ts-ignore assignment to read-only property + window[name] = originalFn; + }); + }); + }); + + afterEach(() => { + // clean up event listeners, timers, etc. + for (const call of resetCalls) { + call(); + } + resetCalls.splice(0); + + // other cleanup + localStorage.clear(); + sessionStorage.clear(); + }); +} diff --git a/test/utils/SessionLock-test.ts b/test/utils/SessionLock-test.ts index 17d4da6257..6863b93edf 100644 --- a/test/utils/SessionLock-test.ts +++ b/test/utils/SessionLock-test.ts @@ -15,46 +15,23 @@ limitations under the License. */ import { checkSessionLockFree, getSessionLock, SESSION_LOCK_CONSTANTS } from "../../src/utils/SessionLock"; +import { resetJsDomAfterEach } from "../test-utils"; describe("SessionLock", () => { const otherWindows: Array = []; - let windowEventListeners: Array<[string, any]>; - let documentEventListeners: Array<[string, any]>; beforeEach(() => { jest.useFakeTimers({ now: 1000 }); - - // keep track of the registered event listeners, so that we can unregister them in `afterEach` - windowEventListeners = []; - const realWindowAddEventListener = window.addEventListener.bind(window); - jest.spyOn(window, "addEventListener").mockImplementation((type, listener, options) => { - const res = realWindowAddEventListener(type, listener, options); - windowEventListeners.push([type, listener]); - return res; - }); - - documentEventListeners = []; - const realDocumentAddEventListener = document.addEventListener.bind(document); - jest.spyOn(document, "addEventListener").mockImplementation((type, listener, options) => { - const res = realDocumentAddEventListener(type, listener, options); - documentEventListeners.push([type, listener]); - return res; - }); }); afterEach(() => { // shut down other windows created by `createWindow` otherWindows.forEach((window) => window.close()); otherWindows.splice(0); - - // remove listeners on our own window - windowEventListeners.forEach(([type, listener]) => window.removeEventListener(type, listener)); - documentEventListeners.forEach(([type, listener]) => document.removeEventListener(type, listener)); - - localStorage.clear(); - jest.restoreAllMocks(); }); + resetJsDomAfterEach(); + it("A single instance starts up normally", async () => { const onNewInstance = jest.fn(); const result = await getSessionLock(onNewInstance); diff --git a/yarn.lock b/yarn.lock index 0d072ee917..8d49728c1a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1848,10 +1848,10 @@ resolved "https://registry.yarnpkg.com/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz#497c67a1cef50d1a2459ba60f315e448d2ad87fe" integrity sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q== -"@matrix-org/analytics-events@^0.6.0": - version "0.6.0" - resolved "https://registry.yarnpkg.com/@matrix-org/analytics-events/-/analytics-events-0.6.0.tgz#6552882f94d026f13da25d49e2a208287521c275" - integrity sha512-bTvNpp8LkC/2sItHABd1vGHdB8iclAcdlIYrL0Cn6qT+aohpdjb1wZ0dhUcx3NK5Q98IduI43RVH33V4Li/X0A== +"@matrix-org/analytics-events@^0.7.0": + version "0.7.0" + resolved "https://registry.yarnpkg.com/@matrix-org/analytics-events/-/analytics-events-0.7.0.tgz#a9ea47209473d1075704db4eabb6d94c8d99be25" + integrity sha512-9M1ESpFbXaU0v8Kzm0N61eAiVymv0tlXP5FfqCUH+BDP7DmW/tqyIpDs9ooUxXoFg1bBEQaRy/xOyO15ZykCAg== "@matrix-org/emojibase-bindings@^1.1.2": version "1.1.2"