Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions e2e/lan-pairing.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,24 @@ test('a key named before names were capped still adds, in both directions', asyn
await stop(ana, ben)
}
})

test('adding back ends it: neither side is asked to add the other again', 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)
} finally {
await stop(ana, ben)
}
})
6 changes: 6 additions & 0 deletions e2e/lan-send.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ test('a snippet sent on the network opens in a tab under the received band', asy
const band = ben.page.getByRole('region', { name: `From ${ana.name}` })
await expect(band).toBeVisible()
await expect(band.getByRole('button', { name: 'Save snippet' })).toBeVisible()
await band.getByRole('button', { name: 'Save snippet' }).click()
const lanTag = ben.page.locator('.snippets-section').getByText('lan', { exact: true })
await expect(lanTag).toBeVisible()
await expect(
ben.page.locator('.snippets-section').getByText(ana.name.toLowerCase(), { exact: true })
).toBeVisible()
} finally {
await stop(ana, ben)
}
Expand Down
8 changes: 6 additions & 2 deletions e2e/lanPeers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,12 @@ export async function addPeer(adder, holder) {
await adding.getByTestId('lan-code-input').fill(code)
await adding.getByRole('button', { name: 'Add', exact: true }).click()
await expect(row.getByText('Trusted')).toBeVisible()
const back = holder.page.getByRole('dialog', { name: `${adder.name} added you` })
await back.locator('.dialog-actions').getByRole('button', { name: 'Not now' }).click()
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)
}

Expand Down
10 changes: 7 additions & 3 deletions src/main/lan/pairing.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,14 @@ function onReveal(ctx, { header }, conn) {
ctx.emit(view(s))
}

