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
|
// Your own posts and the feeds. A Following feed's opening ask takes the
// authors in chunks of 400, and your own key used to be added last — with
// hundreds of follows it sat in a later chunk, and the feed opened without
// your newest post. Now your key leads, and every chunk is asked. And a new
// post goes to the top of the feeds it would reach (Following; a topic feed
// whose tag it wears, which is now a t tag on the event) — not to a topic
// feed that happens to be open and doesn't match.
// Run: bun tools/own-post-feeds-test.js
import puppeteer from './puppeteer.js';
import { cacheKeyFor } from '../src/wallet.js';
import { privateKeyFromSeedWords } from 'nostr-tools/nip06';
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import { buildHtml } from '../build.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 FOLLOWS = Array.from({ length: 450 }, () => getPublicKey(generateSecretKey()));
const html = await buildHtml({ minify: true, pwa: false });
const server = Bun.serve({ port: 0, fetch: (req) => {
const path = new URL(req.url).pathname;
if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path));
return 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(() => {
window.__reqs = [];
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' && m[2] && Array.isArray(m[2].kinds) && m[2].kinds.includes(1)) window.__reqs.push(m[2]); } catch {}
return send(data);
};
return ws;
};
window.WebSocket.prototype = Real.prototype;
Object.assign(window.WebSocket, Real);
});
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 waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; };
const waitFor = async (fn, arg, ms = 10000) => { for (let i = 0; i < ms / 200; i++) { if (await page.evaluate(fn, arg)) return true; await sleep(200); } return false; };
const chip = (label) => page.evaluate((l) => { const c = [...document.querySelectorAll('.feed-chips > .feed-chip')].find((x) => x.textContent.trim() === l); if (c) c.click(); return !!c; }, label);
const feedTexts = () => page.evaluate(() => [...document.querySelectorAll('.notes-feed [data-key]')].map((r) => r.innerText.replace(/\s+/g, ' ').slice(0, 60)));
const post = async (text) => {
await page.evaluate(() => document.querySelector('.feed-post-fab').click());
await page.waitForSelector('.post-input', { timeout: 5000 });
await page.focus('.post-input');
await page.keyboard.type(text);
await sleep(200);
await page.evaluate(() => document.querySelector('.post-actions .btn-primary').click());
await sleep(1200);
};
try {
await page.setViewport({ width: 390, height: 844 });
await page.goto(server.url.href, { waitUntil: 'domcontentloaded' });
await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
await page.reload({ waitUntil: 'domcontentloaded' });
await sleep(400);
await click('create a new wallet'); 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);
const base = cacheKeyFor(mn + '\n');
const ME = getPublicKey(privateKeyFromSeedWords(mn));
await page.evaluate(([k, pks]) => {
localStorage.setItem(k + ':follows', JSON.stringify({ tags: pks.map((pk) => ['p', pk]), c: '', at: Math.floor(Date.now() / 1000) }));
localStorage.setItem(k + ':feedNotes', JSON.stringify([]));
localStorage.setItem('btc-wallet-feed:' + k, 'following');
}, [base, FOLLOWS]);
await page.reload({ waitUntil: 'domcontentloaded' });
await waitText('receive', 20000);
await page.evaluate(() => { window.__reqs.length = 0; document.querySelector('.app-nav-button[aria-label="Feed"]').click(); });
await sleep(2500);
console.log('\n[the opening ask, with 450 follows]');
const reqs = await page.evaluate(() => window.__reqs.filter((f) => Array.isArray(f.authors)));
const union = new Set(reqs.flatMap((f) => f.authors));
check('every follow is asked for, in chunks', FOLLOWS.every((pk) => union.has(pk)) && reqs.every((f) => f.authors.length <= 400), `${reqs.length} asks, ${union.size} authors`);
check('my own key leads the first chunk', reqs.some((f) => f.authors[0] === ME), JSON.stringify(reqs.map((f) => f.authors.length)));
console.log('\n[a post from Following]');
await post('hello from the composer #gardenstr');
check('it sits at the top of Following', (await feedTexts())[0]?.includes('hello from the composer'), JSON.stringify((await feedTexts()).slice(0, 2)));
const sent = await page.evaluate(() => window.__relayGuard.events.filter((e) => e.kind === 1));
check('the hashtag went out as a t tag', sent.some((e) => /hello from the composer/.test(e.content) && e.tags.some((x) => x[0] === 't' && x[1] === 'gardenstr')), JSON.stringify(sent.map((e) => e.tags.filter((x) => x[0] === 't'))));
console.log('\n[a post from a topic feed it does not match]');
check('the #gardenstr feed opens', await chip('#gardenstr') && await waitFor(() => [...document.querySelectorAll('.feed-chips > .feed-chip')].some((c) => c.classList.contains('on') && c.textContent.trim() === '#gardenstr'), null, 4000));
await post('no tag this time, just words');
check('it does not land in #gardenstr', !(await feedTexts()).some((x) => x.includes('no tag this time')), JSON.stringify((await feedTexts()).slice(0, 2)));
await chip('Following'); await sleep(800);
check('…but it is at the top of Following', (await feedTexts())[0]?.includes('no tag this time'), JSON.stringify((await feedTexts()).slice(0, 2)));
console.log('\n[a tagged post from the topic feed]');
await chip('#gardenstr'); await sleep(800);
await post('tagged this time #gardenstr');
check('it lands at the top of #gardenstr', (await feedTexts())[0]?.includes('tagged this time'), JSON.stringify((await feedTexts()).slice(0, 2)));
await chip('Following'); await sleep(800);
check('…and of Following', (await feedTexts())[0]?.includes('tagged this time'), JSON.stringify((await feedTexts()).slice(0, 2)));
check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
} finally { await browser.close(); server.stop(true); }
console.log(ok ? '\n✅ your posts reach the feeds they belong to' : '\n❌ failed');
process.exit(ok ? 0 : 1);
|