import { mediaServers } from './media-servers.js'; import { sha256 } from '@noble/hashes/sha256'; import { bytesToHex } from '@noble/hashes/utils'; // Independent public hosts: a phone upload should not fail just because one // provider is down or rejects a particular container. Order from a // 2026-09-30 benchmark (4 MB mp4 / 110 KB jpeg, uploaded then fetched): // ditto took the mp4 in ~0.6 s and serves in ~120 ms; primal ~1.5 s; nostr. // download ~1-2 s but refuses a JPEG with bytes after its end marker (motion // photos); blossom.nostr.build ~5 s. The first to accept the file wins. export const PUBLIC_MEDIA_SERVERS = ['https://blossom.ditto.pub', 'https://blossom.primal.net', 'https://nostr.download', 'https://blossom.nostr.build']; export class MediaUploadError extends Error { constructor(code, details = '') { super(code); this.name = 'MediaUploadError'; this.code = code; this.details = details; } } // Private Blossom hosts authorize the user's Nostr identity, which can differ // from the wallet's sync key. Resolve once for the whole upload (including HLS). export async function mediaUploadSigner(wallet, hook) { const id = hook('nostrLoginIdentity'); if (!id) return (event) => wallet.nostrSign(event); const signer = id.signer || await hook('nostrLoginResume'); if (!signer) throw new MediaUploadError('no-identity'); return (event) => signer.signEvent(event); } async function fileHash(file) { const hash = sha256.create(); const chunk = 4 * 1024 * 1024; for (let at = 0; at < file.size; at += chunk) hash.update(new Uint8Array(await file.slice(at, at + chunk).arrayBuffer())); return bytesToHex(hash.digest()); } const responseUrl = (body) => body?.url || body?.data?.[0]?.url || (body?.tags || []).find((x) => x?.[0] === 'url')?.[1] || null; function mediaUrl(url, server, file) { const out = new URL(url, server); const tail = out.pathname.split('/').at(-1) || ''; if (/^[0-9a-f]{64}$/i.test(tail)) { const named = String(file.name || '').match(/\.([a-z0-9]{1,8})$/i)?.[1]; const byType = { 'video/quicktime': 'mov', 'video/mp4': 'mp4', 'video/webm': 'webm', 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'image/avif': 'avif' }[file.type]; const ext = (named || byType || '').toLowerCase(); if (ext) out.pathname += '.' + ext; } return out.href; } // A PUT that reports how much of the body has gone out: fetch() can't, so in // the browser (with the real fetch) it's XMLHttpRequest. Answers like fetch. function putWithProgress(url, { body, headers, signal }, onProgress) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('PUT', url); for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v); xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(e.loaded / e.total); }; xhr.onload = () => resolve(new Response(xhr.responseText, { status: xhr.status, headers: { 'x-reason': xhr.getResponseHeader('x-reason') || '' } })); xhr.onerror = () => reject(new Error('network error')); xhr.ontimeout = () => reject(new Error('timeout')); if (signal) signal.addEventListener('abort', () => { xhr.abort(); reject(new Error('timeout')); }); xhr.send(body); }); } // BUD-02 upload. `signEvent` is deliberately injected: the app can use its // signed-in Nostr identity, while tests need no secret key. export async function uploadPublicMedia(file, signEvent, { servers = mediaServers(PUBLIC_MEDIA_SERVERS), fetcher = globalThis.fetch, timeoutMs = 5 * 60_000, onProgress = null, // (fraction 0..1) as the bytes go out } = {}) { const tracked = onProgress && typeof XMLHttpRequest !== 'undefined' && fetcher === globalThis.fetch; if (!file || !file.size || typeof signEvent !== 'function') throw new MediaUploadError('failed'); const x = await fileHash(file); const now = Math.floor(Date.now() / 1000); const auth = await signEvent({ kind: 24242, created_at: now - 5, content: 'upload', tags: [['t', 'upload'], ['x', x], ['expiration', String(now + Math.ceil(timeoutMs / 1000) + 120)]], }); if (!auth) throw new MediaUploadError('failed'); const authorization = 'Nostr ' + btoa(JSON.stringify(auth)); const failures = []; for (const [i, server] of servers.entries()) { // A host that doesn't answer at all costs a few seconds, not the whole // upload timeout. Any HTTP answer, even an error, means it's there. if (i < servers.length - 1) { try { await fetcher(server.replace(/\/$/, '') + '/upload', { method: 'HEAD', signal: AbortSignal.timeout(5000) }); } catch (error) { failures.push({ status: 0, reason: 'unreachable' }); continue; } } try { const init = { method: 'PUT', body: file, signal: AbortSignal.timeout(timeoutMs), headers: { authorization, 'content-type': file.type || 'application/octet-stream', 'x-sha-256': x, 'x-content-length': String(file.size), }, }; if (onProgress) onProgress(0); const target = server.replace(/\/$/, '') + '/upload'; const response = tracked ? await putWithProgress(target, init, onProgress) : await fetcher(target, init); let body = null; try { body = await response.json(); } catch {} const url = response.ok && responseUrl(body); if (url) return mediaUrl(url, server, file); failures.push({ status: response.status, reason: response.headers.get('x-reason') || body?.message || '' }); } catch (error) { failures.push({ status: 0, reason: error?.message || '' }); } } const details = failures.map((x) => [x.status, x.reason].filter(Boolean).join(' ')).filter(Boolean).join('; '); if (failures.length && failures.every((x) => x.status === 401 || x.status === 403)) throw new MediaUploadError('unauthorized', details); if (failures.length && failures.every((x) => x.status === 413)) throw new MediaUploadError('too-big', details); if (failures.length && failures.every((x) => x.status === 415)) throw new MediaUploadError('unsupported', details); throw new MediaUploadError('failed', details); } // An HLS stream (streamVideo) onto one host: the media files first, then // each playlist with its files' addresses written in, then the master // playlist naming those — its address is the post's. One host for the lot, // and one that serves a playlist as one (ditto and nostr.download do; // primal's says text/plain, nostr.build won't take it); a host that refuses // any piece is passed over for the next. `files` maps each name the // playlists use to its File. export const STREAM_SERVERS = ['https://blossom.ditto.pub', 'https://nostr.download', 'https://blossom.primal.net']; export function rewritePlaylist(text, urls) { const to = (p) => urls.get(p) || p; return text.split('\n').map((line) => { const l = line.trim(); if (l && !l.startsWith('#')) return to(l); return line.replace(/URI="([^"]+)"/g, (m, p) => `URI="${to(p)}"`); }).join('\n'); } export async function uploadStream({ files, master
// Referenced notification notes are fetched before the page opens, persisted,
// and available on the first paint after a reload.
// Run: bun tools/notif-note-cache-test.js
import puppeteer from 'puppeteer-core';
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((resolve) => setTimeout(resolve, ms));
let ok = true;
const check = (name, pass, detail = '') => {
  console.log(` ${pass ? '✓' : '✗'} ${name}${detail ? ` — ${detail}` : ''}`);
  if (!pass) ok = false;
};
const now = Math.floor(Date.now() / 1000);
const actorSk = generateSecretKey();
const actorPk = getPublicKey(actorSk);
const noteSk = generateSecretKey();
const noteText = 'This notification excerpt came from the local note cache.';
const target = finalizeEvent({ kind: 1, created_at: now - 120, tags: [], content: noteText }, noteSk);
const html = await buildHtml({ minify: true, pwa: false });
const server = Bun.serve({
  port: 5307,
  fetch(req) {
    const path = new URL(req.url).pathname;
    if (path.startsWith('/punks') || path === '/verify-worker.js') 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((targetEvent) => {
  window.__targetReqs = 0;
  const Real = window.WebSocket;
  window.WebSocket = function (...args) {
    const ws = new Real(...args);
    const send = ws.send.bind(ws);
    ws.send = (data) => {
      try {
        const msg = JSON.parse(data);
        if (msg[0] === 'REQ') {
          const filter = msg[2] || {};
          const hit = (filter.ids || []).includes(targetEvent.id);
          if (hit) window.__targetReqs++;
          setTimeout(() => {
            if (hit) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', msg[1], targetEvent]) }));
            ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', msg[1]]) }));
          }, 0);
          return;
        }
        if (msg[0] === 'EVENT') return;
      } catch {}
      return send(data);
    };
    return ws;
  };
  window.WebSocket.prototype = Real.prototype;
  Object.assign(window.WebSocket, Real);
}, target);

const clickText = (text) => page.evaluate((needle) => {
  const el = [...document.querySelectorAll('button')].find((node) => node.textContent.trim().toLowerCase().includes(needle));
  if (!el) return false;
  el.click(); return true;
}, text);
const waitText = async (text, timeout = 20_000) => {
  for (let elapsed = 0; elapsed < timeout; elapsed += 200) {
    if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(text.toLowerCase())) return true;
    await sleep(200);
  }
  return false;
};
const openNotifications = () => page.evaluate(() => {
  const el = [...document.querySelectorAll('button')].find((node) => /notifications/i.test(node.getAttribute('aria-label') || ''));
  if (!el) return false;
  el.click(); return true;
});

try {
  await page.setViewport({ width: 390, height: 844 });
  await page.goto('http://localhost:5307/', { waitUntil: 'domcontentloaded' });
  await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
  await page.reload({ waitUntil: 'domcontentloaded' });
  await sleep(400);
  await clickText('create a new wallet');
  await page.waitForSelector('.words .w .t');
  const mnemonic = (await page.$$eval('.words .w .t', (nodes) => nodes.map((node) => node.textContent.trim()))).join(' ');
  await clickText('skip verification');
  await waitText('receive');
  const base = cacheKeyFor(mnemonic + '\n');
  const me = getPublicKey(privateKeyFromSeedWords(mnemonic));
  const item = { id: 'a'.repeat(64), what: 'react', actor: actorPk, target: target.id, hint: [], emoji: '❤️', ts: now - 30 };
  await page.evaluate(([key, owner, notification]) => {
    const state = JSON.parse(localStorage.getItem(key + ':messages') || '{}');
    state.notifs = [notification]; state.notifsPk = owner;
    localStorage.setItem(key + ':messages', JSON.stringify(state));
  }, [base, me, item]);
  await page.reload({ waitUntil: 'domcontentloaded' });
  await waitText('receive');

  let cached = false;
  for (let i = 0; i < 75; i++) {
    cached = await page.evaluate(([key, id]) => {
      const state = JSON.parse(localStorage.getItem(key + ':messages') || '{}');
      return state.notifNoteCache && state.notifNoteCache[id]?.content;
    }, [base, target.id]);
    if (cached) break;
    await sleep(200);
  }
  check('the referenced note is warmed and persisted', cached === noteText);
  check('the relay was queried while the page was still closed', (await page.evaluate(() => window.__targetReqs)) > 0);

  await page.reload({ waitUntil: 'domcontentloaded' });
  await waitText('receive');
  check('notifications opens from the bottom navigation', await openNotifications());
  await sleep(80);
  const firstPaint = await page.evaluate(() => document.body.innerText);
  check('the cached excerpt is present immediately', firstPaint.includes('This notification excerpt'));
  check('there is no Fetching note placeholder', !firstPaint.includes('Fetching note'));
  check('the persisted note avoids another target query', (await page.evaluate(() => window.__targetReqs)) === 0);
} finally {
  await browser.close();
  server.stop(true);
}

console.log(ok ? '\n✅ notification note cache works' : '\n❌ notification note cache failed');
process.exit(ok ? 0 : 1);