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: automatically add public key for Fynbos wallets #643

Merged
merged 19 commits into from
Oct 14, 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
3 changes: 3 additions & 0 deletions .github/workflows/nightly-build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ jobs:
CONNECT_KEY_ID: ${{ vars.E2E_CONNECT_KEY_ID }}
CONNECT_PUBLIC_KEY: ${{ secrets.E2E_CONNECT_PUBLIC_KEY }}
CONNECT_PRIVATE_KEY: ${{ secrets.E2E_CONNECT_PRIVATE_KEY }}
FYNBOS_WALLET_ADDRESS_URL: ${{ vars.E2E_FYNBOS_WALLET_ADDRESS_URL }}
FYNBOS_USERNAME: ${{ vars.E2E_FYNBOS_USERNAME }}
FYNBOS_PASSWORD: ${{ secrets.E2E_FYNBOS_PASSWORD }}

- name: Encrypt report
shell: bash
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/tests-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ jobs:
CONNECT_KEY_ID: ${{ vars.E2E_CONNECT_KEY_ID }}
CONNECT_PUBLIC_KEY: ${{ secrets.E2E_CONNECT_PUBLIC_KEY }}
CONNECT_PRIVATE_KEY: ${{ secrets.E2E_CONNECT_PRIVATE_KEY }}
FYNBOS_WALLET_ADDRESS_URL: ${{ vars.E2E_FYNBOS_WALLET_ADDRESS_URL }}
FYNBOS_USERNAME: ${{ vars.E2E_FYNBOS_USERNAME }}
FYNBOS_PASSWORD: ${{ secrets.E2E_FYNBOS_PASSWORD }}

- name: Encrypt report
shell: bash
Expand Down
21 changes: 12 additions & 9 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,18 @@ Make sure you run `pnpm build chrome` before running tests.
1. Copy `tests/.env.example` to `tests/.env`
2. Update `tests/.env` with your secrets.

