aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore3
-rw-r--r--android/app/build.gradle4
-rw-r--r--android/app/src/webview/java/io/coinos/app/Assets.java4
-rw-r--r--extension/build.js23
-rw-r--r--extension/manifest.json27
-rw-r--r--extension/src/background.js305
-rw-r--r--extension/src/content.js15
-rw-r--r--extension/src/popup.html49
-rw-r--r--extension/src/popup.js81
-rw-r--r--extension/src/prompt.html17
-rw-r--r--extension/src/prompt.js20
-rw-r--r--extension/src/provider.js53
-rw-r--r--extension/src/ui.css49
-rw-r--r--fastlane/metadata/android/en-US/changelogs/16.txt1
-rw-r--r--fdroid/io.coinos.fdroid.yml24
-rw-r--r--src/features/messages.js124
-rw-r--r--src/image-thumbnails.js29
-rw-r--r--src/nostr-login.js21
-rw-r--r--src/nostr.js25
-rw-r--r--src/style.css7
-rw-r--r--tools/connect-relays-test.js18
-rw-r--r--tools/extension-test.js198
-rw-r--r--tools/feed-picture-pager-test.js15
-rw-r--r--tools/gif-loop-test.js21
-rw-r--r--tools/live-stream-test.js24
-rw-r--r--tools/profile-depth-test.js45
26 files changed, 1175 insertions, 27 deletions
diff --git a/.gitignore b/.gitignore
index 2f2f595..483e3c5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,6 @@ tools/.*.tmp.js
# Local runtime session store (server side, not part of the wallet build)
/db/
+
+# Browser extension build (rebuild with `bun extension/build.js`)
+/extension/dist
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 8dcfc04..a03c651 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -47,8 +47,8 @@ android {
applicationId 'io.coinos.app'
minSdk 24
targetSdk 35
- versionCode 15
- versionName '1.14'
+ versionCode 16
+ versionName '1.15'
}
// Two builds of the same wallet.
//
diff --git a/android/app/src/webview/java/io/coinos/app/Assets.java b/android/app/src/webview/java/io/coinos/app/Assets.java
index 9e4f909..5e230e1 100644
--- a/android/app/src/webview/java/io/coinos/app/Assets.java
+++ b/android/app/src/webview/java/io/coinos/app/Assets.java
@@ -32,7 +32,9 @@ final class Assets {
private Assets() {}
static final String HOST = "v3.coinos.io";
- private static final String[] LIVE = { "/electrum", "/esplora/", "/lnurlp/", "/.well-known/", "/api/" };
+ // /live/: streams and the TURN credentials calls need; /vmedia/: video
+ // posters and H.264 copies. Both answer data (JSON, media), never pages.
+ private static final String[] LIVE = { "/electrum", "/esplora/", "/lnurlp/", "/.well-known/", "/api/", "/live/", "/vmedia/" };
private static final Map<String, String> MIME = new HashMap<>();
static {
MIME.put("html", "text/html");
diff --git a/extension/build.js b/extension/build.js
new file mode 100644
index 0000000..e9013e0
--- /dev/null
+++ b/extension/build.js
@@ -0,0 +1,23 @@
+// Builds the browser extension into extension/dist (load that folder
+// unpacked at chrome://extensions, Developer mode on).
+// bun extension/build.js
+import { rm, mkdir, cp } from 'node:fs/promises';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const out = join(here, 'dist');
+await rm(out, { recursive: true, force: true });
+await mkdir(out, { recursive: true });
+
+const r = await Bun.build({
+ entrypoints: ['background.js', 'popup.js', 'prompt.js'].map((f) => join(here, 'src', f)),
+ outdir: out, target: 'browser', format: 'esm', minify: false,
+});
+if (!r.success) { for (const l of r.logs) console.error(l); process.exit(1); }
+
+for (const f of ['content.js', 'provider.js', 'popup.html', 'prompt.html', 'ui.css']) await cp(join(here, 'src', f), join(out, f));
+await cp(join(here, 'manifest.json'), join(out, 'manifest.json'));
+await cp(join(here, '..', 'static', 'icon-192.png'), join(out, 'icon-192.png'));
+await cp(join(here, '..', 'static', 'PublicSans.woff2'), join(out, 'PublicSans.woff2'));
+console.log('extension built →', out);
diff --git a/extension/manifest.json b/extension/manifest.json
new file mode 100644
index 0000000..1035476
--- /dev/null
+++ b/extension/manifest.json
@@ -0,0 +1,27 @@
+{
+ "manifest_version": 3,
+ "name": "Coinos",
+ "version": "0.1.0",
+ "description": "Sign in to nostr sites with your key and pay from your Coinos wallet. Approve a site once and it never asks again.",
+ "minimum_chrome_version": "116",
+ "icons": { "16": "icon-192.png", "48": "icon-192.png", "128": "icon-192.png" },
+ "action": { "default_popup": "popup.html", "default_title": "Coinos", "default_icon": "icon-192.png" },
+ "options_ui": { "page": "popup.html", "open_in_tab": true },
+ "background": { "service_worker": "background.js", "type": "module" },
+ "permissions": ["storage"],
+ "content_scripts": [
+ {
+ "matches": ["http://*/*", "https://*/*"],
+ "js": ["content.js"],
+ "run_at": "document_start",
+ "all_frames": true
+ },
+ {
+ "matches": ["http://*/*", "https://*/*"],
+ "js": ["provider.js"],
+ "run_at": "document_start",
+ "all_frames": true,
+ "world": "MAIN"
+ }
+ ]
+}
diff --git a/extension/src/background.js b/extension/src/background.js
new file mode 100644
index 0000000..dcefa18
--- /dev/null
+++ b/extension/src/background.js
@@ -0,0 +1,305 @@
+// The extension's background worker. It holds the nostr key and the wallet
+// connection, decides which sites may use them, and answers the calls a
+// page makes through window.nostr and window.webln.
+//
+// A site is asked about once: "Always allow" is remembered for good (until
+// the site is removed in the popup), so signing never prompts again. Signing
+// and paying are separate permissions.
+//
+// The wallet is the person's Coinos wallet, reached over Nostr Wallet Connect
+// (NIP-47): the extension holds a connection string, never the wallet's keys,
+// and the wallet enforces that connection's budget.
+
+import { finalizeEvent, getPublicKey, nip04, nip19, nip44 } from 'nostr-tools';
+import { Relay } from 'nostr-tools/relay';
+import { HDKey } from '@scure/bip32';
+import { mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';
+import { wordlist } from '@scure/bip39/wordlists/english.js';
+import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js';
+
+const store = {
+ get: async (k) => (await chrome.storage.local.get(k))[k],
+ set: (k, v) => chrome.storage.local.set({ [k]: v }),
+ del: (k) => chrome.storage.local.remove(k),
+};
+
+// ── the key ────────────────────────────────────────────────────────────────
+// Kept in the extension's own storage, unencrypted: signing without a prompt
+// means the key has to be readable whenever a site asks. No page can read it.
+async function secretKey() {
+ const k = await store.get('key');
+ if (!k || !k.sk) throw new Error('The Coinos extension has no key yet. Click its icon to set it up.');
+ return hexToBytes(k.sk);
+}
+
+// "nsec1…", 64 hex characters, or twelve/twenty-four words (NIP-06, the key
+// Coinos derives for a wallet: m/44'/1237'/0'/0/0).
+function parseKey(input) {
+ const s = String(input || '').trim();
+ if (/^nsec1/i.test(s)) {
+ const d = nip19.decode(s.toLowerCase());
+ if (d.type !== 'nsec') throw new Error('That is not an nsec');
+ return { sk: bytesToHex(d.data), source: 'nsec' };
+ }
+ if (/^[0-9a-f]{64}$/i.test(s)) return { sk: s.toLowerCase(), source: 'hex' };
+ const words = s.toLowerCase().split(/\s+/).join(' ');
+ if (validateMnemonic(words, wordlist)) {
+ const sk = HDKey.fromMasterSeed(mnemonicToSeedSync(words)).derive("m/44'/1237'/0'/0/0").privateKey;
+ return { sk: bytesToHex(sk), source: 'seed' };
+ }
+ throw new Error('Enter an nsec, or the twelve words of a Coinos wallet');
+}
+
+// ── sites ──────────────────────────────────────────────────────────────────
+// sites[origin] = { sign: true|false, pay: true|false, at } — true is "always
+// allow", false is "never", absent means ask.
+const sitesOf = async () => (await store.get('sites')) || {};
+
+const asks = new Map(); // `${origin} ${kind}` → { promise, resolve, reject, windowId }
+let askSeq = 0;
+
+// A worker with nothing to do is stopped after 30 s; one waiting on a prompt
+// or on the wallet has to stay. Any extension API call resets that clock.
+let busy = 0;
+let beat = null;
+function hold() {
+ busy++;
+ if (!beat) beat = setInterval(() => { chrome.runtime.getPlatformInfo(() => {}); }, 20_000);
+ return () => { if (--busy <= 0) { busy = 0; clearInterval(beat); beat = null; } };
+}
+
+async function allowed(origin, kind) {
+ const site = (await sitesOf())[origin];
+ if (site && site[kind] === true) return;
+ if (site && site[kind] === false) throw new Error('This site is blocked in the Coinos extension');
+ const key = `${origin} ${kind}`;
+ let ask = asks.get(key);
+ if (!ask) {
+ ask = { id: `${Date.now().toString(36)}${++askSeq}` };
+ ask.promise = new Promise((resolve, reject) => { ask.resolve = resolve; ask.reject = reject; });
+ asks.set(key, ask);
+ const release = hold();
+ ask.promise.catch(() => {}).finally(() => { asks.delete(key); release(); });
+ const url = chrome.runtime.getURL(`prompt.html?id=${ask.id}&kind=${kind}&origin=${encodeURIComponent(origin)}`);
+ try {
+ const w = await chrome.windows.create({ url, type: 'popup', width: 400, height: 330, focused: true });
+ ask.windowId = w.id;
+ } catch (err) {
+ ask.reject(new Error('Could not open the approval window'));
+ }
+ }
+ return ask.promise;
+}
+
+// the prompt closed without an answer: this request is refused, the site is
+// asked again next time
+chrome.windows.onRemoved.addListener((windowId) => {
+ for (const ask of asks.values()) if (ask.windowId === windowId) ask.reject(new Error('Request was dismissed'));
+});
+
+async function answerAsk({ id, origin, kind, choice }) {
+ const ask = [...asks.values()].find((a) => a.id === id);
+ if (choice === 'always' || choice === 'never') {
+ const sites = await sitesOf();
+ sites[origin] = { ...(sites[origin] || {}), [kind]: choice === 'always', at: Date.now() };
+ await store.set('sites', sites);
+ }
+ if (!ask) return;
+ if (choice === 'always') ask.resolve();
+ else ask.reject(new Error(choice === 'never' ? 'This site is blocked in the Coinos extension' : 'Request was denied'));
+}
+
+// ── the wallet (NIP-47 client) ─────────────────────────────────────────────
+function parseNwc(uri) {
+ const s = String(uri || '').trim();
+ if (!/^nostr\+walletconnect:/i.test(s)) throw new Error('Paste a connection string that starts with nostr+walletconnect://');
+ const u = new URL(s.replace(/^nostr\+walletconnect:(\/\/)?/i, 'http://'));
+ const walletPk = u.hostname.toLowerCase();
+ const secret = (u.searchParams.get('secret') || '').toLowerCase();
+ const relays = u.searchParams.getAll('relay').filter((r) => /^wss?:\/\//.test(r));
+ if (!/^[0-9a-f]{64}$/.test(walletPk) || !/^[0-9a-f]{64}$/.test(secret) || !relays.length) throw new Error('That connection string is incomplete');
+ return { walletPk, secret, relays };
+}
+
+// One request, one answer. The request goes to every relay in the connection
+// and the first reply wins; a relay that is down is skipped.
+async function wallet(method, params = {}, timeout = 60_000) {
+ const c = await store.get('nwc');
+ if (!c) throw new Error('No wallet is connected. Click the Coinos extension to connect one.');
+ const sk = hexToBytes(c.secret);
+ const content = await nip04.encrypt(sk, c.walletPk, JSON.stringify({ method, params }));
+ const req = finalizeEvent({ kind: 23194, created_at: Math.floor(Date.now() / 1000), tags: [['p', c.walletPk]], content }, sk);
+ const release = hold();
+ const open = [];
+ try {
+ return await new Promise((resolve, reject) => {
+ let done = false;
+ let sent = 0;
+ let failed = 0;
+ const finish = (fn, v) => { if (!done) { done = true; clearTimeout(timer); fn(v); } };
+ const timer = setTimeout(() => finish(reject, new Error(sent ? 'The wallet did not answer in time' : 'Could not reach the wallet\'s relays')), timeout);
+ const onevent = async (ev) => {
+ if (done || ev.pubkey !== c.walletPk) return;
+ try {
+ const res = JSON.parse(await nip04.decrypt(sk, c.walletPk, ev.content));
+ if (res.error) finish(reject, new Error(res.error.message || res.error.code || 'The wallet refused'));
+ else finish(resolve, res.result || {});
+ } catch (_) { /* not ours to read */ }
+ };
+ for (const url of c.relays) {
+ (async () => {
+ try {
+ const relay = await Relay.connect(url);
+ open.push(relay);
+ if (done) return;
+ relay.subscribe([{ kinds: [23195], authors: [c.walletPk], '#e': [req.id] }], { onevent });
+ await relay.publish(req);
+ sent++;
+ } catch (_) {
+ if (++failed === c.relays.length) finish(reject, new Error('Could not reach the wallet\'s relays'));
+ }
+ })();
+ }
+ });
+ } finally {
+ for (const r of open) { try { r.close(); } catch (_) {} }
+ release();
+ }
+}
+
+// ── what a page may call ───────────────────────────────────────────────────
+const SIGN = new Set(['nostr.getPublicKey', 'nostr.signEvent', 'nostr.getRelays', 'nostr.nip04.encrypt', 'nostr.nip04.decrypt', 'nostr.nip44.encrypt', 'nostr.nip44.decrypt']);
+const PAY = new Set(['webln.enable', 'webln.getInfo', 'webln.sendPayment', 'webln.makeInvoice', 'webln.getBalance']);
+const hex64 = (s) => typeof s === 'string' && /^[0-9a-f]{64}$/i.test(s);
+
+async function pageCall(origin, method, p = {}) {
+ if (SIGN.has(method)) {
+ const sk = await secretKey(); // "set me up" before "allow this site?"
+ await allowed(origin, 'sign');
+ switch (method) {
+ case 'nostr.getPublicKey': return getPublicKey(sk);
+ case 'nostr.getRelays': return {};
+ case 'nostr.signEvent': {
+ const e = p.event || {};
+ if (!Number.isInteger(e.kind) || typeof e.content !== 'string') throw new Error('Not a nostr event');
+ return finalizeEvent({
+ kind: e.kind,
+ content: e.content,
+ tags: Array.isArray(e.tags) ? e.tags : [],
+ created_at: Number.isInteger(e.created_at) ? e.created_at : Math.floor(Date.now() / 1000),
+ }, sk);
+ }
+ }
+ if (!hex64(p.pubkey)) throw new Error('Not a public key');
+ const pk = p.pubkey.toLowerCase();
+ switch (method) {
+ case 'nostr.nip04.encrypt': return nip04.encrypt(sk, pk, String(p.plaintext));
+ case 'nostr.nip04.decrypt': return nip04.decrypt(sk, pk, String(p.ciphertext));
+ case 'nostr.nip44.encrypt': return nip44.encrypt(String(p.plaintext), nip44.getConversationKey(sk, pk));
+ case 'nostr.nip44.decrypt': return nip44.decrypt(String(p.ciphertext), nip44.getConversationKey(sk, pk));
+ }
+ }
+ if (PAY.has(method)) {
+ if (!(await store.get('nwc'))) throw new Error('No wallet is connected. Click the Coinos extension to connect one.');
+ await allowed(origin, 'pay');
+ switch (method) {
+ case 'webln.enable': return { enabled: true };
+ case 'webln.getInfo': return { node: { alias: 'Coinos' }, methods: ['enable', 'getInfo', 'sendPayment', 'makeInvoice', 'getBalance'], supports: ['lightning'] };
+ case 'webln.sendPayment': {
+ const invoice = String(p.paymentRequest || '').trim().replace(/^lightning:/i, '');
+ if (!/^ln/i.test(invoice)) throw new Error('Not a Lightning invoice');
+ const r = await wallet('pay_invoice', { invoice }, 90_000);
+ return { preimage: r.preimage || '' };
+ }
+ case 'webln.makeInvoice': {
+ const a = p.args;
+ const o = a && typeof a === 'object' ? a : { amount: a };
+ const sats = Number(o.amount ?? o.defaultAmount ?? 0);
+ if (!Number.isFinite(sats) || sats <= 0) throw new Error('An invoice needs an amount');
+ const r = await wallet('make_invoice', { amount: Math.round(sats * 1000), description: String(o.defaultMemo || o.memo || '') });
+ return { paymentRequest: r.invoice, rHash: r.payment_hash || '' };
+ }
+ case 'webln.getBalance': {
+ const r = await wallet('get_balance', {}, 20_000);
+ return { balance: Math.floor((r.balance || 0) / 1000), currency: 'sats' };
+ }
+ }
+ }
+ throw new Error(`${method} is not supported by the Coinos extension`);
+}
+
+// ── what the extension's own pages (popup, prompt) may call ────────────────
+async function profileOf(pk) {
+ // the name and picture for the popup's header, when a relay has them
+ const cached = await store.get('profile');
+ if (cached && cached.pk === pk && Date.now() - cached.at < 6 * 3600_000) return cached;
+ let relay;
+ try {
+ relay = await Relay.connect('wss://relay.coinos.io');
+ const ev = await new Promise((resolve) => {
+ let best = null;
+ const t = setTimeout(() => resolve(best), 3000);
+ relay.subscribe([{ kinds: [0], authors: [pk], limit: 1 }], {
+ onevent: (e) => { if (!best || e.created_at > best.created_at) best = e; },
+ oneose: () => { clearTimeout(t); resolve(best); },
+ });
+ });
+ const m = ev ? JSON.parse(ev.content) : {};
+ const out = { pk, at: Date.now(), name: String(m.display_name || m.name || '').slice(0, 60), picture: /^https:\/\//.test(m.picture || '') ? m.picture : '', nip05: String(m.nip05 || '').slice(0, 80) };
+ await store.set('profile', out);
+ return out;
+ } catch (_) { return cached && cached.pk === pk ? cached : null; }
+ finally { try { relay && relay.close(); } catch (_) {} }
+}
+
+async function ownCall(m) {
+ switch (m.type) {
+ case 'state': {
+ const k = await store.get('key');
+ const pk = k ? getPublicKey(hexToBytes(k.sk)) : null;
+ const c = await store.get('nwc');
+ return { pubkey: pk, npub: pk ? nip19.npubEncode(pk) : null, source: k ? k.source : null, wallet: c ? { relays: c.relays } : null, sites: await sitesOf() };
+ }
+ case 'profile': {
+ const k = await store.get('key');
+ return k ? profileOf(getPublicKey(hexToBytes(k.sk))) : null;
+ }
+ case 'setKey': await store.set('key', parseKey(m.input)); await store.del('profile'); return true;
+ case 'removeKey': await store.del('key'); await store.del('profile'); return true;
+ case 'setWallet': await store.set('nwc', parseNwc(m.uri)); return true;
+ case 'removeWallet': await store.del('nwc'); return true;
+ case 'removeSite': {
+ const sites = await sitesOf();
+ delete sites[m.origin];
+ await store.set('sites', sites);
+ return true;
+ }
+ case 'balance': {
+ const r = await wallet('get_balance', {}, 20_000);
+ return Math.floor((r.balance || 0) / 1000);
+ }
+ case 'transactions': {
+ const r = await wallet('list_transactions', { limit: 12 }, 20_000);
+ return (r.transactions || []).map((t) => ({
+ type: t.type, sats: Math.floor((t.amount || 0) / 1000), at: t.settled_at || t.created_at || 0, memo: String(t.description || '').slice(0, 80),
+ }));
+ }
+ case 'answer': await answerAsk(m); return true;
+ }
+ throw new Error('Unknown message');
+}
+
+chrome.runtime.onMessage.addListener((m, sender, respond) => {
+ if (!m || typeof m !== 'object') return;
+ const own = !!sender.url && sender.url.startsWith(chrome.runtime.getURL('')) && sender.id === chrome.runtime.id;
+ let work;
+ if (m.type === 'request' && !own) {
+ let origin = sender.origin;
+ if (!origin || origin === 'null') { try { origin = new URL(sender.url).origin; } catch (_) { origin = ''; } }
+ work = /^https?:\/\//.test(origin) ? pageCall(origin, String(m.method), m.params || {}) : Promise.reject(new Error('This page cannot use the Coinos extension'));
+ } else if (own) {
+ work = ownCall(m);
+ } else return;
+ work.then((result) => respond({ result }), (err) => respond({ error: String((err && err.message) || err) }));
+ return true; // answered later
+});
diff --git a/extension/src/content.js b/extension/src/content.js
new file mode 100644
index 0000000..bf1ca65
--- /dev/null
+++ b/extension/src/content.js
@@ -0,0 +1,15 @@
+// The bridge between a page's window.nostr / window.webln (provider.js, in
+// the page's own world) and the extension's background worker.
+window.addEventListener('message', async (e) => {
+ if (e.source !== window || !e.data || e.data.__coinos !== 'req') return;
+ const { id, method, params } = e.data;
+ let res;
+ try {
+ res = await chrome.runtime.sendMessage({ type: 'request', method, params });
+ if (!res) res = { error: 'The Coinos extension did not answer' };
+ } catch (err) {
+ // the extension was reloaded or updated under this page
+ res = { error: /context invalidated/i.test(String(err && err.message)) ? 'The Coinos extension was updated. Reload this page.' : String((err && err.message) || err) };
+ }
+ window.postMessage({ __coinos: 'res', id, result: res.result, error: res.error }, '*');
+});
diff --git a/extension/src/popup.html b/extension/src/popup.html
new file mode 100644
index 0000000..331b838
--- /dev/null
+++ b/extension/src/popup.html
@@ -0,0 +1,49 @@
+<!doctype html>
+<html lang="en">
+<head><meta charset="utf-8"><title>Coinos</title><link rel="stylesheet" href="ui.css"></head>
+<body>
+ <section id="setup" hidden>
+ <div class="card">
+ <h1>Set up your key</h1>
+ <p class="muted" style="margin-top:6px">Paste your nsec, or the twelve words of a Coinos wallet. It stays in this browser and is never shown to a site.</p>
+ <textarea id="key-input" spellcheck="false" autocomplete="off" aria-label="nsec or twelve words"></textarea>
+ <p class="err" id="key-err"></p>
+ <button id="key-save" class="primary" style="width:100%">Save key</button>
+ </div>
+ </section>
+
+ <section id="main" hidden>
+ <div class="head">
+ <img id="pic" src="icon-192.png" alt="">
+ <div class="who">
+ <div id="name" style="font-weight:650"></div>
+ <div class="mono muted" id="npub"></div>
+ </div>
+ <button id="copy">Copy</button>
+ </div>
+
+ <div class="card" id="wallet-on" hidden>
+ <h2>Wallet</h2>
+ <div class="balance" id="balance">…</div>
+ <p class="err" id="wallet-err"></p>
+ <ul id="txs"></ul>
+ <p class="small" style="margin:10px 0 0"><button id="wallet-remove" class="link">Disconnect wallet</button></p>
+ </div>
+ <div class="card" id="wallet-off" hidden>
+ <h2>Wallet</h2>
+ <p class="muted">To pay from sites, open Coinos, go to Settings and add a connection under Nostr Wallet Connect, then paste its connection string here.</p>
+ <textarea id="nwc-input" spellcheck="false" autocomplete="off" aria-label="Connection string" placeholder="nostr+walletconnect://…"></textarea>
+ <p class="err" id="nwc-err"></p>
+ <button id="nwc-save" class="primary" style="width:100%">Connect wallet</button>
+ </div>
+
+ <div class="card">
+ <h2>Sites</h2>
+ <p class="muted small" id="no-sites">No site has asked yet. The first time one does, you choose once.</p>
+ <ul id="sites"></ul>
+ </div>
+ <p class="small" style="text-align:center"><button id="key-remove" class="link">Remove key from this browser</button></p>
+ </section>
+ <script type="module" src="popup.js"></script>
+</body>
+</html>
diff --git a/extension/src/popup.js b/extension/src/popup.js
new file mode 100644
index 0000000..8d9f8cf
--- /dev/null
+++ b/extension/src/popup.js
@@ -0,0 +1,81 @@
+// The extension's popup (and, opened in a tab, its settings page): the key,
+// the connected wallet's balance and recent payments, and the sites that
+// were allowed or blocked.
+const $ = (id) => document.getElementById(id);
+const send = async (m) => {
+ const r = await chrome.runtime.sendMessage(m);
+ if (!r || r.error) throw new Error((r && r.error) || 'No answer');
+ return r.result;
+};
+if (new URLSearchParams(location.search).has('tab') || window.innerWidth > 500) document.body.classList.add('tab');
+const sats = (n) => Number(n).toLocaleString('en-US');
+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
+
+async function render() {
+ const s = await send({ type: 'state' });
+ $('setup').hidden = !!s.pubkey;
+ $('main').hidden = !s.pubkey;
+ if (!s.pubkey) { $('key-input').focus(); return; }
+
+ $('npub').textContent = s.npub.slice(0, 14) + '…' + s.npub.slice(-6);
+ $('name').textContent = 'Your key';
+ $('copy').onclick = async () => { await navigator.clipboard.writeText(s.npub); $('copy').textContent = 'Copied'; setTimeout(() => { $('copy').textContent = 'Copy'; }, 1200); };
+ send({ type: 'profile' }).then((p) => {
+ if (!p) return;
+ if (p.name) $('name').textContent = p.name;
+ if (p.picture) $('pic').src = p.picture;
+ }).catch(() => {});
+
+ $('wallet-on').hidden = !s.wallet;
+ $('wallet-off').hidden = !!s.wallet;
+ if (s.wallet) {
+ $('wallet-err').textContent = '';
+ send({ type: 'balance' }).then((b) => {
+ $('balance').textContent = sats(b);
+ $('balance').append(el('span', '', 'sats'));
+ }).catch((e) => { $('balance').textContent = '—'; $('wallet-err').textContent = e.message; });
+ send({ type: 'transactions' }).then((txs) => {
+ $('txs').replaceChildren(...txs.map((t) => {
+ const li = el('li');
+ li.append(el('span', 'grow', t.memo || (t.type === 'incoming' ? 'Received' : 'Sent')));
+ li.append(el('span', t.type === 'incoming' ? 'in' : '', (t.type === 'incoming' ? '+' : '−') + sats(t.sats)));
+ return li;
+ }));
+ }).catch(() => {});
+ }
+
+ const sites = Object.entries(s.sites).sort((a, b) => (b[1].at || 0) - (a[1].at || 0));
+ $('no-sites').hidden = sites.length > 0;
+ $('sites').replaceChildren(...sites.map(([origin, p]) => {
+ const li = el('li');
+ li.append(el('span', 'grow', origin.replace(/^https:\/\//, '')));
+ if (p.sign === true) li.append(el('span', 'tag', 'signs'));
+ if (p.pay === true) li.append(el('span', 'tag', 'pays'));
+ if (p.sign === false || p.pay === false) li.append(el('span', 'tag', 'blocked'));
+ const rm = el('button', 'link', 'Remove');
+ rm.setAttribute('aria-label', 'Remove ' + origin);
+ rm.onclick = async () => { await send({ type: 'removeSite', origin }); render(); };
+ li.append(rm);
+ return li;
+ }));
+}
+
+$('key-save').onclick = async () => {
+ $('key-err').textContent = '';
+ try { await send({ type: 'setKey', input: $('key-input').value }); $('key-input').value = ''; render(); }
+ catch (e) { $('key-err').textContent = e.message; }
+};
+$('nwc-save').onclick = async () => {
+ $('nwc-err').textContent = '';
+ try { await send({ type: 'setWallet', uri: $('nwc-input').value }); $('nwc-input').value = ''; render(); }
+ catch (e) { $('nwc-err').textContent = e.message; }
+};
+$('wallet-remove').onclick = async () => { await send({ type: 'removeWallet' }); render(); };
+$('key-remove').onclick = async () => {
+ const b = $('key-remove');
+ if (b.dataset.sure !== '1') { b.dataset.sure = '1'; b.textContent = 'Click again to remove the key'; return; }
+ await send({ type: 'removeKey' });
+ b.dataset.sure = ''; b.textContent = 'Remove key from this browser';
+ render();
+};
+render();
diff --git a/extension/src/prompt.html b/extension/src/prompt.html
new file mode 100644
index 0000000..bca4f82
--- /dev/null
+++ b/extension/src/prompt.html
@@ -0,0 +1,17 @@
+<!doctype html>
+<html lang="en">
+<head><meta charset="utf-8"><title>Coinos</title><link rel="stylesheet" href="ui.css"></head>
+<body class="prompt">
+ <div class="card">
+ <h2 id="what"></h2>
+ <p class="origin" id="origin"></p>
+ <p class="muted" id="detail"></p>
+ <div class="buttons">
+ <button id="deny">Not now</button>
+ <button id="allow" class="primary">Always allow</button>
+ </div>
+ </div>
+ <p class="small" style="text-align:center"><button id="never" class="link">Never for this site</button></p>
+ <script type="module" src="prompt.js"></script>
+</body>
+</html>
diff --git a/extension/src/prompt.js b/extension/src/prompt.js
new file mode 100644
index 0000000..6637f70
--- /dev/null
+++ b/extension/src/prompt.js
@@ -0,0 +1,20 @@
+// The one question a site ever gets asked: may it use the key (or the
+// wallet)? "Always allow" is remembered; the site is not asked again.
+const q = new URLSearchParams(location.search);
+const origin = q.get('origin') || '';
+const kind = q.get('kind') === 'pay' ? 'pay' : 'sign';
+const $ = (id) => document.getElementById(id);
+$('origin').textContent = origin.replace(/^https:\/\//, '');
+$('what').textContent = kind === 'pay' ? 'Let this site use your wallet?' : 'Let this site use your nostr key?';
+$('detail').textContent = kind === 'pay'
+ ? 'It will be able to see your balance, create invoices and send payments without asking, within the limit you set on the wallet connection.'
+ : 'It will be able to see your public key, sign as you and read your private messages, without asking again.';
+const answer = async (choice) => {
+ for (const b of document.querySelectorAll('button')) b.disabled = true;
+ await chrome.runtime.sendMessage({ type: 'answer', id: q.get('id'), origin, kind, choice });
+ window.close();
+};
+$('allow').onclick = () => answer('always');
+$('deny').onclick = () => answer('deny');
+$('never').onclick = () => answer('never');
+$('allow').focus();
diff --git a/extension/src/provider.js b/extension/src/provider.js
new file mode 100644
index 0000000..d662212
--- /dev/null
+++ b/extension/src/provider.js
@@ -0,0 +1,53 @@
+// Runs in the page itself: window.nostr (NIP-07) and window.webln. Every call
+// is a message to the content script, which hands it to the extension; the
+// key and the wallet connection never enter the page.
+(() => {
+ if (window.nostr && window.nostr._coinos) return;
+ const pending = new Map();
+ let n = 0;
+ window.addEventListener('message', (e) => {
+ if (e.source !== window || !e.data || e.data.__coinos !== 'res') return;
+ const p = pending.get(e.data.id);
+ if (!p) return;
+ pending.delete(e.data.id);
+ if (e.data.error) p.reject(new Error(e.data.error));
+ else p.resolve(e.data.result);
+ });
+ const call = (method, params) => new Promise((resolve, reject) => {
+ const id = `${Date.now().toString(36)}-${++n}-${Math.random().toString(36).slice(2)}`;
+ pending.set(id, { resolve, reject });
+ window.postMessage({ __coinos: 'req', id, method, params }, '*');
+ });
+
+ window.nostr = {
+ _coinos: true,
+ getPublicKey: () => call('nostr.getPublicKey'),
+ signEvent: (event) => call('nostr.signEvent', { event }),
+ getRelays: () => call('nostr.getRelays'),
+ nip04: {
+ encrypt: (pubkey, plaintext) => call('nostr.nip04.encrypt', { pubkey, plaintext }),
+ decrypt: (pubkey, ciphertext) => call('nostr.nip04.decrypt', { pubkey, ciphertext }),
+ },
+ nip44: {
+ encrypt: (pubkey, plaintext) => call('nostr.nip44.encrypt', { pubkey, plaintext }),
+ decrypt: (pubkey, ciphertext) => call('nostr.nip44.decrypt', { pubkey, ciphertext }),
+ },
+ };
+
+ const unsupported = (what) => () => Promise.reject(new Error(`${what} is not supported by the Coinos extension`));
+ window.webln = {
+ _coinos: true,
+ enabled: false,
+ isEnabled: () => Promise.resolve(window.webln.enabled),
+ enable: async () => { const r = await call('webln.enable'); window.webln.enabled = true; return r; },
+ getInfo: () => call('webln.getInfo'),
+ sendPayment: (paymentRequest) => call('webln.sendPayment', { paymentRequest }),
+ makeInvoice: (args) => call('webln.makeInvoice', { args }),
+ getBalance: () => call('webln.getBalance'),
+ keysend: unsupported('keysend'),
+ signMessage: unsupported('signMessage'),
+ verifyMessage: unsupported('verifyMessage'),
+ lnurl: unsupported('lnurl'),
+ };
+ window.dispatchEvent(new Event('webln:ready'));
+})();
diff --git a/extension/src/ui.css b/extension/src/ui.css
new file mode 100644
index 0000000..26c183b
--- /dev/null
+++ b/extension/src/ui.css
@@ -0,0 +1,49 @@
+@font-face { font-family: "Public Sans"; font-weight: 100 900; font-display: swap; src: url("PublicSans.woff2") format("woff2"); }
+:root {
+ --bg: #eef0f3; --paper: #fff; --ink: #15171a; --muted: #6b7280; --line: #e6e8ec; --line-strong: #d4d8de;
+ --fill: #15171a; --fill-fg: #fff; --soft: #f7f8fa; --green: #14935a; --red: #c43b3b;
+ --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
+ --sans: "Public Sans", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+}
+@media (prefers-color-scheme: dark) {
+ :root { --bg: #15171a; --paper: #1d2024; --ink: #eceef1; --muted: #9aa1ac; --line: #2a2e34; --line-strong: #3a3f47; --fill: #34383f; --fill-fg: #fff; --soft: #24272c; --green: #3ecf8e; --red: #ef6b6b; }
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.45 var(--sans); }
+body { width: 360px; padding: 14px; }
+body.prompt { width: auto; }
+body.tab { width: auto; max-width: 440px; margin: 0 auto; padding: 32px 14px; }
+h1 { font-size: 15px; font-weight: 650; margin: 0; }
+h2 { font-size: 12px; font-weight: 600; color: var(--muted); margin: 0 0 8px; }
+p { margin: 0 0 10px; }
+.muted { color: var(--muted); }
+.small { font-size: 12px; }
+.card { background: var(--paper); border: 1px solid var(--line); border-radius: 14px; padding: 14px; margin-bottom: 10px; }
+.head { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
+.head img { width: 36px; height: 36px; border-radius: 50%; object-fit: cover; background: var(--soft); flex: none; }
+.head .who { min-width: 0; flex: 1; }
+.head .who div { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.mono { font-family: var(--mono); font-size: 12px; }
+button { font: inherit; font-weight: 600; border-radius: 10px; border: 1px solid var(--line-strong); background: var(--paper); color: var(--ink); padding: 9px 12px; cursor: pointer; }
+button:hover { background: var(--soft); }
+button.primary { background: var(--fill); border-color: var(--fill); color: var(--fill-fg); }
+button.primary:hover { filter: brightness(1.15); }
+button.link { border: 0; background: none; padding: 0; font-weight: 500; color: var(--muted); text-decoration: underline; }
+button.link:hover { color: var(--ink); background: none; }
+button:disabled { opacity: .55; cursor: default; }
+button:focus-visible, textarea:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
+textarea { width: 100%; font: 13px/1.4 var(--mono); color: var(--ink); background: var(--soft); border: 1px solid var(--line-strong); border-radius: 10px; padding: 10px; resize: vertical; min-height: 68px; margin-bottom: 8px; }
+.row { display: flex; align-items: center; gap: 8px; }
+.grow { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.balance { font-size: 26px; font-weight: 650; letter-spacing: -0.01em; }
+.balance span { font-size: 13px; font-weight: 500; color: var(--muted); margin-left: 4px; }
+ul { list-style: none; margin: 0; padding: 0; }
+li { display: flex; align-items: center; gap: 8px; padding: 7px 0; border-top: 1px solid var(--line); }
+li:first-child { border-top: 0; }
+.in { color: var(--green); }
+.err { color: var(--red); font-size: 12px; min-height: 16px; margin: 0 0 6px; }
+.tag { font-size: 11px; color: var(--muted); border: 1px solid var(--line-strong); border-radius: 999px; padding: 1px 7px; }
+.buttons { display: flex; gap: 8px; }
+.buttons button { flex: 1; }
+.origin { font-weight: 650; font-size: 16px; word-break: break-all; margin: 0 0 8px; }
+[hidden] { display: none !important; }
diff --git a/fastlane/metadata/android/en-US/changelogs/16.txt b/fastlane/metadata/android/en-US/changelogs/16.txt
new file mode 100644
index 0000000..6773eba
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/16.txt
@@ -0,0 +1 @@
+Passkey sign-in and the fingerprint lock work in the app. The app fits between the status and navigation bars and takes the page's colour there. Voice and video calls and live streams reach their servers, and videos that won't play in the phone's browser get a playable copy. Everything added to coinos since 1.9 is included: scheduled posts, post search, relay groups, picture grids in posts, music and film embeds, and more.
diff --git a/fdroid/io.coinos.fdroid.yml b/fdroid/io.coinos.fdroid.yml
index 26bac72..d05e214 100644
--- a/fdroid/io.coinos.fdroid.yml
+++ b/fdroid/io.coinos.fdroid.yml
@@ -53,9 +53,29 @@ Builds:
scandelete:
- node_modules
+ - versionName: '1.15'
+ versionCode: 16
+ commit: 8efa0378a920dfd80951fd03f9aa648608a8ee29
+ subdir: android/app
+ sudo:
+ - curl -fsSL -o /tmp/bun.zip
+ https://github.com/oven-sh/bun/releases/download/bun-v1.3.9/bun-linux-x64-baseline.zip
+ - echo "104d4d037f4b35e10215c0507e1779691f39c57bd91ddeefe11cad781e3fc4b9 /tmp/bun.zip"
+ | sha256sum -c
+ - unzip -q /tmp/bun.zip -d /tmp/bun
+ - install -m 0755 /tmp/bun/bun-linux-x64-baseline/bun /usr/local/bin/bun
+ gradle:
+ - fdroid
+ prebuild:
+ - cd ../..
+ - bun install --frozen-lockfile
+ - COINOS_NO_SW=1 bun run build
+ scandelete:
+ - node_modules
+
AllowedAPKSigningKeys: 766483ab8372c02f8406d29595e7389a2869190b429e0ffd092ebb0bfa2bc2f4
AutoUpdateMode: Version
UpdateCheckMode: Tags ^fdroid-v[0-9.]+$
-CurrentVersion: '1.9'
-CurrentVersionCode: 10
+CurrentVersion: '1.15'
+CurrentVersionCode: 16
diff --git a/src/features/messages.js b/src/features/messages.js
index 245e1ce..57f0e23 100644
--- a/src/features/messages.js
+++ b/src/features/messages.js
@@ -15,7 +15,7 @@ import { mediaServers } from '../media-servers.js';
// listens for both identities and decrypts with whichever keys are present.
import {
- subscribeOn, subscribeAuthed, publishOn, queryOn, queryManyOn, queryStreamOn, fetchInboxRelays, relayAlive, liveRelayList, readRelayList, resetRelay, wakeRelays,
+ subscribeOn, subscribeAuthed, publishOn, queryOn, queryManyOn, queryStreamOn, queryDepthOn, fetchInboxRelays, relayAlive, liveRelayList, readRelayList, resetRelay, wakeRelays,
npubOf, neventOf, parseNostrPubkey, parseNostrRef, generateSecretKey, getPublicKey, finalizeEvent, nip44,
PROFILE_RELAYS, openWrapsOffthread, unwrapDMsOffthread, verifyEventsAsync, setSyncConfig, DEFAULT_SYNC_RELAYS,
} from '../nostr.js';
@@ -36,7 +36,7 @@ import { loadMediaIndex, saveMediaIndex, wipeMediaIndex } from '../media-cache.j
import { mergeFeedWindow } from '../feed-window.js';
import { createThreadStore } from '../thread-cache.js';
import { createThreadPrefetch } from '../thread-prefetch.js';
-import { makeImageThumbnails } from '../image-thumbnails.js';
+import { makeImageThumbnails, loopGif } from '../image-thumbnails.js';
import { createFeedCache, FEED_CACHE_POSTS, FEED_SEED_POSTS } from '../feed-cache.js';
import { POPULAR_RELAYS, FIREHOSE_RELAYS, popularCandidates } from '../popular-feed.js';
import { makeSearcher, resultRows, fallbackAvatar, warmSearch, punkImageUrl, punkSmallUrl, primalCache, searchRecipients, searchable, setLocalPeople } from '../recipient-search.js';
@@ -5361,7 +5361,8 @@ export function messagesFeature(ctx) {
const batch = [...incoming.values()]; incoming.clear();
chain = chain.then(async () => {
const byId = new Map(c.notes.map((e) => [e.id, e]));
- const fresh = batch.filter((e) => !byId.has(e.id));
+ // older than the page already settled: kept back until paging gets there
+ const fresh = batch.filter((e) => !byId.has(e.id) && !holdBack(c, e));
if (!fresh.length) return;
for (const e of fresh) byId.set(e.id, e);
const merged = newestArticles([...byId.values()]).sort((a, b) => b.created_at - a.created_at);
@@ -5384,16 +5385,19 @@ export function messagesFeature(ctx) {
};
const asked = new Set([...NOTE_RELAYS, ...PROFILE_ARCHIVE_RELAYS]);
(async () => {
- await Promise.all([
- queryStreamOn([...asked], filter, take, 4500),
+ const depths = await Promise.all([
+ queryDepthOn([...asked], filter, take, 4500),
// the author's own relays, as soon as their list is known
relaysOf(pk).then((own) => {
const more = (own || []).filter((r) => !asked.has(r));
- return more.length ? queryStreamOn(more, filter, take, 4500) : null;
- }).catch(() => {}),
+ return more.length ? queryDepthOn(more, filter, take, 4500) : [];
+ }).catch(() => []),
+ primalNotes(pk, filter.limit, 0, take),
]);
clearTimeout(timer);
await flush();
+ await chain;
+ settlePage(c, depths.flat(), filter.limit);
if (any) persistPage('notes', pk, c.notes.slice(0, 20).map(slimNote)); // cache stays bounded
})().catch(() => {}).finally(() => {
c.status = 'ready';
@@ -5512,22 +5516,75 @@ export function messagesFeature(ctx) {
whenHide = setTimeout(() => whenEl && whenEl.classList.remove('on'), 250);
});
}
+ // How far back a page of someone's posts can be trusted. Relays each hold
+ // their own part of an author's history, so the oldest post of a merged
+ // answer says little: ours held 6 of Ben Arc's posts reaching back to
+ // April while his own relay's newest 30 ended in late September, and
+ // "older than the oldest" then asked for posts before April — five months
+ // never shown, his Napstr launch among them (Adam, 2026-11-20). A source
+ // that sent a full page has more below its oldest post; the page is
+ // complete down to the NEWEST such floor. Posts below it wait in c.held
+ // and join the page that reaches them. No source full: nothing is left.
+ const fullPage = (n, limit) => n >= Math.ceil(limit / 2);
+ const holdBack = (c, e) => {
+ if (!c.floor || e.created_at >= c.floor) return false;
+ (c.held ||= new Map()).set(e.id, e);
+ return true;
+ };
+ function settlePage(c, depths, limit) {
+ const floors = depths.filter((d) => d && fullPage(d.n, limit) && Number.isFinite(d.min)).map((d) => d.min);
+ const floor = floors.length ? Math.max(...floors) : 0;
+ // a refresh of a page already scrolled deeper never raises the floor
+ c.floor = c.floor && floor ? Math.min(c.floor, floor) : (c.floor && !floor ? c.floor : floor);
+ const all = new Map([...(c.held || new Map()), ...c.notes.map((e) => [e.id, e])]);
+ c.held = new Map();
+ const shown = [];
+ for (const e of all.values()) (c.floor && e.created_at < c.floor ? c.held.set(e.id, e) : shown.push(e));
+ c.notes = newestArticles(shown).sort((a, b) => b.created_at - a.created_at);
+ if (!floors.length && !c.floor) c.end = true;
+ else if (floors.length) c.end = false;
+ return floors.length > 0;
+ }
+ // Primal's cache keeps what relays have pruned (of the nine posts around
+ // the Napstr launch, the relays we ask held none). It answers posts and
+ // replies as separate feeds; each is a source with its own depth. The
+ // events are the signed originals, checked like a relay's.
+ async function primalNotes(pk, limit, until, take) {
+ const ask = async (notes) => {
+ const args = { pubkey: pk, notes, limit };
+ if (until) args.until = until;
+ const evs = await primalCache('feed', args, 5000).catch(() => []);
+ const good = await verifiedPrimal((evs || []).filter((e) => e.pubkey === pk), PROFILE_KINDS);
+ for (const e of good) take(e);
+ return { url: 'primal:' + notes, n: good.length, min: good.length ? Math.min(...good.map((e) => e.created_at)) : Infinity };
+ };
+ return Promise.all([ask('authored'), ask('replies')]);
+ }
async function loadOlderNotes(pk) {
const c = notesCache.get(pk);
if (!c || c.status !== 'ready' || c.loadingMore || c.end) return;
const oldest = c.notes[c.notes.length - 1];
- if (!oldest) { c.end = true; return; }
+ if (!oldest && !c.floor) { c.end = true; return; }
c.loadingMore = true;
render();
try {
- const evs = await queryOn(await notesRelays(pk),
- { kinds: PROFILE_KINDS, authors: [pk], limit: 30, until: oldest.created_at - 1 }, 4500);
+ const limit = 30;
+ const until = (c.floor || oldest.created_at) - 1;
+ const got = new Map();
+ const take = (e) => { if (e && e.pubkey === pk && e.created_at <= until) got.set(e.id, e); };
+ const depths = await Promise.all([
+ queryDepthOn(await notesRelays(pk), { kinds: PROFILE_KINDS, authors: [pk], limit, until }, take, 4500),
+ primalNotes(pk, limit, until, take),
+ ]);
+ const before = c.notes.length;
const seen = new Set(c.notes.map((e) => e.id));
- const older = (evs || [])
- .filter((e) => !seen.has(e.id) && seen.add(e.id))
- .sort((a, b) => b.created_at - a.created_at);
- if (older.length) { await notesReady(older); c.notes = newestArticles([...c.notes, ...older]); }
- else c.end = true; // the relays have nothing older
+ for (const e of got.values()) if (!seen.has(e.id)) (c.held ||= new Map()).set(e.id, e);
+ // this page reaches down to the new floor (or to the bottom: no source had more)
+ c.floor = 0;
+ const more = settlePage(c, depths.flat(), limit);
+ if (!more) { c.floor = 0; c.end = true; }
+ const added = c.notes.slice(before);
+ if (added.length) await notesReady(added.slice(0, FEED_PAGE));
} catch {} finally {
c.loadingMore = false;
if (ui.profilePk === pk) render();
@@ -6988,6 +7045,8 @@ export function messagesFeature(ctx) {
if (!r) return null;
const dims = JSON.parse(r.headers.get('x-dims') || 'null');
if (!dims || !dims.width) return null;
+ // a GIF kept before GIFs were looped: made again, to loop
+ if (r.headers.get('x-original') === '1' && r.headers.get('x-gif') !== '1' && /\.gif(\?|$)/i.test(url)) return null;
const src = r.headers.get('x-original') === '1' ? null : URL.createObjectURL(await r.blob());
return { ...dims, thumb: src };
} catch { return null; }
@@ -7003,17 +7062,22 @@ export function messagesFeature(ctx) {
if (e && e.corsRefused) { noteNoCors(url); corsRefused.add(url); } // refused, as corsFetch confirmed
return null;
}
+ const gif = /gif/i.test(blob.type);
+ // a GIF that would play once and stop is painted from a copy that loops
+ let looped = null;
+ // (up to 4 MB: the copy is kept on disk beside the column copies)
+ if (gif && blob.size < 4e6) { try { const fixed = loopGif(await blob.arrayBuffer()); if (fixed) looped = new Blob([fixed], { type: 'image/gif' }); } catch {} }
const result = await makeImageThumbnails(blob, {
width: MEDIA_THUMB_W, tileSize: tileThumbs.has(url) ? 0 : TILE_PX,
});
if (!result) return null;
- const dims = { width: result.width, height: result.height }, out = result.media;
+ const dims = { width: result.width, height: result.height }, out = result.media || looped;
// Both sizes share one decode in the worker; only cache writes and object
// URLs come back to the page. The lightbox still uses the original.
if (result.tile) await saveTileThumb(url, result.tile).catch(() => {});
try {
const store = await thumbStore();
- await store.put(url, new Response(out || new Blob(), { headers: { 'x-dims': JSON.stringify(dims), 'x-original': out ? '0' : '1' } }));
+ await store.put(url, new Response(out || new Blob(), { headers: { 'x-dims': JSON.stringify(dims), 'x-original': out ? '0' : '1', ...(gif ? { 'x-gif': '1' } : {}) } }));
const keys = await store.keys();
for (const k of keys.slice(0, Math.max(0, keys.length - MEDIA_THUMB_MAX))) store.delete(k);
} catch {}
@@ -10046,8 +10110,32 @@ export function messagesFeature(ctx) {
if (!liveShown) { stopLivePlayer(); return; }
mountLivePlayer();
const box = document.querySelector('.live-chat');
+ fitLiveChat(box);
if (box && box._stick !== false) box.scrollTop = box.scrollHeight;
}
+ // On a phone the chat is as tall as the room left under the stream, so the
+ // message box (and the newest line above it) sits on screen, over the nav:
+ // at a fixed 60vh the card ran off the bottom, and a swipe inside the chat
+ // never moved the page to bring it up (Adam, 2026-11-20). A long
+ // description leaves little room: the chat keeps a floor and the page
+ // scrolls. On a variable of the document: a render takes inline styles back.
+ function fitLiveChat(box) {
+ const root = document.documentElement;
+ const card = box && box.closest('.live-chat-card');
+ if (!card || !matchMedia('(max-width: 520px)').matches) { root.style.removeProperty('--live-chat-max'); return; }
+ const nav = document.querySelector('.app-bottom-nav');
+ const b = box.getBoundingClientRect();
+ const under = card.getBoundingClientRect().bottom - b.bottom; // the message box and the card's foot
+ const room = window.innerHeight - (nav ? nav.getBoundingClientRect().height : 0) - (b.top + window.scrollY) - under;
+ const px = Math.max(170, Math.floor(room)) + 'px';
+ if (root.style.getPropertyValue('--live-chat-max') !== px) root.style.setProperty('--live-chat-max', px);
+ }
+ if (typeof window !== 'undefined') window.addEventListener('resize', () => {
+ const box = ui.liveStream && document.querySelector('.live-chat');
+ if (!box) return;
+ fitLiveChat(box);
+ if (box._stick !== false) box.scrollTop = box.scrollHeight;
+ });
async function sendLiveChat(w, text, reply) {
const id = await requireIdentity();
@@ -10959,7 +11047,7 @@ export function messagesFeature(ctx) {
return h('img', {
src: mediaSrc(url, known), 'data-pic': url, class: 'note-img clickable', loading: feedPaint || known ? 'eager' : 'lazy', alt: label || '',
// a few-ms decode of the copy paints with the page; an original never holds the page for its decode
- decoding: known && known.thumb ? 'sync' : 'async',
+ decoding: known && known.thumb && !/\.gif(\?|$)/i.test(url) ? 'sync' : 'async', // (a looped GIF's copy is the whole animation)
width: size?.width, height: size?.height,
style: size ? 'height:auto;aspect-ratio:' + size.width + '/' + size.height + ';--ar:' + (size.width / size.height).toFixed(4) : undefined,
onClick: (e) => { if (!onPicture(e)) return; e.stopPropagation(); openPicture(url, e); },
diff --git a/src/image-thumbnails.js b/src/image-thumbnails.js
index 2686dac..80e6915 100644
--- a/src/image-thumbnails.js
+++ b/src/image-thumbnails.js
@@ -96,3 +96,32 @@ export function makeImageThumbnails(blob, { width = 0, tileSize = 0 } = {}) {
|| typeof createImageBitmap === 'undefined' || queue.length >= MAX_QUEUE) return Promise.resolve(null);
return new Promise((resolve) => { queue.push({ input: { blob, width, tileSize }, resolve }); drain(); });
}
+
+// A GIF with no loop instruction (the NETSCAPE2.0 application extension)
+// plays once and stops on its last frame: every browser reads it that way.
+// Plenty of GIFs are made without one (a gifs.nostr.build reply GIF froze
+// after a second, Adam, 2026-11-19), and people expect a GIF to loop. The
+// extension, "loop forever", goes right after the global colour table.
+// Returns the patched bytes, or null when the file loops already or isn't
+// a GIF.
+export function loopGif(bytes) {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
+ if (b.length < 13 || b[0] !== 0x47 || b[1] !== 0x49 || b[2] !== 0x46) return null; // "GIF"
+ const tag = [0x4e, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2e, 0x30]; // NETSCAPE2.0
+ const anim = [0x41, 0x4e, 0x49, 0x4d, 0x45, 0x58, 0x54, 0x53, 0x31, 0x2e, 0x30]; // ANIMEXTS1.0
+ outer: for (let i = 13; i < b.length - 11; i++) {
+ if (b[i] !== 0x4e && b[i] !== 0x41) continue;
+ const t = b[i] === 0x4e ? tag : anim;
+ for (let j = 1; j < 11; j++) if (b[i + j] !== t[j]) continue outer;
+ return null;
+ }
+ const packed = b[10];
+ const at = 13 + (packed & 0x80 ? 3 * 2 ** ((packed & 7) + 1) : 0);
+ if (at > b.length) return null;
+ const ext = new Uint8Array([0x21, 0xff, 0x0b, ...tag, 0x03, 0x01, 0x00, 0x00, 0x00]);
+ const out = new Uint8Array(b.length + ext.length);
+ out.set(b.subarray(0, at), 0);
+ out.set(ext, at);
+ out.set(b.subarray(at), at + ext.length);
+ return out;
+}
diff --git a/src/nostr-login.js b/src/nostr-login.js
index 562a5d4..e5490ec 100644
--- a/src/nostr-login.js
+++ b/src/nostr-login.js
@@ -36,7 +36,7 @@ import { hex, bech32 } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
import { entropyToMnemonic } from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
-import { getPublicKey, finalizeEvent, nip44 } from './nostr.js';
+import { getPublicKey, finalizeEvent, nip44, liveRelayList } from './nostr.js';
import { SimplePool } from 'nostr-tools/pool';
import { generateSecretKey } from 'nostr-tools/pure';
import { decode as nip19decode } from 'nostr-tools/nip19';
@@ -208,7 +208,24 @@ export function nostrConnectPending(timeoutMs = 180_000) {
} catch {}
return null;
}
-export async function nostrConnect({ relays = ['wss://relay.coinos.io', 'wss://nos.lol'], timeoutMs = 180_000, resume = null } = {}) {
+// The relays a nostrconnect:// link names: the signer app publishes its
+// approval there and we wait there, so a dead one is a login that spins
+// until it times out. A PAFF account's Amber sign-in sat on "waiting for
+// signer" while nos.lol (the link's second relay) refused connections, and
+// relay.nsec.app was down the same night (Adam, 2026-11-19). So the link
+// leads with relay.coinos.io and relay.primal.net (up, and both keep NIP-46
+// traffic), leaves out any relay this device has recently found dead, and
+// names three: one relay's outage no longer strands the handshake.
+const CONNECT_RELAYS = ['wss://relay.coinos.io', 'wss://relay.primal.net', 'wss://nos.lol', 'wss://offchain.pub'];
+export function connectRelays(candidates = CONNECT_RELAYS, n = 3) {
+ let live = candidates;
+ try { live = liveRelayList(candidates); } catch {}
+ const picked = live.slice(0, n);
+ // our own relay always: its ops are ours to fix, and the poller reads it
+ if (!picked.includes(candidates[0])) picked.unshift(candidates[0]);
+ return picked.slice(0, n);
+}
+export async function nostrConnect({ relays = connectRelays(), timeoutMs = 180_000, resume = null } = {}) {
const { BunkerSigner, createNostrConnectURI } = await loadNip46();
const local = resume ? hex.decode(resume.local) : generateSecretKey();
const secret = resume ? resume.secret : hex.encode(crypto.getRandomValues(new Uint8Array(16)));
diff --git a/src/nostr.js b/src/nostr.js
index 4b7f5c3..d2c9e44 100644
--- a/src/nostr.js
+++ b/src/nostr.js
@@ -602,6 +602,31 @@ export async function queryStreamOn(relays, filter, onEvent, maxWait = 1500) {
});
} catch {} finally { await Promise.all(pending); }
}
+// queryStreamOn that also says how deep each relay's answer went: resolves
+// with [{ url, n, min }] — how many events that relay sent for the filter and
+// the oldest created_at among them. A caller paging backwards needs it:
+// relays hold different parts of an author's history, and the oldest event
+// of the merged answer may be one relay's stray copy from months earlier.
+export async function queryDepthOn(relays, filter, onEvent, maxWait = 1500) {
+ probeRelays(relays);
+ const pending = [], stats = [], seen = new Set();
+ try {
+ const live = readRelays(relays);
+ await Promise.all(live.map((url) => {
+ const s = { url, n: 0, min: Infinity };
+ stats.push(s);
+ return askRelay(url, [filter], maxWait, (event) => {
+ if (!event) return;
+ s.n++;
+ if (event.created_at < s.min) s.min = event.created_at;
+ if (seen.has(event.id)) return;
+ seen.add(event.id);
+ pending.push(verifyOneAsync(event).then((ok) => ok && onEvent(event)).catch(() => {}));
+ });
+ }));
+ } catch {} finally { await Promise.all(pending); }
+ return stats;
+}
export async function publishOn(relays, evt, { onauth = null, onrefused = null } = {}) {
try {
const live = liveRelays(relays);
diff --git a/src/style.css b/src/style.css
index a9ceadb..311cfbb 100644
--- a/src/style.css
+++ b/src/style.css
@@ -975,7 +975,10 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
.live-rec-link { background: var(--paper); color: var(--ink); text-decoration: none; }
.live-say { padding: 6px 12px; border-radius: 8px; color: #fff; background: rgba(0, 0, 0, .65); font-size: 14px; text-align: center; }
/* the top padding is headroom for a hat on the first line's face: a scroller clips what rises out of it */
-.live-chat { display: flex; flex-direction: column; gap: 8px; max-height: 46vh; min-height: 120px; overflow-y: auto; overscroll-behavior: contain; padding-top: 12px; }
+/* no overscroll-behavior here: at the end of the chat the swipe carries on to
+ the page, or the last lines and the message box stay under the screen edge
+ with no way to reach them (Adam, 2026-11-20) */
+.live-chat { display: flex; flex-direction: column; gap: 8px; max-height: 46vh; min-height: 120px; overflow-y: auto; padding-top: 12px; }
.live-line { display: flex; gap: 8px; align-items: flex-start; min-width: 0; }
.live-line-body { min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; line-height: 1.35; }
.live-zap .live-line-body b { color: var(--accent); }
@@ -991,7 +994,7 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
.live-page > .live-chat-card { margin-top: 0; padding-top: 6px; border-top: none; }
.live-page > .card > :not(.live-player, .live-chat) { margin-left: 14px; margin-right: 14px; }
.live-page .live-player { border-radius: 0; }
- .live-page .live-chat { padding: 10px 14px 0; max-height: 60vh; }
+ .live-page .live-chat { padding: 10px 14px 0; max-height: var(--live-chat-max, 60vh); }
.live-page .live-title { font-size: 17px; }
.live-chat .chat-row { gap: 10px; }
.live-chat .chat-bubble { display: block; background: transparent; border: 0; border-radius: 0; padding: 0; font-size: 15px; }
diff --git a/tools/connect-relays-test.js b/tools/connect-relays-test.js
new file mode 100644
index 0000000..f54407d
--- /dev/null
+++ b/tools/connect-relays-test.js
@@ -0,0 +1,18 @@
+// The relays a nostrconnect:// link names: relay.coinos.io first, then the
+// next live ones, three in all, leaving out any this device found dead.
+// Run: bun tools/connect-relays-test.js
+import { connectRelays } from '../src/nostr-login.js';
+import { markRelaySick } from '../src/nostr.js';
+let ok = true;
+const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
+const fresh = connectRelays();
+check('three relays, ours first, primal second', fresh.length === 3 && fresh[0] === 'wss://relay.coinos.io' && fresh[1] === 'wss://relay.primal.net', fresh.join(' '));
+check('nos.lol is no longer second', fresh[1] !== 'wss://nos.lol');
+markRelaySick('wss://nos.lol', 'test');
+const after = connectRelays();
+check('a relay found dead is left out, the next one takes its place', !after.includes('wss://nos.lol') && after.includes('wss://offchain.pub') && after.length === 3, after.join(' '));
+markRelaySick('wss://relay.primal.net', 'test'); markRelaySick('wss://offchain.pub', 'test');
+const one = connectRelays();
+check('relay.coinos.io stays whatever else is down', one[0] === 'wss://relay.coinos.io', one.join(' '));
+console.log(ok ? '\n✅ connect links name live relays' : '\n❌ failed');
+process.exit(ok ? 0 : 1);
diff --git a/tools/extension-test.js b/tools/extension-test.js
new file mode 100644
index 0000000..6ea9e2a
--- /dev/null
+++ b/tools/extension-test.js
@@ -0,0 +1,198 @@
+// The browser extension (extension/): a site is asked once, then signing and
+// paying go through without a prompt; a blocked site stays blocked.
+// Loads the built extension into Chrome, with a relay and a wallet service
+// (NIP-47) of its own on this machine.
+// bun extension/build.js && bun tools/extension-test.js
+import puppeteer from 'puppeteer-core';
+import { finalizeEvent, generateSecretKey, getPublicKey, nip04, nip19, nip44, verifyEvent } from 'nostr-tools';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..');
+let failed = 0;
+const check = (name, ok, extra = '') => { console.log(`${ok ? '✓' : '✗'} ${name}${ok ? '' : ' ' + extra}`); if (!ok) failed++; };
+const hex = (b) => Buffer.from(b).toString('hex');
+
+// ── a relay with a wallet service behind it ────────────────────────────────
+const walletSk = generateSecretKey();
+const walletPk = getPublicKey(walletSk);
+const clientSk = generateSecretKey();
+const clientPk = getPublicKey(clientSk);
+const asked = [];
+const socks = new Set();
+const relay = Bun.serve({
+ port: 0,
+ fetch(req, server) { return server.upgrade(req) ? undefined : new Response('relay'); },
+ websocket: {
+ open(ws) { ws.data = { subs: new Set() }; socks.add(ws); },
+ close(ws) { socks.delete(ws); },
+ async message(ws, raw) {
+ const m = JSON.parse(raw);
+ if (m[0] === 'REQ') { ws.data.subs.add(m[1]); ws.send(JSON.stringify(['EOSE', m[1]])); return; }
+ if (m[0] === 'CLOSE') { ws.data.subs.delete(m[1]); return; }
+ if (m[0] !== 'EVENT') return;
+ const ev = m[1];
+ ws.send(JSON.stringify(['OK', ev.id, true, '']));
+ if (ev.kind !== 23194 || ev.pubkey !== clientPk) return;
+ const req = JSON.parse(await nip04.decrypt(walletSk, ev.pubkey, ev.content));
+ asked.push(req);
+ const result = {
+ get_balance: { balance: 21_000_000 },
+ pay_invoice: { preimage: 'ab'.repeat(32) },
+ make_invoice: { invoice: 'lnbc50n1made', payment_hash: 'cd'.repeat(32) },
+ list_transactions: { transactions: [{ type: 'incoming', amount: 5000_000, description: 'coffee', settled_at: 1 }] },
+ }[req.method];
+ const body = req.method === 'pay_invoice' && req.params.invoice === 'lnbc1toobig'
+ ? { result_type: req.method, error: { code: 'QUOTA_EXCEEDED', message: 'Over this connection\'s budget' } }
+ : { result_type: req.method, result };
+ const res = finalizeEvent({ kind: 23195, created_at: Math.floor(Date.now() / 1000), tags: [['p', ev.pubkey], ['e', ev.id]], content: await nip04.encrypt(walletSk, ev.pubkey, JSON.stringify(body)) }, walletSk);
+ for (const s of socks) for (const sub of s.data.subs) s.send(JSON.stringify(['EVENT', sub, res]));
+ },
+ },
+});
+const site = Bun.serve({ port: 0, fetch: () => new Response('<!doctype html><title>site</title><h1>a site</h1>', { headers: { 'content-type': 'text/html' } }) });
+const nwcUri = `nostr+walletconnect://${walletPk}?relay=${encodeURIComponent('ws://127.0.0.1:' + relay.port)}&secret=${hex(clientSk)}`;
+
+const userSk = generateSecretKey();
+const userPk = getPublicKey(userSk);
+const peerSk = generateSecretKey();
+const peerPk = getPublicKey(peerSk);
+
+const browser = await puppeteer.launch({
+ executablePath: process.env.CHROME || '/usr/bin/google-chrome',
+ headless: true, pipe: true, enableExtensions: [join(root, 'extension', 'dist')],
+ args: ['--no-sandbox'],
+});
+try {
+ const sw = await browser.waitForTarget((t) => t.type() === 'service_worker' && t.url().endsWith('/background.js'), { timeout: 15000 });
+ const base = sw.url().replace(/\/background\.js$/, '');
+ const prompts = () => browser.targets().filter((t) => t.url().startsWith(base + '/prompt.html'));
+ const promptPage = async () => (await browser.waitForTarget((t) => t.url().startsWith(base + '/prompt.html'), { timeout: 8000 })).asPage();
+ const noPrompt = async () => { await new Promise((r) => setTimeout(r, 400)); return prompts().length === 0; };
+ // run a call in the page and report { ok, value | error }
+ const call = (page, expr) => page.evaluate(`(async () => { try { return { ok: true, value: await (${expr}) }; } catch (e) { return { ok: false, error: e.message }; } })()`);
+
+ const page = await browser.newPage();
+ await page.goto(`http://127.0.0.1:${site.port}/`);
+ check('the page has window.nostr and window.webln', await page.evaluate(() => !!(window.nostr && window.nostr._coinos && window.webln && window.webln._coinos)));
+
+ let r = await call(page, 'window.nostr.getPublicKey()');
+ check('without a key a site is told to set the extension up', !r.ok && /no key yet/.test(r.error), JSON.stringify(r));
+
+ // set the key up in the popup
+ const popup = await browser.newPage();
+ await popup.goto(base + '/popup.html?tab');
+ await popup.waitForSelector('#key-input', { visible: true });
+ await popup.type('#key-input', 'not a key');
+ await popup.click('#key-save');
+ await popup.waitForFunction(() => document.getElementById('key-err').textContent.length > 0);
+ check('a wrong key is refused with a reason', true);
+ await popup.$eval('#key-input', (e) => { e.value = ''; });
+ await popup.type('#key-input', nip19.nsecEncode(userSk));
+ await popup.click('#key-save');
+ await popup.waitForSelector('#main', { visible: true });
+ const npub = nip19.npubEncode(userPk);
+ check('the popup shows the key\'s npub', (await popup.$eval('#npub', (e) => e.textContent)).startsWith(npub.slice(0, 14)));
+
+ // first call from a site: one question, then the answer
+ await page.bringToFront();
+ let pending = call(page, 'window.nostr.getPublicKey()');
+ let ask = await promptPage();
+ await ask.waitForSelector('#allow');
+ check('the prompt names the site', (await ask.$eval('#origin', (e) => e.textContent)).includes('127.0.0.1:' + site.port));
+ await ask.click('#allow');
+ r = await pending;
+ check('after Always allow the site gets the public key', r.ok && r.value === userPk, JSON.stringify(r));
+
+ r = await call(page, `window.nostr.signEvent({ kind: 1, content: 'hello', tags: [['t', 'x']], created_at: 1700000000 })`);
+ check('signing needs no second prompt', r.ok && (await noPrompt()));
+ check('the signature verifies under the key', r.ok && r.value.pubkey === userPk && verifyEvent(r.value) && r.value.content === 'hello');
+
+ r = await call(page, `window.nostr.nip44.encrypt('${peerPk}', 'secret words')`);
+ check('nip44 encrypts to a peer', r.ok && nip44.decrypt(r.value, nip44.getConversationKey(peerSk, userPk)) === 'secret words', JSON.stringify(r));
+ const fromPeer = nip44.encrypt('back to you', nip44.getConversationKey(peerSk, userPk));
+ r = await call(page, `window.nostr.nip44.decrypt('${peerPk}', '${fromPeer}')`);
+ check('nip44 decrypts from a peer', r.ok && r.value === 'back to you', JSON.stringify(r));
+ r = await call(page, `window.nostr.nip04.encrypt('${peerPk}', 'old style')`);
+ check('nip04 encrypts to a peer', r.ok && (await nip04.decrypt(peerSk, userPk, r.value)) === 'old style', JSON.stringify(r));
+
+ // the wallet
+ r = await call(page, 'window.webln.enable()');
+ check('with no wallet connected, paying says so', !r.ok && /No wallet is connected/.test(r.error), JSON.stringify(r));
+ await popup.bringToFront();
+ await popup.type('#nwc-input', nwcUri);
+ await popup.click('#nwc-save');
+ await popup.waitForFunction(() => /21,000/.test(document.getElementById('balance').textContent), { timeout: 10000 });
+ check('the popup shows the wallet\'s balance', true);
+ await popup.waitForFunction(() => /coffee/.test(document.getElementById('txs').textContent), { timeout: 10000 });
+ check('the popup lists recent payments', true);
+ if (process.env.SHOTS) { await popup.setViewport({ width: 360, height: 560 }); await popup.screenshot({ path: process.env.SHOTS + '/popup.png' }); }
+
+ await page.bringToFront();
+ pending = call(page, 'window.webln.enable()');
+ ask = await promptPage();
+ await ask.waitForSelector('#allow');
+ if (process.env.SHOTS) await ask.screenshot({ path: process.env.SHOTS + '/prompt.png' });
+ check('paying is asked about separately', /wallet/.test(await ask.$eval('#what', (e) => e.textContent)));
+ await ask.click('#allow');
+ r = await pending;
+ check('the site is enabled for payments', r.ok && r.value.enabled === true, JSON.stringify(r));
+ r = await call(page, 'window.webln.getBalance()');
+ check('the site reads the balance in sats', r.ok && r.value.balance === 21000, JSON.stringify(r));
+ r = await call(page, `window.webln.sendPayment('lnbc1invoice')`);
+ check('a payment returns the preimage, with no prompt', r.ok && r.value.preimage === 'ab'.repeat(32) && (await noPrompt()), JSON.stringify(r));
+ check('the wallet was asked to pay that invoice', asked.some((a) => a.method === 'pay_invoice' && a.params.invoice === 'lnbc1invoice'));
+ r = await call(page, `window.webln.sendPayment('lnbc1toobig')`);
+ check('the wallet\'s refusal reaches the site', !r.ok && /budget/.test(r.error), JSON.stringify(r));
+ r = await call(page, `window.webln.makeInvoice({ amount: 5, defaultMemo: 'tea' })`);
+ check('an invoice is made for the amount in sats', r.ok && r.value.paymentRequest === 'lnbc50n1made' && asked.some((a) => a.method === 'make_invoice' && a.params.amount === 5000 && a.params.description === 'tea'), JSON.stringify(r));
+
+ // another site: blocked for good
+ const other = await browser.newPage();
+ await other.goto(`http://localhost:${site.port}/`);
+ pending = call(other, 'window.nostr.getPublicKey()');
+ ask = await promptPage();
+ await ask.waitForSelector('#never');
+ await ask.click('#never');
+ r = await pending;
+ check('Never for this site refuses the call', !r.ok && /blocked/.test(r.error), JSON.stringify(r));
+ r = await call(other, 'window.nostr.getPublicKey()');
+ check('and it stays refused without asking again', !r.ok && /blocked/.test(r.error) && (await noPrompt()), JSON.stringify(r));
+
+ // a dismissed prompt refuses once and asks again later
+ const third = await browser.newPage();
+ await third.goto(`http://127.0.0.1:${relay.port}/`);
+ pending = call(third, 'window.nostr.getPublicKey()');
+ ask = await promptPage();
+ await ask.close();
+ r = await pending;
+ check('closing the prompt refuses that one call', !r.ok && /dismissed/.test(r.error), JSON.stringify(r));
+ pending = call(third, 'window.nostr.getPublicKey()');
+ ask = await promptPage();
+ await ask.waitForSelector('#deny');
+ await ask.click('#deny');
+ r = await pending;
+ check('the site is asked again, and Not now refuses', !r.ok && /denied/.test(r.error), JSON.stringify(r));
+
+ // the popup lists the sites and can forget one
+ await popup.bringToFront();
+ await popup.reload();
+ await popup.waitForSelector('#sites li');
+ const rows = await popup.$$eval('#sites li', (ls) => ls.map((l) => l.textContent));
+ check('the popup lists the allowed site as signing and paying', rows.some((t) => t.includes('127.0.0.1:' + site.port) && t.includes('signs') && t.includes('pays')), rows.join(' | '));
+ check('and the blocked one as blocked', rows.some((t) => t.includes('localhost') && t.includes('blocked')), rows.join(' | '));
+ await popup.click(`#sites button[aria-label="Remove http://127.0.0.1:${site.port}"]`);
+ await popup.waitForFunction((n) => document.querySelectorAll('#sites li').length === n, {}, rows.length - 1);
+ await page.bringToFront();
+ pending = call(page, 'window.nostr.getPublicKey()');
+ ask = await promptPage();
+ check('a removed site is asked again', !!ask);
+ await ask.close();
+ await pending;
+} finally {
+ await browser.close();
+ relay.stop(true);
+ site.stop(true);
+}
+console.log(failed ? `\n${failed} check(s) failed` : '\nall checks passed');
+process.exit(failed ? 1 : 0);
diff --git a/tools/feed-picture-pager-test.js b/tools/feed-picture-pager-test.js
index 947c6aa..5b5b80f 100644
--- a/tools/feed-picture-pager-test.js
+++ b/tools/feed-picture-pager-test.js
@@ -13,6 +13,8 @@ let ok = true;
const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
const png = (size) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=' + size, '-frames:v', '1', '-f', 'image2', '-c:v', 'png', 'pipe:1']).stdout;
const PICS = { a1: png('400x300'), a2: png('300x400'), b: png('320x320'), d: png('360x240') };
+// a GIF made without a loop instruction (plays once in a browser)
+const GIF = Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=320x240:rate=5:duration=1', '-loop', '-1', '-f', 'gif', 'pipe:1']).stdout;
const SK = generateSecretKey(), AUTHOR = getPublicKey(SK);
const now = Math.floor(Date.now() / 1000);
@@ -23,6 +25,7 @@ const server = Bun.serve({ port: 0, fetch: (req) => {
if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path));
const m = /^\/(a1|a2|b|d)\.png$/.exec(path);
if (m) return new Response(PICS[m[1]], { headers: { 'content-type': 'image/png' } });
+ if (path === '/once.gif') return new Response(GIF, { headers: { 'content-type': 'image/gif' } });
return new Response(html, { headers: { 'content-type': 'text/html' } });
} });
const U = (n) => server.url.origin + '/' + n + '.png';
@@ -30,6 +33,7 @@ const seeded = [
post('two pictures ' + U('a1') + ' ' + U('a2'), 100),
post('one picture ' + U('b'), 200),
post('only words here, nothing to look at', 300),
+ post('a gif reply ' + server.url.origin + '/once.gif', 3000), // (past the fillers: the pager walk above doesn't meet it)
post('a last picture ' + U('d'), 400),
...Array.from({ length: 12 }, (_, i) => post('filler ' + i + ' ' + 'lorem ipsum dolor sit amet. '.repeat(5), 500 + i * 60)),
];
@@ -93,6 +97,17 @@ try {
});
check('two pictures in a post: one gallery, side by side, one height', gal.n === 2 && gal.sameRow && gal.h > 50 && gal.h < 300, JSON.stringify(gal));
check('a lone picture is not put in a gallery', gal.lone);
+ // a GIF that would play once is painted from a copy that loops
+ await waitFor(() => { window.scrollTo(0, document.body.scrollHeight); return [...document.querySelectorAll('.notes-feed [data-key]')].some((n) => n.textContent.includes('a gif reply') && n.querySelector('img.note-img')); }, null, 10000);
+ const gifLoop = await page.evaluate(async () => {
+ const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('a gif reply'));
+ const img = r && r.querySelector('img.note-img');
+ if (!img || !/^blob:/.test(img.src)) return { src: img && img.src.slice(0, 40) };
+ const b = new Uint8Array(await (await fetch(img.src)).arrayBuffer());
+ return { src: 'blob', loops: new TextDecoder('latin1').decode(b).includes('NETSCAPE2.0') };
+ });
+ check('a GIF without a loop is painted from a copy that loops', gifLoop.src === 'blob' && gifLoop.loops, JSON.stringify(gifLoop));
+ await page.evaluate(() => window.scrollTo(0, 0)); await sleep(500);
// painted from the tile copy (a proper resize), not the column copy shrunk by the browser
check('gallery tiles are painted from the tile copies', await waitFor(() => {
const g = document.querySelector('.notes-feed .note-gallery');
diff --git a/tools/gif-loop-test.js b/tools/gif-loop-test.js
new file mode 100644
index 0000000..a135e36
--- /dev/null
+++ b/tools/gif-loop-test.js
@@ -0,0 +1,21 @@
+// A GIF made without a loop instruction plays once in every browser; the
+// copy the feed paints from gets "loop forever" added. One that loops
+// already, or isn't a GIF, is left alone.
+// Run: bun tools/gif-loop-test.js
+import { loopGif } from '../src/image-thumbnails.js';
+let ok = true;
+const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
+const make = (args) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=64x48:rate=5:duration=1', ...args, '-f', 'gif', 'pipe:1']).stdout;
+const once = new Uint8Array(make(['-loop', '-1'])), looping = new Uint8Array(make(['-loop', '0']));
+const has = (b) => Buffer.from(b).includes('NETSCAPE2.0');
+check('ffmpeg made one GIF without a loop and one with', !has(once) && has(looping));
+const fixed = loopGif(once);
+check('the one-shot GIF gets the loop extension', !!fixed && has(fixed));
+const i = Buffer.from(fixed).indexOf('NETSCAPE2.0');
+check('…loop forever (count 0), right after the colour table', fixed[i + 11] === 3 && fixed[i + 12] === 1 && fixed[i + 13] === 0 && fixed[i + 14] === 0 && fixed[i + 15] === 0 && fixed[i - 3] === 0x21 && fixed[i - 2] === 0xff);
+const probe = Bun.spawnSync(['ffprobe', '-v', 'error', '-count_frames', '-show_entries', 'stream=nb_read_frames', '-of', 'csv=p=0', '-i', 'pipe:0'], { stdin: fixed }).stdout.toString().trim();
+check('the patched GIF still decodes, every frame', probe === '5', probe);
+check('a GIF that loops already is left alone', loopGif(looping) === null);
+check('not a GIF: left alone', loopGif(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])) === null);
+console.log(ok ? '\n✅ GIFs loop' : '\n❌ failed');
+process.exit(ok ? 0 : 1);
diff --git a/tools/live-stream-test.js b/tools/live-stream-test.js
index 56dcb71..cf5e056 100644
--- a/tools/live-stream-test.js
+++ b/tools/live-stream-test.js
@@ -224,6 +224,30 @@ try {
const rowSel = '.live-message[data-key="' + chat.id + '"]';
check('comments use the group-chat bubble and shared composer', await page.$(rowSel + ' .chat-bubble') && await page.$('.live-page coinos-text#msg-draft'));
check('...drawn plain on a phone, no bubble walls', await page.evaluate((q) => { const b = document.querySelector(q); return b && getComputedStyle(b).borderStyle === 'none' && getComputedStyle(b).display === 'block'; }, rowSel + ' .chat-bubble'));
+ // the message box is on screen without scrolling the page: the chat takes
+ // the room left under the stream, down to the nav (it was a fixed 60vh and
+ // the card ran off the bottom, where a swipe inside the chat couldn't
+ // bring it up)
+ {
+ const fit = await page.evaluate(() => {
+ window.scrollTo(0, 0);
+ const r = (q) => document.querySelector(q)?.getBoundingClientRect();
+ const box = r('.live-page coinos-text#msg-draft'), nav = r('.app-bottom-nav'), chat = document.querySelector('.live-page .live-chat');
+ return { box: box && Math.round(box.bottom), nav: nav ? Math.round(nav.top) : innerHeight, chat: chat.clientHeight, behaviour: getComputedStyle(chat).overscrollBehaviorY };
+ });
+ check('on a phone the message box sits on screen, over the nav', fit.box && fit.box <= fit.nav && fit.chat >= 120, JSON.stringify(fit));
+ check('...and the chat no longer holds a scroll that reaches its end', fit.behaviour === 'auto');
+ // a wall of chat: the box stays where it is, the newest line just above it
+ await page.addStyleTag({ content: '.live-page .live-chat::before{content:"";flex:none;height:3000px}' }).then((el) => el.evaluate((n) => { n.id = 'tall-chat'; }));
+ await page.evaluate(() => { const c = document.querySelector('.live-page .live-chat'); c.scrollTop = c.scrollHeight; });
+ const tall = await page.evaluate(() => {
+ const r = (q) => document.querySelector(q)?.getBoundingClientRect();
+ const c = document.querySelector('.live-page .live-chat'), last = c.lastElementChild.getBoundingClientRect(), nav = r('.app-bottom-nav');
+ return { box: Math.round(r('.live-page coinos-text#msg-draft').bottom), nav: nav ? Math.round(nav.top) : innerHeight, last: Math.round(last.bottom), chatBottom: Math.round(c.getBoundingClientRect().bottom), pageY: window.scrollY };
+ });
+ check('...with a long chat too, the newest line showing above it', tall.box <= tall.nav && tall.last <= tall.chatBottom + 1 && tall.pageY === 0, JSON.stringify(tall));
+ await page.evaluate(() => document.getElementById('tall-chat')?.remove());
+ }
check('another client’s e-only reaction arrives on the comment', await waitFor(id => document.querySelector('.live-message[data-key="'+id+'"] .chat-reacts')?.textContent.includes('👍'), 6000, chat.id));
check('per-comment zap receipts show under the bubble', await waitFor(id => document.querySelector('.live-message[data-key="'+id+'"] .zap-tally')?.textContent.includes('5'), 6000, chat.id));
await page.click(rowSel + ' .chat-bubble');
diff --git a/tools/profile-depth-test.js b/tools/profile-depth-test.js
new file mode 100644
index 0000000..5aea719
--- /dev/null
+++ b/tools/profile-depth-test.js
@@ -0,0 +1,45 @@
+// A profile's older posts, page after page, with no months skipped. Relays
+// hold different parts of an author's history: paging "older than the oldest
+// post on the page" jumped from late September to April on Ben Arc's profile
+// because one relay held six stray copies reaching back that far, and the
+// posts around his Napstr launch (2026-08-21) are on none of the relays we
+// ask — only in Primal's cache. Reads real relays (relays: 'read'; nothing
+// is published).
+// Run: bun tools/profile-depth-test.js
+import puppeteer from './puppeteer.js';
+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 NPUB = process.env.NPUB || 'npub1c878wu04lfqcl5avfy3p5x83ndpvedaxv0dg7pxthakq3jqdyzcs2n8avm';
+const WANT = process.env.WANT || 'For all the seeders out there';
+
+const html = await buildHtml({ minify: true, pwa: false });
+const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) });
+const browser = await puppeteer.launch({ relays: 'read', 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.stack || e).slice(0, 600)));
+try {
+ await page.setViewport({ width: 390, height: 844 });
+ await page.goto(server.url.href + NPUB, { waitUntil: 'domcontentloaded' });
+ await page.waitForSelector('.notes-feed:not(.note-ghosts) > [data-key]', { timeout: 20000 });
+ const seen = new Map(); // key -> text
+ let found = false, still = 0, last = 0;
+ const t0 = Date.now();
+ for (let i = 0; i < 400 && !found && still < 40; i++) {
+ const rows = await page.evaluate(() => [...document.querySelectorAll('.notes-feed > [data-key]')].map((r) => [r.dataset.key, r.textContent.slice(0, 300)]));
+ for (const [k, t] of rows) seen.set(k, t);
+ found = [...seen.values()].some((t) => t.includes(WANT));
+ still = seen.size === last ? still + 1 : 0;
+ last = seen.size;
+ await page.evaluate(() => window.scrollBy(0, 1400));
+ await sleep(350);
+ }
+ console.log(` ${seen.size} posts read in ${((Date.now() - t0) / 1000).toFixed(1)} s`);
+ check('scrolling back reaches the Napstr launch post', found, WANT);
+ check('...past more than a first page', seen.size > 40, seen.size + ' posts');
+ check('no page errors', !errs.length, errs.join(' | '));
+} catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(); }
+console.log(ok ? '\nPASS' : '\nFAIL');
+process.exit(ok ? 0 : 1);