aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-10-10 07:03:30 -0700
committerAdam Soltys <[email protected]>2026-10-10 07:03:30 -0700
commit572361e2bd1ab16b4618517c2d9531689c6f46a8 (patch)
tree5ca9210aa9b7414a85027b3afb223be1e2cfee9f
parenta70f34f2a5d35352f99bae8f10cbab12637e08ee (diff)
downloadcoinosv3-572361e2bd1ab16b4618517c2d9531689c6f46a8.tar.gz
coinosv3-572361e2bd1ab16b4618517c2d9531689c6f46a8.zip
Messages: NIP-42 inbox relays. isolabellart's kind-10050 inbox is auth.nostr1.com and a personal relay, both of which answer a REQ for their gift wraps with CLOSED "auth-required" — we never authenticated, so DMs delivered only there (anything sent from Amethyst and other 10050-only clients) never reached v3. The DM subscription on our own inbox relays now authenticates as the DM identity (subscribeAuthed: per relay, AUTH then ask again, still closable; the AUTH event is signed before nostr-tools' cached auth promise so a failing signer can't wedge the socket), sends to a peer's inbox authenticate when a relay refuses the write with auth-required, and our sent copy also goes to our own inbox relays so other clients reading that list see it. Never Amber by intent (an app trip per connection). Checked live: auth.nostr1.com accepts the handshake. tools/dm-nip42-test.js
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vps2H27rhbG9ZqseGfMrc3
-rw-r--r--src/features/messages.js36
-rw-r--r--src/nostr.js66
-rw-r--r--tools/dm-nip42-test.js131
3 files changed, 226 insertions, 7 deletions
diff --git a/src/features/messages.js b/src/features/messages.js
index 597cb23..4512818 100644
--- a/src/features/messages.js
+++ b/src/features/messages.js
@@ -13,7 +13,7 @@
// listens for both identities and decrypts with whichever keys are present.
import {
- subscribeOn, publishOn, queryOn, queryManyOn, queryStreamOn, fetchInboxRelays, relayAlive, liveRelayList, readRelayList, resetRelay,
+ subscribeOn, subscribeAuthed, publishOn, queryOn, queryManyOn, queryStreamOn, fetchInboxRelays, relayAlive, liveRelayList, readRelayList, resetRelay,
npubOf, neventOf, parseNostrPubkey, parseNostrRef, generateSecretKey, getPublicKey, finalizeEvent, nip44,
PROFILE_RELAYS, openWrapsOffthread, unwrapDMsOffthread, verifyEventsAsync, setSyncConfig, DEFAULT_SYNC_RELAYS,
} from '../nostr.js';
@@ -514,6 +514,22 @@ export function messagesFeature(ctx) {
if (wallet.nostr && wallet.nostr.sk) return { pubkey: wallet.nostr.pk, signer: wallet.nostr.sk };
return null;
}
+ // NIP-42: sign a relay's AUTH challenge as the DM identity — an inbox
+ // relay (auth.nostr1.com, a personal relay) shows gift wraps only to the
+ // pubkey they're for, and some take writes only from authenticated users.
+ // Never Amber by intent: an app trip per relay connection, for a read
+ // nobody asked for.
+ async function relayAuth(tmpl) {
+ const id = await identity();
+ if (!id) throw new Error('no identity');
+ if (id.signer instanceof Uint8Array) return finalizeEvent(tmpl, id.signer);
+ if (id.signer.interactive) throw new Error('signer is interactive');
+ return id.signer.signEvent(tmpl);
+ }
+ // Our own kind-10050 inbox beyond DM_RELAYS (read at startDMs): sent
+ // copies go there too, so other clients reading that list see them.
+ let ownInbox = [];
+ const toOwnInbox = (wrap) => { if (ownInbox.length) publishOn(ownInbox, wrap, { onauth: relayAuth }); };
// what a feed or a profile lists: notes, and polls (NIP-88)
const FEED_KINDS = [1, 1068];
// A profile shows its articles (NIP-23) among the notes, as Amethyst does.
@@ -3118,7 +3134,14 @@ export function messagesFeature(ctx) {
// them (crypticCypher's replies reached only primal, the 4th extra
// in Adam's list, while a cap of three read the first three)
.slice(0, 8);
- if (extras.length && dmStarted) dmSub(extras);
+ ownInbox = extras;
+ // inbox relays are often NIP-42 gated: authenticate as the identity
+ if (extras.length && dmStarted) {
+ const u = subscribeAuthed(extras, { kinds: [1059], '#p': pks, limit: 400 }, (wrap) => {
+ handleInboxWrap(wrap).catch(() => {});
+ }, { onauth: relayAuth, onclose: noteSubClosed });
+ allUnsubs.push(u); dmUnsubs.push(u);
+ }
} catch {}
})();
ensureDmRelayList().catch(() => {});
@@ -3173,9 +3196,10 @@ export function messagesFeature(ctx) {
// Publishing the same wrap twice is harmless — relays dedupe on id.
const ok = await publishOn(DM_RELAYS, toPeer);
publishOn(DM_RELAYS, toSelf);
+ toOwnInbox(toSelf);
fetchInboxRelays(peer).then((inbox) => {
const extra = inbox.slice(0, 4).filter((r) => !DM_RELAYS.includes(r));
- if (extra.length) publishOn(extra, toPeer);
+ if (extra.length) publishOn(extra, toPeer, { onauth: relayAuth });
}).catch(() => {});
if (!ok) { toast(t('msgSendFailed')); return; }
delete entry.pending;
@@ -3209,9 +3233,10 @@ export function messagesFeature(ctx) {
seenWraps.add(toPeer.id); seenWraps.add(toSelf.id);
const ok = await publishOn(DM_RELAYS, toPeer);
publishOn(DM_RELAYS, toSelf);
+ toOwnInbox(toSelf);
fetchInboxRelays(peer).then((inbox) => {
const extra = inbox.slice(0, 4).filter((x) => !DM_RELAYS.includes(x));
- if (extra.length) publishOn(extra, toPeer);
+ if (extra.length) publishOn(extra, toPeer, { onauth: relayAuth });
}).catch(() => {});
if (!ok) toast(t('msgSendFailed'));
} catch (e) {
@@ -8020,9 +8045,10 @@ export function messagesFeature(ctx) {
const toSelf = await wrapDM(id.signer, id.pubkey, rumor);
const ok = await publishOn(DM_RELAYS, toPeer);
publishOn(DM_RELAYS, toSelf);
+ toOwnInbox(toSelf);
fetchInboxRelays(peer).then((inbox) => {
const extra = inbox.slice(0, 4).filter((r) => !DM_RELAYS.includes(r));
- if (extra.length) publishOn(extra, toPeer);
+ if (extra.length) publishOn(extra, toPeer, { onauth: relayAuth });
}).catch(() => {});
if (!ok) { threadOf(peer).delete(rumor.id); toast(t('msgSendFailed')); render(); return; }
delete entry.pending;
diff --git a/src/nostr.js b/src/nostr.js
index 2ab0b05..e414d57 100644
--- a/src/nostr.js
+++ b/src/nostr.js
@@ -301,6 +301,58 @@ export function subscribeOn(relays, filter, onEvent, extra = {}) {
return () => { try { sub.close(); } catch {} };
} catch { return () => {}; }
}
+// NIP-42: a subscription on relays that may answer CLOSED "auth-required"
+// — a NIP-17 inbox such as auth.nostr1.com shows a user's gift wraps only
+// to that user. `onauth(template)` signs the AUTH event; the relay is then
+// asked again. Per relay rather than the pool's own retry, whose re-asked
+// subscription escapes the closer (a resubscribe would stack copies).
+// `onclose` hears only real closes, not the auth handshake.
+export function subscribeAuthed(relays, filter, onEvent, { onauth = null, onclose = null } = {}) {
+ let closed = false;
+ const subs = [];
+ const gated = (event) => { verifyOneAsync(event).then((ok) => { if (ok) onEvent(event); }); };
+ probeRelays(relays);
+ for (const url of liveRelays(relays)) {
+ (async () => {
+ let relay;
+ try { relay = await pool.ensureRelay(url, { connectionTimeout: 8000 }); } catch (e) { if (!closed) onclose?.([String(e?.message || e)]); return; }
+ let tried = false;
+ const open = () => {
+ if (closed) return;
+ subs.push(relay.subscribe([filter], {
+ onevent: gated,
+ onclose: (reason) => {
+ if (closed) return;
+ if (!tried && onauth && /^auth-required:/.test(String(reason))) {
+ tried = true;
+ // a refused or unsignable auth is not a dropped socket:
+ // rebuilding would only ask again
+ authRelay(relay, onauth).then(open, (e) => dlog('nostr: auth to ' + url + ' failed: ' + (e?.message || e)));
+ return;
+ }
+ onclose?.([reason]);
+ },
+ }));
+ };
+ open();
+ })();
+ }
+ return () => { closed = true; for (const s of subs) { try { s.close(); } catch {} } };
+}
+// The relay's challenge can trail its CLOSED: wait a beat for it.
+// Signed BEFORE handing it to the relay: nostr-tools caches its auth promise
+// per connection, and a signer that throws inside it leaves that promise
+// pending forever — every later auth on the socket would hang.
+async function authRelay(relay, onauth) {
+ for (let i = 0; i < 10 && !relay.challenge; i++) await new Promise((r) => setTimeout(r, 300));
+ if (!relay.challenge) throw new Error('no auth challenge');
+ if (!relay.authPromise) {
+ const signed = await onauth({ kind: 22242, created_at: Math.floor(Date.now() / 1000),
+ tags: [['relay', relay.url], ['challenge', relay.challenge]], content: '' });
+ return relay.auth(async () => signed);
+ }
+ return relay.auth(onauth);
+}
export async function queryOn(relays, filter, maxWait = 1500) {
probeRelays(relays);
try {
@@ -352,14 +404,24 @@ export async function queryStreamOn(relays, filter, onEvent, maxWait = 1500) {
});
} catch {} finally { await Promise.all(pending); }
}
-export async function publishOn(relays, evt) {
+export async function publishOn(relays, evt, { onauth = null } = {}) {
try {
const live = liveRelays(relays);
// A rejected publish is a relay refusing the event (policy, rate limit,
// ban). Swallowing that silently once hid a relay-side rejection behind
// what looked like a client bug — always say which relay refused and why.
+ // with onauth, a relay that answers "auth-required" (NIP-42) is
+ // authenticated and asked again
const pubs = pool.publish(live, evt).map((p, i) =>
- Promise.resolve(p).then(() => true, (reason) => {
+ Promise.resolve(p).then(() => true, async (reason) => {
+ if (onauth && /^auth-required:/.test(reason?.message || String(reason || ''))) {
+ try {
+ const r = await pool.ensureRelay(live[i]);
+ await authRelay(r, onauth);
+ await r.publish(evt);
+ return true;
+ } catch (e) { reason = e; }
+ }
const msg = reason?.message || String(reason || '');
// "relay connection errored/closed" means the socket never came up —
// that's a sick relay, not a rejected event.
diff --git a/tools/dm-nip42-test.js b/tools/dm-nip42-test.js
new file mode 100644
index 0000000..51fa3a9
--- /dev/null
+++ b/tools/dm-nip42-test.js
@@ -0,0 +1,131 @@
+// NIP-42 inbox relays: a NIP-17 inbox such as auth.nostr1.com (or a personal
+// relay) answers a REQ for someone's gift wraps with CLOSED "auth-required"
+// and shows them only after an AUTH signed by that someone; some refuse
+// writes the same way. Messages read our own kind-10050 inbox that way,
+// sends a DM to the peer's gated inbox after authenticating, and keeps a
+// copy of what we send in our own inbox so other clients see it too.
+// Both inboxes are played by this script's WebSocket shim.
+// Run: bun tools/dm-nip42-test.js
+import puppeteer from './puppeteer.js';
+import { cacheKeyFor } from '../src/wallet.js';
+import { generateSecretKey, getPublicKey, finalizeEvent, verifyEvent } from 'nostr-tools/pure';
+import { privateKeyFromSeedWords } from 'nostr-tools/nip06';
+import { wrapEvent } from 'nostr-tools/nip17';
+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 PEER_SK = generateSecretKey(); const PEER = getPublicKey(PEER_SK);
+const MY_INBOX = 'wss://inbox.example.com';
+const PEER_INBOX = 'wss://peer-inbox.example.com';
+const now = Math.floor(Date.now() / 1000);
+
+const html = await buildHtml({ minify: true, pwa: false });
+const server = Bun.serve({ port: 5312, fetch: (req) => { const p = new URL(req.url).pathname; if (p === '/verify-worker.js' || p.startsWith('/punks')) return new Response(Bun.file('dist' + p)); 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(([MY_INBOX, PEER_INBOX]) => {
+ window.__fx = []; window.__gated = []; window.__auths = []; window.__published = [];
+ const gatedHosts = [MY_INBOX, PEER_INBOX].map((u) => new URL(u).host);
+ const fits = (ev, f) => (!f.kinds || f.kinds.includes(ev.kind)) && (!f['#p'] || ev.tags.some((t) => t[0] === 'p' && f['#p'].includes(t[1])))
+ && (!f.authors || f.authors.includes(ev.pubkey));
+ const Real = window.WebSocket;
+ window.WebSocket = function (...a) {
+ const ws = new Real(...a);
+ const host = new URL(a[0]).host;
+ const gated = gatedHosts.includes(host);
+ const challenge = 'ch-' + Math.random().toString(36).slice(2);
+ let authed = null;
+ const say = (m) => setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(m) })), 0);
+ if (gated) ws.addEventListener('open', () => say(['AUTH', challenge]));
+ const send = ws.send.bind(ws);
+ ws.send = (d) => {
+ try {
+ const m = JSON.parse(d);
+ if (m[0] === 'AUTH') {
+ const ev = m[1];
+ const good = ev.kind === 22242 && ev.tags.some((t) => t[0] === 'challenge' && t[1] === challenge);
+ window.__auths.push({ host, ev, good });
+ if (good) authed = ev.pubkey;
+ say(['OK', ev.id, good, good ? '' : 'auth-required: bad challenge']);
+ return;
+ }
+ if (m[0] === 'REQ') {
+ const fs = m.slice(2);
+ if (gated && !authed) { say(['CLOSED', m[1], 'auth-required: you must auth']); return; }
+ const pool = gated ? window.__gated.filter((g) => g.host === host).map((g) => g.ev) : window.__fx;
+ // a gated inbox shows wraps only to the pubkey they're for
+ const evs = pool.filter((ev) => fs.some((f) => fits(ev, f)) && (!gated || ev.kind !== 1059 || ev.tags.some((t) => t[0] === 'p' && t[1] === authed)));
+ setTimeout(() => {
+ for (const ev of evs) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], ev]) }));
+ ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) }));
+ }, 0);
+ return;
+ }
+ if (m[0] === 'EVENT') {
+ if (gated && !authed) { say(['OK', m[1].id, false, 'auth-required: authenticate to write']); return; }
+ window.__published.push({ host, ev: m[1] });
+ say(['OK', m[1].id, true, '']);
+ return;
+ }
+ } catch {}
+ return send(d);
+ };
+ return ws;
+ };
+ window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real);
+}, [MY_INBOX, PEER_INBOX]);
+const errs = [];
+page.on('pageerror', (e) => errs.push(String(e)));
+const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t);
+const text = () => page.evaluate(() => document.body.innerText);
+const waitText = async (x, ms = 20000) => { for (let i = 0; i < ms / 250; i++) { if ((await text()).toLowerCase().includes(x)) return true; await sleep(250); } return false; };
+
+try {
+ await page.setViewport({ width: 390, height: 844 });
+ await page.goto('http://localhost:5312/', { waitUntil: 'domcontentloaded' });
+ await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
+ await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400);
+ await click('create a new wallet'); await sleep(600);
+ await page.waitForSelector('.words .w .t');
+ const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' ');
+ await click('skip verification');
+ await waitText('receive', 20000);
+ const ME_SK = privateKeyFromSeedWords(mn); const ME = getPublicKey(ME_SK);
+ const base = cacheKeyFor(mn + '\n');
+ // our inbox list names the gated relay; the peer's names theirs
+ const fx = [
+ finalizeEvent({ kind: 10050, created_at: now - 100, tags: [['relay', MY_INBOX]], content: '' }, ME_SK),
+ finalizeEvent({ kind: 10050, created_at: now - 100, tags: [['relay', PEER_INBOX]], content: '' }, PEER_SK),
+ finalizeEvent({ kind: 0, created_at: now - 100, tags: [], content: JSON.stringify({ name: 'Gated Peer' }) }, PEER_SK),
+ ];
+ // a DM that exists only on our gated inbox — sent by a client that
+ // delivers to 10050 alone
+ const ONLY = wrapEvent(PEER_SK, { publicKey: ME }, 'only on the gated inbox');
+ // and one to somebody else, which the inbox must never hand us
+ await page.evaluateOnNewDocument(([fx, only, host]) => { window.__fxSeed = fx; window.__gatedSeed = [{ host, ev: only }]; }, [fx, ONLY, new URL(MY_INBOX).host]);
+ await page.evaluateOnNewDocument(() => { window.__fx = window.__fxSeed; window.__gated = window.__gatedSeed; });
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ await waitText('receive', 20000);
+ await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Messages"]')?.click());
+
+ console.log('\n[reading our own NIP-42 inbox]');
+ check('the DM held only by the gated inbox shows', await waitText('only on the gated inbox', 25000));
+ const myAuth = (await page.evaluate(() => window.__auths)).filter((a) => a.host === new URL('wss://inbox.example.com').host);
+ check('...after an AUTH signed by us for that relay\'s challenge', myAuth.some((a) => a.good && a.ev.pubkey === ME && verifyEvent(a.ev) && a.ev.tags.some((t) => t[0] === 'relay' && /inbox\.example\.com/.test(t[1]))), JSON.stringify(myAuth.map((a) => [a.good, a.ev.pubkey.slice(0, 8)])));
+
+ console.log('\n[sending to a peer whose inbox wants AUTH for writes]');
+ await page.evaluate(() => { const r = document.querySelector('[data-key^="dm:"] .chat-preview'); r && r.click(); });
+ await sleep(800);
+ await page.waitForSelector('#msg-draft', { timeout: 8000 });
+ await page.type('#msg-draft', 'hello through the gate');
+ await page.keyboard.press('Enter');
+ let pub = [];
+ for (let i = 0; i < 40; i++) { pub = await page.evaluate(() => window.__published.filter((p) => p.ev.kind === 1059)); if (pub.some((p) => p.host.startsWith('peer-')) && pub.some((p) => p.host.startsWith('inbox.'))) break; await sleep(250); }
+ const peerAuth = (await page.evaluate(() => window.__auths)).filter((a) => a.host.startsWith('peer-'));
+ check('the wrap reaches the peer\'s gated inbox, after authenticating there', pub.some((p) => p.host.startsWith('peer-') && p.ev.tags.some((t) => t[0] === 'p' && t[1] === PEER)) && peerAuth.some((a) => a.good && a.ev.pubkey === ME), JSON.stringify(pub.map((p) => p.host)));
+ check('our own copy lands in our gated inbox too', pub.some((p) => p.host.startsWith('inbox.') && p.ev.tags.some((t) => t[0] === 'p' && t[1] === ME)));
+ check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
+} finally { await browser.close(); server.stop(true); }
+console.log(ok ? '\n✅ NIP-42 inbox relays read and written' : '\n❌ failed');
+process.exit(ok ? 0 : 1);