| Environment Variable | Description | Is secret? |
| ---------------------------- | ----------------------------------------------------------- | ---------- |
| `WALLET_URL_ORIGIN` | URL of the wallet (e.g. https://rafiki.money) | No |
| `WALLET_USERNAME` | Login email for the wallet | No |
| `WALLET_PASSWORD` | Login password for the wallet | Yes |
| `CONNECT_WALLET_ADDRESS_URL` | Your wallet address that will be connected to extension | No |
| `CONNECT_KEY_ID` | ID of the key that will be connected to extension (UUID v4) | No |
| `CONNECT_PRIVATE_KEY` | Private key (hex-encoded Ed25519 private key) | Yes |
| `CONNECT_PUBLIC_KEY` | Public key (base64-encoded Ed25519 public key) | No |
| Environment Variable | Description | Secret? | Optional? |
| ---------------------------- | ----------------------------------------------------------- | ------- | --------- |
| `WALLET_URL_ORIGIN` | URL of the wallet (e.g. https://rafiki.money) | - | - |
| `WALLET_USERNAME` | -- Login email for the wallet | - | - |
| `WALLET_PASSWORD` | -- Login password for the wallet | Yes | - |
sidvishnoi marked this conversation as resolved.
Show resolved Hide resolved
| `CONNECT_WALLET_ADDRESS_URL` | -- Your wallet address that will be connected to extension | - | - |
| `CONNECT_KEY_ID` | ID of the key that will be connected to extension (UUID v4) | - | - |
| `CONNECT_PRIVATE_KEY` | Private key (hex-encoded Ed25519 private key) | Yes | - |
| `CONNECT_PUBLIC_KEY` | Public key (base64-encoded Ed25519 public key) | - | - |
| `FYNBOS_WALLET_ADDRESS_URL` | Fynbos wallet address (used for Fynbos specific tests only) | - | Yes |
| `FYNBOS_USERNAME` | -- Login email for Fynbos wallet | - | Yes |
| `FYNBOS_PASSWORD` | -- Login password for Fynbos wallet | Yes | Yes |

To get the `CONNECT_KEY_ID`, `CONNECT_PRIVATE_KEY` and `CONNECT_PUBLIC_KEY`:

Expand Down
4 changes: 4 additions & 0 deletions esbuild/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ export const options: BuildOptions = {
in: path.join(SRC_DIR, 'content', 'keyAutoAdd', 'testWallet.ts'),
out: path.join('content', 'keyAutoAdd', 'testWallet'),
},
{
in: path.join(SRC_DIR, 'content', 'keyAutoAdd', 'fynbos.ts'),
out: path.join('content', 'keyAutoAdd', 'fynbos'),
},
sidvishnoi marked this conversation as resolved.
Show resolved Hide resolved
{
in: path.join(SRC_DIR, 'content', 'polyfill.ts'),
out: path.join('polyfill', 'polyfill'),
Expand Down
6 changes: 4 additions & 2 deletions src/background/services/keyAutoAdd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,10 @@ export function walletAddressToProvider(walletAddress: WalletAddress): {
switch (host) {
case 'ilp.rafiki.money':
return { url: 'https://rafiki.money/settings/developer-keys' };
// case 'eu1.fynbos.me': // fynbos dev
// case 'fynbos.me': // fynbos production
case 'eu1.fynbos.me':
return { url: 'https://eu1.fynbos.dev/settings/keys' };
case 'fynbos.me':
return { url: 'https://wallet.fynbos.app/settings/keys' };
default:
throw new ErrorWithKey('connectWalletKeyService_error_notImplemented');
}
Expand Down
123 changes: 123 additions & 0 deletions src/content/keyAutoAdd/fynbos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// cSpell:ignore nextjs
import { errorWithKey, ErrorWithKey, sleep } from '@/shared/helpers';
import {
KeyAutoAdd,
LOGIN_WAIT_TIMEOUT,
type StepRun as Run,
} from './lib/keyAutoAdd';
import { isTimedOut, waitForElement, waitForURL } from './lib/helpers';
// #region: Steps

type IndexRouteResponse = {
isUser: boolean;
walletInfo: {
walletID: string;
url: string;
};
};

const waitForLogin: Run<void> = async (
{ keyAddUrl },
{ skip, setNotificationSize },
) => {
let alreadyLoggedIn = window.location.href.startsWith(keyAddUrl);
if (!alreadyLoggedIn) setNotificationSize('notification');
try {
sleep(2000);
raducristianpopa marked this conversation as resolved.
Show resolved Hide resolved
alreadyLoggedIn = await waitForURL(
(url) => (url.origin + url.pathname).startsWith(keyAddUrl),
{ timeout: LOGIN_WAIT_TIMEOUT },
);
setNotificationSize('fullscreen');
} catch (error) {
if (isTimedOut(error)) {
throw new ErrorWithKey('connectWalletKeyService_error_timeoutLogin');
}
throw new Error(error);
}

if (alreadyLoggedIn) {
skip(errorWithKey('connectWalletKeyService_error_skipAlreadyLoggedIn'));
}
};

const findWallet: Run<void> = async (
{ walletAddressUrl },
{ setNotificationSize },
) => {
setNotificationSize('fullscreen');
const url = `/?_data=${encodeURIComponent('routes/_index')}`;
const res = await fetch(url, {
headers: { accept: 'application/json' },
credentials: 'include',
}).catch((error) => {
return Response.json(null, { status: 599, statusText: error.message });
});
if (!res.ok) {
throw new Error(`Failed to get wallet details (${res.statusText})`);
}
const data: IndexRouteResponse = await res.json();
if (data?.walletInfo?.url !== walletAddressUrl) {
throw new ErrorWithKey('connectWalletKeyService_error_accountNotFound');
}
};

const findForm: Run<{
form: HTMLFormElement;
nickNameField: HTMLInputElement;
publicKeyField: HTMLTextAreaElement;
}> = async () => {
const pathname = '/settings/keys/add-public';
const link = await waitForElement<HTMLAnchorElement>(`a[href="${pathname}"]`);
link.click();
await waitForURL((url) => url.pathname === pathname);

const form = await waitForElement<HTMLFormElement>('form#add-public-key');
const nickNameField = await waitForElement<HTMLInputElement>(
'input#applicationName',
{ root: form },
);
const publicKeyField = await waitForElement<HTMLTextAreaElement>(
'textarea#publicKey',
{ root: form },
);
return { form, nickNameField, publicKeyField };
};

const addKey: Run<void> = async ({ publicKey, nickName }, { output }) => {
const { form, nickNameField, publicKeyField } = output(findForm);

nickNameField.focus();
nickNameField.value = nickName;
nickNameField.blur();

publicKeyField.focus();
publicKeyField.value = publicKey;
publicKeyField.blur();

const submitButton = await waitForElement<HTMLButtonElement>(
'button[type="submit"]',
{ root: form },
);
submitButton.click();

await waitForURL((url) => url.pathname === '/settings/keys');
};
// #endregion

// #region: Helpers
// anything?
// #endregion

// #region: Main
new KeyAutoAdd([
{
name: 'Waiting for you to login',
run: waitForLogin,
maxDuration: LOGIN_WAIT_TIMEOUT,
},
{ name: 'Finding wallet', run: findWallet },
{ name: 'Finding form to add public key', run: findForm },
{ name: 'Adding key', run: addKey },
]).init();
// #endregion
62 changes: 55 additions & 7 deletions src/content/keyAutoAdd/lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,63 @@

import { withResolvers } from '@/shared/helpers';

class TimeoutError extends Error {
name = 'TimeoutError';
constructor(message: string, { cause }: { cause: Event }) {
super(message, { cause });
}
}

interface WaitForOptions {
timeout: number;
}

interface WaitForElementOptions extends WaitForOptions {
root: HTMLElement | HTMLHtmlElement | Document;
/**
* Once a selector is matched, you can request an additional check to ensure
* this is the element you're looking for.
*/
match: (el: HTMLElement) => boolean;
}

export function waitForElement<T extends HTMLElement = HTMLElement>(
selector: string,
{
root = document,
timeout = 10 * 1000,
match = () => true,
}: Partial<WaitForElementOptions> = {},
): Promise<T> {
const { resolve, reject, promise } = withResolvers<T>();
if (document.querySelector(selector)) {
resolve(document.querySelector<T>(selector)!);
return promise;
}

const abortSignal = AbortSignal.timeout(timeout);
abortSignal.addEventListener('abort', (e) => {
observer.disconnect();
reject(
new TimeoutError(`Timeout waiting for element: {${selector}}`, {
cause: e,
}),
);
});

const observer = new MutationObserver(() => {
const el = document.querySelector<T>(selector);
if (el && match(el)) {
observer.disconnect();
resolve(el);
}
});

observer.observe(root, { childList: true, subtree: true });

return promise;
}

interface WaitForURLOptions extends WaitForOptions {}

export async function waitForURL(
Expand All @@ -23,7 +76,7 @@ export async function waitForURL(
const abortSignal = AbortSignal.timeout(timeout);
abortSignal.addEventListener('abort', (e) => {
observer.disconnect();
reject(e);
reject(new TimeoutError(`Timeout waiting for URL`, { cause: e }));
});

let url = window.location.href;
Expand All @@ -44,10 +97,5 @@ export async function waitForURL(
}

export function isTimedOut(e: any) {
return (
e instanceof Event &&
e.type === 'abort' &&
e.currentTarget instanceof AbortSignal &&
e.currentTarget.reason?.name === 'TimeoutError'
);
return e instanceof TimeoutError;
}
5 changes: 5 additions & 0 deletions src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
"matches": ["https://rafiki.money/*/*"],
"js": ["content/keyAutoAdd/testWallet.js"],
"run_at": "document_end"
},
{
"matches": ["https://eu1.fynbos.dev/*", "https://wallet.fynbos.app/*"],
"js": ["content/keyAutoAdd/fynbos.js"],
"run_at": "document_end"
}
],
"background": {
Expand Down
7 changes: 7 additions & 0 deletions tests/e2e/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,10 @@ CONNECT_WALLET_ADDRESS_URL="https://ilp.rafiki.money/something"
CONNECT_KEY_ID=uuid-v4-key-id
CONNECT_PUBLIC_KEY="base-64-public-key=="
CONNECT_PRIVATE_KEY="hex-encoded-private-key"

## If following are not provided, tests that use these will be skipped.

# Fynbos specific tests, using https://eu1.fynbos.dev
FYNBOS_WALLET_ADDRESS_URL=
FYNBOS_USERNAME=
FYNBOS_PASSWORD=
Loading
Loading