Skip to content
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
36 changes: 33 additions & 3 deletions extension/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ A Rand site — randbridge.org, and a local build of it — sees this wallet as
contract in randbridge.org/web/lib/rand/provider.ts. Three files, each in its own world:

- `inpage.js` runs in the page's own world (`world: "MAIN"`, document_start) and defines the
object: `connect`, `getAddress`, `getRecipientHash`, `invoke`, `withdraw`, `disconnect`, `on`, plus the
object: `connect`, `getAddress`, `getRecipientHash`, `invoke`, `withdraw`, `deriveKey`, `disconnect`, `on`, plus the
`rand:announceProvider` / `rand:requestProvider` handshake. It knows nothing and can reach nothing.
- `content.js` relays those six method names — and none of the page's data except an `invoke`'s
or a `withdraw`'s request — to the background.
- `content.js` relays those seven method names — and none of the page's data except an `invoke`'s
or a `withdraw`'s request and a `deriveKey`'s `purpose` string — to the background.
- `provider-host.js`, loaded by `background.js`, decides from the *sender's* origin: `connect`
needs a wallet, unlocked, and the user's yes in `connect.html` for that origin; the approval
(address plus its bridge recipient hash, `lib/recipient-hash.js`) is stored under `sites` in
Expand All @@ -113,6 +113,36 @@ contract in randbridge.org/web/lib/rand/provider.ts. Three files, each in its ow
a refusal or a closed window tells the site only that nothing was sent. `node --test extension/test/provider-host.test.mjs` is the policy's suite;
`recipient-hash.test.mjs` pins the hash to the bridge's own fixture.

### `deriveKey` — a key of the site's own

`window.rand.deriveKey({ purpose }) → Promise<{ key }>` gives a site a key it can use to act for
itself — durian.market signs the orders of its own trading account with it — so "sign in with the
wallet" needs no password and nothing new to back up. `key` is 32 bytes as 64 lowercase hex.

- **Policy** (provider-host.js): the origin must already be connected (else `NOT_CONNECTED`) and
the wallet unlocked (else `LOCKED`; `NO_WALLET` with no wallet at all); `purpose` must match
`^[a-z0-9./-]{1,64}$` (else `BAD_REQUEST`). The first request for an (origin, purpose) opens
derive.html, which says which site asks, that it asks for a key it can use to act for itself,
that it gets the same key every time and no other site gets it, and that the key gives no access
to the wallet's funds, notes or address keys. Approve stores the yes under the site's entry in
`sites` (`siteKeys[purpose] = {address, at}`), tied to the address it was given for; later
requests answer at once. `disconnect` deletes the site's entry and so the yes with it, and a
new wallet's connect replaces the entry. Reject or a closed window is `USER_REJECTED`; a request
while another of the site's requests (of any kind) is waiting is `BUSY`.
- **Derivation** (lib/derive-key.js, WebCrypto in the background):
`HKDF-SHA-256(IKM = the spend key's 32 bytes, salt = "rand-wallet/site-key/v1",
info = LP("rand-wallet/site-key/v1") ‖ LP(origin) ‖ LP(purpose) ‖ LP(address), L = 32)`, where
LP is a 4-byte big-endian length then the UTF-8 bytes. `origin` is the *sender's*
(`URL.origin`: scheme, host, and a port only when it is not the default) — never a value from
the page; `address` is the connected `rand1…` address. The spend key is the wallet's root
secret, the one thing a backup holds, so a wallet restored on another device gives every site
the same key again; the viewing key, which a prover is given, is never an input. HKDF is one-way:
the key says nothing about the spend key, nor about the key of any other site, purpose or
wallet. `extension/test/derive-key.test.mjs` pins a vector and recomputes it with node:crypto.
- **What a site learns**: its own key, for the purposes the user approved, and nothing else. The
key is made when it is answered and is in no store and in no other message — not the window's,
not storage's, only the answer to the frame that asked.

