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 4 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pnpm-debug.log*
lerna-debug.log*

node_modules
'node_modules/.cache/prettiercache'
DarianM marked this conversation as resolved.
Show resolved Hide resolved
dist
temp
preview
Expand Down
6 changes: 5 additions & 1 deletion src/background/services/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,11 @@ export class Background {
return success(undefined);

case 'RECONNECT_WALLET': {
await this.openPaymentsService.reconnectWallet();
if (message.payload.auto) {
await this.openPaymentsService.reconnectWallet();
} else {
await this.openPaymentsService.manualReconnectWallet();
}
await this.monetizationService.resumePaymentSessionActiveTab();
await this.updateVisualIndicatorsForCurrentTab();
return success(undefined);
Expand Down
76 changes: 63 additions & 13 deletions src/background/services/openPayments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
errorWithKeyToJSON,
getWalletInformation,
isErrorWithKey,
isWalletAddress,
withResolvers,
type ErrorWithKeyLike,
} from '@/shared/helpers';
Expand Down Expand Up @@ -113,12 +114,15 @@
}

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',
}
Expand Down Expand Up @@ -543,9 +547,9 @@
authServer: walletAddress.authServer,
}).catch(async (e) => {
await this.redirectToWelcomeScreen(
tabId,
GrantResult.ERROR,
GrantResult.GRANT_ERROR,
intent,
tabId,
ErrorCode.HASH_FAILED,
);
throw e;
Expand All @@ -561,9 +565,9 @@
},
).catch(async (e) => {
await this.redirectToWelcomeScreen(
tabId,
GrantResult.ERROR,
GrantResult.GRANT_ERROR,
intent,
tabId,
ErrorCode.CONTINUATION_FAILED,
);
throw e;
Expand Down Expand Up @@ -603,7 +607,11 @@
}

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

Expand All @@ -629,10 +637,11 @@
const tabId = keyAutoAdd.tabId;
const isTabClosed = error.key === 'connectWallet_error_tabClosed';
if (tabId && !isTabClosed) {
// if the tabid exists but is not closed, redirect to welcome screen with error

Check warning on line 640 in src/background/services/openPayments.ts

View workflow job for this annotation

GitHub Actions / Lint

Unknown word (tabid)
await this.redirectToWelcomeScreen(
tabId,
GrantResult.ERROR,
GrantResult.GRANT_ERROR,
InteractionIntent.CONNECT,
tabId,
ErrorCode.KEY_ADD_FAILED,
);
}
Expand Down Expand Up @@ -662,18 +671,24 @@
}

private async redirectToWelcomeScreen(
tabId: NonNullable<Tabs.Tab['id']>,
result: GrantResult,
intent: InteractionIntent,
tabId?: Tabs.Tab['id'],
errorCode?: ErrorCode,
) {
const url = new URL(OPEN_PAYMENTS_REDIRECT_URL);
url.searchParams.set('result', result);
url.searchParams.set('intent', intent);
if (errorCode) url.searchParams.set('errorCode', errorCode);
await this.browser.tabs.update(tabId, {
url: url.toString(),
});
if (!tabId) {
await this.browser.tabs.create({
url: url.toString(),
});
} else {
await this.browser.tabs.update(tabId, {
url: url.toString(),
});
}
sidvishnoi marked this conversation as resolved.
Show resolved Hide resolved
}

private async createOutgoingPaymentGrant({
Expand Down Expand Up @@ -904,16 +919,51 @@
);
}

async manualReconnectWallet() {
DarianM marked this conversation as resolved.
Show resolved Hide resolved
try {
await this.rotateToken();
} catch (error) {
if (isInvalidClientError(error)) {
const msg = this.t('connectWallet_error_invalidClient');
throw new Error(msg, { cause: error });
}
throw error;
}
await this.storage.setState({ key_revoked: false });
}