function onResult(ctx, { header }, conn) {
// Asking someone you already added to add you back is what made adding each other loop.
async function onResult(ctx, { header }, conn) {
const s = ctx.byConn.get(conn)
if (!s || s.role !== 'holder') return conn.destroy()
finish(ctx, s, RESULT_STAGE[header.result])
// 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])
}

export function createPairing(deps) {
Expand All @@ -198,7 +202,7 @@ export function createPairing(deps) {
onResult: (frame, conn) => onResult(ctx, frame, conn),
onClosed: (conn) => {
const s = ctx.byConn.get(conn)
if (s) finish(ctx, s, 'connection-lost')
if (s && !s.resulting) finish(ctx, s, 'connection-lost')
},
cancelAll: () => [...ctx.sessions.values()].forEach((s) => finish(ctx, s, 'connection-lost'))
}
Expand Down
2 changes: 2 additions & 0 deletions src/main/lan/pairingIpc.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ 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
Expand Down Expand Up @@ -35,6 +36,7 @@ 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()
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/src/composables/useSaveDiffTarget.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function useSaveDiffTarget() {
name: tabs.active?.customTitle || derivedName(),
secure: !tabs.active?.sample,
ttl: DEFAULT_TTL_HOURS,
tags: tabs.active?.sample ? [EXAMPLE_TAG] : []
tags: [...(tabs.active?.suggestedTags ?? []), ...(tabs.active?.sample ? [EXAMPLE_TAG] : [])]
}
}

Expand Down
19 changes: 13 additions & 6 deletions src/renderer/src/features/lan/itemActions.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
import { blankSnapshot } from '../../utils/tabs'
import { cleanTag } from '../../utils/snippetState'
import { useTabsStore } from '../../stores/tabsStore'

const snippetDraft = ({ name, snippet }) => ({
// `lan/<sender>`: the sender nests under lan, and a slash in their name must not nest deeper.
export const receivedTag = (from) => cleanTag(`lan/${String(from ?? '').replace(/\//g, '-')}`)

const snippetDraft = ({ name, snippet }, tags) => ({
id: null,
initialName: name,
initialContent: snippet.content,
initialLanguage: snippet.language ?? 'auto',
initialTags: snippet.tags ?? []
initialTags: [...(snippet.tags ?? []), ...tags]
})

export function openReceivedEntry(entry) {
export function openReceivedEntry(entry, from) {
const tabs = useTabsStore()
return entry.kind === 'snippet'
? tabs.openSnippet(snippetDraft(entry), entry.name)
: tabs.open({ ...blankSnapshot(), ...entry.snapshot }, { name: entry.name })
const tags = from ? [receivedTag(from)] : []
if (entry.kind === 'snippet') return tabs.openSnippet(snippetDraft(entry, tags), entry.name)
const id = tabs.open({ ...blankSnapshot(), ...entry.snapshot }, { name: entry.name })
const tab = tabs.tabs.find((t) => t.id === id)
if (tab) tab.suggestedTags = tags
return id
}

export const arePopupsShown = ({ popups, silencedUntil }, now = Date.now()) =>
Expand Down
7 changes: 4 additions & 3 deletions src/renderer/src/features/lan/lanStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,10 @@ export const useLanStore = defineStore('lan', {
},
showPairing(view) {
if (this.holdRequest(view)) return
if (view?.stage !== 'added') return (this.pairing = view)
const notice = { added: 'lan.add.added', 'added-back': 'lan.add.addedBack' }[view?.stage]
if (!notice) return (this.pairing = view)
this.pairing = null
useDiffStore().showNotice(t('lan.add.added', { name: view.name }))
useDiffStore().showNotice(t(notice, { name: view.name }))
},
async add({ fp, name }) {
this.pairing = { role: 'adder', stage: 'connecting', fp, name }
Expand Down Expand Up @@ -107,7 +108,7 @@ export const useLanStore = defineStore('lan', {
this.bellOpen = false
const res = await window.api.lanOpenItem(id)
if (!res?.ok) return useDiffStore().showNotice(t('lan.items.gone'))
const tabId = openReceivedEntry(res.entry)
const tabId = openReceivedEntry(res.entry, res.from ?? item?.from)
if (tabId)
this.received = {
...this.received,
Expand Down
3 changes: 2 additions & 1 deletion src/shared/i18n/en-XA.json
Original file line number Diff line number Diff line change
Expand Up @@ -2012,7 +2012,8 @@
"noCodeOnClipboard": "[Ţĥé çłĩƥƀōàřđ đōéşń’ţ ĥōłđ à ƥàĩřĩńğ çōđé. ·øé·øé·øé·øé·ø]",
"add": "[Àđđ ·ø]",
"button": "[Àđđ ·ø]",
"added": "[Àđđéđ {name} ·øé·]"
"added": "[Àđđéđ {name} ·øé·]",
"addedBack": "[{name} àđđéđ ŷōū ƀàçķ ·øé·øé·]"
},
"code": {
"title": "[{name} ŵàńţş ţō àđđ ŷōū ·øé·øé·]",
Expand Down
3 changes: 2 additions & 1 deletion src/shared/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2012,7 +2012,8 @@
"noCodeOnClipboard": "The clipboard doesn’t hold a pairing code.",
"add": "Add",
"button": "Add",
"added": "Added {name}"
"added": "Added {name}",
"addedBack": "{name} added you back"
},
"code": {
"title": "{name} wants to add you",
Expand Down
9 changes: 9 additions & 0 deletions tests/main/lan/pairing.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,12 @@ describe('when adding fails, the log says why', () => {
expect(ben.logged.join('\n')).toMatch(/closed before/)
})
})

describe('adding back', () => {
it('tells the holder they were added back when it already trusts the adder, with no new Add back', async () => {
const { ana, ben, started } = await startAdding({ isTrusted: async (fp) => fp === B })
await ben.pairing.submitCode(started.id, ana.last().code)
await flush()
expect(ana.last()).toMatchObject({ stage: 'added-back', name: 'Ben', fp: B })
})
})
7 changes: 7 additions & 0 deletions tests/renderer/composables/useSaveDiffTarget.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ async function openSaved({ ttlHours = 1, tags = [] } = {}) {
}

describe('where a save lands', () => {
it('offers the tags the tab suggests, such as who sent it', () => {
const tabs = useTabsStore()
tabs.init()
tabs.active.suggestedTags = ['lan/ana']
expect(useSaveDiffTarget().initial().tags).toEqual(['lan/ana'])
})

it('offers the tour’s sample with the example tag', () => {
const tabs = useTabsStore()
tabs.init()
Expand Down
28 changes: 26 additions & 2 deletions tests/renderer/features/lan/itemActions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { describe, expect, it, vi } from 'vitest'

const open = vi.fn(() => 'tab-d')
const openSnippet = vi.fn(() => 'tab-s')
const tabs = [{ id: 'tab-d' }]
vi.mock('../../../../src/renderer/src/stores/tabsStore', () => ({
useTabsStore: () => ({ open, openSnippet })
useTabsStore: () => ({ open, openSnippet, tabs })
}))
const { arePopupsShown, openReceivedEntry, withoutId } =
const { arePopupsShown, openReceivedEntry, receivedTag, withoutId } =
await import('../../../../src/renderer/src/features/lan/itemActions')
const { SILENCE_CHOICES, silenceLabelKey } =
await import('../../../../src/renderer/src/features/lan/silenceChoices')
Expand Down Expand Up @@ -47,6 +48,29 @@ describe('opening a received entry', () => {
})
})

describe('tagging what arrived on the network', () => {
it('nests the sender under lan', () => {
expect(receivedTag('Ana Petrauskė')).toBe('lan/ana petrauskė')
})

it('keeps a slash in the name from nesting deeper', () => {
expect(receivedTag('ops/infra laptop')).toBe('lan/ops-infra laptop')
})

it('adds the tag to a snippet beside its own tags', () => {
openReceivedEntry(
{ kind: 'snippet', name: 'n', snippet: { content: '', tags: ['ops'] } },
'Ana'
)
expect(openSnippet.mock.calls.at(-1)[0].initialTags).toEqual(['ops', 'lan/ana'])
})

it('suggests the tag when a diff is saved', () => {
openReceivedEntry({ kind: 'diff', name: 'cfg', snapshot: {} }, 'Ana')
expect(tabs[0].suggestedTags).toEqual(['lan/ana'])
})
})

describe('helpers', () => {
it('shows popups only when on and not silenced', () => {
expect(arePopupsShown({ popups: true, silencedUntil: 0 }, 10)).toBe(true)
Expand Down
Loading