When the extension itself is reloaded — a store update, or Reload at chrome://extensions on an
unpacked build — the browser orphans `content.js` in every tab that has it and never puts a new
one in, so every open bridge tab would answer "Rand Wallet did not respond" until reloaded. So
Expand Down
16 changes: 13 additions & 3 deletions extension/shared/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,11 @@ ext.runtime.onStartup?.addListener(() => {});

// ---- the page provider (`window.rand`) ----
//
// inpage.js/content.js relay a Rand site's requests here; provider-host.js decides. Chrome's
// service worker pulls that file in with importScripts; Firefox's event page lists it before this
// one in the manifest's `background.scripts`, so the factory is already on the global there.
// inpage.js/content.js relay a Rand site's requests here; provider-host.js decides, and
// lib/derive-key.js makes the key a site's `deriveKey` gets. Chrome's service worker pulls both in
// with importScripts; Firefox's event page lists them before this one in the manifest's
// `background.scripts`, so they are already on the global there.
if (typeof importScripts === 'function' && typeof globalThis.RandSiteKey !== 'object') importScripts('lib/derive-key.js');
if (typeof importScripts === 'function' && typeof globalThis.makeRandProviderHost !== 'function') importScripts('provider-host.js');

const providerHost = globalThis.makeRandProviderHost({
Expand All @@ -142,6 +144,14 @@ const providerHost = globalThis.makeRandProviderHost({
const win = await ext.windows.create({ url: ext.runtime.getURL(`withdraw.html?${query}`), type: 'popup', width: 400, height: 660 });
return win && Number.isInteger(win.id) ? win.id : null;
},
// The approval window for a site's first `deriveKey` of a purpose (derive.html): one yes or no,
// but parked and answered like an invoke's, so closing it answers the site (`windowClosed`).
openDerive: async ({ id, origin }) => {
const query = new URLSearchParams({ id, origin });
const win = await ext.windows.create({ url: ext.runtime.getURL(`derive.html?${query}`), type: 'popup', width: 380, height: 600 });
return win && Number.isInteger(win.id) ? win.id : null;
},
deriveSiteKey: globalThis.RandSiteKey && globalThis.RandSiteKey.deriveSiteKey,
});

ext.windows?.onRemoved?.addListener((windowId) => { void providerHost.windowClosed(windowId); });
Expand Down
16 changes: 13 additions & 3 deletions extension/shared/content.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// The relay between the page's `window.rand` (inpage.js, in the page's world) and the extension
// (background.js). Isolated world, classic script, no imports. It forwards exactly six method
// names, and nothing the page put in the message except the request of `invoke` or `withdraw`:
// (background.js). Isolated world, classic script, no imports. It forwards exactly seven method
// names, and nothing the page put in the message except the request of `invoke` or `withdraw`
// and the `purpose` string of `deriveKey` (that one field, at most `MAX_PURPOSE_CHARS`):
// the background decides everything else from who is asking (`sender`), never from what they
// said, and that request is data the user is shown and approves in the wallet's own window,
// capped here at `MAX_INVOKE_CHARS` of JSON. A connect or an invoke that needs the user comes back as
Expand All @@ -26,7 +27,9 @@
const FROM_PAGE = 'rand-wallet:page';
const TO_PAGE = 'rand-wallet:content';
const TAKEOVER = 'rand-wallet:content-takeover';
const METHODS = new Set(['connect', 'getAddress', 'getRecipientHash', 'disconnect', 'invoke', 'withdraw']);
const METHODS = new Set(['connect', 'getAddress', 'getRecipientHash', 'disconnect', 'invoke', 'withdraw', 'deriveKey']);
/** The background checks a purpose in full (`^[a-z0-9./-]{1,64}$`); here only its type and length. */
const MAX_PURPOSE_CHARS = 64;
/** An invoke request (a withdraw's is smaller still) is a few kilobytes (eight cells, a few dozen input words); 256 KiB of JSON
* is far past any real one and well short of a page using the relay to push megabytes. */
const MAX_INVOKE_CHARS = 256 * 1024;
Expand Down Expand Up @@ -59,6 +62,13 @@
return;
}
msg.params = d.params;
} else if (d.method === 'deriveKey') {
const purpose = d.params && typeof d.params === 'object' ? d.params.purpose : undefined;
if (typeof purpose !== 'string' || purpose.length > MAX_PURPOSE_CHARS) {
reply(d.id, { ok: false, error: { code: 'BAD_REQUEST', message: 'Rand Wallet could not read that request.' } });
return;
}
msg.params = { purpose };
}
let res, why = '';
try { res = await ext.runtime.sendMessage(msg); } catch (e) { res = null; why = String((e && e.message) || e); }
Expand Down
18 changes: 18 additions & 0 deletions extension/shared/derive.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en" data-theme="system">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark light">
<meta name="referrer" content="no-referrer">
<title>Approve in Rand Wallet</title>
<!-- The approval window a site's first `window.rand.deriveKey()` for a purpose opens (background.js).
Same CSP and stylesheets as the popup; no inline script. derive.js reads the request from the
background by id and answers it with the yes or no. -->
<link rel="stylesheet" href="ui/tokens.css">
<link rel="stylesheet" href="ui/base.css">
<link rel="stylesheet" href="ui/components.css">
<script src="derive.js" type="module"></script>
</head>
<body class="compact"></body>
</html>
113 changes: 113 additions & 0 deletions extension/shared/derive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// The approval window for a site's first `deriveKey` of a purpose: "<site> asks Rand Wallet for a
// key of its own". One yes or no, sent to background.js as a `rand:deriveResult`, which stores the
// yes, makes the key and gives it to the asking tab. This window never sees the key: the
// background answers it `{ok: true}` and nothing more.
//
// The request is read from the background by id (`rand:deriveRequest`), as invoke.js reads its
// own: nothing in the URL is trusted beyond the id, so the site shown is the origin the background
// recorded from the message's sender. Closing the window is a no (background.js `windowClosed`).
// Everything shown is built from DOM nodes and textContent: the origin and the purpose are data,
// never markup.
//
// No app.js here, so the language is this page's own job (lib/window-locale.js), as in connect.js:
// the wallet's `settings.locale` is read straight from storage and nothing is rendered before the
// dictionary is in force. Every string shown goes through `t()`.
import { ext } from './lib/browser.js';
import { applyWindowLocale, sentenceWith } from './lib/window-locale.js';
import { markSvg } from './ui/lib/entropy.js';
import { t } from './ui/i18n.js';

