diff options
| author | Adam Soltys <[email protected]> | 2026-10-10 07:03:30 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-10-10 07:03:30 -0700 |
| commit | 572361e2bd1ab16b4618517c2d9531689c6f46a8 (patch) | |
| tree | 5ca9210aa9b7414a85027b3afb223be1e2cfee9f /src | |
| parent | a70f34f2a5d35352f99bae8f10cbab12637e08ee (diff) | |
| download | coinosv3-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
Diffstat (limited to 'src')
| -rw-r--r-- | src/features/messages.js | 36 | ||||
| -rw-r--r-- | src/nostr.js | 66 |
2 files changed, 95 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. |
