Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logout sync #329

Draft
wants to merge 4 commits into
base: develop
Choose a base branch
from
Draft
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
44 changes: 39 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"@solana/spl-token": "0.2.0",
"@solana/web3.js": "^1.42.0",
"@toruslabs/base-controllers": "^2.1.0",
"@toruslabs/broadcast-channel": "^5.0.2",
"@toruslabs/broadcast-channel": "^6.1.0",
"@toruslabs/eccrypto": "^1.1.8",
"@toruslabs/http-helpers": "^3.0.0",
"@toruslabs/loglevel-sentry": "^4.0.0",
Expand Down
37 changes: 34 additions & 3 deletions src/controllers/TorusController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
TX_EVENTS,
UserInfo,
} from "@toruslabs/base-controllers";
import { BroadcastChannel } from "@toruslabs/broadcast-channel";
import eccrypto from "@toruslabs/eccrypto";
import { LOGIN_PROVIDER_TYPE } from "@toruslabs/openlogin";
import {
Expand Down Expand Up @@ -96,8 +97,9 @@ import {
TorusControllerState,
TransactionChannelDataType,
} from "@/utils/enums";
import { getRandomWindowId, getRelaySigned, getUserLanguage, isMain, normalizeJson, parseJwt } from "@/utils/helpers";
import { constructTokenData } from "@/utils/instructionDecoder";
import { getLogoutBcChannelName, getRandomWindowId, getRelaySigned, getUserLanguage, isMain, normalizeJson, parseJwt } from "@/utils/helpers";
import { constructTokenData } from "@/utils/instruction_decoder";
import { LogoutMessage } from "@/utils/interfaces";
import TorusStorageLayer from "@/utils/tkey/storageLayer";
import { TOPUP } from "@/utils/topup";

Expand Down Expand Up @@ -216,6 +218,8 @@ export default class TorusController extends BaseController<TorusControllerConfi

private instanceId = "";

private logoutBcAttached!: boolean;

constructor({ _config, _state }: { _config: Partial<TorusControllerConfig>; _state: Partial<TorusControllerState> }) {
super({ config: _config, state: _state });
}
Expand Down Expand Up @@ -774,7 +778,7 @@ export default class TorusController extends BaseController<TorusControllerConfi
logout(req: JRPCRequest<[]>, res: JRPCResponse<boolean>, _: JRPCEngineNextCallback, end: JRPCEngineEndCallback): void {
this.handleLogout();
res.result = true;
end();
setTimeout(() => end(), 100); // Make sure all async ops are executed.
}

public handleLogout(): void {
Expand Down Expand Up @@ -1384,6 +1388,7 @@ export default class TorusController extends BaseController<TorusControllerConfi
// This call sync and refresh blockchain state
this.setSelectedAccount(selectedAddress, true);

this.attachLogoutBC();
return true;
} catch (e) {
log.error(e, "Error restoring state after successful decrypt!");
Expand All @@ -1401,6 +1406,32 @@ export default class TorusController extends BaseController<TorusControllerConfi
return this.preferencesController.getDappList();
}

attachLogoutBC() {
if (this.logoutBcAttached) {
log.warn("Logout BC already attached");
return;
}

const channelName = getLogoutBcChannelName(this.origin, this.userInfo);
const bc = new BroadcastChannel<LogoutMessage>(channelName);
this.logoutBcAttached = true;

const thisInstance = this.instanceId.slice(0, 8);
const eventListener = (msg: LogoutMessage) => {
if (thisInstance === msg.instanceId) return;
bc.removeEventListener("message", eventListener);
bc.close()
.then(() => {
this.logoutBcAttached = false;
this.emit("logout", true);
if (!isMain) this.notifyEmbedLogout();
return null;
})
.catch((err) => log.error("broadcastchannel close error", err));
};
bc.addEventListener("message", eventListener);
}

private async providerRequestAccounts(req: JRPCRequest<unknown>) {
const accounts = await this.requestAccounts(req);

Expand Down
15 changes: 10 additions & 5 deletions src/modules/controllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import { i18n } from "@/plugins/i18nPlugin";
import installStorePlugin from "@/plugins/persistPlugin";
import { WALLET_SUPPORTED_NETWORKS } from "@/utils/const";
import { CONTROLLER_MODULE_KEY, LOCAL_STORAGE_KEY, TorusControllerState } from "@/utils/enums";
import { delay, isMain } from "@/utils/helpers";
import { delay, isMain, logoutWithBC } from "@/utils/helpers";
import { NAVBAR_MESSAGES } from "@/utils/messages";

import store from "../store";
Expand Down Expand Up @@ -413,9 +413,13 @@ class ControllerModule extends VuexModule {
}
});

