aboutsummaryrefslogtreecommitdiffstats
path: root/createExceptions.js
diff options
context:
space:
mode:
Diffstat (limited to 'createExceptions.js')
0 files changed, 0 insertions, 0 deletions
; padding-right: 5px; } .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888 } /* Comment */ .highlight .err { color: #A61717; background-color: #E3D2D2 } /* Error */ .highlight .k { color: #080; font-weight: bold } /* Keyword */ .highlight .ch { color: #888 } /* Comment.Hashbang */ .highlight .cm { color: #888 } /* Comment.Multiline */ .highlight .cp { color: #C00; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888 } /* Comment.Single */ .highlight .cs { color: #C00; font-weight: bold; background-color: #FFF0F0 } /* Comment.Special */ .highlight .gd { color: #000; background-color: #FDD } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ .highlight .gr { color: #A00 } /* Generic.Error */ .highlight .gh { color: #333 } /* Generic.Heading */ .highlight .gi { color: #000; background-color: #DFD } /* Generic.Inserted */ .highlight .go { color: #888 } /* Generic.Output */ .highlight .gp { color: #555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666 } /* Generic.Subheading */ .highlight .gt { color: #A00 } /* Generic.Traceback */ .highlight .kc { color: #080; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #080; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #080; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #080 } /* Keyword.Pseudo */ .highlight .kr { color: #080; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #00D; font-weight: bold } /* Literal.Number */ .highlight .s { color: #D20; background-color: #FFF0F0 } /* Literal.String */ .highlight .na { color: #369 } /* Name.Attribute */ .highlight .nb { color: #038 } /* Name.Builtin */ .highlight .nc { color: #B06; font-weight: bold } /* Name.Class */ .highlight .no { color: #036; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555 } /* Name.Decorator */ .highlight .ne { color: #B06; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #06B; font-weight: bold } /* Name.Function */ .highlight .nl { color: #369; font-style: italic } /* Name.Label */ .highlight .nn { color: #B06; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #369; font-weight: bold } /* Name.Property */ .highlight .nt { color: #B06; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #369 } /* Name.Variable */ .highlight .ow { color: #080 } /* Operator.Word */ .highlight .w { color: #BBB } /* Text.Whitespace */ .highlight .mb { color: #00D; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #00D; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #00D; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #00D; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #00D; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #D20; background-color: #FFF0F0 } /* Literal.String.Affix */ .highlight .sb { color: #D20; background-color: #FFF0F0 } /* Literal.String.Backtick */ .highlight .sc { color: #D20; background-color: #FFF0F0 } /* Literal.String.Char */ .highlight .dl { color: #D20; background-color: #FFF0F0 } /* Literal.String.Delimiter */ .highlight .sd { color: #D20; background-color: #FFF0F0 } /* Literal.String.Doc */ .highlight .s2 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Double */ .highlight .se { color: #04D; background-color: #FFF0F0 } /* Literal.String.Escape */ .highlight .sh { color: #D20; background-color: #FFF0F0 } /* Literal.String.Heredoc */ .highlight .si { color: #33B; background-color: #FFF0F0 } /* Literal.String.Interpol */ .highlight .sx { color: #2B2; background-color: #F0FFF0 } /* Literal.String.Other */ .highlight .sr { color: #080; background-color: #FFF0FF } /* Literal.String.Regex */ .highlight .s1 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Single */ .highlight .ss { color: #A60; background-color: #FFF0F0 } /* Literal.String.Symbol */ .highlight .bp { color: #038 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #06B; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #369 } /* Name.Variable.Class */ .highlight .vg { color: #D70 } /* Name.Variable.Global */ .highlight .vi { color: #33B } /* Name.Variable.Instance */ .highlight .vm { color: #369 } /* Name.Variable.Magic */ .highlight .il { color: #00D; font-weight: bold } /* Literal.Number.Integer.Long */
// A face or banner whose host has lost the file is found on another server
// that holds the same Blossom blob (same sha256 name): the one the person
// publishes in their kind 10063 first. The small avatar's thumbnail is made
// from the copy, the profile page's big face and banner paint from it, and
// the find is remembered on the device.
// Run: bun tools/blob-alt-test.js
import assert from 'node:assert/strict';
import puppeteer from './puppeteer.js';
import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
import { nip19 } from 'nostr-tools';
import { buildHtml } from '../build.js';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const sk = generateSecretKey(), PK = getPublicKey(sk), now = Math.floor(Date.now() / 1000);
const H1 = 'c11a29785c1af623a45ebfdb23860170a9d0c0ead31c1bcb209085cd662f7a17';
const H2 = '479711427c577f040a5bf8cb05c47f75abfef37580893dd63b66f777c34dc327';
const png = (color) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', `color=c=${color}:size=320x320`, '-frames:v', '1', '-f', 'image2', '-c:v', 'png', 'pipe:1']).stdout;
const FACE = png('orange'), COVER = png('teal');
const html = await buildHtml({ minify: true, pwa: false });
const hits = { dead: 0, alt: 0 };
let origin = '';
const server = Bun.serve({ port: 0, fetch: (req) => {
  const u = new URL(req.url);
  if (u.pathname.startsWith('/dead/')) { hits.dead++; return new Response('{"error":"The requested blob was not found."}', { status: 404, headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*' } }); }
  if (u.pathname === `/alt/${H1}.png`) { hits.alt++; return new Response(FACE, { headers: { 'content-type': 'image/png', 'access-control-allow-origin': '*' } }); }
  if (u.pathname === `/alt/${H2}.png`) { hits.alt++; return new Response(COVER, { headers: { 'content-type': 'image/png', 'access-control-allow-origin': '*' } }); }
  if (u.pathname === '/api/feed') return new Response(snapshot, { headers: { 'content-type': 'application/json' } });
  return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } });
} });
origin = server.url.origin;
const notes = Array.from({ length: 12 }, (_, i) => finalizeEvent({ kind: 1, created_at: now - 60 - i * 60, tags: [], content: `Post ${i}: the harbour at dusk, boats coming in.` }, sk));
const profile = finalizeEvent({ kind: 0, created_at: now, tags: [], content: JSON.stringify({ name: 'Karnage', picture: `${origin}/dead/${H1}.png`, banner: `${origin}/dead/${H2}.png`, about: 'Saying the quiet part out loud.' }) }, sk);
const servers = finalizeEvent({ kind: 10063, created_at: now, tags: [['server', `${origin}/alt/`]], content: '' }, sk);
const snapshot = JSON.stringify({ version: 1, generatedAt: Date.now(), notes, profiles: [profile], popUntil: now - 3600 });
const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] });
try {
  const page = await browser.newPage();
  const errors = [];
  page.on('pageerror', (e) => errors.push(String(e)));
  await page.setViewport({ width: 390, height: 844, isMobile: true, hasTouch: true });
  await page.setRequestInterception(true);
  page.on('request', (r) => r.url().startsWith(origin) ? r.continue() : r.abort()); // the public hosts: unreachable here
  await page.evaluateOnNewDocument(([notes, profile, servers]) => {
    class FakeSocket extends EventTarget {
      constructor(url) { super(); this.url = url; this.readyState = 0; this.subs = new Set();
        setTimeout(() => { this.readyState = 1; this.emit('open', new Event('open')); }, 0); }
      emit(type, ev) { this.dispatchEvent(ev); this['on' + type]?.(ev); }
      message(d) { this.emit('message', new MessageEvent('message', { data: JSON.stringify(d) })); }
      send(raw) {
        let m; try { m = JSON.parse(raw); } catch { return; }
        if (m[0] === 'CLOSE') { this.subs.delete(m[1]); return; }
        if (m[0] !== 'REQ') return;
        const [, id, f] = m; this.subs.add(id);
        let evs = [];
        if (f.kinds?.includes(1) && !f.since) evs = notes.filter((e) => (!f.until || e.created_at <= f.until)
          && (!f.authors || f.authors.includes(e.pubkey)) && (!f.ids || f.ids.includes(e.id))).slice(0, f.limit || 100);
        if (f.kinds?.includes(0) && f.authors?.includes(profile.pubkey)) evs = [profile];
        if (f.kinds?.includes(10063) && f.authors?.includes(servers.pubkey)) evs = [servers];
        if (f.ids) evs = notes.filter((e) => f.ids.includes(e.id));
        setTimeout(() => { if (!this.subs.has(id)) return; for (const e of evs) this.message(['EVENT', id, e]); this.message(['EOSE', id]); }, 30);
      }
      close() { this.readyState = 3; this.emit('close', new Event('close')); }
    }
    Object.assign(FakeSocket, { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 });
    window.WebSocket = FakeSocket;
  }, [notes, profile, servers]);
  const bg = (sel) => page.evaluate((s) => document.querySelector(s)?.style.backgroundImage || '', sel);
  // the feed: the small face's thumbnail is made from the copy
  await page.goto(origin + '/feed', { waitUntil: 'domcontentloaded' });
  await page.waitForFunction(() => document.querySelectorAll('.notes-feed > [data-zap-post]').length >= 5, { timeout: 20000 });
  // the copy is found and the thumbnail made from it (the probe and the
  // thumbnail's own fetch: two hits); the row keeps the look it was admitted
  // with, the next paint wears the face
  for (let i = 0; i < 80 && hits.alt < 2; i++) await sleep(250);
  assert.ok(hits.dead >= 1 && hits.alt >= 2, `the dead host was asked (${hits.dead}) and the copy fetched for the thumbnail (${hits.alt})`);
  console.log('✓ the thumbnail is made from the copy on the published server');
  const remembered = await page.evaluate(() => localStorage.getItem('btc-wallet-blob-alts') || '');
  assert.ok(remembered.includes(`/alt/${H1}.png`), 'the find is remembered on the device');
  // the profile page (the screen that showed an empty circle and no cover):
  // big face and banner from the copies, the post rows' small faces from
  // the thumbnail
  await page.goto(origin + '/' + nip19.npubEncode(PK), { waitUntil: 'domcontentloaded' });
  await page.waitForFunction((h) => (document.querySelector('.profile-banner')?.style.backgroundImage || '').includes('/alt/' + h), { timeout: 20000 }, H2)
    .catch(async () => { throw new Error('banner not from the copy: ' + await bg('.profile-banner')); });
  const face = await bg('.profile-avatar');
  assert.ok(face.includes(`/alt/${H1}.png`), 'the big face paints from the copy: ' + face);
  console.log('✓ the profile page paints the big face and the banner from the copies');
  const rowSel = `.note-post[data-zap-post="${notes[0].id}"] .ava-img`;
  await page.waitForFunction((s, h) => /^url\("data:/.test(document.querySelector(s)?.style.backgroundImage || '') || (document.querySelector(s)?.style.backgroundImage || '').includes('/alt/' + h), { timeout: 20000 }, rowSel, H1)
    .catch(async () => { throw new Error('post row face: ' + await page.evaluate((id) => [...document.querySelector('.note-post[data-zap-post="' + id + '"]')?.querySelectorAll('[class*=avatar], .ava-img') || []].map((e) => e.outerHTML.slice(0, 220)).join(' || '), notes[0].id)); });
  assert.deepEqual(errors, []);
  console.log('✓ the post rows wear the face, and no page errors');
} finally { await browser.close(); server.stop(true); }