const id = new URLSearchParams(location.search).get('id') || '';

const el = (tag, className, text) => {
const node = document.createElement(tag);
if (className) node.className = className;
if (text != null) node.textContent = text;
return node;
};

/** The wallet's language setting, from the settings the engine keeps under `settings`; nothing when unset. */
async function localeSetting() {
try {
const bag = await ext.storage.local.get('settings');
const settings = bag && bag.settings;
return settings && typeof settings === 'object' ? settings.locale : undefined;
} catch { return undefined; }
}

const root = el('div', 'app');
let answered = false;
async function answer(approved) {
if (answered) return;
answered = true;
try { await ext.runtime.sendMessage({ type: 'rand:deriveResult', id, approved }); } catch { /* closing answers for us */ }
window.close();
}

function shell(titleText, subText) {
root.replaceChildren();
const box = el('div', 'onboard');
const mark = el('span', 'mark-lg bare');
// Our own SVG, no user data in it — parsed rather than assigned to innerHTML.
mark.append(new DOMParser().parseFromString(markSvg(), 'image/svg+xml').documentElement);
const head = el('div', 'stack tight');
const title = el('h1', 'title', titleText);
const sub = el('p', 'subtitle');
if (subText != null) sub.append(subText);
head.append(title, sub);
box.append(mark, head);
root.append(box);
return box;
}

function nothing(reason) {
const box = shell(t('Nothing to approve'), reason);
const actions = el('div', 'onboard-actions');
const close = el('button', 'btn block', t('Close'));
close.type = 'button';
close.addEventListener('click', () => window.close());
actions.append(close);
box.append(actions);
}

