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

Allow allowlisted accounts to connect/requestAccounts without unlocking #373

Closed
wants to merge 5 commits into from
Closed
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
6 changes: 6 additions & 0 deletions packages/browser-wallet/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Changed

- Allow allowlisted sites to connect/requestAccounts/getSelectedChain/getMostRecentlySelectedAccount without unlocking. The user will still be prompted to unlock if other requests are made.

## 1.0.7

### Added
Expand Down
86 changes: 28 additions & 58 deletions packages/browser-wallet/src/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
storedConnectedSites,
storedSelectedAccount,
storedCurrentNetwork,
sessionPasscode,
sessionOpenPrompt,
storedAcceptedTerms,
getGenesisHash,
Expand Down Expand Up @@ -40,17 +39,12 @@ import { sendCredentialHandler } from './credential-deployment';
import { startRecovery, setupRecoveryHandler } from './recovery';
import { createIdProofHandler, runIfValidProof } from './id-proof';

const rpcCallNotAllowedMessage = 'RPC Call can only be performed by whitelisted sites';
const walletLockedMessage = 'The wallet is locked';
async function isWalletLocked(): Promise<boolean> {
const passcode = await sessionPasscode.get();
return !passcode;
}
const rpcCallNotAllowedMessage = 'RPC Call can only be performed by allowlisted sites';