this.torus.on("logout", () => {
// logoutWithBC();
this.logout();
this.torus.on("logout", (fromBC?: boolean) => {
this.logout(fromBC);
});
this.torus.on("LOGIN_RESPONSE", (message?: string, address?: string) => {
if (message === null && address) {
this.torus.attachLogoutBC();
}
});
this.setInstanceId(instanceId);

Expand Down Expand Up @@ -486,10 +490,11 @@ class ControllerModule extends VuexModule {
}

@Action
async logout(): Promise<void> {
async logout(fromBC?: boolean): Promise<void> {
if (isMain && this.selectedAddress) {
this.openloginLogout();
}
if (!fromBC) await logoutWithBC(this.torus.origin, this.instanceId, this.torus.userInfo);
const initialState = { ...cloneDeep(DEFAULT_STATE) };
// this.updateTorusState(initialState);

Expand Down
2 changes: 2 additions & 0 deletions src/utils/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export const WALLET_SUPPORTED_NETWORKS = {
},
};

export const CHANNEL_LOGOUT = "LOGOUT_WINDOWS_CHANNEL";

// testnet: {
// blockExplorerUrl: "?cluster=testnet",
// chainId: "0x2",
Expand Down
28 changes: 23 additions & 5 deletions src/utils/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { concatSig } from "@toruslabs/base-controllers";
import { concatSig, UserInfo } from "@toruslabs/base-controllers";
import { BroadcastChannel } from "@toruslabs/broadcast-channel";
import { post } from "@toruslabs/http-helpers";
import bowser from "bowser";
Expand All @@ -10,6 +10,7 @@ import config from "@/config";
import { addToast } from "@/modules/app";

import { LOCALE_EN, LOGIN_CONFIG, STORAGE_TYPE } from "./enums";
import { LogoutMessage } from "./interfaces";

export function getStorage(key: STORAGE_TYPE): Storage | undefined {
if (config.isStorageAvailable[key]) return window[key];
Expand Down Expand Up @@ -190,10 +191,27 @@ export const parseJwt = (token: string) => {
return JSON.parse(jsonPayload);
};

export const logoutWithBC = async () => {
const bc = new BroadcastChannel("LOGOUT_WINDOWS_CHANNEL");
await bc.postMessage("logout");
bc.close();
// Get a sufficiently unique channel name for
// the current window
export const getLogoutBcChannelName = (origin: string, userInfo: UserInfo) => {
const browser = bowser.getParser(window.navigator.userAgent);
const browserId = `${browser.getBrowserName()}_${browser.getBrowserVersion}`;
const platformId = `${browser.getOSName()}_${browser.getPlatformType()}`;
const userId = `${userInfo.verifier}_${userInfo.verifierId}`;
const id = `${userId}_${origin}_${browserId}_${platformId}`;
const hash = keccak(Buffer.from(id)).toString("hex");
return hash;
};

export const logoutWithBC = async (origin: string, _instanceId: string, userInfo: UserInfo) => {
const channelName = getLogoutBcChannelName(origin, userInfo);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const bc = new BroadcastChannel<LogoutMessage>(`${channelName}`, { server: { timeout: 5 } });
const timestamp = new Date().getTime();
const instanceId = _instanceId.slice(0, 8);
await bc.postMessage({ instanceId, timestamp });
await bc.close();
};

export function getBrowserKey() {
Expand Down
5 changes: 5 additions & 0 deletions src/utils/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,8 @@ export interface FinalTxData {
totalFiatCost: string;
isGasless: boolean;
}

export interface LogoutMessage {
instanceId: string;
timestamp: number;
}