// A plain link in a post becomes the card its page describes: the registrar // is asked for the page's Open Graph data (shimmed here), the picture is // warmed with the rest of the post, and the row paints whole. A page with // nothing to say stays a bare link; pictures and YouTube keep their own // boxes. // Run: bun tools/link-preview-test.js import puppeteer, { seedWords, skipSeedCheck } 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 AUTHOR = generateSecretKey(); const APK = getPublicKey(AUTHOR); const now = Math.floor(Date.now() / 1000); const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64'); const POSTS = [ finalizeEvent({ kind: 1, created_at: now - 30, tags: [], content: 'Well, yeah https://news.example/story/1' }, AUTHOR), finalizeEvent({ kind: 1, created_at: now - 60, tags: [], content: 'nothing here https://blank.example/page' }, AUTHOR), finalizeEvent({ kind: 1, created_at: now - 90, tags: [], content: 'a picture http://localhost:5311/pic.png' }, AUTHOR), finalizeEvent({ kind: 1, created_at: now - 120, tags: [], content: 'film night https://paff.club/movie/1382-hackers-1995/play?q=1080p&t=4910' }, AUTHOR), finalizeEvent({ kind: 1, created_at: now - 150, tags: [], content: 'on repeat https://paff.club/song/abc123' }, AUTHOR), ]; const PROFILE = finalizeEvent({ kind: 0, created_at: now - 100, tags: [], content: JSON.stringify({ name: 'Linker', picture: 'http://localhost:5311/face.png' }) }, AUTHOR); const html = await buildHtml({ minify: true, pwa: false }); const previewHits = []; const server = Bun.serve({ port: 5311, fetch: (req) => { const u = new URL(req.url); if (u.pathname === '/preview') { const target = u.searchParams.get('url'); previewHits.push(target); const meta = target === 'https://news.example/story/1' ? { url: target, title: 'Lawmakers doubt the plan', description: 'A story in one line.', image: 'http://localhost:5311/card.png', site: 'News Example' } : target === 'https://movies.example/movie/1382/play?t=4910' || target.startsWith('https://paff.club/movie/1382') ? { url: target, title: 'Hackers (1995) · from 1:21:50', description: 'Teenage hackers.', image: 'http://localhost:5311/movie.png', site: 'PAFF' } : target === 'https://paff.club/song/abc123' ? { url: target, title: 'Halcyon · Orbital', description: 'Orbital 2 · 1993', image: 'http://localhost:5311/cover.png', site: 'PAFF' } : {}; return new Response(JSON.stringify(meta), { headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*' } }); } if (u.pathname.endsWith('.png')) return new Response(PNG, { headers: { 'content-type': 'image/png' } }); if (u.pathname.startsWith('/punks') || u.pathname === '/verify-worker.js') return new Response(Bun.file('dist' + u.pathname)); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); // a stand-in paff.club (self-signed, resolved here): its embed player speaks // PAFF's postMessage protocol and logs the commands it gets const certDir = (await import('node:fs')).mkdtempSync((await import('node:os')).tmpdir() + '/paff-cert-'); Bun.spawnSync(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-days', '1', '-subj', '/CN=paff.club', '-keyout', certDir + '/k.pem', '-out', certDir + '/c.pem']); const paffLog = []; const paffServer = Bun.serve({ port: 5313, tls: { cert: Bun.file(certDir + '/c.pem'), key: Bun.file(certDir + '/k.pem') }, fetch: async (req) => { const u = new URL(req.url); if (u.pathname === '/log') { paffLog.push(await req.text()); return new Response('ok'); } return new Response(`player`, { headers: { 'content-type': 'text/html' } }); } }); const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox', '--host-resolver-rules=MAP paff.club:443 127.0.0.1:5313', '--ignore-certificate-errors'] }); const page = await browser.newPage(); await page.evaluateOnNewDocument((posts, profile) => { // the registrar's preview endpoint answers from this test's server const realFetch = window.fetch; window.fetch = (u, o) => realFetch(String(u).startsWith('https://names.coinos.io/preview') ? String(u).replace('https://names.coinos.io', 'http://localhost:5311') : u, o); 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] || {}; let evs = []; if ((f.kinds || []).includes(1) && (f.authors || []).includes(profile.pubkey)) evs = posts; if ((f.kinds || []).includes(0) && (f.authors || []).includes(profile.pubkey)) evs = [profile]; setTimeout(() => { for (const e of evs) 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); }, POSTS, PROFILE); 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; }; try { await page.setViewport({ width: 390, height: 844 }); await page.goto('http://localhost:5311/', { 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 seedWords(page); const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' '); await skipSeedCheck(page); await waitText('receive', 20000); const base = cacheKeyFor(mn + '\n'); // follow the author, so the feed asks for their posts await page.evaluate(([k, pk]) => { localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) })); localStorage.setItem(k + ':profiles', JSON.stringify({ [pk]: { name: 'Linker', t: Date.now() } })); localStorage.setItem('btc-wallet-feed:' + k, 'following'); // new wallets open on Popular }, [base, APK]); await page.reload({ waitUntil: 'domcontentloaded' }); await waitText('receive', 20000); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]').click()); await page.waitForSelector('.notes-feed:not([data-booting]) > .row', { timeout: 30000 }); await sleep(800); const rows = await page.evaluate(() => [...document.querySelectorAll('.notes-feed > .row')].map((r) => ({ text: r.textContent.trim().slice(0, 60), card: !!r.querySelector('.link-card'), title: r.querySelector('.link-title')?.textContent, thumb: r.querySelector('.link-thumb')?.getAttribute('src') || r.querySelector('.link-thumb')?.dataset.lazySrc, thumbShown: (() => { const i = r.querySelector('.link-thumb'); return !!i && i.complete && i.naturalWidth > 0; })(), bareLink: !!r.querySelector('a[href^="https://blank.example"]'), img: !!r.querySelector('img.note-img'), }))); const story = rows.find((r) => /well, yeah/i.test(r.text)); const blank = rows.find((r) => /nothing here/i.test(r.text)); const pic = rows.find((r) => /a picture/i.test(r.text)); check('a post with a link paints its card', !!story && story.card, JSON.stringify(story)); check('...with the page\'s title', story?.title === 'Lawmakers doubt the plan', story?.title); check('...and its picture, already decoded', !!story?.thumb && story.thumbShown, JSON.stringify({ thumb: story?.thumb, shown: story?.thumbShown })); check('a page with nothing to show stays a bare link', !!blank && blank.bareLink && !blank.card, JSON.stringify(blank)); check('a picture link is still a picture, not a card', !!pic && pic.img && !pic.card, JSON.stringify(pic)); // a PAFF film link plays in the post, PAFF's bare player loaded only on a tap const paff = await page.evaluate(() => { const r = [...document.querySelectorAll('.notes-feed > .row')].find((n) => /film night/.test(n.textContent)); const b = r && r.querySelector('.paff-embed'); return b && { title: b.querySelector('.paff-title')?.textContent, poster: !!b.querySelector('img.yt-poster'), frame: !!b.querySelector('iframe') }; }); check('a PAFF film link shows as a player with its backdrop and title', !!paff && paff.poster && /Hackers/.test(paff.title || '') && !paff.frame, JSON.stringify(paff)); const src = await page.evaluate(() => { const b = [...document.querySelectorAll('.paff-embed')][0]; b.scrollIntoView({ block: 'center' }); b.querySelector('.yt-play').click(); return b.querySelector('iframe')?.getAttribute('src'); }); check('...and a tap loads PAFF\'s embed player there, the link\'s query kept', src === 'https://paff.club/embed/movie/1382-hackers-1995?q=1080p&t=4910', src); await sleep(900); // the stand-in reports it's playing await page.evaluate(() => scrollTo(0, document.documentElement.scrollHeight + 5000)); await page.evaluate(() => { const s = document.createElement('div'); s.style.height = '3000px'; s.id = 'pad'; document.body.append(s); scrollTo(0, document.documentElement.scrollHeight); }); for (let i = 0; i < 20 && !paffLog.includes('pause'); i++) await sleep(150); check('a playing film pauses once its post is off the screen', paffLog.includes('pause'), JSON.stringify(paffLog)); await page.evaluate(() => document.querySelector('.paff-embed').scrollIntoView({ block: 'center' })); for (let i = 0; i < 20 && !paffLog.includes('play'); i++) await sleep(150); check('...and carries on when it comes back', paffLog.join() === 'pause,play', JSON.stringify(paffLog)); await page.evaluate(() => { document.getElementById('pad')?.remove(); scrollTo(0, 0); }); // a PAFF song plays in the bar above the nav, and keeps playing as you go const song = await page.evaluate(() => { const c = document.querySelector('.paff-song'); return c && { title: c.querySelector('.paff-song-title')?.textContent, cover: !!c.querySelector('img.paff-song-cover'), frame: !!c.querySelector('iframe') }; }); check('a PAFF song link is a card with its cover and title', !!song && song.cover && song.title === 'Halcyon · Orbital' && !song.frame, JSON.stringify(song)); await page.evaluate(() => { const c = document.querySelector('.paff-song'); c.scrollIntoView({ block: 'center' }); c.click(); }); await sleep(300); const bar = await page.evaluate(() => { const b = document.querySelector('.music-bar'), f = b?.querySelector('iframe'), nav = document.querySelector('.app-bottom-nav'); const r = b?.getBoundingClientRect(), n = nav?.getBoundingClientRect(); return b && { src: f?.getAttribute('src'), above: !n || r.bottom <= n.top + 1, playing: document.querySelector('.paff-song')?.textContent.includes('Playing below') }; }); check('a tap plays it in the bar above the nav', !!bar && bar.src === 'https://paff.club/embed/song/abc123?bar=1' && bar.above, JSON.stringify(bar)); check('...and the card says it is playing', !!bar?.playing); if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT }); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Wallet"]')?.click()); await sleep(500); const still = await page.evaluate(() => document.querySelector('.music-bar iframe')?.getAttribute('src')); check('the song carries on on another page', still === 'https://paff.club/embed/song/abc123?bar=1', still); await page.evaluate(() => document.querySelector('.music-close').click()); check('× stops and closes it', await page.evaluate(() => !document.querySelector('.music-bar') && !document.body.classList.contains('music-open'))); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]').click()); await sleep(500); check('the registrar was asked once per link', previewHits.filter((u) => u === 'https://news.example/story/1').length === 1 && !previewHits.some((u) => u.endsWith('.png')), JSON.stringify(previewHits)); let kept = 0; // written behind, a second after the card was learned for (let i = 0; i < 12 && kept < 3; i++) { kept = await page.evaluate(() => JSON.parse((window.coinosCache || localStorage).getItem('coinos-link-previews') || '[]').length); if (kept < 3) await sleep(300); } check('the cards are remembered for next time', kept === 3, kept + ' kept'); // the story's, the film's and the song's // a draft's preview shows the card too (Adam, 2026-11-17: a paff.club // movie link stayed a bare URL in Preview), once the typing settles const opened = await page.evaluate(() => { const b = [...document.querySelectorAll('button')].find((n) => (n.getAttribute('aria-label') || n.textContent).trim().toLowerCase() === 'new post'); if (b) { b.click(); return true; } return false; }); await sleep(400); const typeDraft = (v) => page.evaluate((val) => { const e = document.querySelector('coinos-text'); e.focus(); e.value = val; e.dispatchEvent(new Event('input', { bubbles: true })); }, v); await typeDraft('watch this\n\nhttps://movies.example/movie/1382/play?t=4910'); await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => /preview/i.test(b.getAttribute('aria-label') || ''))?.click()); let draft = null; for (let i = 0; i < 20; i++) { draft = await page.evaluate(() => { const p = document.querySelector('.draft-preview'); return p && { card: !!p.querySelector('.link-card'), title: p.querySelector('.link-title')?.textContent }; }); if (draft?.card) break; await sleep(250); } check('a draft\'s preview shows the link as its card', opened && draft?.card && /Hackers/.test(draft.title || ''), JSON.stringify(draft)); check('...asked for once the typing settled, not per keystroke', previewHits.filter((u) => u.startsWith('https://movies.example')).length === 1, JSON.stringify(previewHits)); check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); } finally { await browser.close(); server.stop(true); paffServer.stop(true); } console.log(ok ? '\n✅ links show as the cards their pages describe' : '\n❌ failed'); process.exit(ok ? 0 : 1);