async reconnectWallet() {
try {
const { walletAddress } = await this.storage.get(['walletAddress']);
if (
!isWalletAddress(walletAddress) ||
DarianM marked this conversation as resolved.
Show resolved Hide resolved
!KeyAutoAddService.supports(walletAddress)
) {
// this.updateConnectStateError(error);
throw new ErrorWithKey('connectWalletKeyService_error_notImplemented');
sidvishnoi marked this conversation as resolved.
Show resolved Hide resolved
}
const tabId = await this.addPublicKeyToWallet(walletAddress);
this.setConnectState('connecting');
await this.rotateToken();
await this.redirectToWelcomeScreen(
GrantResult.KEY_ADD_SUCCESS,
InteractionIntent.RECONNECT,
tabId,
);
} catch (error) {
if (isInvalidClientError(error)) {
const msg = this.t('connectWallet_error_invalidClient');
throw new Error(msg, { cause: error });
}
await this.redirectToWelcomeScreen(
GrantResult.KEY_ADD_ERROR,
InteractionIntent.RECONNECT,
undefined,
ErrorCode.KEY_ADD_FAILED,
);
throw error;
}
this.setConnectState(null);
await this.storage.setState({ key_revoked: false });
}

Expand Down
85 changes: 73 additions & 12 deletions src/popup/components/ErrorKeyRevoked.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ import { Code } from '@/popup/components/ui/Code';
import { useTranslation } from '@/popup/lib/context';
import { useLocalStorage } from '@/popup/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,21 +35,38 @@ 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({ auto: true });
} catch (error) {
setScreen('manual-reconnect');
throw error;
}
}}
onDecline={() => setScreen('manual-reconnect')}
/>
</AnimatePresence>
);
} else {
return (
<AnimatePresence mode="sync">
<ReconnectScreen
<ManualReconnectScreen
info={info}
reconnectWallet={reconnectWallet}
onReconnect={() => {
clearScreen();
onReconnect?.();
window.location.reload();
DarianM marked this conversation as resolved.
Show resolved Hide resolved
}}
/>
</AnimatePresence>
Expand All @@ -60,13 +77,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 +126,11 @@ const MainScreen = ({
<Button onClick={() => requestDisconnect()} loading={loading}>
{t('keyRevoked_action_disconnect')}
</Button>
<Button onClick={() => requestReconnect()}>
<Button
onClick={() => {
setScreen('consent-reconnect');
}}
DarianM marked this conversation as resolved.
Show resolved Hide resolved
>
{t('keyRevoked_action_reconnect')}
</Button>
</m.form>
Expand All @@ -123,7 +144,7 @@ interface ReconnectScreenProps {
onReconnect?: Props['onDisconnect'];
}

const ReconnectScreen = ({
const ManualReconnectScreen = ({
info,
reconnectWallet,
onReconnect,
Expand All @@ -137,11 +158,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({ auto: false });
if (res.success) {
onReconnect?.();
} else {
Expand All @@ -161,7 +182,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 Expand Up @@ -193,3 +214,43 @@ const ReconnectScreen = ({
</m.form>
);
};

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>
);
};
2 changes: 1 addition & 1 deletion src/popup/pages/ErrorKeyRevoked.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,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
2 changes: 1 addition & 1 deletion src/shared/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const formatCurrency = (
}).format(Number(value));
};

const isWalletAddress = (o: any): o is WalletAddress => {
export const isWalletAddress = (o: any): o is WalletAddress => {
return (
o.id &&
typeof o.id === 'string' &&
Expand Down
6 changes: 5 additions & 1 deletion src/shared/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ export interface ConnectWalletPayload {
autoKeyAddConsent: boolean | null;
}

export interface ReconnectWalletPayload {
auto: boolean;
}

export interface AddFundsPayload {
amount: string;
recurring: boolean;
Expand Down Expand Up @@ -130,7 +134,7 @@ export type PopupToBackgroundMessage = {
output: void;
};
RECONNECT_WALLET: {
input: never;
input: ReconnectWalletPayload;
output: never;
};
ADD_FUNDS: {
Expand Down
Loading