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

feat(ErrorKeyRevoked): reconnect with automatic key addition #714

Merged
merged 19 commits into from
Dec 9, 2024
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
3 changes: 3 additions & 0 deletions src/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,9 @@
"connectWalletKeyService_text_consentP1": {
"message": "We will automatically connect with your wallet provider."
},
"reconnectWalletKeyService_text_consentP1": {
"message": "We will automatically reconnect with your wallet provider."
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo: ask to improve message later

},
"connectWalletKeyService_text_consentLearnMore": {
"message": "Learn more",
"description": "Learn more about how this works"
Expand Down
2 changes: 1 addition & 1 deletion src/background/services/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export class Background {
return success(undefined);

case 'RECONNECT_WALLET': {
await this.openPaymentsService.reconnectWallet();
await this.openPaymentsService.reconnectWallet(message.payload);
await this.monetizationService.resumePaymentSessionActiveTab();
await this.updateVisualIndicatorsForCurrentTab();
return success(undefined);
Expand Down
86 changes: 77 additions & 9 deletions src/background/services/openPayments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
import type {
AddFundsPayload,
ConnectWalletPayload,
ReconnectWalletPayload,
UpdateBudgetPayload,
} from '@/shared/messages';
import {
Expand Down Expand Up @@ -116,14 +117,17 @@ const enum ErrorCode {
}

const enum GrantResult {
SUCCESS = 'grant_success',
ERROR = 'grant_error',
GRANT_SUCCESS = 'grant_success',
GRANT_ERROR = 'grant_error',
KEY_ADD_SUCCESS = 'key_add_success',
KEY_ADD_ERROR = 'key_add_error',
}

const enum InteractionIntent {
DarianM marked this conversation as resolved.
Show resolved Hide resolved
CONNECT = 'connect',
RECONNECT = 'reconnect',
FUNDS = 'funds',
BUDGET_UPDATE = 'budget_update',
UPDATE_BUDGET = 'update_budget',
}

export class OpenPaymentsService {
Expand Down Expand Up @@ -481,7 +485,7 @@ export class OpenPaymentsService {
amount,
walletAddress!,
recurring,
InteractionIntent.BUDGET_UPDATE,
InteractionIntent.UPDATE_BUDGET,
);

// Revoke all existing grants.
Expand Down Expand Up @@ -550,7 +554,7 @@ export class OpenPaymentsService {
}).catch(async (e) => {
await this.redirectToWelcomeScreen(
tabId,
GrantResult.ERROR,
GrantResult.GRANT_ERROR,
intent,
ErrorCode.HASH_FAILED,
);
Expand All @@ -568,7 +572,7 @@ export class OpenPaymentsService {
).catch(async (e) => {
await this.redirectToWelcomeScreen(
tabId,
GrantResult.ERROR,
GrantResult.GRANT_ERROR,
intent,
ErrorCode.CONTINUATION_FAILED,
);
Expand Down Expand Up @@ -609,7 +613,11 @@ export class OpenPaymentsService {
}

this.grant = grantDetails;
await this.redirectToWelcomeScreen(tabId, GrantResult.SUCCESS, intent);
await this.redirectToWelcomeScreen(
tabId,
GrantResult.GRANT_SUCCESS,
intent,
);
return grantDetails;
}

Expand Down Expand Up @@ -638,7 +646,7 @@ export class OpenPaymentsService {
if (tabId && !isTabClosed) {
await this.redirectToWelcomeScreen(
tabId,
GrantResult.ERROR,
GrantResult.GRANT_ERROR,
InteractionIntent.CONNECT,
ErrorCode.KEY_ADD_FAILED,
);
Expand Down Expand Up @@ -968,7 +976,7 @@ export class OpenPaymentsService {
);
}

async reconnectWallet() {
private async validateReconnect() {
try {
await this.rotateToken();
} catch (error) {
Expand All @@ -981,6 +989,66 @@ export class OpenPaymentsService {
await this.storage.setState({ key_revoked: false });
}

async reconnectWallet({ autoKeyAddConsent }: ReconnectWalletPayload) {
if (!autoKeyAddConsent) {
await this.validateReconnect();
return;
}

const { walletAddress } = await this.storage.get(['walletAddress']);
if (!walletAddress) {
throw new Error('reconnectWallet_error_walletAddressMissing');
}
if (!KeyAutoAddService.supports(walletAddress)) {
throw new ErrorWithKey('connectWalletKeyService_error_notImplemented');
}

try {
this.setConnectState('connecting');
await this.validateReconnect();
} catch (error) {
if (!isInvalidClientError(error?.cause)) {
this.updateConnectStateError(error);
throw error;
}

let tabId: number | undefined;
try {
// add key to wallet and try again
tabId = await this.addPublicKeyToWallet(walletAddress);
await this.validateReconnect();

tabId ??= await this.ensureTabExists();
await this.redirectToWelcomeScreen(
tabId,
GrantResult.KEY_ADD_SUCCESS,
InteractionIntent.RECONNECT,
);
} catch (error) {
const isTabClosed = error.key === 'connectWallet_error_tabClosed';
if (tabId && !isTabClosed) {
await this.redirectToWelcomeScreen(
tabId,
GrantResult.KEY_ADD_ERROR,
InteractionIntent.RECONNECT,
);
}
this.updateConnectStateError(error);
throw error;
}
}

this.setConnectState(null);
}

private async ensureTabExists(): Promise<number> {
const tab = await this.browser.tabs.create({});
if (!tab.id) {
throw new Error('Could not create tab');
}
return tab.id;
}

/**
* Switches to the next grant that can be used.
* @returns the type of grant that should be used now, or null if no grant can
Expand Down
43 changes: 2 additions & 41 deletions src/pages/popup/components/ConnectWalletForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Switch } from '@/pages/shared/components/ui/Switch';
import { Code } from '@/pages/shared/components/ui/Code';
import { ErrorMessage } from '@/pages/shared/components/ErrorMessage';
import { LoadingSpinner } from '@/pages/shared/components/LoadingSpinner';
import { AutoKeyAddConsent } from '@/pages/shared/components/AutoKeyAddConsent';
import {
InputAmount,
validateAmount,
Expand Down Expand Up @@ -224,7 +225,6 @@ export const ConnectWalletForm = ({
<AutoKeyAddConsent
onAccept={() => {
autoKeyAddConsent.current = true;
// saveValue('autoKeyAddConsent', true);
setShowConsent(false);
handleSubmit();
}}
Expand All @@ -233,6 +233,7 @@ export const ConnectWalletForm = ({
setErrors((prev) => ({ ...prev, keyPair: toErrorInfo(error) }));
setShowConsent(false);
}}
intent="CONNECT_WALLET"
/>
);
}
Expand Down Expand Up @@ -389,46 +390,6 @@ export const ConnectWalletForm = ({
);
};

const AutoKeyAddConsent: React.FC<{
onAccept: () => void;
onDecline: () => void;
}> = ({ onAccept, onDecline }) => {
const t = useTranslation();
return (
<form
className="space-y-4 text-center"
data-testid="connect-wallet-auto-key-consent"
>
<p className="text-lg leading-snug text-weak">
{t('connectWalletKeyService_text_consentP1')}{' '}
<a
hidden
href="https://webmonetization.org"
className="text-primary hover:underline"
target="_blank"
rel="noreferrer"
>
{t('connectWalletKeyService_text_consentLearnMore')}
</a>
</p>

<div className="space-y-2 pt-12 text-medium">
<p>{t('connectWalletKeyService_text_consentP2')}</p>
<p>{t('connectWalletKeyService_text_consentP3')}</p>
</div>

<div className="mx-auto flex w-3/4 justify-around gap-4">
<Button onClick={onAccept}>
{t('connectWalletKeyService_label_consentAccept')}
</Button>
<Button onClick={onDecline} variant="destructive">
{t('connectWalletKeyService_label_consentDecline')}
</Button>
</div>
</form>
);
};

const ManualKeyPairNeeded: React.FC<{
error: { message: string; details: null | ErrorInfo; whyText: string };
hideError?: boolean;
Expand Down
44 changes: 32 additions & 12 deletions src/pages/popup/components/ErrorKeyRevoked.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import React from 'react';
import { AnimatePresence, m } from 'framer-motion';
import { AutoKeyAddConsent } from '@/pages/shared/components/AutoKeyAddConsent';
import { WarningSign } from '@/pages/shared/components/Icons';
import { Button } from '@/pages/shared/components/ui/Button';
import { Code } from '@/pages/shared/components/ui/Code';
import { useTranslation } from '@/pages/shared/lib/context';
import { useLocalStorage } from '@/pages/shared/lib/hooks';
import type { PopupStore } from '@/shared/types';
import type { Response } from '@/shared/messages';
import type { ReconnectWalletPayload, Response } from '@/shared/messages';

interface Props {
info: Pick<PopupStore, 'publicKey' | 'walletAddress'>;
disconnectWallet: () => Promise<Response>;
reconnectWallet: () => Promise<Response>;
reconnectWallet: (data: ReconnectWalletPayload) => Promise<Response>;
onReconnect?: () => void;
onDisconnect?: () => void;
}

type Screen = 'main' | 'reconnect';
type Screen = 'main' | 'manual-reconnect' | 'consent-reconnect';

export const ErrorKeyRevoked = ({
info,
Expand All @@ -35,16 +36,35 @@ export const ErrorKeyRevoked = ({
return (
<AnimatePresence mode="sync">
<MainScreen
requestReconnect={() => setScreen('reconnect')}
disconnectWallet={disconnectWallet}
onDisconnect={onDisconnect}
setScreen={setScreen}
/>
</AnimatePresence>
);
} else if (screen === 'consent-reconnect') {
return (
<AnimatePresence mode="sync">
<AutoKeyAddConsent
onAccept={async () => {
try {
await reconnectWallet({ autoKeyAddConsent: true });
clearScreen();
onReconnect?.();
} catch (error) {
setScreen('manual-reconnect');
throw error;
}
}}
onDecline={() => setScreen('manual-reconnect')}
intent="RECONNECT_WALLET"
/>
</AnimatePresence>
);
} else {
return (
<AnimatePresence mode="sync">
<ReconnectScreen
<ManualReconnectScreen
info={info}
reconnectWallet={reconnectWallet}
onReconnect={() => {
Expand All @@ -60,13 +80,13 @@ export const ErrorKeyRevoked = ({
interface MainScreenProps {
disconnectWallet: Props['disconnectWallet'];
onDisconnect?: Props['onDisconnect'];
requestReconnect: () => void;
setScreen: (screen: Screen) => void;
}

const MainScreen = ({
disconnectWallet,
onDisconnect,
requestReconnect,
setScreen,
}: MainScreenProps) => {
const t = useTranslation();
const [errorMsg, setErrorMsg] = React.useState('');
Expand Down Expand Up @@ -109,7 +129,7 @@ const MainScreen = ({
<Button onClick={() => requestDisconnect()} loading={loading}>
{t('keyRevoked_action_disconnect')}
</Button>
<Button onClick={() => requestReconnect()}>
<Button onClick={() => setScreen('consent-reconnect')}>
{t('keyRevoked_action_reconnect')}
</Button>
</m.form>
Expand All @@ -123,7 +143,7 @@ interface ReconnectScreenProps {
onReconnect?: Props['onDisconnect'];
}

const ReconnectScreen = ({
const ManualReconnectScreen = ({
info,
reconnectWallet,
onReconnect,
Expand All @@ -137,11 +157,11 @@ const ReconnectScreen = ({
root: null,
});

const requestReconnect = async () => {
const requestManualReconnect = async () => {
setErrors({ root: null });
try {
setIsSubmitting(true);
const res = await reconnectWallet();
const res = await reconnectWallet({ autoKeyAddConsent: false });
if (res.success) {
onReconnect?.();
} else {
Expand All @@ -161,7 +181,7 @@ const ReconnectScreen = ({
className="flex flex-col items-stretch gap-4"
onSubmit={(ev) => {
ev.preventDefault();
requestReconnect();
requestManualReconnect();
}}
>
<div className="space-y-1 text-sm">
Expand Down
3 changes: 2 additions & 1 deletion src/pages/popup/pages/ErrorKeyRevoked.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const Component = () => {
data: { state: {}, prevState: {} },
});
navigate(ROUTES_PATH.HOME);
window.location.reload();
};

const onDisconnect = () => {
Expand All @@ -29,7 +30,7 @@ export const Component = () => {
return (
<ErrorKeyRevoked
info={{ publicKey, walletAddress }}
reconnectWallet={() => message.send('RECONNECT_WALLET')}
reconnectWallet={(data) => message.send('RECONNECT_WALLET', data)}
onReconnect={onReconnect}
disconnectWallet={() => message.send('DISCONNECT_WALLET')}
onDisconnect={onDisconnect}
Expand Down
Loading