/**
* Determines whether the given url has been whitelisted by any account.
* Determines whether the given url has been allowlisted by any account.
*/
async function isWhiteListedForAnyAccount(url: string): Promise<boolean> {
async function isAllowlistedForAnyAccount(url: string): Promise<boolean> {
const urlOrigin = new URL(url).origin;
const connectedSites = await storedConnectedSites.get();
if (connectedSites) {
Expand All @@ -66,13 +60,8 @@ async function performRpcCall(
onSuccess: (response: string | undefined) => void,
onFailure: (response: string) => void
) {
const locked = await isWalletLocked();
if (locked) {
onFailure(walletLockedMessage);
}

const isWhiteListed = await isWhiteListedForAnyAccount(senderUrl);
if (isWhiteListed) {
const isAllowlisted = await isAllowlistedForAnyAccount(senderUrl);
if (isAllowlisted) {
const url = (await storedCurrentNetwork.get())?.jsonRpcUrl;
if (!url) {
onFailure('No JSON-RPC URL available');
Expand Down Expand Up @@ -101,8 +90,8 @@ async function exportGRPCLocation(
onSuccess: (response: string | undefined) => void,
onFailure: (response: string) => void
): Promise<void> {
const isWhiteListed = await isWhiteListedForAnyAccount(callerUrl);
if (!isWhiteListed) {
const isAllowlisted = await isAllowlistedForAnyAccount(callerUrl);
if (!isAllowlisted) {
return onFailure(rpcCallNotAllowedMessage);
}
const network = await storedCurrentNetwork.get();
Expand Down Expand Up @@ -252,26 +241,25 @@ bgMessageHandler.handleMessage(createMessageTypeFilter(MessageType.GrpcRequest),

bgMessageHandler.handleMessage(createMessageTypeFilter(InternalMessageType.CreateIdProof), createIdProofHandler);

const NOT_WHITELISTED = 'Site is not whitelisted';
const NOT_ALLOWLISTED = 'Site is not allowlisted';

/**
* Run condition which looks up URL in connected sites for the provided account. Runs handler if URL is included in connected sites.
*/
const runIfWhitelisted: RunCondition<MessageStatusWrapper<undefined>> = async (msg, sender) => {
const runIfAllowlisted: RunCondition<MessageStatusWrapper<undefined>> = async (msg, sender) => {
const { accountAddress } = msg.payload;
const connectedSites = await storedConnectedSites.get();
const locked = await isWalletLocked();

if (!accountAddress || connectedSites === undefined || locked) {
return { run: false, response: { success: false, message: NOT_WHITELISTED } };
if (!accountAddress || connectedSites === undefined) {
return { run: false, response: { success: false, message: NOT_ALLOWLISTED } };
}

const accountConnectedSites = connectedSites[accountAddress] ?? [];
if (sender.url !== undefined && accountConnectedSites.includes(new URL(sender.url).origin)) {
return { run: true };
}

return { run: false, response: { success: false, message: NOT_WHITELISTED } };
return { run: false, response: { success: false, message: NOT_ALLOWLISTED } };
};

const INCORRECT_SIGN_MESSAGE_FORMAT = 'The given message does not have correct format.';
Expand Down Expand Up @@ -349,13 +337,12 @@ async function findPrioritizedAccountConnectedToSite(url: string): Promise<strin
* Run condition that runs the handler if the wallet is non-empty (an account exists), and no
* account in the wallet is connected to the sender URL.
*
* 1. If the wallet is locked, then do run.
* 1. If no selected account exists (the wallet is empty), then do not run and return undefined.
* 1. Else if the selected account is connected to the sender URL, then do not run and return the selected account address.
* 1. Else if any other account is connected to the sender URL, then do not run and return that account's address.
* 1. Else run the handler.
*/
const runIfNotWhitelisted: RunCondition<MessageStatusWrapper<string | undefined>> = async (_msg, sender) => {
const runIfNotAllowlisted: RunCondition<MessageStatusWrapper<string | undefined>> = async (_msg, sender) => {
if (!sender.url) {
throw new Error('Expected URL to be available for sender.');
}
Expand All @@ -367,11 +354,6 @@ const runIfNotWhitelisted: RunCondition<MessageStatusWrapper<string | undefined>
return { run: false, response: { success: false, message: 'No account in the wallet' } };
}

const locked = await isWalletLocked();
if (locked) {
return { run: true };
}

const accountConnectedToSite = await findPrioritizedAccountConnectedToSite(sender.url);
if (accountConnectedToSite) {
return { run: false, response: { success: true, result: accountConnectedToSite } };
Expand Down Expand Up @@ -411,16 +393,10 @@ const handleConnectionResponse: HandleResponse<MessageStatusWrapper<string | und
* Callback method which returns the prioritized account's address.
*/
const getMostRecentlySelectedAccountHandler: ExtensionMessageHandler = (_msg, sender, respond) => {
isWalletLocked().then((locked) => {
if (locked) {
respond(undefined);
} else {
if (!sender.url) {
throw new Error('Expected URL to be available for sender.');
}
findPrioritizedAccountConnectedToSite(sender.url).then(respond);
}
});
if (!sender.url) {
throw new Error('Expected URL to be available for sender.');
}
findPrioritizedAccountConnectedToSite(sender.url).then(respond);
return true;
};

Expand All @@ -430,19 +406,13 @@ bgMessageHandler.handleMessage(
);

const getSelectedChainHandler: ExtensionMessageHandler = (_msg, sender, respond) => {
isWalletLocked().then((locked) => {
if (locked) {
respond(undefined);
} else {
if (!sender.url) {
throw new Error('Expected URL to be available for sender.');
}
if (!sender.url) {
throw new Error('Expected URL to be available for sender.');
}
getGenesisHash()
.then(respond)
.catch(() => respond(undefined));

getGenesisHash()
.then(respond)
.catch(() => respond(undefined));
}
});
return true;
};

Expand All @@ -465,39 +435,39 @@ function withPromptEnd() {
forwardToPopup(
MessageType.Connect,
InternalMessageType.Connect,
runConditionComposer(runIfNotWhitelisted, withPromptStart),
runConditionComposer(runIfNotAllowlisted, withPromptStart),
handleConnectMessage,
handleConnectionResponse,
withPromptEnd
);
forwardToPopup(
MessageType.SendTransaction,
InternalMessageType.SendTransaction,
runConditionComposer(runIfWhitelisted, ensureTransactionPayloadParse, withPromptStart),
runConditionComposer(runIfAllowlisted, ensureTransactionPayloadParse, withPromptStart),
appendUrlToPayload,
undefined,
withPromptEnd
);
forwardToPopup(
MessageType.SignMessage,
InternalMessageType.SignMessage,
runConditionComposer(runIfWhitelisted, ensureMessageWithSchemaParse, withPromptStart),
runConditionComposer(runIfAllowlisted, ensureMessageWithSchemaParse, withPromptStart),
appendUrlToPayload,
undefined,
withPromptEnd
);
forwardToPopup(
MessageType.AddTokens,
InternalMessageType.AddTokens,
runConditionComposer(runIfWhitelisted, withPromptStart),
runConditionComposer(runIfAllowlisted, withPromptStart),
appendUrlToPayload,
undefined,
withPromptEnd
);
forwardToPopup(
MessageType.IdProof,
InternalMessageType.IdProof,
runConditionComposer(runIfWhitelisted, runIfValidProof, withPromptStart),
runConditionComposer(runIfAllowlisted, runIfValidProof, withPromptStart),
appendUrlToPayload,
undefined,
withPromptEnd
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import React, { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { Navigate, useLocation } from 'react-router-dom';
import { absoluteRoutes } from '@popup/constants/routes';
import Logo from '@assets/svg/concordium.svg';
import Toast from '@popup/shared/Toast/Toast';

import { useCredential } from '@popup/shared/utils/account-helpers';
import AccountDetails from '@popup/pages/Account/AccountDetails';
import { useAtomValue } from 'jotai';
import { sessionPasscodeAtom } from '@popup/store/settings';

function Header() {
const { t } = useTranslation('mainLayout');
Expand Down Expand Up @@ -54,6 +56,16 @@ interface Props {
export default function ExternalRequestLayout({ children }: Props) {
const { state } = useLocation() as Location;
const account = useCredential(state.payload.accountAddress);
const { loading: loadingPasscode, value: sessionPasscode } = useAtomValue(sessionPasscodeAtom);

if (loadingPasscode) {
// This will be near instant, as we're just waiting for the Chrome async store
return null;
}

if (!sessionPasscode) {
return <Navigate to={absoluteRoutes.login.path} state={{ to: -1 }} />;
}

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ export default function IdProofRequest({ onReject, onSubmit }: Props) {
const network = useAtomValue(networkConfigurationAtom);
const client = useAtomValue(grpcClientAtom);
const addToast = useSetAtom(addToastAtom);
const recoveryPhrase = useDecryptedSeedPhrase((e) => addToast(e.message));
// TODO log this;
const recoveryPhrase = useDecryptedSeedPhrase(undefined);
const dappName = displayUrl(url);
const [creatingProof, setCreatingProof] = useState<boolean>(false);
const [canProve, setCanProve] = useState(statement.length > 0);
Expand Down
2 changes: 1 addition & 1 deletion packages/browser-wallet/src/popup/pages/Login/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default function Login() {
try {
await decrypt(encryptedSeedPhrase.value, vs.passcode);
// If decryption did not throw an error, then the password is correct.
setPasscodeInSession(vs.passcode);
await setPasscodeInSession(vs.passcode);
navigate(state.to, { state: state.toState });
} catch {
form.setError('passcode', { message: t('incorrectPasscode') });
Expand Down
Loading