diff options
| -rw-r--r-- | src/features/messages.js | 40 | ||||
| -rw-r--r-- | src/features/nostrlogin.js | 41 | ||||
| -rw-r--r-- | src/i18n.js | 4 | ||||
| -rw-r--r-- | tools/amber-dm-upgrade-test.js | 154 |
4 files changed, 229 insertions, 10 deletions
diff --git a/src/features/messages.js b/src/features/messages.js index 06371cf..597cb23 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -2898,11 +2898,28 @@ export function messagesFeature(ctx) { // "nothing to wait for": counting those passes gave every wrap sealed to // the login npub up after ~40 s with only the wallet key tried, and the // wrap log then hid it from every later session (a phone kept 9 of 186 - // messages). An interactive signer (Amber) is live from the moment it - // resumes and never decrypts here, so it counts as complete. + // messages). An interactive signer (Amber by intent) never decrypts here + // either, so it is incomplete too: counted as complete, every wrap sealed + // to the login npub was given up on the wallet key and logged as opened + // — an Amber user's threads held only what that device had sent. function decryptorsComplete() { const login = hook('nostrLoginIdentity'); - return !login || !!(login.signer && (login.signer.interactive || login.signer.decryptFrom)); + return !login || !!(login.signer && !login.signer.interactive && login.signer.decryptFrom); + } + const interactiveLogin = () => { const l = hook('nostrLoginIdentity'); return !!(l && l.signer && l.signer.interactive); }; + // Wraps logged while an interactive signer stood in for the login npub + // may be messages no key here ever tried. Once a signer that can decrypt + // takes over (Amber reconnected over NIP-46), the heal pass re-opens + // every wrap the relays still hold. + function noteSignerGap() { + const s = st(); + if (interactiveLogin()) { if (!s.dmSignerGap) { s.dmSignerGap = true; save(s); } return; } + if (!s.dmSignerGap || !decryptorsComplete()) return; + delete s.dmSignerGap; + s.dmHeal = 0; + save(s); + wrapLog = null; healed.clear(); seenWraps.clear(); + if (dmStarted) resubscribeStreams(); } // Raw-key unwraps (seed-derived / pasted nsec — the common case) run in @@ -3055,6 +3072,7 @@ export function messagesFeature(ctx) { const pks = dmSubKeys(); if (!pks.length) return; dmStarted = true; + if (interactiveLogin()) noteSignerGap(); loadSeenWraps(); // warm threads from the local cache. A self-thread of our own messages is // the residue of the old sent-copy misthreading (each welcome DM landed @@ -12140,6 +12158,17 @@ export function messagesFeature(ctx) { }, ui.msgReconnecting ? h('span', { class: 'spinner sm' }) : t('msgReconnect'))); } + // Amber by intent signs, but each decrypt would be a trip through the app, + // so nothing sent TO the login npub is opened here — a thread shows only + // what this device sent. Amber also speaks NIP-46; connected that way it + // decrypts quietly, and the messages held back open. + function amberDmNotice() { + if (wallet.watchOnly || !interactiveLogin()) return null; + return h('div', { class: 'row gap6 chat-signer-off', style: 'align-items:center' }, + h('span', { class: 'small muted grow' }, t('msgAmberDms')), + h('button', { class: 'btn-sm', onClick: () => hook('nostrSignerUpgrade') }, t('msgAmberConnect'))); + } + // Enter sends; Shift+Enter (the textarea's native edit) and Ctrl+J insert // a newline. Height follows the text as it's typed — imperatively, since // typing doesn't re-render — with rows as the re-render fallback. @@ -12402,6 +12431,8 @@ export function messagesFeature(ctx) { // that quietly won't open are listed. const lockedRow = signerNotice(); if (lockedRow && wallet.watchOnly) kids.push(lockedRow); + const amberRow = amberDmNotice(); + if (amberRow) kids.push(amberRow); if (pendingLink && pendingLink.where !== 'communities') kids.push(linkInviteCard()); for (const [rid, inv] of pendingDirect) kids.push(directInviteCard(rid, inv)); @@ -13319,6 +13350,7 @@ export function messagesFeature(ctx) { h('div', { class: 'chat-time' }, timeLabel(m.rumor.created_at * 1000))))) : [h('div', { class: 'muted small', style: 'text-align:center;padding:24px 0' }, t('msgNoDmsYet'))])), dmReplyBar(), + amberDmNotice(), composer(t('msgDmPlaceholder'), () => sendDM(peer), null, 'dm:' + peer, (f) => sendDMFile(peer, f)), ui.msgSheet ? dmSheet(peer) : null, choice && ui.msgRoutePick ? routeSheet(peer, choice) : null); @@ -13796,7 +13828,7 @@ export function messagesFeature(ctx) { }, // nostr-login just connected or resumed a signer: wraps the backfill // couldn't open a moment ago can be opened now — drain right away. - nostrSignerLive() { scheduleDrain(0); }, + nostrSignerLive() { noteSignerGap(); scheduleDrain(0); }, // Anyone (ark's history, other features) can open a profile or render a // small clickable identity chip. showProfile(pk) { openProfile(pk); return true; }, diff --git a/src/features/nostrlogin.js b/src/features/nostrlogin.js index 306a12f..2023931 100644 --- a/src/features/nostrlogin.js +++ b/src/features/nostrlogin.js @@ -278,6 +278,16 @@ export function nostrLoginFeature(ctx) { // approval and the login finishes on its own. Deferred a beat so the boot // restore has decided whether this tab is even logged out. setTimeout(() => { + // the same, for a wallet that was reconnecting its own account (Amber + // moving to NIP-46 so messages can be read): back to that screen + const again = !nc && wallet.mnemonic && load().pubkey && nostrConnectPending(); + if (again) { + ui.nostrReconnect = 'upgrade'; + ui.nostrConnectOpen = true; + startNostrConnect(reconnectRun, again); + render(); + return; + } const pending = !nc && !wallet.mnemonic && ui.screen === 'unlock' && nostrConnectPending(); if (!pending) return; if (ui.onb && ['welcome', 'signin'].includes(ui.onb.step)) ui.onb = { step: 'signin' }; @@ -676,6 +686,11 @@ export function nostrLoginFeature(ctx) { linkSection()); } + const reconnectRun = (makeSigner) => reconnectSigner(makeSigner).then(() => { + // an upgrade is done only once the new signer can decrypt + if (liveSigner() && !(ui.nostrReconnect === 'upgrade' && live.interactive)) { ui.nostrReconnect = null; ui.nostrConnectOpen = false; render(); } + }); + // The reconnect takeover: opened by any feature whose action just found // the signer missing (a reload dropped it; Amethyst and friends can't // reattach silently). Same guarded buttons as the settings card — an @@ -683,15 +698,18 @@ export function nostrLoginFeature(ctx) { // refuses a different account. function reconnectScreen() { const st = load(); - const run = (makeSigner) => reconnectSigner(makeSigner).then(() => { - if (liveSigner()) { ui.nostrReconnect = null; render(); } - }); + // 'upgrade': Amber by intent is live but can't read messages — offer + // only its NIP-46 door (nostrconnect), same account enforced + const upgrade = ui.nostrReconnect === 'upgrade'; + const run = reconnectRun; + // straight to the link: the screen exists for this one door + if (upgrade && ui.nostrUpgradeStart) { ui.nostrUpgradeStart = false; ui.nostrConnectOpen = true; startNostrConnect(run); } return h('div', { class: 'col', style: 'gap:16px' }, ctx.brandHeader(false), h('div', { class: 'card col', style: 'gap:12px' }, - h('h3', { style: 'margin:0' }, t('nlReconnectTitle')), - h('p', { class: 'small muted', style: 'margin:0' }, t('nlReconnectBody', { npub: (npubOf(st.pubkey) || '').slice(0, 12) })), - signerButtons(run, { reconnectVia: reconnectViaOf(st) }), + h('h3', { style: 'margin:0' }, t(upgrade ? 'nlAmberUpgradeTitle' : 'nlReconnectTitle')), + h('p', { class: 'small muted', style: 'margin:0' }, upgrade ? t('nlAmberUpgradeBody') : t('nlReconnectBody', { npub: (npubOf(st.pubkey) || '').slice(0, 12) })), + upgrade ? nostrConnectSection(run) : signerButtons(run, { reconnectVia: reconnectViaOf(st) }), ui.nostrLoginError ? h('div', { class: 'notice err' }, ui.nostrLoginError) : null), h('button', { class: 'btn-ghost btn-block', onClick: () => { stopNostrConnect(); @@ -710,6 +728,17 @@ export function nostrLoginFeature(ctx) { // An action needed the login signer and it isn't there: open the // reconnect screen (and try the silent extension reattach in the // background — it closes the screen by itself when it lands). + // Messages found an Amber-by-intent login that can't decrypt: offer to + // reconnect the same account over NIP-46. + nostrSignerUpgrade() { + const st = load(); + if (!st.pubkey) return false; + ui.nostrReconnect = 'upgrade'; + ui.nostrUpgradeStart = true; + ui.nostrLoginError = ''; + render(); + return true; + }, nostrReconnectPrompt() { const st = load(); if (!st.pubkey || liveSigner()) return false; diff --git a/src/i18n.js b/src/i18n.js index 32c55b0..e80e2f8 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -515,6 +515,8 @@ const STR = { addrRead: '{min} min read', addrList: 'A list by {name}', msgSignerOff: "Your nostr signer isn't connected, so you can't post as yourself yet.", + msgAmberDms: 'Signed in with Amber, messages sent to you can’t be opened here, only ones you sent from this device.', + msgAmberConnect: 'Connect Amber', msgReconnect: 'Reconnect', msgDmsTitle: 'Messages', msgCommunitiesTitle: 'Communities', @@ -1226,6 +1228,8 @@ const STR = { nlDisconnected: 'not connected', nlReconnectDesc: "Your signer isn't connected, so this app can't sign as you. Reconnect it to post and update your profile. Your wallet and balance aren't affected.", nlReconnectTitle: 'Reconnect your signer', + nlAmberUpgradeTitle: 'Read your messages', + nlAmberUpgradeBody: 'Amber can only open messages here when it’s connected as a remote signer. Tap below, approve in Amber (allow decrypting), and your messages will load. Signing works as before.', nlReconnectBody: 'Your Nostr signer isn’t connected on this device. Reconnect to keep acting as {npub}…', nlWrongAccount: 'That signer is a different Nostr account. Reconnect with {npub}.', nlLinked: 'Wallet linked to your Nostr account', diff --git a/tools/amber-dm-upgrade-test.js b/tools/amber-dm-upgrade-test.js new file mode 100644 index 0000000..4e34a94 --- /dev/null +++ b/tools/amber-dm-upgrade-test.js @@ -0,0 +1,154 @@ +// Signed in with Amber by intent (NIP-55), nothing sealed to the login npub +// is decrypted — each decrypt would be a trip through the app — so a thread +// showed only what that device had sent (isolabellart, 2026-10-09). Worse, those +// wraps were given up on the wallet key alone and logged as opened, so they +// stayed hidden for good. Now Messages says so and offers "Connect Amber": +// the same account over NIP-46 (nostrconnect), after which every wrap the +// relays hold is opened again — including ones the old code wrote off. +// The remote signer is played by this script over a shimmed relay. +// Run: bun tools/amber-dm-upgrade-test.js +import puppeteer from './puppeteer.js'; +import { cacheKeyFor } from '../src/wallet.js'; +import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure'; +import * as nip44 from 'nostr-tools/nip44'; +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 SK = generateSecretKey(); const PK = getPublicKey(SK); // the Amber account +const PEER_SK = generateSecretKey(); const PEER = getPublicKey(PEER_SK); +const OLD = wrapEvent(PEER_SK, { publicKey: PK }, 'an old message the wrap log wrote off'); +const NEW = wrapEvent(PEER_SK, { publicKey: PK }, 'a message from before the upgrade'); + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5311, fetch: (req) => { const p = new URL(req.url).pathname; if (p === '/verify-worker.js' || p === '/nip46.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.setUserAgent('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Mobile Safari/537.36'); +await page.evaluateOnNewDocument((fx) => { + window.__amberUrls = []; + window.__coinosAmberLaunch = (u) => { window.__amberUrls.push(u); }; + window.__published = []; + const subs = []; + 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)) && (!f.since || ev.created_at >= f.since); + // the test pushes the signer's answers through here, to every live sub that wants them + window.__inject = (ev) => { for (const s of subs) if (s.fs.some((f) => fits(ev, f))) s.ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', s.id, ev]) })); }; + const Real = window.WebSocket; + window.WebSocket = function (...a) { + const ws = new Real(...a); + const send = ws.send.bind(ws); + ws.send = (d) => { + try { + const m = JSON.parse(d); + if (m[0] === 'REQ') { + const fs = m.slice(2); + for (let i = subs.length - 1; i >= 0; i--) if (subs[i].ws === ws && subs[i].id === m[1]) subs.splice(i, 1); + subs.push({ ws, id: m[1], fs }); + const evs = fx.filter((ev) => fs.some((f) => fits(ev, f))); + 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] === 'CLOSE') { for (let i = subs.length - 1; i >= 0; i--) if (subs[i].ws === ws && subs[i].id === m[1]) subs.splice(i, 1); return; } + if (m[0] === 'EVENT') { + window.__published.push(m[1]); + setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['OK', m[1].id, true, '']) })), 0); + return; + } + } catch {} + return send(d); + }; + return ws; + }; + window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); +}, [OLD, NEW]); +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; }; + +// The remote signer: answers the connect, then get_public_key / nip44_decrypt. +let client = null, handled = new Set(), decrypts = 0; +const signerLoop = async () => { + const pub = await page.evaluate(() => window.__published.filter((e) => e.kind === 24133)); + for (const ev of pub) { + if (handled.has(ev.id) || !client || ev.pubkey !== client) continue; + handled.add(ev.id); + const ck = nip44.getConversationKey(SK, ev.pubkey); + const req = JSON.parse(nip44.decrypt(ev.content, ck)); + let result; + if (req.method === 'get_public_key') result = PK; + else if (req.method === 'nip44_decrypt') { decrypts++; result = nip44.decrypt(req.params[1], nip44.getConversationKey(SK, req.params[0])); } + else if (req.method === 'nip44_encrypt') result = nip44.encrypt(req.params[1], nip44.getConversationKey(SK, req.params[0])); + else if (req.method === 'sign_event') { const u = JSON.parse(req.params[0]); result = JSON.stringify(finalizeEvent(u, SK)); } + else if (req.method === 'ping') result = 'pong'; + else if (req.method === 'connect') result = 'ack'; + const resp = finalizeEvent({ kind: 24133, created_at: Math.floor(Date.now() / 1000), tags: [['p', ev.pubkey]], content: nip44.encrypt(JSON.stringify({ id: req.id, result }), ck) }, SK); + await page.evaluate((e) => window.__inject(e), resp); + } +}; + +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto('http://localhost:5311/', { 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 base = cacheKeyFor(mn + '\n'); + // an Amber login, and a wrap log in which the old code had already + // written OLD off as opened + await page.evaluate(([k, pk, oldId]) => { + localStorage.setItem(k + ':nostrlogin', JSON.stringify({ pubkey: pk, session: { amber: pk }, via: 'amber' })); + const m = JSON.parse(localStorage.getItem(k + ':messages') || '{}'); + m.wraps = [oldId.slice(0, 16)]; m.dmHeal = 2; + localStorage.setItem(k + ':messages', JSON.stringify(m)); + }, [base, PK, OLD.id]); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Messages"]')?.click()); + + console.log('\n[signed in with Amber by intent]'); + check('Messages says messages sent to you can\'t be opened, and offers Connect Amber', await waitText('can’t be opened here', 10000) && await page.evaluate(() => [...document.querySelectorAll('button')].some((b) => b.textContent.trim() === 'Connect Amber'))); + await sleep(4000); + check('no decrypt intent went to Amber for an arriving wrap', !(await page.evaluate(() => window.__amberUrls.some((u) => /nip44_decrypt/.test(u))))); + check('neither message shows', !(await text()).includes('a message from before the upgrade') && !(await text()).includes('wrote off')); + check('the arriving wrap is not logged as opened', await page.evaluate(([k, id]) => !(JSON.parse(localStorage.getItem(k + ':messages') || '{}').wraps || []).includes(id.slice(0, 16)), [base, NEW.id])); + + console.log('\n[Connect Amber: the same account over NIP-46]'); + await click('connect amber'); await sleep(300); + check('a screen explains it and offers the signer-app link', await waitText('read your messages', 5000)); + let uri = null; + for (let i = 0; i < 40 && !uri; i++) { uri = await page.evaluate(() => document.querySelector('a[href^="nostrconnect://"]')?.getAttribute('href')); if (!uri) await sleep(250); } + check('...a nostrconnect:// link asking to decrypt', !!uri && /nip44_decrypt/.test(decodeURIComponent(uri)), uri && uri.slice(0, 60)); + const u = new URL(uri.replace('nostrconnect://', 'http://')); + client = u.host; + const secret = u.searchParams.get('secret'); + // the signer app accepts: an answer carrying the secret + await sleep(1000); + const accept = finalizeEvent({ kind: 24133, created_at: Math.floor(Date.now() / 1000), tags: [['p', client]], + content: nip44.encrypt(JSON.stringify({ id: 'x', result: secret }), nip44.getConversationKey(SK, client)) }, SK); + await page.evaluate((e) => window.__inject(e), accept); + let opened = false; + for (let i = 0; i < 120 && !opened; i++) { + await signerLoop(); + await page.evaluate(() => { if (!document.querySelector('.chat-log')) { const r = document.querySelector('[data-key^="dm:"]'); const c = r && r.querySelector('.chat-preview'); if (c) c.click(); } }); + opened = (await text()).includes('a message from before the upgrade') && (await text()).includes('wrote off'); + if (!opened) await sleep(500); + } + check('the screen closes and the notice is gone', !(await text()).includes('read your messages') && !(await text()).includes('can’t be opened here')); + check('both messages open — the one held back and the one written off', opened, 'decrypts asked of the signer: ' + decrypts); + const st = await page.evaluate((k) => JSON.parse(localStorage.getItem(k + ':nostrlogin') || '{}'), base); + check('the account is now a bunker session for the same npub', st.pubkey === PK && st.via === 'bunker' && !!st.session && !st.session.amber, JSON.stringify({ via: st.via })); + check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); +} finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ Amber users can read their messages' : '\n❌ failed'); +process.exit(ok ? 0 : 1); |