function review({ origin, purpose }) {
let host = origin;
try { host = new URL(origin).host; } catch { host = origin || t('A site'); }
const box = shell(t('Give this site a key?'), sentenceWith(t('{host} asks Rand Wallet for a key of its own.'), 'host', el('strong', null, host)));
const card = el('div', 'card');
for (const [k, v] of [[t('Site'), origin], [t('Purpose'), purpose]]) {
const kv = el('div', 'kv');
kv.append(el('span', 'k', k), el('span', 'v mono', v));
card.append(kv);
}
const what = el('p', 'caption pitch', t('The site can use the key to act for you on that site, for example to sign trades in your trading account there.') + ' '
+ t('Rand Wallet gives this site the same key every time, on any device with this wallet, and gives it to no other site.'));
const safe = el('p', 'caption pitch', t('The key gives no access to this wallet’s funds, notes or address keys.') + ' '
+ t('You are asked once for each purpose; disconnecting the site forgets your answer.'));
const actions = el('div', 'onboard-actions');
const yes = el('button', 'btn btn-primary block', t('Approve'));
yes.type = 'button';
const no = el('button', 'btn block', t('Reject'));
no.type = 'button';
yes.addEventListener('click', () => { void answer(true); });
no.addEventListener('click', () => { void answer(false); });
actions.append(yes, no);
box.append(card, what, safe, actions);
yes.focus();
}

(async () => {
await applyWindowLocale(await localeSetting());
document.title = t('Approve in Rand Wallet');
document.body.append(root);
if (!id) { nothing(t('This window was not opened by a site.')); return; }
shell(t('Reading the request…'), null);
let res = null;
try { res = await ext.runtime.sendMessage({ type: 'rand:deriveRequest', id }); } catch { /* shown as gone */ }
const r = res && res.ok && res.result;
if (!r || typeof r.origin !== 'string' || !r.request || typeof r.request.purpose !== 'string') {
nothing(t('That request is no longer waiting.'));
return;
}
review({ origin: r.origin, purpose: r.request.purpose });
})();
17 changes: 14 additions & 3 deletions extension/shared/inpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@
// `invoke(request) → {tx}`, an RPL-2 program call (durian.market's `web/lib/rand/provider.ts`),
// which the user approves in the wallet's own window before anything is proved, and
// `withdraw(request) → {tx}`, a bridge burn (randbridge.org), approved the same way, whose proof
// phases arrive as `withdrawPhase` events while it works.
// phases arrive as `withdrawPhase` events while it works, and `deriveKey({purpose}) → {key}`, a
// key of the site's own (durian.market's trading key), derived by the extension from this wallet,
// this origin and the purpose, after the user has said yes once to that origin and purpose.
//
// What is never here: keys, balances, notes, signing. The extension answers with the address and
// What is never here: the wallet's keys, balances, notes, signing. The extension answers with the address and
// its bridge recipient hash, after the user has said yes to this origin, and — for an `invoke` or `withdraw` the
// user approved — the transaction hash and the phase it has reached; nothing else.
// user approved — the transaction hash and the phase it has reached, and for a `deriveKey` the
// user approved, the site's own key; nothing else.
(() => {
if (window.rand && window.rand.isRandWallet) return;
const TO_CONTENT = 'rand-wallet:page';
Expand Down Expand Up @@ -70,6 +73,14 @@
}
return request('withdraw', params);
},
// A key of this site's own, for `purpose` (1–64 of a-z 0-9 . / -): the same 32 bytes (hex)
// every time for this wallet and this site, and to no other site. Only the purpose string is
// sent; the site is the page's origin as the extension sees it.
deriveKey: (req) => {
const purpose = req && typeof req === 'object' ? req.purpose : undefined;
if (typeof purpose !== 'string') return Promise.reject(refused('BAD_REQUEST', 'Rand Wallet could not read that request.'));
return request('deriveKey', { purpose });
},
disconnect: () => request('disconnect').then(() => { emit('disconnect', null); }),
on(event, cb) {
if (!listeners[event] || typeof cb !== 'function') return () => {};
Expand Down
Loading
Loading