aboutsummaryrefslogtreecommitdiffstats
path: root/tools/notif-report-fold-test.js
blob: 678aefd32f26a3d20a3e6851fa1759a2ca1d765b (plain) (blame)
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
// Notifications: a reply or reaction from someone two of your follows
// reported is folded — the row says who it is from and what they did, who
// flagged them, and Show unfolds it — rather than dropped without a trace
// (Adam's phone, 2026-10-14: a reply Amethyst showed was missing here). A
// person one follow flagged, or a stranger nobody did, shows as ever.
// Run: bun tools/notif-report-fold-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';
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 key = () => { const sk = generateSecretKey(); return { sk, pk: getPublicKey(sk) }; };
const FRIEND1 = key(), FRIEND2 = key(), JOHNNY = key(), ONCE = key(), OKAY = key();
const now = Math.floor(Date.now() / 1000);
const html = await buildHtml({ minify: true, pwa: false });
const server = Bun.serve({ port: 5331, fetch: (req) => {
  const path = new URL(req.url).pathname;
  if (path.startsWith('/punks') || path === '/verify-worker.js' || path.startsWith('/locales')) 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();
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 rows = () => page.evaluate(() => [...document.querySelectorAll('.alert-row')].map((r) => (r.classList.contains('note-folded') ? 'FOLD ' : 'ROW ') + r.innerText.replace(/\s+/g, ' ').trim()));

try {
  await page.setViewport({ width: 390, height: 844 });
  await page.goto('http://localhost:5331/', { 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));
  const MINE = finalizeEvent({ kind: 1, created_at: now - 600, tags: [], content: 'my post, replied to' }, FRIEND1.sk); // stands in for a post of mine
  const reply = (who, content, ago) => finalizeEvent({ kind: 1, created_at: now - ago, tags: [['e', MINE.id, '', 'root'], ['p', ME, '', 'mention']], content }, who.sk);
  const JREPLY = reply(JOHNNY, 'johnny says hello there', 100);
  const JREACT = finalizeEvent({ kind: 7, created_at: now - 90, tags: [['e', MINE.id], ['p', ME]], content: '+' }, JOHNNY.sk);
  const OREPLY = reply(ONCE, 'flagged by one friend only', 80);
  const KREPLY = reply(OKAY, 'a reply from a fine person', 70);
  const profile = (who, name) => finalizeEvent({ kind: 0, created_at: now - 1000, tags: [], content: JSON.stringify({ name }) }, who.sk);
  const PROFILES = [profile(FRIEND1, 'mar'), profile(FRIEND2, 'Rich'), profile(JOHNNY, 'Johnny'), profile(ONCE, 'Once'), profile(OKAY, 'Okay')];
  const REPORTS = [
    finalizeEvent({ kind: 1984, created_at: now - 5000, tags: [['p', JOHNNY.pk, 'spam']], content: '' }, FRIEND1.sk),
    finalizeEvent({ kind: 1984, created_at: now - 4000, tags: [['p', JOHNNY.pk, 'spam']], content: '' }, FRIEND2.sk),
    finalizeEvent({ kind: 1984, created_at: now - 3000, tags: [['p', ONCE.pk, 'impersonation']], content: '' }, FRIEND1.sk),
  ];
  await page.evaluateOnNewDocument((fx) => {
    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 hit = [];
            for (const f of m.slice(2)) {
              const kinds = f.kinds || [];
              if (kinds.includes(1984)) hit.push(...fx.reports.filter((e) => (f.authors || []).includes(e.pubkey)));
              if (kinds.includes(0)) hit.push(...fx.profiles.filter((e) => (f.authors || []).includes(e.pubkey)));
              if ((f['#p'] || []).includes(fx.me) && (kinds.includes(1) || kinds.includes(7))) hit.push(...fx.notifs.filter((e) => kinds.includes(e.kind)));
              if (f.ids) hit.push(...[fx.mine, ...fx.notifs].filter((e) => f.ids.includes(e.id)));
            }
            setTimeout(() => {
              for (const e of hit) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], e]) }));
              ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) }));
            }, 0);
            return;
          }
          if (m[0] === 'EVENT') return;
        } catch {}
        return send(data);
      };
      return ws;
    };
    window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real);
  }, { me: ME, mine: MINE, notifs: [JREPLY, JREACT, OREPLY, KREPLY], reports: REPORTS, profiles: PROFILES });
  await page.evaluate(([k, f1, f2]) => {
    localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', f1], ['p', f2]], c: '', at: Math.floor(Date.now() / 1000) }));
  }, [base, FRIEND1.pk, FRIEND2.pk]);
  await page.reload({ waitUntil: 'domcontentloaded' });
  await waitText('receive', 20000);
  await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Notifications"]')?.click());
  let got = [];
  for (let i = 0; i < 80; i++) { got = await rows(); if (got.length >= 4 && got.some((r) => r.startsWith('FOLD') && /mar, Rich|Rich, mar/.test(r))) break; await sleep(250); }
  console.log('\n[a reply from someone two follows reported]');
  check('four rows: nothing is dropped', got.length === 4, got.length + ' rows');
  const jr = got.find((r) => r.includes('replied to you') && r.includes('Johnny'));
  check('Johnny\'s reply is folded, saying who he is and what he did', !!jr && jr.startsWith('FOLD'), jr);
  check('...naming the two follows who flagged him', !!jr && /Reported by (mar, Rich|Rich, mar)/.test(jr), jr);
  check('...and its text is not shown', !!jr && !jr.includes('johnny says hello'), jr);
  check('his reaction is folded too', got.some((r) => r.startsWith('FOLD') && r.includes('reacted')), got.join(' | '));
  check('a person one friend flagged shows as ever', got.some((r) => r.startsWith('ROW') && r.includes('flagged by one friend only')));
  check('a fine person\'s reply shows', got.some((r) => r.startsWith('ROW') && r.includes('a reply from a fine person')));
  await page.evaluate(() => { const fold = [...document.querySelectorAll('.alert-row.note-folded')].find((r) => r.innerText.includes('replied')); fold.querySelector('button').click(); });
  await sleep(400);
  got = await rows();
  console.log('\n[Show]');
  check('Show unfolds the reply', got.some((r) => r.startsWith('ROW') && r.includes('johnny says hello there')), got.join(' | '));
  check('the reaction stays folded', got.some((r) => r.startsWith('FOLD') && r.includes('reacted')));
  await page.evaluate(() => [...document.querySelectorAll('.alert-row:not(.note-folded)')].find((r) => r.innerText.includes('johnny says hello')).click());
  check('tapping the unfolded reply opens its thread, with the reply in it', await waitText('johnny says hello there', 8000) && await page.evaluate(() => !document.querySelector('.alert-row') && !!document.querySelector('.note-folded') === false), (await text()).slice(0, 200).replace(/\n/g, ' / '));
  check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
} catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(true); }
console.log(ok ? '\n✅ reported authors\' notifications fold with Show' : '\n❌ failed');
process.exit(ok ? 0 : 1);