From 320533c45039935e285ce89a39e6d5db2142e691 Mon Sep 17 00:00:00 2001 From: Mindaugas Date: Wed, 18 Nov 2026 01:17:53 +0200 Subject: [PATCH] feat(lan): add nearby people from the Share dialog; one mutual add (#262) Nearby people are listed under your people in the Share dialog, each with Add, and the person you add is ticked while the dialog stays open. Adding is now mutual in one exchange: after a correct pairing code both screens show a four-character confirm code, and the person being added presses Add to store both keys, or Decline to store nothing. Add back is gone. Announcements carry v=2; an older peer is listed with Add disabled and "Needs update". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PJaGuL4V5ghYxXSGoyYU8n --- design/render/262-lan-add-share.render.mjs | 388 ++++++++++++++++++ docs/features.md | 2 +- docs/glossary.md | 5 + docs/roadmap.md | 2 +- docs/security.md | 17 +- e2e/lan-pairing.spec.mjs | 56 ++- e2e/lanPeers.mjs | 34 +- e2e/share.spec.mjs | 4 +- scripts/theme-sweep.mjs | 52 +++ specs/2026-11-18-lan-add-from-share/plan.md | 88 ++++ src/main/lan/dnsSd.js | 9 +- src/main/lan/frames.js | 5 +- src/main/lan/pairing.js | 67 ++- src/main/lan/pairingCode.js | 14 +- src/main/lan/pairingIpc.js | 7 +- src/main/lan/peers.js | 16 +- src/preload/lanApi.js | 1 + .../lan/components/ConfirmCodeDialog.vue | 51 +++ .../lan/components/NetworkSettings.vue | 10 +- .../lan/components/PairingDialogs.vue | 2 + .../lan/components/PairingResultDialog.vue | 9 +- .../lan/components/styles/ShowCodeDialog.css | 10 + src/renderer/src/features/lan/index.js | 1 + src/renderer/src/features/lan/lanStore.js | 18 +- .../src/features/lan/pairingResult.js | 7 +- src/renderer/src/features/lan/peerVersion.js | 3 + .../share/components/NearbyPeople.vue | 30 ++ .../share/components/RecipientPicker.vue | 13 +- .../share/components/ShareDiffDialog.vue | 24 +- .../components/styles/RecipientPicker.css | 12 + src/shared/i18n/en-XA.json | 24 +- src/shared/i18n/en.json | 24 +- src/shared/lanProtocol.js | 2 + tests/main/lan/dnsSd.test.js | 20 +- tests/main/lan/pairing.test.js | 61 ++- tests/main/lan/pairingCode.test.js | 19 +- tests/main/lan/peers.test.js | 12 + tests/renderer/features/lan/lanStore.test.js | 73 +++- .../features/lan/pairingResult.test.js | 8 +- .../renderer/features/lan/peerVersion.test.js | 14 + 40 files changed, 1088 insertions(+), 126 deletions(-) create mode 100644 design/render/262-lan-add-share.render.mjs create mode 100644 specs/2026-11-18-lan-add-from-share/plan.md create mode 100644 src/renderer/src/features/lan/components/ConfirmCodeDialog.vue create mode 100644 src/renderer/src/features/lan/peerVersion.js create mode 100644 src/renderer/src/features/share/components/NearbyPeople.vue create mode 100644 src/shared/lanProtocol.js create mode 100644 tests/renderer/features/lan/peerVersion.test.js diff --git a/design/render/262-lan-add-share.render.mjs b/design/render/262-lan-add-share.render.mjs new file mode 100644 index 00000000..37aded78 --- /dev/null +++ b/design/render/262-lan-add-share.render.mjs @@ -0,0 +1,388 @@ +import { join } from 'node:path' +import { mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { randomBytes } from 'node:crypto' +import { test, launchApp, freshUserDataDir, firstReadyPage } from '../../e2e/fixtures.mjs' +import { SNIPPETS } from '../../scripts/lib/seedData.mjs' + +// #262: adding nearby people from the Share dialog. Real components opened through their stores; +// only the new parts are patched in, by cloning real elements so they keep the shipped styles. +const OUT = 'design/render/out/262' + +const fp = () => randomBytes(16).toString('hex') +const BASE_PEOPLE = [ + { label: 'Ana Petrauskė', email: 'ana@acme.lt', online: true }, + { label: 'QA team', email: 'qa@acme.lt', online: true }, + { label: 'Rūta Vaitkutė', email: 'ruta@acme.lt', online: true }, + { label: 'Jonas Kazlauskas', online: false }, + { label: 'Marius Jankus', email: 'marius@acme.lt', online: false } +].map((p) => ({ ...p, fingerprint: fp() })) +const BASE_NEARBY = [ + { name: 'Ben Okafor', fp: fp() }, + { name: 'DESKTOP-NHBCR5M', fp: fp() }, + { name: 'Chen Liu', fp: fp(), old: true } +] + +// Each state starts from its own copy: adding someone moves them from nearby to your people. +let PEOPLE = [] +let NEARBY = [] + +const piniaStore = (id) => + `document.querySelector('#app').__vue_app__.config.globalProperties.$pinia._s.get('${id}')` + +async function setStore(page, id, patch) { + await page.evaluate( + ({ expr, patch }) => { + // eslint-disable-next-line no-new-func -- render script only, runs in the page + const store = new Function(`return ${expr}`)() + Object.assign(store, typeof patch === 'function' ? patch(store) : patch) + }, + { expr: piniaStore(id), patch } + ) + await page.waitForTimeout(250) +} + +async function seed(dir) { + writeFileSync( + join(dir, 'trusted-keys.json'), + JSON.stringify( + PEOPLE.map(({ label, email, fingerprint }) => ({ + fingerprint, + label, + sign: 'c2lnbg==', + box: 'Ym94', + ...(email ? { email } : {}) + })) + ) + ) +} + +async function seedSnippets(page) { + await page.evaluate(async (snippets) => { + const entries = [] + let t = Date.now() + for (const s of snippets.slice(0, 8)) { + const id = crypto.randomUUID() + const aadSalt = crypto.randomUUID() + const createdAt = t + t -= 3 * 3600_000 + const box = await window.api.vaultEncrypt(s.content, [id, aadSalt, createdAt].join('|')) + entries.push({ + id, + aadSalt, + name: s.name, + createdAt, + updatedAt: createdAt, + language: s.language, + detected: s.language, + tags: [], + iv: box.iv, + tag: box.tag, + data: box.data + }) + } + await window.api.storeSave('snippets', JSON.stringify({ tags: {}, entries })) + await window.api.storeSave( + 'onboarding', + JSON.stringify({ schema: 2, offerTours: true, tours: {}, offer: false, tips: { on: false } }) + ) + }, SNIPPETS) +} + +const online = () => + PEOPLE.filter((p) => p.online).map((p) => ({ fp: p.fingerprint, name: p.label, trusted: true })) + +async function lanOn(page) { + await setStore(page, 'lan', { + loaded: true, + enabled: true, + visible: true, + online: true, + peers: [...online(), ...NEARBY.map((n) => ({ fp: n.fp, name: n.name, trusted: false }))] + }) +} + +async function openShare(page) { + await lanOn(page) + await setStore(page, 'share', { + shareDraft: { + name: 'nginx.conf ↔ nginx.prod.conf', + ttlHours: 24, + tags: [], + snapshot: { mode: 'paste', pasteLeft: 'a', pasteRight: 'b' } + } + }) + await page.locator('.dialog .recipients').waitFor() + await page.waitForTimeout(300) + await page.evaluate(() => { + const ana = [...document.querySelectorAll('.dialog .recipient')].find((r) => + r.textContent.includes('Ana Petrauskė') + ) + ana?.querySelector('input')?.click() + }) +} + +// Option A: Nearby under your people, built from the picker's own label and rows. +async function addNearbyGroup(page, { only = false } = {}) { + await page.evaluate( + ({ nearby, only }) => { + const list = document.querySelector('.dialog .recipients') + const label = document.querySelector('.dialog .field-label') + const sample = list.querySelector('li') + const addBtn = document.querySelector('.dialog .dialog-actions .btn-sm') + if (only) { + list.querySelectorAll('li').forEach((li) => li.remove()) + document.querySelector('.dialog .filterbar')?.remove() + document.querySelector('.dialog .picked')?.remove() + document.querySelector('.dialog .listfoot')?.remove() + } + const head = label.cloneNode(false) + head.setAttribute('data-design-mock', '') + head.textContent = 'Nearby' + head.style.marginTop = only ? '0' : 'var(--space-2)' + const group = list.cloneNode(false) + group.setAttribute('data-design-mock', '') + const nearbyRow = (n) => { + const li = sample.cloneNode(true) + const row = li.querySelector('label') + row.classList.remove('active') + row.classList.toggle('off', !!n.old) + row.querySelector('input')?.remove() + row.querySelector('.rc-name').textContent = n.name + row.querySelector('.rc-mail')?.remove() + const net = row.querySelector('.rc-net') + net.textContent = 'Needs update' + net.classList.remove('on') + if (!n.old) net.remove() + const btn = addBtn.cloneNode(false) + btn.textContent = 'Add' + btn.disabled = !!n.old + row.appendChild(btn) + return li + } + for (const n of nearby) group.appendChild(nearbyRow(n)) + list.after(head) + head.after(group) + const scroller = document.querySelector('.dialog .rows') + scroller.scrollTop = scroller.scrollHeight + }, + { nearby: NEARBY, only } + ) + await page.waitForTimeout(150) +} + +// Option B: one plain button under the list. +async function addNearbyButton(page) { + await page.evaluate((n) => { + const scroller = document.querySelector('.dialog .rows') + const addBtn = document.querySelector('.dialog .dialog-actions .btn-sm') + const btn = addBtn.cloneNode(false) + btn.setAttribute('data-design-mock', '') + btn.disabled = false + btn.textContent = `Add someone nearby · ${n}` + btn.style.alignSelf = 'flex-start' + btn.style.marginTop = 'var(--space-2)' + scroller.after(btn) + }, NEARBY.length) +} + +async function showCode(page, { name, code, title, note, actions }) { + await setStore(page, 'lan', { + pairing: { + id: 'x', + role: 'holder', + stage: 'show-code', + fp: NEARBY[0].fp, + name, + code, + expiresAt: Date.now() + 98_000 + } + }) + await page.locator('.dialog .code-box').waitFor() + if (!title) return + await page.evaluate( + ({ title, note, code, actions }) => { + const dlg = [...document.querySelectorAll('.dialog')].at(-1) + dlg.querySelector('.dialog-header h3').textContent = title + dlg.querySelector('.show-code > .dialog-note').textContent = note + const box = dlg.querySelector('.code-box') + box.querySelector('.code').textContent = code + box.querySelector('.hint')?.remove() + box.style.cursor = 'default' + const row = dlg.querySelector('.dialog-actions') + const cancel = row.querySelector('.btn-ghost') + cancel.textContent = actions[0] + if (actions[1]) { + const primary = cancel.cloneNode(false) + primary.className = cancel.className.replace('btn-ghost', 'btn-primary') + primary.textContent = actions[1] + row.appendChild(primary) + } + }, + { title, note, code, actions } + ) +} + +async function adderResult(page, stage, patch) { + await setStore(page, 'lan', { + pairing: { id: 'x', role: 'adder', stage, fp: NEARBY[0].fp, name: 'Ben Okafor' } + }) + await page.locator('.dialog').waitFor() + if (!patch) return + await page.evaluate(({ title, note, close }) => { + const dlg = [...document.querySelectorAll('.dialog')].at(-1) + dlg.querySelector('.dialog-header h3').textContent = title + const n = dlg.querySelector('.dialog-body .dialog-note') + if (note) n.textContent = note + else n?.remove() + const row = dlg.querySelector('.dialog-actions') + row.querySelectorAll('.btn-primary').forEach((b) => b.remove()) + const ghost = row.querySelector('.btn-ghost, .btn') + if (ghost) ghost.textContent = close + }, patch) +} + +async function notice(page, text) { + await page.evaluate( + ({ expr, text }) => { + // eslint-disable-next-line no-new-func -- render script only, runs in the page + new Function(`return ${expr}`)().showNotice(text) + }, + { expr: piniaStore('diff'), text } + ) + await page.waitForTimeout(250) +} + +const STATES = { + 'share-a': async (page) => { + await openShare(page) + await addNearbyGroup(page) + }, + 'share-b': async (page) => { + await openShare(page) + await addNearbyButton(page) + }, + 'share-nobody': async (page) => { + await openShare(page) + await addNearbyGroup(page, { only: true }) + }, + 'add-code': async (page) => { + await openShare(page) + await addNearbyGroup(page) + await setStore(page, 'lan', { + pairing: { + id: 'x', + role: 'adder', + stage: 'enter-code', + fp: NEARBY[0].fp, + name: 'Ben Okafor', + expiresAt: Date.now() + 110_000 + } + }) + await page.locator('[data-testid=lan-code-input]').fill('K7Q 4ZP') + }, + 'add-waiting': async (page) => { + await openShare(page) + await addNearbyGroup(page) + await showCode(page, { + name: 'Ben Okafor', + code: '4F7K', + title: 'Waiting for Ben Okafor', + note: 'Ben’s screen should show this code.', + actions: ['Cancel'] + }) + }, + 'share-after': async (page) => { + await openShare(page) + await page.evaluate((name) => { + for (const row of document.querySelectorAll('.dialog .recipient')) { + if (row.querySelector('.rc-name')?.textContent.trim() === name) + row.querySelector('input')?.click() + } + }, 'Ben Okafor') + await addNearbyGroup(page) + await notice(page, 'Added Ben Okafor') + }, + 'holder-code': async (page) => { + await showCode(page, { name: 'Ana Petrauskė', code: 'K7Q4ZP' }) + }, + 'holder-confirm': async (page) => { + await showCode(page, { + name: 'Ana Petrauskė', + code: '4F7K', + title: 'Add Ana Petrauskė?', + note: 'Check Ana’s screen shows the same code.', + actions: ['Decline', 'Add Ana'] + }) + }, + 'holder-added': async (page) => { + await notice(page, 'Added Ana Petrauskė') + }, + 'add-mismatch': async (page) => adderResult(page, 'mismatch'), + 'add-declined': async (page) => + adderResult(page, 'mismatch', { title: 'Ben Okafor declined', note: null, close: 'Close' }), + 'add-expired': async (page) => adderResult(page, 'expired') +} + +async function settingsNetwork(page) { + await lanOn(page) + await page.evaluate(() => document.querySelector('[data-testid=toolbar-settings]').click()) + await page.locator('.settings-nav').waitFor({ timeout: 8000 }) + await page.locator('.settings-nav .nav-group-row', { hasText: 'Integrations' }).click() + await page.locator('.settings-nav .nav-child', { hasText: 'Network' }).click() + await page.waitForTimeout(500) + await lanOn(page) + await page.locator('.network-settings .person').first().waitFor() + await page.evaluate((old) => { + for (const row of document.querySelectorAll('.network-settings .person')) { + if (row.querySelector('.row-2-name')?.textContent.trim() !== old) continue + const btn = row.querySelector('button') + btn.disabled = true + const status = document.createElement('span') + status.className = 'status' + for (const a of row.attributes) + if (a.name.startsWith('data-v-')) status.setAttribute(a.name, '') + status.textContent = 'Needs update' + btn.before(status) + } + }, 'Chen Liu') +} + +test('262 LAN add from Share', async () => { + test.setTimeout(240_000) + mkdirSync(OUT, { recursive: true }) + const ONLY = process.env.ONLY ? process.env.ONLY.split(',') : null + for (const theme of ['light', 'dark']) { + for (const [name, draw] of Object.entries({ ...STATES, 'settings-network': settingsNetwork })) { + if (ONLY && !ONLY.includes(name)) continue + PEOPLE = BASE_PEOPLE.map((p) => ({ ...p })) + NEARBY = BASE_NEARBY.map((n) => ({ ...n })) + if (name === 'share-after') { + const [ben] = NEARBY.splice(0, 1) + PEOPLE.splice(1, 0, { label: ben.name, fingerprint: ben.fp, online: true }) + } + const dir = freshUserDataDir() + await seed(dir) + const app = await launchApp(dir) + try { + const page = await firstReadyPage(app) + await page.setViewportSize({ width: 1280, height: 800 }) + await seedSnippets(page) + await page.evaluate((t) => window.api.storeSave('theme', t), theme) + await page.evaluate(() => window.api.lanUpdate({ enabled: false })) + await page.addInitScript(() => + Object.defineProperty(navigator, 'platform', { get: () => 'MacIntel' }) + ) + await page.reload() + await page.locator('[data-testid=toolbar-settings]').waitFor() + await page.waitForTimeout(600) + await draw(page) + await page.mouse.move(1270, 790) + await page.waitForTimeout(350) + await page.screenshot({ path: join(OUT, `${name}-${theme}.png`) }) + } finally { + await app.close() + rmSync(dir, { recursive: true, force: true }) + } + } + } +}) diff --git a/docs/features.md b/docs/features.md index 837b6677..be54110b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -27,7 +27,7 @@ Everything Diff Bro does, in detail. The [README](../README.md) has the short ve | **Open with** | Diff Bro appears in Finder's **Open With** menu and Explorer's **Open with** list for text and data files — `.txt`, `.md`, `.json`, `.xml`, `.yaml`, `.csv`, `.log`, `.diff` and the rest. One file opens as an unsaved snippet — read it, edit it, or save it to your library; the status bar says where it came from. Open a second while the first is still open and Diff Bro asks whether to compare the two. Select two at once and they open as one comparison. A single file dropped on an empty window opens the same way. It is offered, never imposed: Diff Bro does not make itself the default handler for anything, so double-clicking a JSON still opens whatever it always did. | | **Terminal** | `diffbro compare a.json b.json` opens a comparison in the running app, and either side can name a git revision instead of a file — `diffbro compare HEAD~1:src/app.js src/app.js` reads the old copy straight out of the repository, so you never have to produce one first. `diffbro open` raises the app, `diffbro backup ` writes an encrypted archive. No port, no daemon. | | **Use with Claude** | Turn on Settings ▸ Integrations ▸ Claude and a Claude app on the same machine can read the snippets and saved diffs you allow, and offer new ones. **Connect** adds Diff Bro to Claude Code or Claude Desktop in one click; the command and config are still there to copy. Anything Claude offers waits under **From Claude** at the top of Snippets or Diffs, and opens as a tab you can edit before you accept it. It is off until you turn it on, never sees secret snippets or diffs you received, and every request is listed. | -| **Share on your network** | DiffBro instances on the same local network see each other in Settings ▸ Integrations ▸ Network. **Add** next to a person: their screen shows a one-time pairing code with a countdown (click it to copy), and you type or paste it; one try. Once you have added each other, **Send now** in the Share dialog sends a diff, and **Share…** in a snippet's ⋯ menu sends a snippet, sealed exactly as a `.diffbro` file. They get a dialog with Open / Decline, or **Silence for** a while; anything they close or silence waits under a bell beside the gear. **Stop sharing** removes someone's key and tells them. On by default; **Show me to others** and **Share on this network** turn it down or off. | +| **Share on your network** | DiffBro instances on the same local network see each other in Settings ▸ Integrations ▸ Network. **Add** next to a person, there or under **Nearby** in the Share dialog: their screen shows a one-time pairing code with a countdown (click it to copy), and you type or paste it; one try. Both screens then show the same short confirm code, and they press **Add** to add each other in one go (or **Decline**, which adds no one). Added from Share, they're ticked and the dialog stays open. Someone on an older version shows **Needs update**. Once added, **Send now** in the Share dialog sends a diff, and **Share…** in a snippet's ⋯ menu sends a snippet, sealed exactly as a `.diffbro` file. They get a dialog with Open / Decline, or **Silence for** a while; anything they close or silence waits under a bell beside the gear. **Stop sharing** removes someone's key and tells them. On by default; **Show me to others** and **Share on this network** turn it down or off. | | **Yours to arrange** | A System theme, the default, that follows the OS between Light and Dark, and twenty named ones (Nord, Sepia, Solar, Nyan, Matrix, Volcano, Tide, Graphite, plus accessibility-grade Contrast and Beacon), shared tags, adjustable limits. |
diff --git a/docs/glossary.md b/docs/glossary.md index 2b817c56..c8934622 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -227,6 +227,11 @@ literally). uses to say which services a device offers (`dnsSd.js`). - **Pairing code** — the one-time six-character code shown on the screen of the person being added and typed by the person adding (`pairingCode.js`). +- **Confirm code** — the four characters both screens show after a correct + pairing code; the person being added presses Add only when theirs matches, + and only then are both keys stored (`confirmCode` in `pairingCode.js`). +- **Nearby** — people on your network you haven't added yet, listed under your + people in the Share dialog and in Settings ▸ Network, each with Add. - **Commit-then-reveal** — the adder sends a hash of a random value first and reveals the value only after seeing the other side's, so the pairing code cannot be steered: someone in the middle gets one guess per request. diff --git a/docs/roadmap.md b/docs/roadmap.md index 908116ab..eb143402 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -345,7 +345,7 @@ flowchart LR trust --> stop["Stop sharing
signed notice"] ``` -- Done. Add someone with a one-time pairing code (copy, paste, countdown, one try). +- Done. Add someone with a one-time pairing code (copy, paste, countdown, one try); they confirm a short code and you add each other in one go, from Settings or the Share dialog. - Done. Send diffs and snippets, sealed as a `.diffbro`; people not on the network are disabled in the Share dialog. - Done. Receive in a dialog queued "1 of N"; Silence for 1 min to Forever; a bell diff --git a/docs/security.md b/docs/security.md index 3ada670d..79f6ffcd 100644 --- a/docs/security.md +++ b/docs/security.md @@ -470,13 +470,22 @@ Diff Bro instances on the same network find each other and exchange keys, diffs and snippets directly. The sockets, and what fences them, are in the [Offline guarantee](#offline-guarantee). -- **Adding someone** stores their public key exactly as importing a - `.diffbrokey` does. They prove it is theirs with a one-time pairing code: - - their screen shows the code, and you type or paste it; +- **Adding someone** stores both public keys, each exactly as importing a + `.diffbrokey` does. One exchange proves both: + - their screen shows a one-time pairing code, and you type or paste it; - the code is derived from both keys and two nonces, the adder committing to its nonce first, so someone in the middle gets one guess per request; - a wrong code cancels the request; - - the code is never stored. + - a correct code stores nothing yet. Both screens show a four-character + confirm code derived from the pairing code, and they press Add only if + theirs matches yours. A key swapped in the middle gives the two sides + different pairing codes, so your typed code fails before any confirm code + is shown; + - their Add stores your key and tells your side to store theirs. Decline, + expiry or a dropped connection stores nothing on either side; + - neither code is stored. + An instance on the version before the confirm step announces `v=1` and is + listed as needing an update, with Add disabled. - **Sending** seals the diff or snippet exactly as Share does, then sends the sealed envelope. The recipient opens it with the same checks a `.diffbro` file gets (signature, audience, expiry). Secret snippets are never sent. diff --git a/e2e/lan-pairing.spec.mjs b/e2e/lan-pairing.spec.mjs index 555fff95..c4f218ce 100644 --- a/e2e/lan-pairing.spec.mjs +++ b/e2e/lan-pairing.spec.mjs @@ -1,7 +1,7 @@ import { readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { test, expect, openSettingsPage, launchApp, firstReadyPage } from './fixtures.mjs' -import { addPeer, startPeer, stop } from './lanPeers.mjs' +import { addPeer, confirmAdd, shareDiff, startPeer, stop, typeCode } from './lanPeers.mjs' // Two launches per test. test.describe.configure({ timeout: 90_000 }) @@ -30,10 +30,13 @@ test('the code copied on one screen and pasted on the other adds the key', async await expect(adding.getByTestId('lan-code-input')).toHaveValue(/^[2-9A-Z]{6}$/) await adding.getByRole('button', { name: 'Add', exact: true }).click() await expect(adding).toBeHidden() + const confirming = ana.page.getByRole('dialog', { name: `Add ${ben.name}?` }) + await confirming.getByRole('button', { name: 'Add', exact: true }).click() await expect(anaRow.getByText('Trusted')).toBeVisible() - const back = ana.page.getByRole('dialog', { name: `${ben.name} added you` }) - await expect(back).toBeVisible() - await expect(back.getByRole('button', { name: 'Add back' })).toBeVisible() + const anaSettings = await openSettingsPage(ana.page, 'Network') + await expect( + anaSettings.locator('.person', { hasText: ben.name }).getByText('Trusted') + ).toBeVisible() } finally { await stop(ana, ben) } @@ -96,28 +99,45 @@ test('a key named before names were capped still adds, in both directions', asyn const ben = await startPeer('Ben') try { await addPeer(ben, ana) - await addPeer(ana, ben) + const anaSettings = await openSettingsPage(ana.page, 'Network') + await expect( + anaSettings.locator('.person', { hasText: ben.name }).getByText('Trusted') + ).toBeVisible() } finally { await stop(ana, ben) } }) -test('adding back ends it: neither side is asked to add the other again', async () => { +test('declining at the confirm step adds no one on either screen', async () => { + const { ana, ben, anaRow } = await benAddsAna() + try { + const { confirming } = await typeCode(ben, ana) + await confirming.getByRole('button', { name: 'Decline' }).click() + await expect(ben.page.getByRole('dialog', { name: `${ana.name} declined` })).toBeVisible() + await expect(anaRow.getByText('Trusted')).toHaveCount(0) + const anaSettings = await openSettingsPage(ana.page, 'Network') + await expect(anaSettings.locator('.person', { hasText: ben.name })).toBeVisible() + await expect( + anaSettings.locator('.person', { hasText: ben.name }).getByText('Trusted') + ).toHaveCount(0) + } finally { + await stop(ana, ben) + } +}) + +test('someone nearby is added from the Share dialog, ticked, and the dialog stays', async () => { const ana = await startPeer('Ana') const ben = await startPeer('Ben') try { - await addPeer(ben, ana) - const settings = await openSettingsPage(ana.page, 'Network') - const benRow = settings.locator('.person', { hasText: ben.name }) - await benRow.getByRole('button', { name: 'Add' }).click() - const shown = ben.page.getByRole('dialog', { name: `${ana.name} wants to add you` }) - const code = (await shown.getByTestId('lan-code').innerText()).replace(/\W/g, '').slice(0, 6) - const adding = ana.page.getByRole('dialog', { name: `Add ${ben.name}` }) - await adding.getByTestId('lan-code-input').fill(code) - await adding.getByRole('button', { name: 'Add', exact: true }).click() - await expect(benRow.getByText('Trusted')).toBeVisible() - await expect(ben.page.getByText(`${ana.name} added you back`)).toBeVisible() - await expect(ben.page.getByRole('dialog', { name: `${ana.name} added you` })).toHaveCount(0) + const share = await shareDiff(ben.page) + const nearby = share.getByTestId('share-nearby') + const anaRow = nearby.locator('li', { hasText: ana.name }) + await expect(anaRow).toBeVisible({ timeout: 20_000 }) + await anaRow.getByRole('button', { name: 'Add' }).click() + await confirmAdd(ben, ana) + await expect(share).toBeVisible() + await expect(share.getByRole('checkbox', { name: ana.name })).toBeChecked() + await expect(nearby.locator('li', { hasText: ana.name })).toHaveCount(0) } finally { await stop(ana, ben) } diff --git a/e2e/lanPeers.mjs b/e2e/lanPeers.mjs index 956d1e0c..ce783935 100644 --- a/e2e/lanPeers.mjs +++ b/e2e/lanPeers.mjs @@ -22,23 +22,34 @@ export async function startPeer(base) { return { dir, app, page, name } } -export async function addPeer(adder, holder) { - const settings = await openSettingsPage(adder.page, 'Network') - const row = settings.locator('.person', { hasText: holder.name }) - await expect(row).toBeVisible({ timeout: 20_000 }) - await row.getByRole('button', { name: 'Add' }).click() +export async function typeCode(adder, holder) { const shown = holder.page.getByRole('dialog', { name: `${adder.name} wants to add you` }) const code = (await shown.getByTestId('lan-code').innerText()).replace(/\W/g, '').slice(0, 6) const adding = adder.page.getByRole('dialog', { name: `Add ${holder.name}` }) await adding.getByTestId('lan-code-input').fill(code) await adding.getByRole('button', { name: 'Add', exact: true }).click() + const waiting = adder.page.getByRole('dialog', { name: `Waiting for ${holder.name}` }) + const confirming = holder.page.getByRole('dialog', { name: `Add ${adder.name}?` }) + await expect(waiting).toBeVisible() + const confirm = await confirming.getByTestId('lan-confirm-code').innerText() + await expect(waiting.getByTestId('lan-confirm-code')).toHaveText(confirm) + return { waiting, confirming } +} + +export async function confirmAdd(adder, holder) { + const { waiting, confirming } = await typeCode(adder, holder) + await confirming.getByRole('button', { name: 'Add', exact: true }).click() + await expect(waiting).toBeHidden() + await expect(holder.page.getByText(`Added ${adder.name}`)).toBeVisible() +} + +export async function addPeer(adder, holder) { + const settings = await openSettingsPage(adder.page, 'Network') + const row = settings.locator('.person', { hasText: holder.name }) + await expect(row).toBeVisible({ timeout: 20_000 }) + await row.getByRole('button', { name: 'Add' }).click() + await confirmAdd(adder, holder) await expect(row.getByText('Trusted')).toBeVisible() - const asked = holder.page.getByRole('dialog', { name: `${adder.name} added you` }) - const addedBack = holder.page.getByText(`${adder.name} added you back`) - await expect(asked.or(addedBack)).toBeVisible() - if (await asked.isVisible()) { - await asked.locator('.dialog-actions').getByRole('button', { name: 'Not now' }).click() - } await closeSettings(adder.page) } @@ -46,7 +57,6 @@ export async function pairBoth() { const ana = await startPeer('Ana') const ben = await startPeer('Ben') await addPeer(ben, ana) - await addPeer(ana, ben) return { ana, ben } } diff --git a/e2e/share.spec.mjs b/e2e/share.spec.mjs index 669215be..6a6061be 100644 --- a/e2e/share.spec.mjs +++ b/e2e/share.spec.mjs @@ -11,6 +11,8 @@ import { test, expect } from './fixtures.mjs' // process for this install's fingerprint, which creates its keypair in // safeStorage — a path jsdom can't reach. test('sharing with no trusted keys walks through first-time key setup', async ({ page }) => { + // Parallel workers share the network; anyone on it would be listed as Nearby instead. + await page.evaluate(() => window.api.lanUpdate({ enabled: false })) await page.getByRole('button', { name: 'Paste mode' }).click() await page.getByPlaceholder('Paste or type the original text').fill('before') await page.getByPlaceholder('Paste or type the changed text').fill('after') @@ -22,7 +24,7 @@ test('sharing with no trusted keys walks through first-time key setup', async ({ await expect(save).toBeVisible() await save.getByRole('button', { name: 'Next: choose recipient' }).click() - // Step 2: no trusted keys → the one-time setup, not the recipient picker. + // Step 2: no trusted keys and no one nearby → the one-time setup, not the recipient picker. const setup = page.getByRole('dialog', { name: 'Share diff — one-time setup' }) await expect(setup).toBeVisible() // Exact: each step's heading text is a substring of its action button's label diff --git a/scripts/theme-sweep.mjs b/scripts/theme-sweep.mjs index 1404be6c..86a81c51 100644 --- a/scripts/theme-sweep.mjs +++ b/scripts/theme-sweep.mjs @@ -633,7 +633,59 @@ async function seedClaudeInbox(page, userDataDir) { claudeInboxSeeded = true } +async function patchLan(page, patch) { + await page.evaluate((p) => { + const pinia = document.querySelector('#app').__vue_app__.config.globalProperties.$pinia + Object.assign(pinia._s.get('lan'), p) + }, patch) +} + +const NEARBY_PEERS = [ + { fp: 'b'.repeat(64), name: 'Ben Okafor', trusted: false, version: 2 }, + { fp: 'c'.repeat(64), name: 'Chen Liu', trusted: false, version: 1 } +] + const SURFACES = [ + { + name: 'lan-confirm', + open: async (page) => { + const pairing = { id: 'x', role: 'holder', stage: 'confirm', name: 'Ana', confirm: '4F7K' } + await patchLan(page, { pairing: { ...pairing, expiresAt: Date.now() + 100_000 } }) + await page.getByTestId('lan-confirm-code').waitFor() + }, + close: async (page) => { + await patchLan(page, { pairing: null }) + await page.getByTestId('lan-confirm-code').waitFor({ state: 'detached' }) + }, + probes: { + 'confirm code': ['[data-testid="lan-confirm-code"] .code', TEXT], + note: ['.show-code .dialog-note', TEXT] + } + }, + { + name: 'share-nearby', + open: async (page) => { + await page.getByRole('button', { name: 'Paste mode' }).click() + await page.getByPlaceholder('Paste or type the original text').fill('a\n') + await page.getByPlaceholder('Paste or type the changed text').fill('b\n') + await page.getByRole('button', { name: 'Compare', exact: true }).click() + await page.getByRole('button', { name: 'Share', exact: true }).click() + const save = page.getByRole('dialog', { name: 'Share diff — step 1 of 2: save it' }) + await save.getByRole('button', { name: 'Next: choose recipient' }).click() + await patchLan(page, { enabled: true, online: true, peers: NEARBY_PEERS }) + await page.getByTestId('share-nearby').waitFor() + }, + close: async (page) => { + await page.keyboard.press('Escape') + await page.getByTestId('share-nearby').waitFor({ state: 'detached' }) + await clearComparison(page) + }, + probes: { + heading: ['.nearby-head', TEXT], + name: ['.nearby-row:not(.off) .rc-name', TEXT], + 'needs update': ['.nearby-row.off .rc-net', DIM] + } + }, { name: 'settings-network', open: async (page) => { diff --git a/specs/2026-11-18-lan-add-from-share/plan.md b/specs/2026-11-18-lan-add-from-share/plan.md new file mode 100644 index 00000000..c937a32a --- /dev/null +++ b/specs/2026-11-18-lan-add-from-share/plan.md @@ -0,0 +1,88 @@ +# Add nearby people from the Share dialog; one mutual add + +| | | +| ------------------ | --------------------------------------------------- | +| **Status** | in-progress (Approved design signed off 2026-11-18) | +| **Issue** | #262 | +| **Branch** | `feat/lan-add-from-share` | +| **Started** | 2026-11-18 | +| **Token baseline** | 2026-11-17T22:49:48Z | + +## Problem + +The Share dialog lists only people you have already added. Adding someone means +leaving the share for Settings ▸ Network, and adding is one-way: the other side +has to Add back with a second code exchange before either can send. + +## Design + +Canvas: https://claude.ai/artifact/XvWgSvNfZ1WEnssqab125D — its **Approved +design** page is the reference. Every board is the live app, drawn by +`design/render/262-lan-add-share.render.mjs`, in light and dark. + +| board | shows | +| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| Share — A | Nearby people listed under your people in the Share list, each with Add; an older version greyed with "Needs update" | +| Share — nobody added yet | the picker with only Nearby, instead of the one-time setup screen | +| 1 · You type their code | today's Add dialog, opened over Share | +| 2 · Waiting for their confirm | "Waiting for {name}", the confirm code their screen should show, Cancel | +| 3 · Back in Share, ticked | the new person in your people, ticked; "Added {name}" | +| Their 1 · code / 2 · confirm / 3 · added | today's code screen; "Add {name}?" with the same confirm code, Decline / Add; then only the notice | +| Wrong code / They declined / Ran out of time | nothing stored on either side | +| Settings ▸ Network | the same flow; "Needs update" | + +## Protocol + +1. Unchanged up to the code: add-request (commit), add-reply, add-reveal, the + holder shows the pairing code, the adder types it. +2. Correct code: the adder sends `add-result: matched` and **stores nothing**. + Both sides derive a 4-character confirm code from the pairing code + (`confirmCode`). The adder shows it ("Waiting for {name}"); the holder shows + it with Decline / Add. +3. Holder **Add**: stores the adder's key, sends `add-result: accepted`. The + adder stores the holder's key on `accepted`. Both: "Added {name}". +4. Holder **Decline**: sends `declined`; nothing is stored anywhere. Expiry or + cancel at any point: the same. + +Why the confirm step is sound: a key swapped in the middle gives the two sides +different pairing codes, so the adder's typed code fails and no confirm code is +shown on the adder's screen; the holder's confirm code then has nothing to match. + +Announcements carry `v=2`; a `v=1` peer is listed with Add disabled and "Needs +update". There is no mixed flow. + +## Decisions + +| date | decision | why | rejected | +| ---------- | ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- | --------------------------------------- | +| 2026-11-18 | nearby people are added from inside the Share dialog | adding meant leaving the share | Settings only | +| 2026-11-18 | adder types the code, holder confirms against a short code both screens show; both keys stored at once | one exchange, no Add back, MITM-safe | Add back; a bare "Add Ana too?" | +| 2026-11-18 | one flow everywhere, Settings too | two behaviours to learn | Share only | +| 2026-11-18 | after adding from Share, the person is ticked and the dialog stays | nothing sent without the user seeing it | send at once; leave unticked | +| 2026-11-18 | declined or expired after a correct code stores nothing on either side | no half-added state | keep the holder's key | +| 2026-11-18 | older peers shown with Add disabled, "Needs update" | no mixed flow | fall back; hide them | +| 2026-11-18 | Share list layout A (Nearby under your people) | who is around, without a click | B, behind one button | +| 2026-11-18 | the search field filters Nearby too | typing a name finds them wherever they are listed | Nearby always unfiltered | +| 2026-11-18 | only the adder's Share dialog ticks the new person; the holder's only refreshes | a tick nobody made could seal for someone unintended | tick on both sides | +| 2026-11-18 | the protocol version lives in `src/shared/lanProtocol.js` | main announces it, the renderer compares against it | a copy on each side | +| 2026-11-18 | the one-time setup shows only when nobody is nearby; `share.spec` turns sharing off to reach it | the approved nobody-added board replaces it while someone is around, and parallel workers share the network | keep setup whenever no keys are trusted | + +## Steps + +- [x] 1. `confirmCode` in pairingCode.js, unit-tested. +- [x] 2. pairing.js: confirm stage on both sides, `confirm(id, accept)`, accepted/declined results; storing only on accept. Unit tests first. +- [x] 3. Frames: `add-result` gains accepted/declined. Discovery: announce `v=2`, accept `v=1` as needing an update; peers carry `version`. +- [x] 4. IPC + preload: `lan:confirm`. +- [x] 5. Renderer: ConfirmCodeDialog (waiting / confirm), declined result, "Added {name}" for both roles; Add back removed. +- [x] 6. Share dialog: Nearby group (A), Add from inside it, tick the new person; nobody-added state. +- [x] 7. Settings ▸ Network: "Needs update". +- [x] 8. e2e: mutual add in one exchange, decline stores nothing, add from Share ticks the person; helpers updated. +- [x] 9. Docs: features, security (the confirm step), glossary. +- [x] 10. `npm run check`, full `make e2e`, PR. + +## Validation + +- `npm run check`: exit 0. 365 files, 4998 tests passed (2 skipped); coverage 95.68 / 89.08 / 96.47 / 96.78; lint, styles, themes, structure, i18n (1624 keys, all used), rawtext clean. +- `make e2e`: 802 passed, 4 skipped, 1 failed (`share.spec` saw other workers' apps as Nearby). Fixed by turning sharing off in that spec; `share`, `lan-pairing` and `lan-send` then 12/12 with two workers. +- Red check: with the refresh-and-tick watcher disabled, "someone nearby is added from the Share dialog, ticked, and the dialog stays" fails at `toBeChecked`; restored, it passes. +- Theme sweep (`SWEEP_ONLY=lan-confirm,share-nearby,settings-network`): 160 measurements across 20 themes, all above floor. Two surfaces added: `lan-confirm`, `share-nearby`. diff --git a/src/main/lan/dnsSd.js b/src/main/lan/dnsSd.js index 288f7f33..7484fc21 100644 --- a/src/main/lan/dnsSd.js +++ b/src/main/lan/dnsSd.js @@ -1,8 +1,10 @@ // In-repo rather than multicast-dns / bonjour-service: one service is a small subset, and rule 2 stays at zero. import { cleanPeerName } from './peerName' +import { LAN_PROTOCOL_VERSION } from '../../shared/lanProtocol' export const SERVICE = '_diffbro._tcp.local' export const ANNOUNCE_TTL = 120 +const KNOWN_VERSIONS = ['1', '2'] const TYPE = { PTR: 12, TXT: 16, SRV: 33 } const CLASS_IN = 1 @@ -69,7 +71,7 @@ const IPV4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/ // replaces the packet's source with its own address, which has nothing listening. export function encodeAnnouncement({ fp, name, port, ttl = ANNOUNCE_TTL, addr }) { const instance = `${fp}.${SERVICE}` - const fields = ['v=1', `fp=${fp}`, `name=${fitName(name)}`, `port=${port}`] + const fields = [`v=${LAN_PROTOCOL_VERSION}`, `fp=${fp}`, `name=${fitName(name)}`, `port=${port}`] if (IPV4.test(addr ?? '')) fields.push(`addr=${addr}`) const txt = txtData(fields) const srv = Buffer.concat([u16(0), u16(0), u16(port), encodeName(`${fp}.local`)]) @@ -182,10 +184,11 @@ function txtEntries(rec) { function peerFromTxt(txt, ttl) { const port = Number(txt.port) + const version = KNOWN_VERSIONS.indexOf(txt.v) + 1 const ok = - txt.v === '1' && FP.test(txt.fp ?? '') && Number.isInteger(port) && port > 0 && port < 65536 + version > 0 && FP.test(txt.fp ?? '') && Number.isInteger(port) && port > 0 && port < 65536 if (!ok || typeof txt.name !== 'string') return null - const peer = { fp: txt.fp, name: cleanPeerName(txt.name, NAME_CHARS), port, version: 1, ttl } + const peer = { fp: txt.fp, name: cleanPeerName(txt.name, NAME_CHARS), port, version, ttl } return IPV4.test(txt.addr ?? '') ? { ...peer, addr: txt.addr } : peer } diff --git a/src/main/lan/frames.js b/src/main/lan/frames.js index 12c9470d..3f5b1741 100644 --- a/src/main/lan/frames.js +++ b/src/main/lan/frames.js @@ -10,7 +10,10 @@ const SHAPES = { 'add-request': { key: isKey, name: (v) => isText(v, 64), commit: (v) => B64_32.test(v) }, 'add-reply': { key: isKey, name: (v) => isText(v, 64), nonce: (v) => B64_32.test(v) }, 'add-reveal': { nonce: (v) => B64_32.test(v) }, - 'add-result': { result: (v) => ['matched', 'mismatched', 'cancelled', 'expired'].includes(v) }, + 'add-result': { + result: (v) => + ['matched', 'mismatched', 'cancelled', 'expired', 'accepted', 'declined'].includes(v) + }, item: { fp: (v) => FP.test(v) }, 'item-ack': { ok: (v) => typeof v === 'boolean', diff --git a/src/main/lan/pairing.js b/src/main/lan/pairing.js index 136f1b45..9f2b5902 100644 --- a/src/main/lan/pairing.js +++ b/src/main/lan/pairing.js @@ -1,5 +1,12 @@ import { randomUUID } from 'crypto' -import { codesMatch, commitmentOf, isRevealValid, newNonce, pairingCode } from './pairingCode' +import { + codesMatch, + commitmentOf, + confirmCode, + isRevealValid, + newNonce, + pairingCode +} from './pairingCode' import { cleanPeerName } from './peerName' export const PAIRING_MS = 120_000 @@ -8,11 +15,12 @@ export const REVEAL_MS = 10_000 const NAME_CHARS = 64 const RESULT_STAGE = { - matched: 'added-you', mismatched: 'mismatch', cancelled: 'cancelled', - expired: 'expired' + expired: 'expired', + declined: 'declined' } +const CONFIRMING = new Set(['confirming', 'confirm']) const view = (s) => ({ id: s.id, @@ -21,7 +29,8 @@ const view = (s) => ({ fp: s.peerFp, name: s.name, expiresAt: s.expiresAt, - ...(s.role === 'holder' && s.stage === 'show-code' ? { code: s.code } : {}) + ...(s.role === 'holder' && s.stage === 'show-code' ? { code: s.code } : {}), + ...(CONFIRMING.has(s.stage) ? { confirm: s.confirm } : {}) }) const short = (fp) => fp.slice(0, 8) @@ -63,9 +72,22 @@ function parsedOrNull(ctx, text) { } } +// Nothing is stored until the holder confirms: a declined or expired add leaves both sides as they were. +function onAdderResult(ctx, s, result) { + if (result === 'accepted' && s.stage === 'confirming') { + // The holder closes right after accepting; that close must not win over the store. + s.storing = true + return ctx.storeKey(s.holderKey, s.peerFp, s.name).then(() => finish(ctx, s, 'added')) + } + finish( + ctx, + s, + RESULT_STAGE[result] && result !== 'mismatched' ? RESULT_STAGE[result] : 'cancelled' + ) +} + function onAdderFrame(ctx, s, { header }) { - if (header.type === 'add-result' && RESULT_STAGE[header.result]) - return finish(ctx, s, header.result === 'expired' ? 'expired' : 'cancelled') + if (header.type === 'add-result') return onAdderResult(ctx, s, header.result) const parsed = header.type === 'add-reply' && parsedOrNull(ctx, header.key) if (s.stage !== 'connecting' || !parsed || parsed.fp !== s.peerFp) { note( @@ -92,6 +114,7 @@ async function add(ctx, peerFp, name) { s.conn = await ctx.connect(peerFp, { onFrame: (frame) => onAdderFrame(ctx, s, frame), onClose: () => { + if (s.storing) return if (s.stage === 'connecting') note(ctx, `add ${short(peerFp)}: closed before the code step`) finish(ctx, s, 'connection-lost') } @@ -115,9 +138,13 @@ async function submitCode(ctx, id, code) { const s = ctx.sessions.get(id) if (!s || s.role !== 'adder' || s.stage !== 'enter-code') return { error: 'no-request' } const matched = codesMatch(s.expected, code) - if (matched) await ctx.storeKey(s.holderKey, s.peerFp, s.name) s.conn.send({ type: 'add-result', result: matched ? 'matched' : 'mismatched' }) - finish(ctx, s, matched ? 'added' : 'mismatch') + if (!matched) { + finish(ctx, s, 'mismatch') + return { ok: true, matched } + } + Object.assign(s, { stage: 'confirming', confirm: confirmCode(s.expected) }) + ctx.emit(view(s)) return { ok: true, matched } } @@ -149,6 +176,7 @@ function onRequest(ctx, { header }, conn) { role: 'holder', conn, peerFp: parsed.fp, + adderKey: parsed.key, name: cleanPeerName(header.name, NAME_CHARS), commit: header.commit, nonce: newNonce(), @@ -175,14 +203,22 @@ function onReveal(ctx, { header }, conn) { ctx.emit(view(s)) } -// Asking someone you already added to add you back is what made adding each other loop. -async function onResult(ctx, { header }, conn) { +function onResult(ctx, { header }, conn) { const s = ctx.byConn.get(conn) if (!s || s.role !== 'holder') return conn.destroy() - // The adder closes right after sending this; the close must not win the trust lookup. - s.resulting = true - const isBack = header.result === 'matched' && (await ctx.isTrusted?.(s.peerFp)) - finish(ctx, s, isBack ? 'added-back' : RESULT_STAGE[header.result]) + if (header.result !== 'matched' || s.stage !== 'show-code') + return finish(ctx, s, RESULT_STAGE[header.result] ?? 'cancelled') + Object.assign(s, { stage: 'confirm', confirm: confirmCode(s.code) }) + ctx.emit(view(s)) +} + +async function confirm(ctx, id, accept) { + const s = ctx.sessions.get(id) + if (!s || s.role !== 'holder' || s.stage !== 'confirm') return { error: 'no-request' } + if (accept) await ctx.storeKey(s.adderKey, s.peerFp, s.name) + s.conn.send({ type: 'add-result', result: accept ? 'accepted' : 'declined' }) + finish(ctx, s, accept ? 'added' : 'declined', { silent: !accept }) + return { ok: true } } export function createPairing(deps) { @@ -200,9 +236,10 @@ export function createPairing(deps) { onRequest: (frame, conn) => onRequest(ctx, frame, conn), onReveal: (frame, conn) => onReveal(ctx, frame, conn), onResult: (frame, conn) => onResult(ctx, frame, conn), + confirm: (id, accept) => confirm(ctx, id, accept), onClosed: (conn) => { const s = ctx.byConn.get(conn) - if (s && !s.resulting) finish(ctx, s, 'connection-lost') + if (s) finish(ctx, s, 'connection-lost') }, cancelAll: () => [...ctx.sessions.values()].forEach((s) => finish(ctx, s, 'connection-lost')) } diff --git a/src/main/lan/pairingCode.js b/src/main/lan/pairingCode.js index c2e9cbc5..8530bfaf 100644 --- a/src/main/lan/pairingCode.js +++ b/src/main/lan/pairingCode.js @@ -4,6 +4,7 @@ import { CODE_ALPHABET, CODE_LENGTH, normalizeCode } from '../../shared/pairingC export { CODE_ALPHABET, CODE_LENGTH, formatCode, normalizeCode } from '../../shared/pairingCodeText' export const NONCE_BYTES = 32 +const CONFIRM_LENGTH = 4 const sha256 = (...parts) => { const hash = createHash('sha256') @@ -30,17 +31,24 @@ export function isRevealValid(commit, nonce) { return isSameBytes(Buffer.from(commitmentOf(nonce)), Buffer.from(commit)) } -export function pairingCode({ holderFp, adderFp, holderNonce, adderNonce }) { - let value = BigInt(`0x${sha256(holderFp, adderFp, holderNonce, adderNonce).toString('hex')}`) +function encode(digest, length) { + let value = BigInt(`0x${digest.toString('hex')}`) const base = BigInt(CODE_ALPHABET.length) let code = '' - for (let i = 0; i < CODE_LENGTH; i++) { + for (let i = 0; i < length; i++) { code += CODE_ALPHABET[Number(value % base)] value /= base } return code } +export const pairingCode = ({ holderFp, adderFp, holderNonce, adderNonce }) => + encode(sha256(holderFp, adderFp, holderNonce, adderNonce), CODE_LENGTH) + +// Both screens show this after a correct code; the holder adds only when the two match. +export const confirmCode = (code) => + encode(sha256('diffbro-confirm/1', normalizeCode(code) ?? ''), CONFIRM_LENGTH) + export function codesMatch(expected, typed) { const a = normalizeCode(expected) const b = normalizeCode(typed) diff --git a/src/main/lan/pairingIpc.js b/src/main/lan/pairingIpc.js index 0794eee6..0f8341f0 100644 --- a/src/main/lan/pairingIpc.js +++ b/src/main/lan/pairingIpc.js @@ -6,7 +6,6 @@ import { connectTo } from './server' import { pairingKeyText, parsePairingKey } from '../keyText' import { checkedTrustedName, storeTrusted } from '../trustedKeys' import { appendLog } from '../logger' -import { readTrusted } from '../trustedKeys' const FP = /^[0-9a-f]{32}$/ let pairing = null @@ -36,7 +35,6 @@ export function setUpPairing({ lan, identity, onTrustChanged }) { return endpoint ? connectTo(endpoint, handlers) : Promise.reject(new Error('gone')) }, parseKey: parsePairingKey, - isTrusted: async (fp) => (await readTrusted()).some((t) => t.fingerprint === fp), storeKey: async (key, fp, name) => { await storeTrusted(key, fp, await labelFor(fp, name)) onTrustChanged() @@ -68,6 +66,11 @@ export function registerPairingIpc({ nameOf }) { ipcMain.handle('lan:cancel', (_e, id) => pairing && typeof id === 'string' ? pairing.cancel(id) : { error: 'no-request' } ) + ipcMain.handle('lan:confirm', (_e, id, accept) => + pairing && typeof id === 'string' + ? pairing.confirm(id, accept === true) + : { error: 'no-request' } + ) ipcMain.handle('lan:pasteCode', () => { const code = normalizeCode(clipboard.readText()) return code ? { code } : { error: 'no-code' } diff --git a/src/main/lan/peers.js b/src/main/lan/peers.js index 408a587e..b8bbf22d 100644 --- a/src/main/lan/peers.js +++ b/src/main/lan/peers.js @@ -2,7 +2,8 @@ export const MAX_PEERS = 256 export const MAX_PER_ADDRESS = 16 const TTL_CAP_S = 120 -const sameEntry = (a, b) => a && a.name === b.name && a.address === b.address && a.port === b.port +const sameEntry = (a, b) => + a && a.name === b.name && a.address === b.address && a.port === b.port && a.version === b.version function hasRoomFor(peers, address) { if (peers.size >= MAX_PEERS) return false @@ -14,14 +15,21 @@ function hasRoomFor(peers, address) { export function createPeerTable({ self = null } = {}) { const peers = new Map() return { - saw({ fp, name, port, address, ttl }, now) { + saw({ fp, name, port, address, ttl, version }, now) { if (fp === self) return false const current = peers.get(fp) // A live entry keeps its address: anyone can announce someone else's fingerprint. if (current && current.expiresAt > now && current.address !== address) return false if (ttl === 0) return peers.delete(fp) if (!current && !hasRoomFor(peers, address)) return false - const next = { fp, name, port, address, expiresAt: now + Math.min(ttl, TTL_CAP_S) * 1000 } + const next = { + fp, + name, + port, + address, + version, + expiresAt: now + Math.min(ttl, TTL_CAP_S) * 1000 + } const changed = !sameEntry(peers.get(fp), next) peers.set(fp, next) return changed @@ -37,7 +45,7 @@ export function createPeerTable({ self = null } = {}) { }, list() { return [...peers.values()] - .map(({ fp, name }) => ({ fp, name })) + .map(({ fp, name, version }) => ({ fp, name, version })) .sort((a, b) => a.name.localeCompare(b.name)) }, endpointOf(fp) { diff --git a/src/preload/lanApi.js b/src/preload/lanApi.js index 9ebc53eb..bebe9586 100644 --- a/src/preload/lanApi.js +++ b/src/preload/lanApi.js @@ -9,6 +9,7 @@ export const lanApi = (ipcRenderer) => ({ lanAdd: (fp) => ipcRenderer.invoke('lan:add', String(fp)), lanSubmitCode: (id, code) => ipcRenderer.invoke('lan:submitCode', String(id), String(code)), lanCancel: (id) => ipcRenderer.invoke('lan:cancel', String(id)), + lanConfirm: (id, accept) => ipcRenderer.invoke('lan:confirm', String(id), accept === true), lanPasteCode: () => ipcRenderer.invoke('lan:pasteCode'), onLanPairing: (handler) => { ipcRenderer.on('lan:pairing', (_e, view) => handler(view)) diff --git a/src/renderer/src/features/lan/components/ConfirmCodeDialog.vue b/src/renderer/src/features/lan/components/ConfirmCodeDialog.vue new file mode 100644 index 00000000..583fe2f8 --- /dev/null +++ b/src/renderer/src/features/lan/components/ConfirmCodeDialog.vue @@ -0,0 +1,51 @@ + + + + + diff --git a/src/renderer/src/features/lan/components/NetworkSettings.vue b/src/renderer/src/features/lan/components/NetworkSettings.vue index 02f33e9f..2afdb0b5 100644 --- a/src/renderer/src/features/lan/components/NetworkSettings.vue +++ b/src/renderer/src/features/lan/components/NetworkSettings.vue @@ -2,6 +2,7 @@ import { onMounted, ref, watch } from 'vue' import SettingToggle from '../../../components/SettingToggle.vue' import { useLanStore } from '../lanStore' +import { needsUpdate } from '../peerVersion' const lan = useLanStore() const name = ref(lan.name) @@ -72,7 +73,14 @@ function commitName() { > {{ $t('lan.stop.button') }} - diff --git a/src/renderer/src/features/lan/components/PairingDialogs.vue b/src/renderer/src/features/lan/components/PairingDialogs.vue index 9004a8f1..d8ade530 100644 --- a/src/renderer/src/features/lan/components/PairingDialogs.vue +++ b/src/renderer/src/features/lan/components/PairingDialogs.vue @@ -2,6 +2,7 @@ import { computed, onMounted } from 'vue' import AddCodeDialog from './AddCodeDialog.vue' import ShowCodeDialog from './ShowCodeDialog.vue' +import ConfirmCodeDialog from './ConfirmCodeDialog.vue' import PairingResultDialog from './PairingResultDialog.vue' import ItemOfferDialog from './ItemOfferDialog.vue' import StopSharingDialog from './StopSharingDialog.vue' @@ -18,6 +19,7 @@ const isEntering = computed(() => ['connecting', 'enter-code'].includes(stage.va diff --git a/src/renderer/src/features/lan/components/PairingResultDialog.vue b/src/renderer/src/features/lan/components/PairingResultDialog.vue index 42a45576..f4b98672 100644 --- a/src/renderer/src/features/lan/components/PairingResultDialog.vue +++ b/src/renderer/src/features/lan/components/PairingResultDialog.vue @@ -6,9 +6,6 @@ import { useLanStore } from '../lanStore' const lan = useLanStore() const result = computed(() => pairingResult(lan.pairing)) -const primaryKey = computed(() => - result.value.action === 'addBack' ? 'lan.result.addBack' : 'lan.result.tryAgain' -)