Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Lock out the first tab if Element is opened in a second tab. #11425

Merged
merged 7 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions res/css/_components.pcss
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
30 changes: 30 additions & 0 deletions res/css/structures/auth/_ConfirmSessionLockTheftView.pcss
Original file line number Diff line number Diff line change
@@ -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;
}
30 changes: 30 additions & 0 deletions res/css/structures/auth/_SessionLockStolenView.pcss
Original file line number Diff line number Diff line change
@@ -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;
}
}
50 changes: 50 additions & 0 deletions src/Lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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;
Expand Down Expand Up @@ -153,6 +188,9 @@ export async function loadSession(opts: ILoadSessionOpts = {}): Promise<boolean>
if (success) {
return true;
}
if (sessionLockStolen) {
return false;
}

if (enableGuest && guestHsUrl) {
return registerAsGuest(guestHsUrl, guestIsUrl, defaultDeviceDisplayName);
Expand All @@ -166,6 +204,12 @@ export async function loadSession(opts: ILoadSessionOpts = {}): Promise<boolean>
// 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);
}
}
Expand Down Expand Up @@ -719,6 +763,7 @@ export async function hydrateSession(credentials: IMatrixClientCreds): Promise<M
* @returns {Promise} promise which resolves to the new MatrixClient once it has been started
*/
async function doSetLoggedIn(credentials: IMatrixClientCreds, clearStorageEnabled: boolean): Promise<MatrixClient> {
checkSessionLock();
credentials.guest = Boolean(credentials.guest);

const softLogout = isSoftLogout();
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();

Expand Down
2 changes: 2 additions & 0 deletions src/PosthogTrackers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type InteractionName = InteractionEvent["name"];

const notLoggedInMap: Record<Exclude<Views, Views.LOGGED_IN>, ScreenName> = {
[Views.LOADING]: "Loading",
[Views.CONFIRM_LOCK_THEFT]: "ConfirmStartup",
[Views.WELCOME]: "Welcome",
[Views.LOGIN]: "Login",
[Views.REGISTER]: "Register",
Expand All @@ -35,6 +36,7 @@ const notLoggedInMap: Record<Exclude<Views, Views.LOGGED_IN>, ScreenName> = {
[Views.COMPLETE_SECURITY]: "CompleteSecurity",
[Views.E2E_SETUP]: "E2ESetup",
[Views.SOFT_LOGOUT]: "SoftLogout",
[Views.LOCK_STOLEN]: "SessionLockStolen",
};

const loggedInPageTypeMap: Record<PageType, ScreenName> = {
Expand Down
6 changes: 6 additions & 0 deletions src/Views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Expand Down Expand Up @@ -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;
52 changes: 51 additions & 1 deletion src/components/structures/MatrixChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -307,11 +310,23 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {

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.
Expand All @@ -324,6 +339,13 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
* * If all else fails, present a login screen.
*/
private async initSession(): Promise<void> {
// 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.
Expand Down Expand Up @@ -378,6 +400,18 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
}

private async onSessionLockStolen(): Promise<void> {
// 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<void>((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<void> {
const cli = MatrixClientPeg.safeGet();
const cryptoEnabled = cli.isCryptoEnabled();
Expand Down Expand Up @@ -574,6 +608,11 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}

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
Expand Down Expand Up @@ -2051,6 +2090,15 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
<Spinner />
</div>
);
} else if (this.state.view === Views.CONFIRM_LOCK_THEFT) {
view = (
<ConfirmSessionLockTheftView
onConfirm={() => {
this.setState({ view: Views.LOADING });
this.startInitSession();
}}
/>
);
} else if (this.state.view === Views.COMPLETE_SECURITY) {
view = <CompleteSecurity onFinished={this.onCompleteSecurityE2eSetupFinished} />;
} else if (this.state.view === Views.E2E_SETUP) {
Expand Down Expand Up @@ -2157,6 +2205,8 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
);
} else if (this.state.view === Views.USE_CASE_SELECTION) {
view = <UseCaseSelection onFinished={(useCase): Promise<void> => this.onShowPostLoginScreen(useCase)} />;
} else if (this.state.view === Views.LOCK_STOLEN) {
view = <SessionLockStolenView />;
} else {
logger.error(`Unknown view ${this.state.view}`);
return null;
Expand Down
51 changes: 51 additions & 0 deletions src/components/structures/auth/ConfirmSessionLockTheftView.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="mx_ConfirmSessionLockTheftView">
<div className="mx_ConfirmSessionLockTheftView_body">
<p>
{_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") },
)}
</p>

<AccessibleButton kind="primary" onClick={props.onConfirm}>
{_t("action|continue")}
</AccessibleButton>
</div>
</div>
);
}
Loading
Loading