1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
|
// Switching accounts while the previous one's relay query is still out: the
// answer used to land in the NEXT account's notifications and be saved there
// under its key, so a throwaway account showed adam's zaps and reactions for
// good. Also: a DM cache already polluted that way is swept on load.
// Run: bun tools/account-switch-leak-test.js
import puppeteer from './puppeteer.js';
import { cacheKeyFor } from '../src/wallet.js';
import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
import { privateKeyFromSeedWords } from 'nostr-tools/nip06';
import { buildHtml } from '../build.js';
import { makeDM } from '../src/dm.js';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let ok = true;
const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
const ACTOR = (() => { const sk = generateSecretKey(); return { sk, pk: getPublicKey(sk) }; })();
const STRANGER = getPublicKey(generateSecretKey());
const now = Math.floor(Date.now() / 1000);
const html = await buildHtml({ minify: true, pwa: false });
const server = Bun.serve({ port: 5302, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) });
const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] });
const page = await browser.newPage();
await page.evaluateOnNewDocument(() => {
// notification queries (#p, reactions) for the account under test are
// answered slowly — long enough to switch accounts while one is out
const Real = window.WebSocket;
window.WebSocket = function (...a) {
const ws = new Real(...a);
const send = ws.send.bind(ws);
ws.send = (data) => {
try {
const m = JSON.parse(data);
if (m[0] === 'REQ') {
const f = m[2] || {};
const victim = window.__victim && (f['#p'] || []).includes(window.__victim.pk) && (f.kinds || []).includes(7);
const dm = window.__dm && (f['#p'] || []).includes(window.__dm.pk) && (f.kinds || []).includes(1059) ? [window.__dm.wrap] : [];
if (victim) (window.__asked = (window.__asked || 0) + 1);
setTimeout(() => {
if (victim) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], window.__victim.react]) }));
for (const w of dm) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], w]) }));
ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) }));
}, victim ? 4000 : 0);
return;
}
if (m[0] === 'EVENT') return;
} catch {}
return send(data);
};
return ws;
};
window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real);
try { const v = sessionStorage.getItem('__victim'); if (v) window.__victim = JSON.parse(v); } catch {}
try { const v = sessionStorage.getItem('__dm'); if (v) window.__dm = JSON.parse(v); } catch {}
});
const errs = [];
page.on('pageerror', (e) => errs.push(String(e)));
const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t);
const text = () => page.evaluate(() => document.body.innerText);
const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await text()).toLowerCase().includes(x)) return true; await sleep(250); } return false; };
const nav = (label) => page.evaluate((l) => document.querySelector(`.app-nav-button[aria-label="${l}"]`)?.click(), label);
async function newWallet() {
await click('create a new wallet'); await sleep(600);
if (!(await page.$('.words .w .t'))) { await click('generate'); await sleep(600); }
await page.waitForSelector('.words .w .t');
const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' ');
await click('skip verification');
await waitText('receive', 20000);
return mn;
}
try {
await page.setViewport({ width: 390, height: 844 });
await page.goto('http://localhost:5302/', { waitUntil: 'domcontentloaded' });
await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
await page.reload({ waitUntil: 'domcontentloaded' });
await sleep(400);
const mnA = await newWallet();
const A = getPublicKey(privateKeyFromSeedWords(mnA));
const react = finalizeEvent({ kind: 7, created_at: now - 30, tags: [['e', 'f'.repeat(64)], ['p', A]], content: '🔥' }, ACTOR.sk);
await page.evaluate((v) => { sessionStorage.setItem('__victim', JSON.stringify(v)); }, { pk: A, react });
await page.reload({ waitUntil: 'domcontentloaded' });
await waitText('receive', 20000);
console.log('\n[account A asks for its notifications; the answer is slow]');
await nav('Notifications'); await sleep(800);
check('A\'s notification query is out', (await page.evaluate(() => window.__asked || 0)) > 0);
console.log('\n[switch to a new account B before it answers]');
await page.evaluate(() => document.querySelector('.header-avatar')?.click()); await sleep(1200);
if (process.env.DEBUG) console.log(await page.evaluate(() => [...document.querySelectorAll('button')].map((b) => b.textContent.trim() || b.getAttribute('aria-label')).join(' | ')));
check('the accounts page offers another sign-in', await click('sign into another account'));
await sleep(500);
const mnB = await newWallet();
const B = getPublicKey(privateKeyFromSeedWords(mnB));
check('B is a different identity', B !== A);
await sleep(6000); // A's answer has long since landed
await nav('Notifications'); await sleep(1500);
const baseB = cacheKeyFor(mnB + '\n');
const stB = await page.evaluate((k) => JSON.parse(localStorage.getItem(k + ':messages') || '{}'), baseB);
check('B\'s saved notifications hold nothing of A\'s', !(stB.notifs || []).some((x) => x.actor === ACTOR.pk), JSON.stringify((stB.notifs || []).map((x) => x.actor.slice(0, 8))));
check('...and its page doesn\'t show A\'s reaction', !(await page.evaluate(() => document.body.innerText.includes('🔥'))));
console.log('\n[a DM cache polluted before the fix is swept]');
await page.evaluate(([k, a, s]) => {
const st = JSON.parse(localStorage.getItem(k + ':messages') || '{}');
st.dms = { [s]: [{ id: 'd'.repeat(64), from: a, text: 'adam wrote this to someone', t: Math.floor(Date.now() / 1000) - 60 },
{ id: 'e'.repeat(64), from: s, text: 'their answer to adam', t: Math.floor(Date.now() / 1000) - 30 }] };
localStorage.setItem(k + ':messages', JSON.stringify(st));
}, [baseB, A, STRANGER]);
// and a real DM to B, so the sweep is seen not to cost B its own messages
const { toPeer } = await makeDM(ACTOR.sk, B, 'hello B, a real DM');
await page.evaluate((v) => sessionStorage.setItem('__dm', JSON.stringify(v)), { pk: B, wrap: toPeer });
await page.reload({ waitUntil: 'domcontentloaded' });
await waitText('receive', 20000);
await nav('Messages'); await sleep(2500);
check('a DM sent to B still arrives', await waitText('hello b, a real dm', 10000));
check('A\'s conversation isn\'t in B\'s messages', !(await page.evaluate(() => document.body.innerText.includes('their answer to adam'))));
const dmsB = await page.evaluate((k) => JSON.parse(localStorage.getItem(k + ':messages') || '{}').dms || {}, baseB);
check('...and is gone from its cache', !dmsB[STRANGER], Object.keys(dmsB).length + ' thread(s)');
check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
} finally { await browser.close(); server.stop(true); }
console.log(ok ? '\n✅ an account switch keeps each identity\'s notifications and DMs apart' : '\n❌ failed');
process.exit(ok ? 0 : 1);
|