Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(devices): make every key on the account visible, and its history tamper-evident (#606)

0xken154f0a05c163a7
diff --git a/SECURITY.md b/SECURITY.md
index 2de30f170..aeeeba1ab 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -22,9 +22,14 @@ directory.
**Signing in is what makes a device trusted.** Every device signed in to an account publishes its
identity key to the account's device key log, and the account's other devices trust it end to end
with no password. So anyone who can sign in as you — or whoever runs the backend — can add a device.
-This is deliberate, and it is not prevented, only made visible: each device announces a key it has
-not trusted before ("New device: X"), the device list shows every one with a Remove, and devices
-compare the log among themselves so a backend cannot show one device a key the others do not see.
+This is deliberate, and it is not prevented, only made visible: every device announces each key added
+after it joined ("New device: X") and keeps it marked New until you look, says who removed a device,
+and the device list shows every one with a Remove and the full add/remove history. Devices check the
+log against what they already verified and compare it among themselves, so the backend cannot rewrite
+or roll back that history, hide a key from one device, or move a device to another account's list
+without a fresh sign-in there: the list freezes instead, and keys added after a detected split are
+not trusted until someone reviews it. Stopping the backend from adding a device in the first place is
+future work.
**A phone can sign a computer in by scanning its QR.** Approving one hands that computer the account's
terminals, so two mistakes matter: approving a stranger's computer (a QR you were shown), and a
diff --git a/cli/scripts/gen-devhistory-vectors.ts b/cli/scripts/gen-devhistory-vectors.ts
new file mode 100644
index 000000000..e4a24d497
--- /dev/null
+++ b/cli/scripts/gen-devhistory-vectors.ts
@@ -0,0 +1,83 @@
+/**
+ * Regenerates src/lib/e2ee/deviceHistory.vectors.json — the fixture the device history (`devLogHistory`)
+ * and the fork locator (`devLogDivergence`) are held to by the CLI and by both Dart ports. Deterministic:
+ * fixed seeds, Ed25519 signs deterministically. Run: `npx tsx scripts/gen-devhistory-vectors.ts`, then
+ * copy the file to desktop/test/viewer/ and mobile/test/viewer/.
+ */
+import { writeFileSync } from 'fs'
+import { join } from 'path'
+import { ed25519 } from '@noble/curves/ed25519'
+import { applyDevLogEntries, emptyDevLogState, nextDevLogEntry, signDevLogEntry, type DevLogEntry, type DevLogState } from '../src/lib/e2ee/deviceLog.js'
+import { devLogHistory } from '../src/lib/e2ee/deviceHistory.js'
+
+const b64 = (u: Uint8Array): string => Buffer.from(u).toString('base64')
+const seeds = { a: new Uint8Array(32).fill(1), b: new Uint8Array(32).fill(2), c: new Uint8Array(32).fill(3), d: new Uint8Array(32).fill(4) }
+type Who = keyof typeof seeds
+const pubs = Object.fromEntries(Object.entries(seeds).map(([k, s]) => [k, b64(ed25519.getPublicKey(s))])) as Record<Who, string>
+const acct = 'acct-history-1'
+const MID = 'a'.repeat(32)
+
+function chain(steps: Array<[op: 'add' | 'remove', key: Who, signer: Who, label: string, kind: 'machine' | 'viewer', at: number]>): { entries: DevLogEntry[]; state: DevLogState } {
+ let state = emptyDevLogState(acct)
+ const entries: DevLogEntry[] = []
+ for (const [op, key, signer, label, kind, at] of steps) {
+ const e = signDevLogEntry(nextDevLogEntry(state, {
+ op, pub: pubs[key], kind, machineId: kind === 'machine' ? MID : '', label, signer: pubs[signer],
+ }, at), seeds[signer])
+ state = applyDevLogEntries(state, [e]).state
+ entries.push(e)
+ }
+ return { entries, state }
+}
+
+// The remove entries carry labels and kinds of their own choosing ('LIE', viewer): what the history
+// and the notices say must come from the key's add.
+const main = chain([
+ ['add', 'a', 'a', 'mac', 'machine', 10],
+ ['add', 'b', 'b', 'phone', 'viewer', 20],
+ ['add', 'b', 'b', 'pixel', 'viewer', 30],
+ ['add', 'c', 'c', 'ipad', 'viewer', 40],
+ ['remove', 'c', 'a', 'LIE', 'machine', 50],
+ ['remove', 'b', 'b', 'pixel', 'viewer', 60],
+])
+// A log that shares entries 1-2 with `main` and then goes its own way.
+const fork = chain([
+ ['add', 'a', 'a', 'mac', 'machine', 10],
+ ['add', 'b', 'b', 'phone', 'viewer', 20],
+ ['add', 'd', 'd', 'evil', 'viewer', 31],
+ ['add', 'c', 'c', 'ipad', 'viewer', 41],
+])
+
+const row = (r: ReturnType<typeof devLogHistory>[number]) => ({
+ seq: r.seq, op: r.op, label: r.label, kind: r.kind, ...(r.previousLabel !== undefined ? { previousLabel: r.previousLabel } : {}),
+ ...(r.by ? { by: r.by.label } : {}), thisDevice: r.thisDevice, afterJoin: r.afterJoin, pending: r.pending, active: r.active, whileFrozen: r.whileFrozen,
+})
+
+const histCases = [
+ { name: 'the whole log, newest first', self: 'a', joinedSeq: 1, pending: ['b'], seqs: [1, 2, 3, 4, 5, 6], loose: [] as number[] },
+ { name: 'only the recent tail is known (offline)', self: 'a', joinedSeq: 1, pending: [], seqs: [4, 5, 6], loose: [] },
+ { name: 'a removal whose add is outside the known window', self: 'a', joinedSeq: 1, pending: [], seqs: [5, 6], loose: [] },
+ { name: 'a removal applied while frozen', self: 'a', joinedSeq: 1, pending: [], seqs: [1, 2, 3, 4, 6], loose: [5] },
+ { name: 'no joined point known', self: 'b', pending: [], seqs: [1, 2, 3, 4, 5, 6], loose: [] },
+].map((c) => {
+ const pick = (seqs: number[]) => seqs.map((s) => main.entries[s - 1])
+ const rows = devLogHistory(pick(c.seqs), {
+ selfPub: pubs[c.self as Who], ...('joinedSeq' in c ? { joinedSeq: c.joinedSeq } : {}),
+ pending: c.pending.map((k) => pubs[k as Who]), active: main.state.active, loose: pick(c.loose),
+ })
+ return { ...c, rows: rows.map(row) }
+})
+
+// `from`..`to` is the window of `log`'s hashes the peer sends; `tamper` breaks it on purpose.
+const divCases: Array<{ name: string; log: 'main' | 'fork'; from: number; to: number; tamper?: 'gap' | 'head' | 'junk'; expect: number | null }> = [
+ { name: 'the first differing position, the one before it matching', log: 'fork', from: 1, to: 4, expect: 3 },
+ { name: 'a window that starts at the split cannot prove it', log: 'fork', from: 3, to: 4, expect: null },
+ { name: 'the same log has no split', log: 'main', from: 1, to: 4, expect: null },
+ { name: 'a window with a gap is not usable', log: 'fork', from: 1, to: 4, tamper: 'gap', expect: null },
+ { name: 'a window that does not end at the peer head is not usable', log: 'fork', from: 1, to: 4, tamper: 'head', expect: null },
+ { name: 'not a window at all', log: 'fork', from: 1, to: 4, tamper: 'junk', expect: null },
+]
+
+writeFileSync(join(import.meta.dirname, '../src/lib/e2ee/deviceHistory.vectors.json'), `${JSON.stringify({
+ acct, pubs, entries: main.entries, fork: fork.entries, history: histCases, divergence: divCases,
+}, null, 2)}\n`)
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.ts
index 1ab64857e..24907eae1 100644
--- a/cli/src/authCommand.spec.ts
+++ b/cli/src/authCommand.spec.ts
@@ -466,7 +466,8 @@ describe('harness login --json', () => {
expect(await login.next()).toEqual({ type: 'result', status: 'success', email: '[email protected]', fingerprint: expect.stringMatching(FP) })
expect(await login.exit).toBe(0)
const session = JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')) as Record<string, unknown>
- expect(session).toMatchObject({ accessToken: 'tok_qr', method: 'qr' })
+ // A sign-in by hand: a sign-in epoch of its own, which the device key log keeps its marks by.
+ expect(session).toMatchObject({ accessToken: 'tok_qr', method: 'qr', signInEpoch: expect.stringMatching(/^[0-9a-f]{32}@\d+$/) })
expect(calls.map((c) => c.url)).not.toContain('/api/auth/qr/cancel')
}, 30_000)
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index c3cd46ae5..cf8148aae 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -3118,6 +3118,39 @@ describe('machine_meta carries the grid name without clobbering it on rename', (
expect(removed).toBe(0)
await plain.stop()
})
+
+ it('keeps running when the removed key is ANOTHER key under this machine id (an earlier install it waits behind)', async () => {
+ // A reinstall that kept the computer id finds its machine id held by the old install's key
+ // (device_conflict). Removing that key makes the backend send `machine_revoked` to the machine id —
+ // which this daemon now answers for. That removal is what lets this key register, not a sign-out.
+ const socket = new BackendSocket('token')
+ const seen: string[] = []
+ socket.isOwnDeviceKey = (pub) => pub === 'MINE'
+ socket.onDeviceRemoved = (pub) => { seen.push(`removed:${pub}`) }
+ socket.onRevoked = () => { seen.push('revoked') }
+ socket.onDeviceKeysChanged = () => { seen.push('reread') }
+ socket.connect()
+ const ws = wsMock.instances.at(-1)!
+ ws.open()
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_revoked', payload: { reason: 'device_removed', pub: 'OLD_INSTALL' } } })
+ await vi.waitFor(() => expect(seen).toEqual(['reread']))
+ // Still linked: a later frame for its OWN key signs it out as before.
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_revoked', payload: { reason: 'device_removed', pub: 'MINE' } } })
+ await vi.waitFor(() => expect(seen).toEqual(['reread', 'removed:MINE', 'revoked']))
+ await socket.stop()
+
+ // A plain revoke (the machine deleted) still ends the sign-in whatever the key.
+ const plain = new BackendSocket('token')
+ let revoked = 0
+ plain.isOwnDeviceKey = () => false
+ plain.onRevoked = () => { revoked += 1 }
+ plain.connect()
+ const ws2 = wsMock.instances.at(-1)!
+ ws2.open()
+ ws2.message({ t: 'down', connId: '', frame: { type: 'machine_revoked', payload: {} } })
+ await vi.waitFor(() => expect(revoked).toBe(1))
+ await plain.stop()
+ })
})
/** The read-only hardware line for the run-a-harness-compute dialog, answered next to `grid_models_list`. */
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index c934b0c52..fd08dd788 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -801,6 +801,9 @@ export class BackendSocket {
onDeviceKeysChanged: (() => void) | null = null
/** This machine's key was taken out of the account's device key log (`machine_revoked` says so). */
onDeviceRemoved: ((pub: string) => void) | null = null
+ /** Whether [pub] is this machine's own device key. Set, a `machine_revoked` naming another key (an earlier
+ * install under the same machine id) does not sign this one out. Null: every removal signs out. */
+ isOwnDeviceKey: ((pub: string) => boolean) | null = null
/** The link to the backend just came up (each reconnect too). */
onLinkUp: (() => void) | null = null
/** Appends to the device key log waiting for the backend's answer, by requestId. */
@@ -1909,9 +1912,16 @@ export class BackendSocket {
// The machine was deleted/revoked from the web → stop for good (don't reconnect) and let the CLI
// clear the saved token. `closed` blocks the reconnect that would otherwise fire on socket drop.
if (type === 'machine_revoked') {
+ const p = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as { reason?: unknown; pub?: unknown }
+ // Another key under this machine id was removed — an earlier install of this computer that this one
+ // waits behind (`device_conflict`). The frame goes to the machine id, so it reaches this install too:
+ // that removal is what lets this key register, not a sign-out. Re-read the log instead.
+ if (p.reason === 'device_removed' && typeof p.pub === 'string' && this.isOwnDeviceKey && !this.isOwnDeviceKey(p.pub)) {
+ this.onDeviceKeysChanged?.()
+ return
+ }
this.closed = true
// Removed from the account's device key log (not just signed out): the key itself is spent.
- const p = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as { reason?: unknown; pub?: unknown }
if (p.reason === 'device_removed' && typeof p.pub === 'string') {
try { this.onDeviceRemoved?.(p.pub) } catch { /* signing out still happens */ }
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 4dc281b49..88e24ad5a 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -67,7 +67,7 @@ import { ensureTmuxOnPath } from './lib/tmuxOnPath.js'
import { flashCommand } from './lib/flash.js'
import { readOrMintComputerId } from './lib/computerIdentity.js'
import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE } from './lib/loginCallback.js'
-import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, knownSsoClientId, readAuthSession, ssoClientIdFor, writeAuthSession, type AuthSession } from './lib/authSession.js'
+import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, ensureSignInEpoch, knownSsoClientId, newSignInEpoch, readAuthSession, signInOf, ssoClientIdFor, writeAuthSession, type AuthSession } from './lib/authSession.js'
import { LocalPresence, PAIR_HARNESS_DSH, ZooTurnCounter, ZooTurnReporter } from './lib/zooTurns.js'
import { ZooLessonReporter } from './lib/zooLessons.js'
import { DAEMONS_OFF, DAEMONS_OFF_DETAIL, DaemonsSwitch, localKillSwitch, zooPassthrough, type ZooRead } from './lib/daemonsSwitch.js'
@@ -244,7 +244,7 @@ import type { CableAgent } from './cable/cableSession.js'
import { routeVoiceTask, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
import { E2eeStore, identitySpent, peekIdentityPub } from './lib/e2ee/store.js'
-import { confirmsRemoval, deviceRegistration, deviceStatusValue, formatDeviceDetail, formatDeviceList, logOrder, removeConfirmation } from './lib/e2ee/deviceDisplay.js'
+import { confirmsRemoval, deviceRegistration, deviceStatusValue, formatDeviceDetail, formatDeviceHistory, formatDeviceList, logOrder, removeConfirmation } from './lib/e2ee/deviceDisplay.js'
import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'
import { b64e } from './lib/e2ee/core.js'
import { MachinePeerStore } from './lib/e2ee/machinePeers.js'
@@ -514,6 +514,9 @@ every future connect, until you change or clear it:
harness devices show <#|fp> one device in full: its key code and how to check it on that device
harness devices remove <fp> take a device out of the account on every device, by key code (or its
first 4+ characters); a # or a shorter start asks first, --yes skips it
+ harness devices history every device added to or removed from the account, newest first, as this
+ machine verified it (--json for the rows)
+ harness devices dismiss [<#|fp>] mark every new device as seen, or just that one
harness devices rebaseline the device list froze (the backend served one that does not match what
this machine verified): show what changed, --yes to trust it again
(both \`remote-password set\` and \`link connect\` prompt for the password interactively, or read one
@@ -1064,6 +1067,7 @@ async function qrSignInCommand(
computerId: computerId(),
method: 'qr',
updatedAt: Date.now(),
+ signInEpoch: newSignInEpoch(),
})
try {
await resolveComputerMachine()
@@ -1161,6 +1165,7 @@ async function browserSignIn(
// the clients were split signs every sign-in in as its configured one, and names none.
...(knownSsoClientId(exchanged.clientId) ? { clientId: knownSsoClientId(exchanged.clientId) } : {}),
updatedAt: Date.now(),
+ signInEpoch: newSignInEpoch(),
}
writeAuthSession(session)
try {
@@ -4512,9 +4517,19 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const status = r.error === 'NOT_IN_LOG' ? 404 : r.error === 'UNAVAILABLE' ? 503 : 409
return { status, body: { error: r.error, ...(r.detail ? { detail: r.detail } : {}) } }
},
- onDevicesRebaseline: async (confirm) => {
+ onDevicesHistory: async () => {
if (!devLogSyncer) return { status: 503, body: { error: 'UNAVAILABLE' } }
- const r = await devLogSyncer.rebaseline(confirm)
+ return { status: 200, body: { ...(await devLogSyncer.history()) } }
+ },
+ onDevicesDismiss: (body) => {
+ if (!devLogSyncer) return { status: 503, body: { error: 'UNAVAILABLE' } }
+ devLogSyncer.dismiss(body)
+ return { status: 200, body: { ok: true } }
+ },
+ onDevicesRebaseline: async (confirm, head) => {
+ if (!devLogSyncer) return { status: 503, body: { error: 'UNAVAILABLE' } }
+ const r = await devLogSyncer.rebaseline(confirm, head)
+ if (r && 'error' in r) return { status: 409, body: { error: r.error } }
return r ? { status: 200, body: { ...r, applied: confirm } } : { status: 502, body: { error: 'LOG_UNAVAILABLE' } }
},
// Local dashboard (GET /api/status): adapter health + computer fingerprint + local pairings. It
@@ -4652,7 +4667,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// reads the log: keep its pin through a few denials, and nudge it (and us) to read.
expectsTrust: (machineId, pub) => {
const m = devLogSyncer?.list().members.find((x) => x.pub === pub)
- const expected = !!m && m.kind === 'machine' && m.machineId === machineId
+ const expected = !!m && m.kind === 'machine' && m.machineId === machineId && !devLogSyncer?.suspendedKeys().includes(pub)
if (expected) void devLogSyncer?.refresh()
return expected
},
@@ -4669,6 +4684,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
paired: () => backend.pairedPeers(),
request: relayRequester(relayPool, () => readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV),
dropSessions: (machineId) => { relayPool.invalidate(machineId); relayPool.invalidateIsolated(machineId) },
+ suspended: () => new Set(devLogSyncer?.suspendedKeys() ?? []),
reachable: () => {
// Only a list the backend answered says who is offline; otherwise try every member.
const { machines, source } = machineListCache.list()
@@ -4688,11 +4704,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
store: new DeviceLogStore(),
identity: () => { const id = relayIdentityStore.getIdentity(); return { pub: b64e(id.pub), priv: id.priv } },
self: () => ({ machineId: readAuthSession()?.machineId ?? null, label: thisDeviceLabel() }),
+ // Which sign-in by hand this machine is under (minted by `harness login`, never a backend answer —
+ // the machine id is one): the device log can start over only when THIS changes.
+ signIn: () => signInOf(readAuthSession()?.signInEpoch),
fetch: async (since) => {
const r = await proxyBackend('GET', `/api/device-keys?since=${since}`)
const data = r.status === 200 ? r.body.data as Partial<DeviceLogFetched> | undefined : undefined
const head = data?.head as { seq?: unknown; hash?: unknown } | undefined
- if (!data || typeof data.acct !== 'string' || !Array.isArray(data.entries) || typeof head?.seq !== 'number' || typeof head.hash !== 'string') return null
+ if (!data || typeof data.acct !== 'string' || !Array.isArray(data.entries) || typeof head?.seq !== 'number'
+ || !Number.isSafeInteger(head.seq) || head.seq < 0 || typeof head.hash !== 'string') return null
return { acct: data.acct, head: { seq: head.seq, hash: head.hash }, entries: data.entries }
},
append: async (entry) => {
@@ -4705,8 +4725,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
adopt: (members) => groupSyncer?.adoptFromLog(members),
drop: (pub) => { groupSyncer?.remove(pub) },
- knownBefore: (pub) => backend.pairedPeers().some((p) => p.identityPub === pub)
- || relayPeers.list().some((p) => p.pub === pub) || !!groupSyncer?.isMember(pub),
+ // Snapshotted once, when this machine joins the log: what it already trusts then is never news.
+ trustedNow: () => [...new Set([
+ ...backend.pairedPeers().map((p) => p.identityPub),
+ ...relayPeers.list().map((p) => p.pub),
+ ...(groupSyncer?.roster().members.map((m) => m.pub) ?? []),
+ ])],
tombstoned: (pub) => !!groupSyncer?.tombstoned(pub),
blocked: (pub) => !!groupSyncer?.isBlocked(pub),
announce: (m) => {
@@ -4714,6 +4738,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {
console.log(`[devlog] NEW DEVICE on this account: ${m.label || '(no name)'} (${m.kind}) ${fp} — not yours? harness devices remove ${fp}`)
backend.sendLocal({ type: 'device_key_added', payload: { pub: m.pub, label: m.label, kind: m.kind, machineId: m.machineId, at: m.addedAt, fingerprint: fp } })
},
+ removed: (n) => {
+ if (n.selfRemoved) console.log(`[devlog] ${n.label || '(no name)'} signed out of this account (${n.fingerprint})`)
+ else if (n.signerPending) console.log(`[devlog] ⚠ ${n.label || '(no name)'} (${n.fingerprint}) was removed by a NEW device you have not looked at: ${n.signerLabel || 'another device'} (${n.signerFingerprint}) — not yours? harness devices remove ${n.signerFingerprint}`)
+ else console.log(`[devlog] ${n.label || '(no name)'} (${n.fingerprint}) was removed from this account by ${n.signerLabel || 'another device'}`)
+ backend.sendLocal({ type: 'device_key_removed', payload: { ...n } })
+ },
+ conflict: (c) => {
+ backend.sendLocal({ type: 'device_conflict', payload: { pub: c.pub, label: c.label, fingerprint: c.fingerprint, addedAt: c.addedAt, afterJoin: c.afterJoin } })
+ },
+ suspend: (pubs) => groupSyncer?.suspend(pubs),
+ resume: () => groupSyncer?.resume(),
signedOut: () => {
// This machine's key was removed from the account: it is signed out, and comes back — after a
// new `harness login` — with a NEW key, which every other device announces as a new device.
@@ -4731,6 +4766,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.onDeviceRemoved = (pub) => {
if (pub === b64e(relayIdentityStore.getIdentity().pub)) spendIdentity()
}
+ // A removal of another key under this machine id — the earlier install a reinstall waits behind — is
+ // not this machine signed out: the log re-read that follows registers this key (deviceLogSyncer).
+ backend.isOwnDeviceKey = (pub) => pub === b64e(relayIdentityStore.getIdentity().pub)
// A removal the trust group carried in — typically `harness group remove` on a machine that predates
// the log — goes into the log as well, signed by this machine, so a device that only reads the log
// stops trusting that key too. A key the log no longer has is left alone.
@@ -4742,8 +4780,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Every time the link comes up: a sign-in from before the log existed joins it with no one doing
// anything, and one that joined already only reads what it missed while offline.
backend.onLinkUp = () => { void devLogSyncer?.register() }
- // The link may have come up before this line; a second register in flight is harmless.
- void devLogSyncer.register()
+ // The link may have come up before this line; a second register in flight is harmless. A session
+ // from before sign-in epochs gets one first: adopted, so it never starts the device log over.
+ void ensureSignInEpoch().catch(() => null).then(() => devLogSyncer?.register())
setInterval(() => { void devLogSyncer?.refresh() }, 10 * 60_000).unref()
}
// THE PAIR BRAIN (pair/brain.ts, daemons/BRAIN.md): thinks only while a window or `hn` is attached to
@@ -8399,7 +8438,7 @@ async function groupCommand(sub: string | undefined, arg: string | undefined, js
process.exit(1)
}
-/** `harness devices list|show|remove|rebaseline` — the account's device key log, as this machine verified it. */
+/** `harness devices list|show|remove|history|dismiss|rebaseline` — the account's device key log, as this machine verified it. */
async function devicesCommand(sub: string | undefined, arg: string | undefined, flags: string[]): Promise<void> {
const json = flags.includes('--json')
const call = async (method: 'GET' | 'POST', path: string, body?: unknown): Promise<{ status: number; json: Record<string, unknown> }> => {
@@ -8411,8 +8450,18 @@ async function devicesCommand(sub: string | undefined, arg: string | undefined,
process.exit(1)
}
}
- type Row = { pub: string; label: string; kind: string; machineId: string; addedAt: number; fingerprint: string; self: boolean; seq?: number; firstSeen?: number }
- const listing = async (): Promise<{ members: Row[]; frozen: { reason: string } | null; frozenPeers: string[]; lastSeen?: Record<string, number> }> => {
+ /** A route an older running daemon does not have answers 404: it needs restarting onto this version. */
+ const needsNewerDaemon = (status: number): void => {
+ if (status !== 404) return
+ console.error('\n ✗ This needs a newer Harness running here. Restart it: harness stop && harness start\n')
+ process.exit(1)
+ }
+ type Row = { pub: string; label: string; kind: string; machineId: string; addedAt: number; fingerprint: string; self: boolean; seq?: number; firstSeen?: number; pending?: boolean; suspended?: boolean }
+ const listing = async (): Promise<{
+ members: Row[]; frozen: { reason: string } | null; frozenPeers: string[]; lastSeen?: Record<string, number>
+ pending?: string[]; suspended?: string[]; conflict?: { pub: string; label: string; fingerprint: string; addedAt: number; afterJoin: boolean } | null
+ departed?: Array<{ pub: string; label: string; fingerprint: string; removedBy: string; removedByLabel: string; selfRemoved: boolean }>
+ }> => {
const { status, json: out } = await call('GET', '/api/devices')
if (status !== 200) { console.error('\n ✗ The device list is not available (is this machine signed in?).\n'); process.exit(1) }
return out as never
@@ -8428,6 +8477,8 @@ async function devicesCommand(sub: string | undefined, arg: string | undefined,
for (const line of formatDeviceList(out, Date.now(), selfFp ? { label: thisDeviceLabel(), fp: selfFp } : undefined)) console.log(line)
process.exit(0)
}
+ /** A key code or selector as matched: upper case, spaces and separators dropped. */
+ const norm = (v: string): string => v.toUpperCase().replace(/[·\s-]/g, '')
// A device by its number in the list (its place in the log, which `list` prints on each row and
// which only shifts when a device is removed) or by the start of its fingerprint; `show` and
// `remove` resolve it the same way. The number is NOT the display position: that moves with activity.
@@ -8439,7 +8490,6 @@ async function devicesCommand(sub: string | undefined, arg: string | undefined,
// Decided on the selector as matched (spaces and separators dropped), so " 1" is #1 and not the
// key code starting with 1. `key` is what `remove` echoes when it is a number.
const resolve = (arg: string, members: Row[]): { row: Row; byNumber: boolean; key: string } => {
- const norm = (v: string): string => v.toUpperCase().replace(/[·\s-]/g, '')
const key = norm(arg)
// Only spaces and separators: an empty prefix would match every device.
if (key === '') { console.error('Usage: harness devices show|remove <#|fingerprint> (see: harness devices list)'); process.exit(1) }
@@ -8482,17 +8532,60 @@ async function devicesCommand(sub: string | undefined, arg: string | undefined,
console.log(`\n ✓ Removed ${target.label}. Every device stops trusting it; it is signed out.\n`)
process.exit(0)
}
+ if (sub === 'history') {
+ const { status, json: out } = await call('GET', '/api/devices/history')
+ needsNewerDaemon(status)
+ if (status !== 200) { console.error('\n ✗ The device history is not available (is this machine signed in?).\n'); process.exit(1) }
+ if (json) { console.log(JSON.stringify(out)); process.exit(0) }
+ for (const line of formatDeviceHistory(out as never)) console.log(line)
+ process.exit(0)
+ }
+ if (sub === 'dismiss') {
+ let target: { pub: string; label: string } | null = null
+ if (arg) {
+ const out = await listing()
+ // A key that joined and left before anyone looked is no longer in the list: named by its key code.
+ const key = norm(arg)
+ const gone = key.length >= 4 ? (out.departed ?? []).filter((d) => norm(d.fingerprint).startsWith(key)) : []
+ const listed = out.members.some((m) => norm(m.fingerprint).startsWith(key))
+ target = gone.length === 1 && !listed ? gone[0] : resolve(arg, out.members).row
+ }
+ const { status } = await call('POST', '/api/devices/dismiss', target ? { pub: target.pub } : {})
+ needsNewerDaemon(status)
+ if (status !== 200) { console.error(`\n ✗ Could not mark ${target ? 'it' : 'them'} as seen (is this machine signed in?).\n`); process.exit(1) }
+ console.log(target ? `\n ✓ Marked ${target.label || '(no name)'} as seen.\n` : '\n ✓ Marked every device as seen.\n')
+ process.exit(0)
+ }
if (sub === 'rebaseline') {
const confirm = flags.includes('--yes')
- const { status, json: out } = await call('POST', '/api/devices/rebaseline', { confirm })
+ // Always preview first: --yes confirms with the head that was shown, so what gets trusted is what
+ // was listed (a backend that swaps the list in between is refused).
+ // The backend serves another account's list under this sign-in: a review does not switch accounts.
+ const otherAccount = (s: number, body: unknown): boolean => s === 409 && (body as { error?: unknown } | null)?.error === 'OTHER_ACCOUNT'
+ const OTHER_ACCOUNT = '\n ✗ The device list now belongs to a different account than the one you signed in with. Sign in again (harness login) to switch accounts.\n'
+ const { status, json: out } = await call('POST', '/api/devices/rebaseline', { confirm: false })
+ if (otherAccount(status, out)) { console.error(OTHER_ACCOUNT); process.exit(1) }
if (status !== 200) { console.error('\n ✗ Could not read a valid device list from the backend.\n'); process.exit(1) }
- const r = out as { added: Row[]; removed: Row[] }
- if (json) { console.log(JSON.stringify(out)); process.exit(0) }
- console.log('\n Trusting the backend\'s device list again would:')
- for (const m of r.added) console.log(` + add ${m.label || '(no name)'} ${m.kind}`)
- for (const m of r.removed) console.log(` − remove ${m.label || '(no name)'} ${m.kind}`)
- if (!r.added.length && !r.removed.length) console.log(' (change no device)')
- console.log(confirm ? '\n ✓ Done.\n' : '\n Only if every device listed is yours: harness devices rebaseline --yes\n')
+ const r = out as { head?: { seq: number; hash: string }; added: Row[]; removed: Row[] }
+ if (!confirm) {
+ if (json) { console.log(JSON.stringify(out)); process.exit(0) }
+ console.log('\n Trusting the backend\'s device list again would:')
+ for (const m of r.added) console.log(` + add ${m.label || '(no name)'} ${m.kind}`)
+ for (const m of r.removed) console.log(` − remove ${m.label || '(no name)'} ${m.kind}`)
+ if (!r.added.length && !r.removed.length) console.log(' (change no device)')
+ console.log('\n Only if every device listed is yours: harness devices rebaseline --yes\n')
+ process.exit(0)
+ }
+ const done = await call('POST', '/api/devices/rebaseline', { confirm: true, ...(r.head ? { head: r.head } : {}) })
+ if (otherAccount(done.status, done.json)) { console.error(OTHER_ACCOUNT); process.exit(1) }
+ if (done.status === 409) { console.error('\n ✗ The device list changed while you were reviewing it. Run it again.\n'); process.exit(1) }
+ if (done.status !== 200) { console.error('\n ✗ Could not read a valid device list from the backend.\n'); process.exit(1) }
+ if (json) { console.log(JSON.stringify(done.json)); process.exit(0) }
+ console.log('\n Trusting the backend\'s device list again:')
+ for (const m of r.added) console.log(` + added ${m.label || '(no name)'} ${m.kind}`)
+ for (const m of r.removed) console.log(` − removed ${m.label || '(no name)'} ${m.kind}`)
+ if (!r.added.length && !r.removed.length) console.log(' (no device changed)')
+ console.log('\n ✓ Done.\n')
process.exit(0)
}
console.error(`Unknown command: devices ${sub}`)
@@ -8663,12 +8756,16 @@ async function status(): Promise<void> {
// `status` can say "(in your account)" from it for a while; that window is accepted.
// A retired key with none in its place still says something, though: being removed from the
// account is itself what signs a machine out (the daemon clears the session as it spends the key).
- device: deviceStatusValue(
- thisDeviceFingerprint(false),
- session
- ? deviceRegistration(peekIdentityPub(), new DeviceLogStore().read(), identitySpent())
- : !peekIdentityPub() && identitySpent() ? 'removed' : null,
- ) ?? undefined,
+ device: (() => {
+ const devlog = new DeviceLogStore().read()
+ return deviceStatusValue(
+ thisDeviceFingerprint(false),
+ session
+ ? deviceRegistration(peekIdentityPub(), devlog, identitySpent())
+ : !peekIdentityPub() && identitySpent() ? 'removed' : null,
+ devlog.conflict?.fingerprint,
+ ) ?? undefined
+ })(),
// A status command can run with different shell settings from the daemon. Report the daemon's
// connection, not those of this short-lived caller; missing fields on older daemons stay unknown.
connection: {
diff --git a/cli/src/devicesCommand.spec.ts b/cli/src/devicesCommand.spec.ts
index 86f16475b..bf2af27ca 100644
--- a/cli/src/devicesCommand.spec.ts
+++ b/cli/src/devicesCommand.spec.ts
@@ -11,6 +11,9 @@ const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')
const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')
const DAY = 86_400_000
const dirs: string[] = []
+let rebaseConflict = false
+/** The daemon answers OTHER_ACCOUNT: on the preview, or only on the confirm. */
+let rebaseOther: 'no' | 'preview' | 'confirm' = 'no'
const servers: Server[] = []
afterEach(async () => {
@@ -31,8 +34,10 @@ const MEMBERS = [
]
/** A daemon that answers the two device routes `harness devices` calls; records each removal. */
-function fakeDaemon(lastSeen: Record<string, number> = { 'pub-old': now - 3 * DAY }, members: typeof MEMBERS = MEMBERS): Promise<{ port: number; removed: string[] }> {
+function fakeDaemon(lastSeen: Record<string, number> = { 'pub-old': now - 3 * DAY }, members: typeof MEMBERS = MEMBERS, extra: Record<string, unknown> = {}, newRoutes = false): Promise<{ port: number; removed: string[]; dismissed: unknown[]; rebased: Array<{ confirm?: boolean; head?: unknown }> }> {
+ const rebased: Array<{ confirm?: boolean; head?: unknown }> = []
const removed: string[] = []
+ const dismissed: unknown[] = []
return new Promise((resolve) => {
const server = createServer((req, res) => {
let raw = ''
@@ -40,12 +45,26 @@ function fakeDaemon(lastSeen: Record<string, number> = { 'pub-old': now - 3 * DA
req.on('end', () => {
res.setHeader('content-type', 'application/json')
if (req.method === 'GET' && req.url === '/api/devices') {
- res.end(JSON.stringify({ head: null, frozen: null, self: 'pub-self', members, frozenPeers: [], lastSeen }))
+ res.end(JSON.stringify({ head: null, frozen: null, self: 'pub-self', members, frozenPeers: [], lastSeen, ...extra }))
} else if (req.method === 'POST' && req.url === '/api/devices/remove') {
removed.push((JSON.parse(raw) as { pub: string }).pub)
res.end(JSON.stringify({ ok: true }))
+ } else if (newRoutes && req.method === 'GET' && req.url === '/api/devices/history') {
+ res.end(JSON.stringify({ complete: false, frozen: null, rows: [{
+ seq: 3, op: 'added', pub: 'pub-new', kind: 'viewer', machineId: '', label: 'phone', fingerprint: '1111·2222·3333·4444',
+ at: new Date(2026, 9, 1, 14, 5).getTime(), thisDevice: false, afterJoin: true, pending: true, active: true, whileFrozen: false,
+ }] }))
+ } else if (newRoutes && req.method === 'POST' && req.url === '/api/devices/dismiss') {
+ dismissed.push(JSON.parse(raw))
+ res.end(JSON.stringify({ ok: true }))
+ } else if (newRoutes && req.method === 'POST' && req.url === '/api/devices/rebaseline') {
+ const body = JSON.parse(raw) as { confirm?: boolean; head?: unknown }
+ rebased.push(body)
+ if (rebaseOther === 'preview' || (body.confirm && rebaseOther === 'confirm')) { res.statusCode = 409; res.end(JSON.stringify({ error: 'OTHER_ACCOUNT' })); return }
+ if (body.confirm && rebaseConflict) { res.statusCode = 409; res.end(JSON.stringify({ error: 'LOG_CHANGED' })); return }
+ res.end(JSON.stringify({ head: { seq: 7, hash: 'h7' }, added: [{ label: 'phone', kind: 'viewer' }], removed: [], applied: !!body.confirm }))
} else {
- res.writeHead(404)
+ res.statusCode = 404
res.end('{}')
}
})
@@ -53,7 +72,7 @@ function fakeDaemon(lastSeen: Record<string, number> = { 'pub-old': now - 3 * DA
servers.push(server)
server.listen(0, '127.0.0.1', () => {
const address = server.address()
- resolve({ port: typeof address === 'object' && address ? address.port : 0, removed })
+ resolve({ port: typeof address === 'object' && address ? address.port : 0, removed, dismissed, rebased })
})
})
}
@@ -335,4 +354,95 @@ describe('harness devices', () => {
expect(status).not.toBe(0)
expect(daemon.removed).toEqual([])
}, 30_000)
+
+ it('history prints the rows and says when older history needs a connection', async () => {
+ const { port } = await fakeDaemon(undefined, undefined, {}, true)
+ const { status, stdout } = await run(port, ['history'])
+ expect(status).toBe(0)
+ expect(stdout).toContain('Device history, newest first (as this machine verified it):')
+ expect(stdout).toContain(' 3 1 Oct 2026, 14:05 added phone app 1111·2222·3333·4444 new')
+ expect(stdout).toContain('Older history needs a connection.')
+ const asJson = await run(port, ['history', '--json'])
+ expect(JSON.parse(asJson.stdout.trim()).rows).toHaveLength(1)
+ }, 20_000)
+
+ it('history and dismiss against a daemon that predates them print the restart hint and exit 1', async () => {
+ const { port } = await fakeDaemon()
+ for (const args of [['history'], ['dismiss']]) {
+ const r = await run(port, args)
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain('This needs a newer Harness running here. Restart it: harness stop && harness start')
+ }
+ }, 30_000)
+
+ it('rebaseline --yes previews, then confirms with the previewed head', async () => {
+ rebaseConflict = false
+ const d = await fakeDaemon(undefined, MEMBERS, {}, true)
+ const { status, stdout } = await run(d.port, ['rebaseline', '--yes'])
+ expect(status).toBe(0)
+ expect(d.rebased).toEqual([{ confirm: false }, { confirm: true, head: { seq: 7, hash: 'h7' } }])
+ expect(stdout).toContain('+ added')
+ expect(stdout).toContain('✓ Done.')
+ expect(stdout).not.toContain('would')
+ })
+
+ it('rebaseline --yes refuses when the list changed after the preview', async () => {
+ rebaseConflict = true
+ try {
+ const d = await fakeDaemon(undefined, MEMBERS, {}, true)
+ const { status, stderr, stdout } = await run(d.port, ['rebaseline', '--yes'])
+ expect(status).toBe(1)
+ expect(stderr).toContain('The device list changed while you were reviewing it. Run it again.')
+ expect(stdout).not.toContain('Done')
+ } finally { rebaseConflict = false }
+ })
+
+ for (const at of ['preview', 'confirm'] as const) {
+ it(`rebaseline tells to sign in again when the list is another account's (${at})`, async () => {
+ rebaseOther = at
+ try {
+ const d = await fakeDaemon(undefined, MEMBERS, {}, true)
+ const { status, stderr, stdout } = await run(d.port, ['rebaseline', '--yes'])
+ expect(status).toBe(1)
+ expect(stderr).toContain(' ✗ The device list now belongs to a different account than the one you signed in with. Sign in again (harness login) to switch accounts.')
+ expect(stderr).not.toContain('changed while you were reviewing')
+ expect(stdout).not.toContain('Done')
+ expect(stdout).not.toContain('would')
+ expect(d.rebased).toHaveLength(at === 'preview' ? 1 : 2)
+ } finally { rebaseOther = 'no' }
+ })
+ }
+
+ it('dismiss marks everything, or one device, as seen', async () => {
+ const d = await fakeDaemon(undefined, undefined, {}, true)
+ const all = await run(d.port, ['dismiss'])
+ expect(all.stdout).toContain('Marked every device as seen.')
+ const one = await run(d.port, ['dismiss', '3'])
+ expect(one.stdout).toContain('Marked phone as seen.')
+ expect(d.dismissed).toEqual([{}, { pub: 'pub-new' }])
+ }, 30_000)
+
+ it('lists a key that joined and left before you looked, and dismisses it by its key code', async () => {
+ const d = await fakeDaemon(undefined, undefined, {
+ departed: [{ pub: 'pub-gone', label: 'Chrome', kind: 'viewer', machineId: '', fingerprint: '7777·6666·5555·4444', addedAt: now - DAY, removedAt: now, removedBy: 'pub-gone', removedByLabel: '', selfRemoved: true }],
+ }, true)
+ const list = await run(d.port, ['list'])
+ expect(list.stdout).toContain('⚠ Chrome joined and left before you looked — mark it seen: harness devices dismiss 7777·6666·5555·4444')
+ const one = await run(d.port, ['dismiss', '7777·6666'])
+ expect(one.stdout).toContain('Marked Chrome as seen.')
+ expect(d.dismissed).toEqual([{ pub: 'pub-gone' }])
+ }, 30_000)
+
+ it('list flags only what the daemon says is pending, and shows the conflict and suspended lines', async () => {
+ const members = MEMBERS.map((m) => ({ ...m, pending: m.pub === 'pub-old', suspended: m.pub === 'pub-new' }))
+ const { port } = await fakeDaemon(undefined, members as never, {
+ pending: ['pub-old'], suspended: ['pub-new'], conflict: { pub: 'h', label: 'older', fingerprint: '9999·8888', addedAt: now - DAY, afterJoin: false },
+ })
+ const { stdout } = await run(port, ['list'])
+ expect(stdout).toMatch(/old-box.* new$/m)
+ expect(stdout).toMatch(/phone.* suspended$/m)
+ expect(stdout).toContain('This computer is held by another key on your account: older')
+ expect(stdout).toContain('Not trusted here until you review the list: phone')
+ expect(stdout).toContain('harness devices dismiss')
+ }, 20_000)
})
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index f99b54a48..293795607 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -754,3 +754,51 @@ describe('the daemon socket', () => {
rmSync(dir, { recursive: true, force: true })
})
})
+
+describe('the device history and dismiss endpoints', () => {
+ const local = { 'x-adapter-local': '1', 'content-type': 'application/json' }
+
+ it('history needs the local header', async () => {
+ const onDevicesHistory = vi.fn(async () => ({ status: 200, body: { rows: [], complete: true, frozen: null } }))
+ const { base } = await start({ onDevicesHistory })
+ expect((await fetch(`${base}/api/devices/history`)).status).toBe(403)
+ expect(onDevicesHistory).not.toHaveBeenCalled()
+ const ok = await fetch(`${base}/api/devices/history`, { headers: local })
+ expect(ok.status).toBe(200)
+ expect(await ok.json()).toEqual({ rows: [], complete: true, frozen: null })
+ })
+
+ it('dismiss needs the local header, parses the body and refuses bad JSON', async () => {
+ const onDevicesDismiss = vi.fn(() => ({ status: 200, body: { ok: true } }))
+ const { base } = await start({ onDevicesDismiss })
+ const post = (body: string, headers: Record<string, string> = local) => fetch(`${base}/api/devices/dismiss`, { method: 'POST', headers, body })
+ expect((await post('{}', { 'content-type': 'application/json' })).status).toBe(403)
+ expect(onDevicesDismiss).not.toHaveBeenCalled()
+ expect((await post('{bad')).status).toBe(400)
+ expect((await post(JSON.stringify({ pub: 5 }))).status).toBe(400)
+ expect((await post(JSON.stringify({ pub: 'k' }))).status).toBe(200)
+ expect(onDevicesDismiss).toHaveBeenLastCalledWith({ pub: 'k' })
+ expect((await post(JSON.stringify({ baseline: true }))).status).toBe(200)
+ expect(onDevicesDismiss).toHaveBeenLastCalledWith({ baseline: true })
+ expect((await post('{}')).status).toBe(200)
+ expect(onDevicesDismiss).toHaveBeenLastCalledWith({})
+ // The keys a window displayed: a list of strings, bounded.
+ expect((await post(JSON.stringify({ pubs: ['a', 'b'] }))).status).toBe(200)
+ expect(onDevicesDismiss).toHaveBeenLastCalledWith({ pubs: ['a', 'b'] })
+ expect((await post(JSON.stringify({ pubs: 'a' }))).status).toBe(400)
+ expect((await post(JSON.stringify({ pubs: ['a', 5] }))).status).toBe(400)
+ expect((await post(JSON.stringify({ pubs: Array.from({ length: 257 }, (_, i) => `k${i}`) }))).status).toBe(400)
+ })
+
+ it('rebaseline passes the previewed head on, and refuses a malformed one', async () => {
+ const onDevicesRebaseline = vi.fn(async () => ({ status: 200, body: {} }))
+ const { base } = await start({ onDevicesRebaseline })
+ const post = (body: unknown) => fetch(`${base}/api/devices/rebaseline`, { method: 'POST', headers: local, body: JSON.stringify(body) })
+ expect((await post({ confirm: true, head: { seq: 3, hash: 'h' } })).status).toBe(200)
+ expect(onDevicesRebaseline).toHaveBeenLastCalledWith(true, { seq: 3, hash: 'h' })
+ expect((await post({ confirm: true })).status).toBe(200)
+ expect(onDevicesRebaseline).toHaveBeenLastCalledWith(true, undefined)
+ expect((await post({ confirm: true, head: { seq: -1, hash: 'h' } })).status).toBe(400)
+ expect((await post({ confirm: true, head: 'x' })).status).toBe(400)
+ })
+})
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 262397f74..2928a960e 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -147,7 +147,11 @@ export interface HookServerHandlers {
* log as this machine verified it (lib/e2ee/deviceLogSyncer.ts). */
onDevicesList?: () => Promise<PairOutcome>
onDevicesRemove?: (pub: string) => Promise<PairOutcome>
- onDevicesRebaseline?: (confirm: boolean) => Promise<PairOutcome>
+ onDevicesRebaseline?: (confirm: boolean, head?: { seq: number; hash: string }) => Promise<PairOutcome>
+ /** `harness devices history` and the window's History — every add and remove, as this machine verified it. */
+ onDevicesHistory?: () => Promise<PairOutcome>
+ /** `harness devices dismiss` and the window's "It's mine" / "Got it" — mark new devices as seen. */
+ onDevicesDismiss?: (body: { pub?: string; pubs?: string[]; baseline?: boolean }) => PairOutcome
/** Local dashboard status snapshot (GET /api/status). */
onStatus?: () => Record<string, unknown> | Promise<Record<string, unknown>>
/** Recent adapter log tail (GET /api/logs). */
@@ -805,9 +809,43 @@ export function startHookServer(
if (req.method === 'POST' && url === '/api/devices/rebaseline') {
if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
if (!handlers.onDevicesRebaseline) { json(503, { error: 'UNAVAILABLE' }); return }
- let body: { confirm?: unknown }
+ let body: { confirm?: unknown; head?: unknown }
try { body = JSON.parse(await readBody(req)) as typeof body } catch { json(400, { error: 'bad json' }); return }
- const out = await handlers.onDevicesRebaseline(body.confirm === true); json(out.status, out.body); return
+ if (!body || typeof body !== 'object') { json(400, { error: 'bad json' }); return }
+ // The head the person was shown in the preview: a confirm only goes ahead on that same list.
+ let head: { seq: number; hash: string } | undefined
+ if (body.head !== undefined) {
+ const h = body.head as { seq?: unknown; hash?: unknown } | null
+ if (!h || typeof h !== 'object' || typeof h.seq !== 'number' || !Number.isSafeInteger(h.seq) || h.seq < 0
+ || typeof h.hash !== 'string' || h.hash.length > 128) { json(400, { error: 'BAD_HEAD' }); return }
+ head = { seq: h.seq, hash: h.hash }
+ }
+ const out = await handlers.onDevicesRebaseline(body.confirm === true, head); json(out.status, out.body); return
+ }
+
+ // `harness devices history` → the log's adds and removes, newest first. Local only: it is the
+ // account's whole device story, and the fetch behind it is a backend call as this machine.
+ if (req.method === 'GET' && url === '/api/devices/history') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onDevicesHistory) { json(503, { error: 'UNAVAILABLE' }); return }
+ const out = await handlers.onDevicesHistory(); json(out.status, out.body); return
+ }
+ // `harness devices dismiss [<fp>]` / "It's mine" / "Got it" → new devices marked as seen here.
+ if (req.method === 'POST' && url === '/api/devices/dismiss') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onDevicesDismiss) { json(503, { error: 'UNAVAILABLE' }); return }
+ let body: { pub?: unknown; pubs?: unknown; baseline?: unknown }
+ try { body = JSON.parse(await readBody(req)) as typeof body } catch { json(400, { error: 'bad json' }); return }
+ if (!body || typeof body !== 'object') { json(400, { error: 'bad json' }); return }
+ if (body.pub !== undefined && (typeof body.pub !== 'string' || !body.pub)) { json(400, { error: 'MISSING_PUB' }); return }
+ // The keys a window displayed, so a key accepted since the window read the list is not cleared unseen.
+ if (body.pubs !== undefined && (!Array.isArray(body.pubs) || body.pubs.length > 256
+ || body.pubs.some((k) => typeof k !== 'string' || !k || k.length > 256))) { json(400, { error: 'BAD_PUBS' }); return }
+ const out = handlers.onDevicesDismiss({
+ ...(typeof body.pub === 'string' ? { pub: body.pub } : {}),
+ ...(Array.isArray(body.pubs) ? { pubs: body.pubs as string[] } : {}),
+ ...(body.baseline === true ? { baseline: true } : {}),
+ }); json(out.status, out.body); return
}
// `harness remote-password status` → whether one is set, and its fingerprint. Read-only, same
diff --git a/cli/src/lib/authSession.spec.ts b/cli/src/lib/authSession.spec.ts
index 2b16b6f7f..edd0cb0ab 100644
--- a/cli/src/lib/authSession.spec.ts
+++ b/cli/src/lib/authSession.spec.ts
@@ -6,12 +6,16 @@ const authDir = await mkdtemp(`${tmpdir()}/harness-auth-session-`)
process.env.HARNESS_AUTH_DIR = authDir
const {
+ ADOPTED_SIGN_IN,
AUTH_SESSION_FILE,
AuthSessionError,
AuthSessionManager,
clearAuthSession,
+ ensureSignInEpoch,
+ newSignInEpoch,
readAuthSession,
releaseHeldAuthLock,
+ signInOf,
writeAuthSession,
} = await import('./authSession.js')
@@ -36,6 +40,42 @@ afterAll(async () => {
await rm(authDir, { recursive: true, force: true })
})
+describe('sign-in epoch', () => {
+ it('rides along every rewrite of the session — a refresh and a new machine id', async () => {
+ const epoch = newSignInEpoch()
+ writeAuthSession({ ...baseSession(), signInEpoch: epoch })
+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({
+ success: true, data: { token: 'refreshed-access', refreshToken: 'refreshed-refresh', expiresIn: 3600 },
+ }))))
+ const manager = new AuthSessionManager('https://api.example.test')
+ await manager.accessToken()
+ manager.updateMachineId('machine-2')
+ expect(readAuthSession()).toMatchObject({ accessToken: 'refreshed-access', machineId: 'machine-2', signInEpoch: epoch })
+ expect(newSignInEpoch()).not.toBe(epoch)
+ })
+
+ it('gives a session from before epochs an adopted one, once, keeping its tokens', async () => {
+ writeAuthSession(baseSession())
+ const epoch = await ensureSignInEpoch()
+ expect(epoch?.startsWith(ADOPTED_SIGN_IN)).toBe(true)
+ expect(readAuthSession()).toMatchObject({ signInEpoch: epoch, refreshToken: 'refresh-1' })
+ expect(await ensureSignInEpoch()).toBe(epoch)
+ clearAuthSession()
+ expect(await ensureSignInEpoch()).toBeNull()
+ })
+
+ it('says when it was made, and whether it was adopted — as the device key log reads it', () => {
+ const epoch = newSignInEpoch(1_234)
+ expect(epoch).toMatch(/^[0-9a-f]{32}@1234$/)
+ expect(signInOf(epoch)).toEqual({ epoch, adopted: false, at: 1_234 })
+ expect(signInOf(`${ADOPTED_SIGN_IN}${epoch}`)).toEqual({ epoch: `${ADOPTED_SIGN_IN}${epoch}`, adopted: true, at: 1_234 })
+ // One from before the time was recorded.
+ expect(signInOf('0123456789abcdef0123456789abcdef')).toMatchObject({ adopted: false, at: null })
+ expect(signInOf(undefined)).toBeNull()
+ expect(signInOf('')).toBeNull()
+ })
+})
+
describe('AuthSessionManager', () => {
it('binds the memory owner to a verified sign-in, preserves it across refresh, and rejects stale responses', async () => {
writeAuthSession(baseSession())
diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.ts
index 064c503bc..206ad8706 100644
--- a/cli/src/lib/authSession.ts
+++ b/cli/src/lib/authSession.ts
@@ -1,7 +1,7 @@
import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'
import { homedir } from 'os'
import { join } from 'path'
-import { createHash } from 'node:crypto'
+import { createHash, randomBytes } from 'node:crypto'
export interface AuthSession {
version: 1
@@ -20,6 +20,9 @@ export interface AuthSession {
updatedAt: number
/** Opaque local knowledge owner, learned from authenticated /auth/me, bound to this sign-in. */
memoryOwner?: { key: string; binding: string }
+ /** Which sign-in by hand this session is: minted here when the person signs in, never anything the
+ * backend sends — the device key log keeps its marks per sign-in (deviceLogSyncer `signIn`). */
+ signInEpoch?: string
}
/**
@@ -71,10 +74,41 @@ function parse(raw: string): AuthSession | null {
...(value.memoryOwner && /^[a-f0-9]{64}$/.test(value.memoryOwner.key)
&& value.memoryOwner.binding === memoryOwnerBinding(value.accessToken, value.autonomousEnv)
? { memoryOwner: value.memoryOwner } : {}),
+ ...(typeof value.signInEpoch === 'string' && value.signInEpoch ? { signInEpoch: value.signInEpoch } : {}),
}
} catch { return null }
}
+/** A new `signInEpoch`, for a session a sign-in by hand just made: random, then `@` and when it was
+ * made (ms) — the device key log lets a sign-in start its file over only shortly after it was made. */
+export const newSignInEpoch = (now = Date.now()): string => `${randomBytes(16).toString('hex')}@${now}`
+
+/** How a `signInEpoch` given to a session from before epochs existed starts: nobody saw that sign-in
+ * being made here, so the device key log may take its file over for it but never starts one over. */
+export const ADOPTED_SIGN_IN = 'adopted:'
+
+/** Give a session from before epochs existed one (`ADOPTED_SIGN_IN`), under the refresh lock so a
+ * rotated refresh token is never written back over. The session's epoch; null when signed out. */
+export async function ensureSignInEpoch(): Promise<string | null> {
+ if (!readAuthSession()) return null
+ return withLock(async () => {
+ const latest = readAuthSession()
+ if (!latest) return null
+ if (latest.signInEpoch) return latest.signInEpoch
+ const signInEpoch = ADOPTED_SIGN_IN + newSignInEpoch()
+ writeAuthSession({ ...latest, signInEpoch })
+ return signInEpoch
+ })
+}
+
+/** A `signInEpoch` as the device key log reads it (deviceLogSyncer `signIn`): whether it was adopted,
+ * and when it was made — null when it does not say (one from before the time was recorded). */
+export function signInOf(epoch: string | undefined | null): { epoch: string; adopted: boolean; at: number | null } | null {
+ if (!epoch) return null
+ const at = /@(\d{1,15})$/.exec(epoch)
+ return { epoch, adopted: epoch.startsWith(ADOPTED_SIGN_IN), at: at ? Number(at[1]) : null }
+}
+
function memoryOwnerBinding(token: string, environment: AuthSession['autonomousEnv']): string {
return createHash('sha256').update(JSON.stringify(['memory-owner-binding-v1', environment, token])).digest('hex')
}
diff --git a/cli/src/lib/e2ee/deviceDisplay.spec.ts b/cli/src/lib/e2ee/deviceDisplay.spec.ts
index d504e2199..55abfc86c 100644
--- a/cli/src/lib/e2ee/deviceDisplay.spec.ts
+++ b/cli/src/lib/e2ee/deviceDisplay.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
- activityPhrase, COMPARE_HINT, deviceRegistration, deviceStatusValue, formatDeviceDetail, formatDeviceList, fullDateTime, isNewDevice,
+ activityPhrase, COMPARE_HINT, deviceRegistration, deviceStatusValue, formatDeviceDetail, formatDeviceHistory, formatDeviceList, shortFingerprint, fullDateTime, isNewDevice,
confirmsRemoval, logOrder, orderDevices, relativeAgo, removeConfirmation, type DeviceRow,
} from './deviceDisplay.js'
@@ -217,3 +217,62 @@ describe('confirmsRemoval', () => {
it.each(['y', 'Y', 'yes', 'YES', ' y ', 'yes\n'])('%j removes', (a) => expect(confirmsRemoval(a)).toBe(true))
it.each(['', 'n', 'no', 'yep', 'sure', 'y y', '\n'])('%j does not', (a) => expect(confirmsRemoval(a)).toBe(false))
})
+
+describe('pending, taken and history display', () => {
+ it('isNewDevice follows pending when the daemon sends it, else the 7-day rule', () => {
+ expect(isNewDevice(row('x', 0, { pending: true, firstSeen: NOW - 30 * D }), NOW)).toBe(true)
+ expect(isNewDevice(row('x', 0, { pending: false, firstSeen: NOW - D }), NOW)).toBe(false)
+ expect(isNewDevice(row('x', 0, { pending: true, self: true }), NOW)).toBe(false)
+ })
+ it('words the taken status and shortens a key code', () => {
+ const f = { state: { active: { h: {} }, removed: [] }, conflict: { pub: 'h' } } as never
+ expect(deviceRegistration('p', f, false)).toBe('taken')
+ expect(deviceStatusValue('AAAA', 'taken', 'E2FB·0DF5·5FD8·E6C7')).toBe('AAAA (not registered — another key holds this computer: E2FB·0DF5…)')
+ expect(shortFingerprint('E2FB·0DF5·5FD8·E6C7')).toBe('E2FB…')
+ })
+ it('lists conflict, suspended and pending lines and the history footer', () => {
+ const lines = formatDeviceList({
+ ...listing(), pending: ['new'], suspended: ['old'],
+ conflict: { label: 'old-install', fingerprint: FP_OLD, addedAt: NOW - D, afterJoin: true },
+ }, NOW).join('\n')
+ expect(lines).toContain("Another key took this computer's place on your account after it joined: old-install · AAAA·BBBB·CCCC·DDDD. If you did not set up")
+ expect(lines).not.toContain('added yesterday')
+ expect(lines).toContain('New since you last looked — mark them seen: harness devices dismiss')
+ expect(lines).toContain('History: harness devices history')
+ const neutral = formatDeviceList({ ...listing(), conflict: { label: 'x', fingerprint: FP_OLD, addedAt: NOW, afterJoin: false } }, NOW).join('\n')
+ expect(neutral).toContain('This computer is held by another key on your account: x')
+ const susp = formatDeviceList({ members: listing().members.map((m) => (m.pub === 'old' ? { ...m, suspended: true } : m)) }, NOW).join('\n')
+ expect(susp).toContain('Not trusted here until you review the list: old-mac')
+ expect(susp).toMatch(/old-mac.* suspended/)
+ })
+ it('lists a new key that joined and left before anyone looked, with how to dismiss it', () => {
+ const gone = { label: 'Chrome', fingerprint: FP_NEW, removedBy: 'x', removedByLabel: '', selfRemoved: true }
+ const lines = formatDeviceList({ ...listing(), pending: ['new'], departed: [
+ gone,
+ { ...gone, label: '', fingerprint: FP_OLD, removedBy: 'old', removedByLabel: 'old-mac', selfRemoved: false },
+ { ...gone, label: 'iPad', removedBy: 'new', removedByLabel: 'Evil', selfRemoved: false },
+ ] }, NOW)
+ expect(lines).toContain(` ⚠ Chrome joined and left before you looked — mark it seen: harness devices dismiss ${FP_NEW}`)
+ expect(lines).toContain(` ⚠ (no name) joined and left before you looked (removed by old-mac) — mark it seen: harness devices dismiss ${FP_OLD}`)
+ expect(lines).toContain(` ⚠ iPad joined and left before you looked (removed by a new device you have not looked at: Evil) — mark it seen: harness devices dismiss ${FP_NEW}`)
+ expect(formatDeviceList(listing(), NOW).join('\n')).not.toContain('joined and left')
+ })
+ it('says nothing about who removed a departed key that nothing removed (a review of the list)', () => {
+ const reviewed = { label: 'Chrome', fingerprint: FP_NEW, removedBy: '', removedByLabel: '', selfRemoved: false }
+ const lines = formatDeviceList({ ...listing(), departed: [reviewed] }, NOW)
+ expect(lines).toContain(` ⚠ Chrome joined and left before you looked — mark it seen: harness devices dismiss ${FP_NEW}`)
+ expect(lines.join('\n')).not.toContain('removed by')
+ })
+ it('formats the history', () => {
+ const r = { seq: 3, op: 'removed' as const, pub: 'p', kind: 'machine' as const, machineId: 'abcdef0123456789', label: 'box', fingerprint: FP_OLD, by: { pub: 'q', label: 'mac', fingerprint: FP_SELF },
+ at: new Date(2026, 9, 1, 14, 5).getTime(), thisDevice: false, afterJoin: true, pending: true, active: false, whileFrozen: true }
+ const lines = formatDeviceHistory({ rows: [r], complete: false })
+ expect(lines).toContain(` 3 1 Oct 2026, 14:05 removed box computer abcdef01 ${FP_OLD} by mac left before you looked (applied while the list was frozen)`)
+ expect(formatDeviceHistory({ rows: [{ ...r, active: true }], complete: true }).join('\n')).toMatch(/by mac new \(applied/)
+ expect(lines).toContain(' Older history needs a connection.')
+ // A signer with no known name is "another device", never an empty or raw-key label.
+ const nameless = formatDeviceHistory({ rows: [{ ...r, by: { pub: 'q', label: '', fingerprint: FP_SELF } }], complete: true }).join('\n')
+ expect(nameless).toContain('by another device (E2FB·0DF5…)')
+ expect(formatDeviceHistory({ rows: [], complete: true })).toContain(' No history yet.')
+ })
+})
diff --git a/cli/src/lib/e2ee/deviceDisplay.ts b/cli/src/lib/e2ee/deviceDisplay.ts
index d059c16db..f83527308 100644
--- a/cli/src/lib/e2ee/deviceDisplay.ts
+++ b/cli/src/lib/e2ee/deviceDisplay.ts
@@ -3,8 +3,9 @@
* `devices list|show` and the `status` row. Pure — the clock is passed in — so the same rules the
* desktop and mobile apps follow (their `relative_time.dart`) are pinned by one spec here.
*/
-import type { DevLogFile } from './deviceLogStore.js'
+import type { DevLogConflict, DevLogDeparted, DevLogFile } from './deviceLogStore.js'
import type { DeviceLogListing } from './deviceLogSyncer.js'
+import type { DevLogHistoryRow } from './deviceHistory.js'
/** The fields of a listing row this module reads. `seq` (log position) and `firstSeen` (when this
* machine first applied the add) are the two a device cannot choose for itself; both optional so a
@@ -13,6 +14,10 @@ export type DeviceRow = Pick<DeviceLogListing['members'][number], 'pub' | 'label
kind: string
seq?: number
firstSeen?: number
+ /** Not yet marked as seen on this machine / not trusted after a fork — only a daemon that has the
+ * joined-point marks sends them; absent, `new` falls back to the 7-day `firstSeen` rule. */
+ pending?: boolean
+ suspended?: boolean
}
const MIN = 60_000
@@ -60,7 +65,8 @@ export function activityPhrase(lastSeen: number | undefined, addedAt: number, no
/** `new` rests on when THIS machine applied the add, never the entry's `at`: the adding device picks
* that itself, and a backdated one would hide exactly the device the flag is for. */
-export function isNewDevice(row: Pick<DeviceRow, 'self' | 'firstSeen'>, now: number): boolean {
+export function isNewDevice(row: Pick<DeviceRow, 'self' | 'firstSeen' | 'pending'>, now: number): boolean {
+ if (row.pending !== undefined) return !row.self && row.pending
return !row.self && row.firstSeen !== undefined && now - row.firstSeen < NEW_DEVICE_MS
}
@@ -101,7 +107,7 @@ export function removeConfirmation(
/** The answer to `remove`'s `[y/N]`: only an explicit yes removes. */
export const confirmsRemoval = (answer: string): boolean => /^y(es)?$/i.test(answer.trim())
-export type DeviceRegistration = 'active' | 'removed' | 'unregistered'
+export type DeviceRegistration = 'active' | 'removed' | 'unregistered' | 'taken'
/** Whether the account's device log holds this machine's key. No key on disk but a retired one means
* this machine was signed out of the account; neither means there is nothing to say. */
@@ -109,24 +115,41 @@ export function deviceRegistration(pub: string | null, file: DevLogFile, spent:
if (!pub) return spent ? 'removed' : null
if (file.state?.active[pub]) return 'active'
if (file.state?.removed.includes(pub)) return 'removed'
+ if (file.conflict && file.state?.active[file.conflict.pub]) return 'taken'
return 'unregistered'
}
-/** The text after `device ` in `harness status`, or null for no row. */
-export function deviceStatusValue(fp: string | null, reg: DeviceRegistration | null): string | null {
+/** The text after `device ` in `harness status`, or null for no row. `holderFp` is the key code of
+ * the key holding this computer's place (`taken`), shortened to its first two groups. */
+export function deviceStatusValue(fp: string | null, reg: DeviceRegistration | null, holderFp?: string): string | null {
if (!reg) return null
+ if (reg === 'taken') {
+ const note = `not registered — another key holds this computer${holderFp ? `: ${shortFingerprint(holderFp, 2)}` : ''}`
+ return fp ? `${fp} (${note})` : `(${note})`
+ }
const note = reg === 'active' ? 'in your account' : reg === 'removed' ? 'removed — run harness login' : 'not registered yet'
return fp ? `${fp} (${note})` : `(${note})`
}
+/** The first `groups` groups of a key code and an ellipsis: enough to tell two keys apart in a sentence. */
+export function shortFingerprint(fp: string, groups = 1): string {
+ return `${fp.split('·').slice(0, groups).join('·')}…`
+}
+
const nameOf = (row: Pick<DeviceRow, 'label'>): string => row.label || '(no name)'
const kindOf = (row: Pick<DeviceRow, 'kind' | 'machineId'>): string => (row.kind === 'machine' ? `computer ${row.machineId.slice(0, 8)}` : 'app')
/** The lines of `harness devices list`: shown in `orderDevices` order, each row keeping its `logOrder`
- * number. `selfFallback` is this machine's own
- * key code for when the log has no row for it yet. */
+ * number. Above the rows, when the listing has them: the key holding this computer's place
+ * (`conflict`, worded by `afterJoin`), keys not trusted here after a fork (`suspended`), new keys
+ * that joined and left before anyone looked (`departed`), and how to mark `pending` ones seen.
+ * `selfFallback` is this machine's own key code for when the log has no row for it yet. */
export function formatDeviceList(
- listing: { members: DeviceRow[]; lastSeen?: Record<string, number> },
+ listing: {
+ members: DeviceRow[]; lastSeen?: Record<string, number>; pending?: string[]; suspended?: string[]
+ conflict?: Pick<DevLogConflict, 'label' | 'fingerprint' | 'addedAt' | 'afterJoin'> | null
+ departed?: Array<Pick<DevLogDeparted, 'label' | 'fingerprint' | 'removedBy' | 'removedByLabel' | 'selfRemoved'>>
+ },
now: number,
selfFallback?: { label: string; fp: string },
): string[] {
@@ -136,13 +159,55 @@ export function formatDeviceList(
const self = rows.find((r) => r.self)
if (self) lines.push(` This machine: ${nameOf(self)} ${self.fingerprint}`, '')
else if (selfFallback) lines.push(` This machine: ${selfFallback.label} ${selfFallback.fp} (not registered yet)`, '')
+ const c = listing.conflict
+ if (c) {
+ // No "added <when>": the holder's `addedAt` is whatever its signer wrote.
+ const who = `${nameOf(c)} · ${c.fingerprint}`
+ lines.push(c.afterJoin
+ ? ` ⚠ Another key took this computer's place on your account after it joined: ${who}. If you did not set up Harness here again, remove that key from another device now.`
+ : ` ⚠ This computer is held by another key on your account: ${who}. If that was an earlier install of this computer, remove it from another device (Your devices) — this computer joins on its own once it is gone.`, '')
+ }
+ const suspended = listing.members.filter((m) => m.suspended || listing.suspended?.includes(m.pub))
+ if (suspended.length) {
+ lines.push(` ⚠ Not trusted here until you review the list: ${suspended.map(nameOf).join(', ')} — added after this computer's and another device's lists split apart. Review it: harness devices rebaseline Yours? harness devices dismiss <key code>`, '')
+ }
+ // A new key that was removed again before anyone looked: gone, but nobody saw it come.
+ // Removed by a key that is itself new here (unlooked at): said so.
+ const unlooked = new Set([...(listing.pending ?? []), ...listing.members.filter((m) => m.pending).map((m) => m.pub)])
+ for (const d of listing.departed ?? []) {
+ const by = d.selfRemoved || !d.removedBy ? '' : ` (removed by ${unlooked.has(d.removedBy) ? 'a new device you have not looked at: ' : ''}${d.removedByLabel || 'another device'})`
+ lines.push(` ⚠ ${nameOf(d)} joined and left before you looked${by} — mark it seen: harness devices dismiss ${d.fingerprint}`)
+ }
+ if (listing.departed?.length) lines.push('')
+ if (listing.members.some((m) => !m.self && (m.pending || listing.pending?.includes(m.pub)))) {
+ lines.push(' New since you last looked — mark them seen: harness devices dismiss', '')
+ }
lines.push(' Devices on this account — each one trusts every other:', '')
rows.forEach((m) => {
- const flag = m.self ? ' (this machine)' : isNewDevice(m, now) ? ' new' : ''
+ const flag = m.self ? ' (this machine)' : m.suspended ? ' suspended' : isNewDevice(m, now) ? ' new' : ''
lines.push(` ${String(numbers.get(m.pub)).padStart(2)}. ${nameOf(m)} ${kindOf(m)} ${m.fingerprint} ${activityPhrase(listing.lastSeen?.[m.pub], m.addedAt, now)}${flag}`)
})
// `remove` takes the key code here, not a number: a code names one device however the list moves.
- lines.push('', ' Details: harness devices show <#|fingerprint> Not yours? harness devices remove <fingerprint>', '')
+ lines.push('', ' Details: harness devices show <#|fingerprint> Not yours? harness devices remove <fingerprint>')
+ lines.push(' History: harness devices history', '')
+ return lines
+}
+
+const OP_WORDS: Record<DevLogHistoryRow['op'], string> = { added: 'added', renamed: 'renamed', removed: 'removed', signedOut: 'signed out' }
+
+/** The lines of `harness devices history`: newest first, with what to say when the log could not be
+ * read in full. A still-unseen key is flagged `new`, or `left before you looked` once it is gone. */
+export function formatDeviceHistory(h: { rows: DevLogHistoryRow[]; complete: boolean }): string[] {
+ const lines = ['', ' Device history, newest first (as this machine verified it):', '']
+ for (const r of h.rows) {
+ const name = r.op === 'renamed' && r.previousLabel !== undefined ? `${r.previousLabel || '(no name)'} → ${nameOf(r)}` : nameOf(r)
+ const by = r.by ? ` by ${r.by.label || `another device (${shortFingerprint(r.by.fingerprint, 2)})`}` : ''
+ lines.push(` ${r.seq} ${fullDateTime(r.at)} ${OP_WORDS[r.op]} ${name} ${kindOf(r)} ${r.fingerprint}${by}`
+ + `${r.pending ? (r.active ? ' new' : ' left before you looked') : ''}${r.thisDevice ? ' (this machine)' : ''}${r.whileFrozen ? ' (applied while the list was frozen)' : ''}`)
+ }
+ if (!h.complete) lines.push('', ' Older history needs a connection.')
+ else if (!h.rows.length) lines.push(' No history yet.')
+ lines.push('')
return lines
}
diff --git a/cli/src/lib/e2ee/deviceHistory.spec.ts b/cli/src/lib/e2ee/deviceHistory.spec.ts
new file mode 100644
index 000000000..af6028113
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceHistory.spec.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { ed25519 } from '@noble/curves/ed25519'
+import { emptyDevLogState, nextDevLogEntry, signDevLogEntry, applyDevLogEntries, type DevLogEntry, type DevLogState } from './deviceLog.js'
+import { devLogHistory } from './deviceHistory.js'
+import { devLogDivergence } from './deviceLogSyncer.js'
+import vectors from './deviceHistory.vectors.json' with { type: 'json' }
+
+const b64 = (u: Uint8Array): string => Buffer.from(u).toString('base64')
+const key = (n: number) => { const priv = new Uint8Array(32).fill(n); return { priv, pub: b64(ed25519.getPublicKey(priv)) } }
+const a = key(1), b = key(2), c = key(3)
+
+function build() {
+ let state: DevLogState = emptyDevLogState('acct')
+ const entries: DevLogEntry[] = []
+ const push = (op: 'add' | 'remove', k: { pub: string }, signer: { pub: string; priv: Uint8Array }, label: string, at: number, kind: 'machine' | 'viewer' = 'viewer') => {
+ const e = signDevLogEntry(nextDevLogEntry(state, { op, pub: k.pub, kind, machineId: kind === 'machine' ? 'a'.repeat(32) : '', label, signer: signer.pub }, at), signer.priv)
+ state = applyDevLogEntries(state, [e]).state
+ entries.push(e)
+ }
+ push('add', a, a, 'mac', 10, 'machine')
+ push('add', b, b, 'phone', 20)
+ push('add', b, b, 'pixel', 30)
+ push('add', c, c, 'ipad', 40)
+ push('remove', c, a, 'ipad', 50)
+ push('remove', b, b, 'pixel', 60)
+ return { state, entries }
+}
+
+describe('devLogHistory', () => {
+ const { state, entries } = build()
+ const rows = devLogHistory(entries, { selfPub: a.pub, joinedSeq: 1, pending: [b.pub], active: state.active })
+
+ it('is newest first and tells each operation apart', () => {
+ expect(rows.map((r) => [r.seq, r.op])).toEqual([[6, 'signedOut'], [5, 'removed'], [4, 'added'], [3, 'renamed'], [2, 'added'], [1, 'added']])
+ })
+ it('names who removed a key that is gone, and the old label of a rename', () => {
+ expect(rows[1]).toMatchObject({ label: 'ipad', by: { pub: a.pub, label: 'mac' }, active: false })
+ expect(rows[3]).toMatchObject({ label: 'pixel', previousLabel: 'phone' })
+ })
+ it('flags this device, entries after joining, pending and active', () => {
+ expect(rows[5]).toMatchObject({ thisDevice: true, afterJoin: false, active: true })
+ expect(rows[4]).toMatchObject({ afterJoin: true, pending: true, active: false })
+ })
+ it('marks loose removals as applied while frozen, and does not duplicate', () => {
+ const loose = entries[4]
+ const out = devLogHistory(entries.slice(0, 4), { selfPub: a.pub, pending: [], active: state.active, loose: [loose, loose] })
+ expect(out[0]).toMatchObject({ seq: 5, whileFrozen: true })
+ expect(out).toHaveLength(5)
+ })
+ it('reads a partial tail: an add of an already-active key is a rename', () => {
+ const out = devLogHistory(entries.slice(2, 3), { selfPub: a.pub, pending: [], active: { [b.pub]: { pub: b.pub, kind: 'viewer', machineId: '', label: 'pixel', addedAt: 20, seq: 2 } } })
+ expect(out[0].op).toBe('renamed')
+ })
+})
+
+// The same fixture the Dart ports are held to (desktop|mobile/test/viewer/device_history_test.dart).
+describe('shared history and divergence vectors', () => {
+ it('the Dart copies are byte-identical to this fixture', () => {
+ const here = readFileSync(fileURLToPath(new URL('./deviceHistory.vectors.json', import.meta.url)))
+ for (const app of ['desktop', 'mobile']) {
+ const copy = readFileSync(fileURLToPath(new URL(`../../../../${app}/test/viewer/deviceHistory.vectors.json`, import.meta.url)))
+ expect(copy.equals(here), `${app} copy differs: run scripts/gen-devhistory-vectors.ts and copy it`).toBe(true)
+ }
+ })
+ const pubs = vectors.pubs as Record<string, string>
+ const entries = vectors.entries as unknown as DevLogEntry[]
+ const state = applyDevLogEntries(emptyDevLogState(vectors.acct), entries).state
+
+ for (const c of vectors.history) {
+ it(`history: ${c.name}`, () => {
+ const pick = (seqs: number[]) => seqs.map((n) => entries[n - 1])
+ const rows = devLogHistory(pick(c.seqs), {
+ selfPub: pubs[c.self], ...('joinedSeq' in c ? { joinedSeq: c.joinedSeq as number } : {}),
+ pending: c.pending.map((k) => pubs[k]), active: state.active, loose: pick(c.loose),
+ })
+ expect(rows.map((r) => ({
+ seq: r.seq, op: r.op, label: r.label, kind: r.kind, ...(r.previousLabel !== undefined ? { previousLabel: r.previousLabel } : {}),
+ ...(r.by ? { by: r.by.label } : {}), thisDevice: r.thisDevice, afterJoin: r.afterJoin, pending: r.pending, active: r.active, whileFrozen: r.whileFrozen,
+ }))).toEqual(c.rows)
+ })
+ }
+
+ for (const c of vectors.divergence) {
+ it(`divergence: ${c.name}`, () => {
+ const other = applyDevLogEntries(emptyDevLogState(vectors.acct), (c.log === 'fork' ? vectors.fork : vectors.entries) as unknown as DevLogEntry[]).state
+ const hashes: Array<{ seq: number; hash: string }> = []
+ for (let seq = c.from; seq <= c.to; seq++) hashes.push({ seq, hash: other.hashes[seq - 1] })
+ let theirs: unknown = { head: { seq: c.to, hash: other.hashes[c.to - 1] }, hashes }
+ if (c.tamper === 'gap') theirs = { head: (theirs as { head: unknown }).head, hashes: hashes.filter((h) => h.seq !== 2) }
+ if (c.tamper === 'head') theirs = { head: { seq: c.to, hash: 'nope' }, hashes }
+ if (c.tamper === 'junk') theirs = { head: (theirs as { head: unknown }).head, hashes: 'junk' }
+ expect(devLogDivergence(state, theirs)).toBe(c.expect)
+ })
+ }
+})
diff --git a/cli/src/lib/e2ee/deviceHistory.ts b/cli/src/lib/e2ee/deviceHistory.ts
new file mode 100644
index 000000000..adb71b1c6
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceHistory.ts
@@ -0,0 +1,107 @@
+/**
+ * The device key log read as a history: who was added, renamed or removed, newest first — what
+ * `harness devices history` and the apps' History dialog show. Pure: the entries are whatever this
+ * machine verified (or kept), the context says what is known about them now.
+ *
+ * ⚠ Ported to Dart (desktop|mobile/lib/viewer/device_history.dart); the rows are the wire format of
+ * `GET /api/devices/history` — change both together.
+ */
+import type { DevLogEntry, DevLogKind, DevLogMember } from './deviceLog.js'
+import { b64d, fingerprint } from './core.js'
+
+export interface DevLogHistoryRow {
+ seq: number
+ op: 'added' | 'renamed' | 'removed' | 'signedOut'
+ pub: string
+ kind: DevLogKind
+ machineId: string
+ label: string
+ /** For `renamed`: the name it had before, when known. */
+ previousLabel?: string
+ fingerprint: string
+ /** For `removed`: the key that signed the removal. */
+ by?: { pub: string; label: string; fingerprint: string }
+ at: number
+ thisDevice: boolean
+ /** Added after this device joined (its entry is past `joinedSeq`). */
+ afterJoin: boolean
+ /** Still new: nobody has marked it as seen here. */
+ pending: boolean
+ /** The key is active in the log now. */
+ active: boolean
+ /** A removal this device applied while its copy of the log was frozen (unchained, so unverified). */
+ whileFrozen: boolean
+}
+
+export interface DevLogHistoryContext {
+ selfPub: string
+ joinedSeq?: number
+ pending: readonly string[]
+ active: Readonly<Record<string, DevLogMember>>
+ /** Removals applied while frozen: not part of `entries`, shown last-known. */
+ loose?: readonly DevLogEntry[]
+}
+
+const fp = (pub: string): string => {
+ try { return fingerprint(b64d(pub)) } catch { return '' }
+}
+
+/** Newest first. `entries` may have gaps at the front (only the recent tail is known offline). */
+export function devLogHistory(entries: readonly DevLogEntry[], ctx: DevLogHistoryContext): DevLogHistoryRow[] {
+ const seen = new Set<string>()
+ const ordered: Array<{ e: DevLogEntry; loose: boolean }> = []
+ for (const e of [...entries].sort((a, b) => a.seq - b.seq)) {
+ const key = `${e.seq}:${e.sig}`
+ if (seen.has(key)) continue
+ seen.add(key)
+ ordered.push({ e, loose: false })
+ }
+ for (const e of ctx.loose ?? []) {
+ const key = `${e.seq}:${e.sig}`
+ if (seen.has(key)) continue
+ seen.add(key)
+ ordered.push({ e, loose: true })
+ }
+ // The name each key last went by, to say "renamed from" and to name a signer that is gone.
+ const labels = new Map<string, string>()
+ for (const m of Object.values(ctx.active)) labels.set(m.pub, m.label)
+ const known = new Map<string, { label: string; kind: DevLogKind; machineId: string }>()
+ const rows: DevLogHistoryRow[] = []
+ for (const { e, loose } of ordered) {
+ // A removal names the key as the log had it BEFORE: the remove entry's own label and kind are
+ // chosen by whoever signed it, and say nothing checked.
+ // When the add is outside what is known (offline, the newest entries only) it is named by its
+ // fingerprint alone — an empty label, shown as "A device", and no kind or machine id of the signer's.
+ const prior = e.op === 'remove' ? known.get(e.pub) : undefined
+ const base = {
+ seq: e.seq, pub: e.pub,
+ kind: e.op === 'remove' ? prior?.kind ?? 'viewer' : e.kind,
+ machineId: e.op === 'remove' ? prior?.machineId ?? '' : e.machineId,
+ label: e.op === 'remove' ? prior?.label ?? '' : e.label, fingerprint: fp(e.pub), at: e.at,
+ thisDevice: e.pub === ctx.selfPub,
+ afterJoin: ctx.joinedSeq !== undefined && e.seq > ctx.joinedSeq,
+ pending: ctx.pending.includes(e.pub),
+ active: !!ctx.active[e.pub],
+ whileFrozen: loose,
+ }
+ if (e.op === 'add') {
+ const before = known.get(e.pub)
+ const member = ctx.active[e.pub]
+ if (before !== undefined || (member && member.seq < e.seq)) {
+ rows.push({ ...base, op: 'renamed', ...(before !== undefined ? { previousLabel: before.label } : {}) })
+ } else {
+ rows.push({ ...base, op: 'added' })
+ }
+ known.set(e.pub, { label: e.label, kind: e.kind, machineId: e.machineId })
+ labels.set(e.pub, e.label)
+ } else if (e.signer === e.pub) {
+ rows.push({ ...base, op: 'signedOut' })
+ known.delete(e.pub)
+ } else {
+ const label = known.get(e.signer)?.label ?? labels.get(e.signer) ?? ''
+ rows.push({ ...base, op: 'removed', by: { pub: e.signer, label, fingerprint: fp(e.signer) } })
+ known.delete(e.pub)
+ }
+ }
+ return rows.sort((a, b) => b.seq - a.seq)
+}
diff --git a/cli/src/lib/e2ee/deviceHistory.vectors.json b/cli/src/lib/e2ee/deviceHistory.vectors.json
new file mode 100644
index 000000000..679ffc2d5
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceHistory.vectors.json
@@ -0,0 +1,543 @@
+{
+ "acct": "acct-history-1",
+ "pubs": {
+ "a": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "b": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "c": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "d": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw="
+ },
+ "entries": [
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 10,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "mac",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "TGq35MQKMb9h+RVuiWBdKkeGL0CpoDzz28ZWmTsgRCr9+Q5EUYP0cBOEvL2l1En0W7pghYv8nrUnQa6pvPrUAQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 2,
+ "prev": "CovFBIdOBn7wiD9rCG4NzW31/eiYY2aQcLLFK7P08bc=",
+ "at": 20,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "phone",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "G3NPtWdtHRzO0qVbbd1jABC7EPAFCf0L7NXcaNC1tPfjkrSo4IqpFF1kMOMQkodYenWVTqr/lbxciclDAROfBA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 3,
+ "prev": "B5nsulFGuwg49bsCmFEg0lJUYigEX/VA/bCccUr94bM=",
+ "at": 30,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "pixel",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "CW+lpHmqR4qSoFxTIbY+fzKZr4G0dSZMfs0ULd6s3kdNpE4zVbkOpaKpL+bzA5bEghk6CiGki5NkV/0ZjYjnAQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 4,
+ "prev": "rQt1wtdStS0QRgoTyNQxnPHCCo+OcAdJoTIEBoXes7c=",
+ "at": 40,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "ipad",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "LAdnsHZy255R8J9jeMq5AMC4QuJxz2Bq+QYnF/YQQarH3QOkTf3jzKk6XweiBouhXSLnposVThku9mI6cl8DBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 5,
+ "prev": "bC4N5mAJgT276SBzBqiEOQSptTRcIQYM+mnpRygEYHM=",
+ "at": 50,
+ "op": "remove",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "LIE",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "xMGVbx5ArRy/NpTcLzBJGYD+oZT+GlJPaX3DbOJ8T9mKy+7wv8zhxzgYRQq4L0FHrX5LXlcEv1Fd6+1w6msuBQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 6,
+ "prev": "yis5+Ci1yxF/tUx+lO0DIExsqBMxDm8bv516DD+0XdA=",
+ "at": 60,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "pixel",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "sL2JKbDDzTcoZSQYcOlp5soXgp8II7n/Mrq5lI1zrmtZE3u0zsB/i3hayhBA1bdxC40Pl9B7vLJQtVxG7yrKCA=="
+ }
+ ],
+ "fork": [
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 10,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "mac",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "TGq35MQKMb9h+RVuiWBdKkeGL0CpoDzz28ZWmTsgRCr9+Q5EUYP0cBOEvL2l1En0W7pghYv8nrUnQa6pvPrUAQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 2,
+ "prev": "CovFBIdOBn7wiD9rCG4NzW31/eiYY2aQcLLFK7P08bc=",
+ "at": 20,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "phone",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "G3NPtWdtHRzO0qVbbd1jABC7EPAFCf0L7NXcaNC1tPfjkrSo4IqpFF1kMOMQkodYenWVTqr/lbxciclDAROfBA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 3,
+ "prev": "B5nsulFGuwg49bsCmFEg0lJUYigEX/VA/bCccUr94bM=",
+ "at": 31,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "evil",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "I5yBaoADRLpyN3I+0t0qhZR7wehgWo6oZqWsj9CY3tb5dotNiCkmf+7YnqW5ir0dwFa4XCz9k/yBxod63p0vBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 4,
+ "prev": "sEpMlwosMHwGtmqVx5x1Dx3Nc8qf3rTnmjXVrUI+YRY=",
+ "at": 41,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "ipad",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "0pp4FidRF84ismPAL5P55sJ/1ZEXdToIxQ6i6glOLHO025TdJF51L4nhoRSAxW3Cuk2YS6yrSK+RsLYpwZ22Dg=="
+ }
+ ],
+ "history": [
+ {
+ "name": "the whole log, newest first",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [
+ "b"
+ ],
+ "seqs": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "pixel",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 3,
+ "op": "renamed",
+ "label": "pixel",
+ "kind": "viewer",
+ "previousLabel": "phone",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 2,
+ "op": "added",
+ "label": "phone",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 1,
+ "op": "added",
+ "label": "mac",
+ "kind": "machine",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "only the recent tail is known (offline)",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [],
+ "seqs": [
+ 4,
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "a removal whose add is outside the known window",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [],
+ "seqs": [
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "a removal applied while frozen",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [],
+ "seqs": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 6
+ ],
+ "loose": [
+ 5
+ ],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "pixel",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": true
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 3,
+ "op": "renamed",
+ "label": "pixel",
+ "kind": "viewer",
+ "previousLabel": "phone",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 2,
+ "op": "added",
+ "label": "phone",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 1,
+ "op": "added",
+ "label": "mac",
+ "kind": "machine",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "no joined point known",
+ "self": "b",
+ "pending": [],
+ "seqs": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "pixel",
+ "kind": "viewer",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 3,
+ "op": "renamed",
+ "label": "pixel",
+ "kind": "viewer",
+ "previousLabel": "phone",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 2,
+ "op": "added",
+ "label": "phone",
+ "kind": "viewer",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 1,
+ "op": "added",
+ "label": "mac",
+ "kind": "machine",
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false
+ }
+ ]
+ }
+ ],
+ "divergence": [
+ {
+ "name": "the first differing position, the one before it matching",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "expect": 3
+ },
+ {
+ "name": "a window that starts at the split cannot prove it",
+ "log": "fork",
+ "from": 3,
+ "to": 4,
+ "expect": null
+ },
+ {
+ "name": "the same log has no split",
+ "log": "main",
+ "from": 1,
+ "to": 4,
+ "expect": null
+ },
+ {
+ "name": "a window with a gap is not usable",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "tamper": "gap",
+ "expect": null
+ },
+ {
+ "name": "a window that does not end at the peer head is not usable",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "tamper": "head",
+ "expect": null
+ },
+ {
+ "name": "not a window at all",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "tamper": "junk",
+ "expect": null
+ }
+ ]
+}
diff --git a/cli/src/lib/e2ee/deviceLogStore.spec.ts b/cli/src/lib/e2ee/deviceLogStore.spec.ts
index 20d617530..7974ca291 100644
--- a/cli/src/lib/e2ee/deviceLogStore.spec.ts
+++ b/cli/src/lib/e2ee/deviceLogStore.spec.ts
@@ -1,8 +1,8 @@
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
-import { afterEach, describe, expect, it } from 'vitest'
-import { DeviceLogStore, type DevLogFile } from './deviceLogStore.js'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { DEVLOG_ARCHIVED, DEVLOG_DEPARTED, DeviceLogStore, type DevLogFile } from './deviceLogStore.js'
const dirs: string[] = []
afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })
@@ -42,3 +42,111 @@ describe('DeviceLogStore — firstSeen across versions', () => {
expect(read.firstSeen).toBeUndefined()
})
})
+
+describe('DeviceLogStore — joined point and marks', () => {
+ it('reads an old file with none of them, and keeps them through a write and a read', () => {
+ const path = file()
+ writeFileSync(path, JSON.stringify({ state, recent: [], frozen: null, notifiedUpTo: 1 }))
+ const store = new DeviceLogStore(path)
+ const old = store.read()
+ expect(old.joinedSeq).toBeUndefined()
+ expect(old.baselineSeen).toBeUndefined()
+ expect(old.pending).toBeUndefined()
+ const conflict = { pub: 'p', label: 'l', machineId: 'm', addedAt: 1, seq: 2, fingerprint: 'f', afterJoin: true }
+ store.write({ ...old, joinedSeq: 1, preLog: ['a'], pending: ['b'], announced: ['c'], baselineSeen: false, suspended: ['d'], conflict })
+ expect(store.read()).toMatchObject({ joinedSeq: 1, preLog: ['a'], pending: ['b'], announced: ['c'], baselineSeen: false, suspended: ['d'], conflict })
+ })
+
+ it('filters junk per field instead of failing the read', () => {
+ const path = file()
+ writeFileSync(path, JSON.stringify({
+ state, recent: [], frozen: null, notifiedUpTo: 1, joinedSeq: 'x', preLog: ['a', 3], pending: 'no', baselineSeen: 'yes',
+ looseRemoved: [{ nope: true }], conflict: { pub: 1 },
+ }))
+ const read = new DeviceLogStore(path).read()
+ expect(read.state).toEqual(state)
+ expect(read.joinedSeq).toBeUndefined()
+ expect(read.preLog).toEqual(['a'])
+ expect(read.pending).toBeUndefined()
+ expect(read.baselineSeen).toBeUndefined()
+ expect(read.looseRemoved).toEqual([])
+ expect(read.conflict).toBeUndefined()
+ })
+})
+
+describe('DeviceLogStore — writes and the archive of other accounts', () => {
+ const of = (acct: string, extra: Partial<DevLogFile> = {}): DevLogFile =>
+ ({ state: { ...state, acct }, recent: [], frozen: null, notifiedUpTo: 1, ...extra })
+
+ it('a write that fails half way leaves the previous file whole', () => {
+ const path = file()
+ const store = new DeviceLogStore(path)
+ store.write(of('a', { pending: ['p'] }))
+ const now = vi.spyOn(Date, 'now').mockReturnValue(42)
+ try {
+ // The temp file cannot be created: the write fails before anything touches devlog.json.
+ mkdirSync(`${path}.${process.pid}.42.tmp`)
+ expect(() => store.write(of('a', { pending: [] }))).toThrow()
+ } finally { now.mockRestore() }
+ expect(store.read().pending).toEqual(['p'])
+ expect(readdirSync(join(path, '..')).filter((n) => n.endsWith('.tmp'))).toHaveLength(1)
+ })
+
+ it('keeps a left account\'s file to restore once, and the newest few only', () => {
+ const store = new DeviceLogStore(file())
+ store.archive(of('a', { suspended: ['evil'], pending: ['evil'], frozen: { reason: 'fork', at: 1, lastGoodHead: state.head } }))
+ for (let i = 0; i < DEVLOG_ARCHIVED; i++) store.archive(of(`b${i}`, { suspended: [`s${i}`] }))
+ expect(store.restore('a')).toBeNull()
+ expect(store.archivedSuspended().sort()).toEqual(['s0', 's1', 's2', 's3'])
+ store.archive(of('a', { suspended: ['evil'], pending: ['evil'] }))
+ expect(store.archivedSuspended()).toContain('evil')
+ expect(store.restore('a')).toMatchObject({ state: { acct: 'a' }, suspended: ['evil'], pending: ['evil'] })
+ expect(store.restore('a')).toBeNull()
+ expect(store.archivedSuspended()).not.toContain('evil')
+ expect(store.read()).toMatchObject({ state: { acct: 'a' }, suspended: ['evil'], pending: ['evil'] })
+ })
+
+ it('a restore that fails half way has the kept file live first: its marks are never lost', () => {
+ const path = file()
+ const store = new DeviceLogStore(path)
+ store.write(of('b'))
+ store.archive(of('a', { suspended: ['evil'], pending: ['evil'] }))
+ const now = vi.spyOn(Date, 'now').mockReturnValue(43)
+ try {
+ // Taking it out of the archive fails: by then it is the live file.
+ mkdirSync(`${path.replace(/\.json$/, '.archive.json')}.${process.pid}.43.tmp`)
+ expect(() => store.restore('a', (k) => ({ ...k, owner: 'u2' }))).toThrow()
+ } finally { now.mockRestore() }
+ expect(store.read()).toMatchObject({ state: { acct: 'a' }, suspended: ['evil'], pending: ['evil'], owner: 'u2' })
+ expect(store.archivedSuspended()).toContain('evil')
+ })
+
+ it('lifting a suspension takes it out of every kept account', () => {
+ const store = new DeviceLogStore(file())
+ store.archive(of('a', { suspended: ['evil', 'x'] }))
+ store.archive(of('b', { suspended: ['evil'] }))
+ store.unsuspendArchived(['evil'])
+ expect(store.archivedSuspended()).toEqual(['x'])
+ })
+
+ it('keeps the newest departed keys only, and drops unreadable ones', () => {
+ const path = file()
+ const store = new DeviceLogStore(path)
+ const d = (i: number) => ({
+ pub: `k${i}`, label: `d${i}`, kind: 'viewer' as const, machineId: '', fingerprint: 'F', addedAt: 1, removedAt: 2,
+ removedBy: `k${i}`, removedByLabel: '', selfRemoved: true,
+ })
+ store.write(of('a', { departed: Array.from({ length: DEVLOG_DEPARTED + 3 }, (_, i) => d(i)) }))
+ expect(store.read().departed?.map((x) => x.pub)).toEqual(Array.from({ length: DEVLOG_DEPARTED }, (_, i) => `k${i + 3}`))
+ writeFileSync(path, JSON.stringify({ ...of('a'), departed: [d(1), { pub: 'k2', label: 3 }, { ...d(4), kind: 'evil' }] }))
+ expect(store.read().departed?.map((x) => x.pub)).toEqual(['k1'])
+ })
+
+ it('never restores a kept file under an account it is not for', () => {
+ const path = file()
+ const store = new DeviceLogStore(path)
+ writeFileSync(path.replace(/\.json$/, '.archive.json'), JSON.stringify({ b: of('a', { suspended: ['evil'] }) }))
+ expect(store.restore('b')).toBeNull()
+ expect(store.archivedSuspended()).toEqual(['evil'])
+ })
+})
diff --git a/cli/src/lib/e2ee/deviceLogStore.ts b/cli/src/lib/e2ee/deviceLogStore.ts
index 345139296..a584bb3ca 100644
--- a/cli/src/lib/e2ee/deviceLogStore.ts
+++ b/cli/src/lib/e2ee/deviceLogStore.ts
@@ -3,12 +3,13 @@
* entries (to hand a peer that is behind, over `group_sync`), and whether the log is frozen.
*
* Persistence mirrors machinePeers.ts: ${ADAPTER_DATA_DIR}/e2e/devlog.json, 0600, never cached — the
- * daemon and a short-lived `harness devices …` process both read and write it.
+ * daemon and a short-lived `harness devices …` process both read and write it. Beside it,
+ * devlog.archive.json: the files of accounts this machine was signed in to before, by account id.
*/
-import { mkdirSync, readFileSync, writeFileSync } from 'fs'
+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'
import { join } from 'path'
import { env } from '../../config/env.js'
-import type { DevLogEntry, DevLogHead, DevLogState } from './deviceLog.js'
+import { parseDevLogEntry, type DevLogEntry, type DevLogHead, type DevLogState } from './deviceLog.js'
/** How many of the newest entries are kept verbatim, for a peer that is behind. */
export const DEVLOG_RECENT = 64
@@ -22,6 +23,43 @@ export interface DevLogFreeze {
lastGoodHead: DevLogHead
}
+/** Another key holds this machine's id in the log, so this machine's own key cannot be registered. */
+export interface DevLogConflict {
+ pub: string
+ label: string
+ machineId: string
+ addedAt: number
+ seq: number
+ fingerprint: string
+ /** The holder joined after this machine did (its entry is past `joinedSeq`). */
+ afterJoin: boolean
+}
+
+/** How many removals applied while the log was frozen are kept (for the history). */
+export const DEVLOG_LOOSE = 64
+
+/** A key that was new here (pending) and was removed before anyone marked it as seen: it stays
+ * flagged — "joined and left before you looked" — until it is dismissed. */
+export interface DevLogDeparted {
+ pub: string
+ label: string
+ kind: 'machine' | 'viewer'
+ machineId: string
+ fingerprint: string
+ /** The `at` of the entry that added it (picked by that device). */
+ addedAt: number
+ /** The `at` of the entry that removed it (picked by its signer). */
+ removedAt: number
+ /** The key that signed the removal, and what it was called then ('' when not known). */
+ removedBy: string
+ removedByLabel: string
+ /** It removed itself (signed out). */
+ selfRemoved: boolean
+}
+
+/** How many departed keys are kept; the oldest goes first. */
+export const DEVLOG_DEPARTED = 32
+
export interface DevLogFile {
state: DevLogState | null
recent: DevLogEntry[]
@@ -31,29 +69,107 @@ export interface DevLogFile {
/** When THIS machine first applied each key's add. The entry's own `at` is picked by the adding
* device, so "new" cannot rest on it; absent for keys already in the log at first read. */
firstSeen?: Record<string, number>
+ /** The head seq this machine's first read of the log ended at: only an `add` past it is news. Absent
+ * in a file from before this existed (migrated on first use). */
+ joinedSeq?: number
+ /** Keys this machine trusted when it joined (or migrated): never news, whatever the log says. */
+ preLog?: string[]
+ /** New keys nobody has marked as seen yet. */
+ pending?: string[]
+ /** Keys already announced (OS notification / log line) — never twice. */
+ announced?: string[]
+ /** false until the "Already on your account" panel is dismissed; absent = true. */
+ baselineSeen?: boolean
+ /** Keys not trusted here after a fork split the lists, until `rebaseline`. */
+ suspended?: string[]
+ /** The head seq of the list a person last reviewed (`rebaseline --yes`): a key at or before it was
+ * looked at, so a later fork never suspends it. */
+ reviewedSeq?: number
+ /** Removals applied while frozen: never in `recent`, which is handed to peers as a chained tail. */
+ looseRemoved?: DevLogEntry[]
+ conflict?: DevLogConflict
+ /** Which local sign-in this file belongs to (the syncer's `signIn()`): the file starts over when THAT
+ * changes — never because the backend says the account id did. Absent in a file from before this
+ * existed (taken to be the current sign-in's). */
+ owner?: string
+ /** true from the fresh write of a log until the first read of it reaches the head (or stops on a
+ * freeze): while set, whatever is verified is what was there at joining — none of it is news. */
+ joining?: boolean
+ /** New keys removed before anyone looked (oldest first, at most DEVLOG_DEPARTED). */
+ departed?: DevLogDeparted[]
}
const empty = (): DevLogFile => ({ state: null, recent: [], frozen: null, notifiedUpTo: 0 })
+const strings = <K extends string>(key: K, v: unknown): { [P in K]?: string[] } =>
+ (Array.isArray(v) ? { [key]: v.filter((x): x is string => typeof x === 'string') } : {}) as { [P in K]?: string[] }
+
+const isConflict = (v: unknown): v is DevLogConflict => {
+ if (!v || typeof v !== 'object') return false
+ const c = v as Record<string, unknown>
+ return typeof c.pub === 'string' && typeof c.label === 'string' && typeof c.machineId === 'string'
+ && typeof c.addedAt === 'number' && typeof c.seq === 'number' && typeof c.fingerprint === 'string' && typeof c.afterJoin === 'boolean'
+}
+
+const isDeparted = (v: unknown): v is DevLogDeparted => {
+ if (!v || typeof v !== 'object') return false
+ const d = v as Record<string, unknown>
+ return typeof d.pub === 'string' && !!d.pub && typeof d.label === 'string' && (d.kind === 'machine' || d.kind === 'viewer')
+ && typeof d.machineId === 'string' && typeof d.fingerprint === 'string' && typeof d.addedAt === 'number'
+ && typeof d.removedAt === 'number' && typeof d.removedBy === 'string' && typeof d.removedByLabel === 'string'
+ && typeof d.selfRemoved === 'boolean'
+}
+
+/** How many other accounts' files are kept (devlog.archive.json); the oldest goes first. */
+export const DEVLOG_ARCHIVED = 4
+
+/** A file as stored, normalized: anything unreadable is dropped field by field. */
+function parseFile(value: unknown): DevLogFile {
+ if (!value || typeof value !== 'object') return empty()
+ const raw = value as Partial<DevLogFile>
+ return {
+ state: raw.state && typeof raw.state === 'object' ? raw.state : null,
+ recent: Array.isArray(raw.recent) ? raw.recent : [],
+ frozen: raw.frozen && typeof raw.frozen === 'object' ? raw.frozen : null,
+ notifiedUpTo: typeof raw.notifiedUpTo === 'number' ? raw.notifiedUpTo : 0,
+ firstSeen: raw.firstSeen && typeof raw.firstSeen === 'object' ? raw.firstSeen : undefined,
+ ...(typeof raw.joinedSeq === 'number' && Number.isSafeInteger(raw.joinedSeq) && raw.joinedSeq >= 0 ? { joinedSeq: raw.joinedSeq } : {}),
+ ...(typeof raw.reviewedSeq === 'number' && Number.isSafeInteger(raw.reviewedSeq) && raw.reviewedSeq >= 0 ? { reviewedSeq: raw.reviewedSeq } : {}),
+ ...strings('preLog', raw.preLog),
+ ...strings('pending', raw.pending),
+ ...strings('announced', raw.announced),
+ ...strings('suspended', raw.suspended),
+ ...(typeof raw.baselineSeen === 'boolean' ? { baselineSeen: raw.baselineSeen } : {}),
+ ...(Array.isArray(raw.looseRemoved)
+ ? { looseRemoved: raw.looseRemoved.map((e) => parseDevLogEntry(e)).filter((e): e is DevLogEntry => e !== null) }
+ : {}),
+ ...(typeof raw.owner === 'string' && raw.owner ? { owner: raw.owner } : {}),
+ ...(raw.joining === true ? { joining: true } : {}),
+ ...(isConflict(raw.conflict) ? { conflict: raw.conflict } : {}),
+ ...(Array.isArray(raw.departed) ? { departed: raw.departed.filter(isDeparted) } : {}),
+ }
+}
+
+const trimmed = (next: DevLogFile): DevLogFile => ({
+ ...next,
+ recent: next.recent.slice(-DEVLOG_RECENT),
+ ...(next.looseRemoved ? { looseRemoved: next.looseRemoved.slice(-DEVLOG_LOOSE) } : {}),
+ ...(next.departed ? { departed: next.departed.slice(-DEVLOG_DEPARTED) } : {}),
+})
+
export class DeviceLogStore {
- constructor(private readonly file = join(env.ADAPTER_DATA_DIR, 'e2e', 'devlog.json')) {}
+ private readonly archiveFile: string
+
+ constructor(private readonly file = join(env.ADAPTER_DATA_DIR, 'e2e', 'devlog.json')) {
+ this.archiveFile = file.replace(/(\.json)?$/, '.archive.json')
+ }
read(): DevLogFile {
- try {
- const raw = JSON.parse(readFileSync(this.file, 'utf-8')) as Partial<DevLogFile>
- return {
- state: raw.state && typeof raw.state === 'object' ? raw.state : null,
- recent: Array.isArray(raw.recent) ? raw.recent : [],
- frozen: raw.frozen && typeof raw.frozen === 'object' ? raw.frozen : null,
- notifiedUpTo: typeof raw.notifiedUpTo === 'number' ? raw.notifiedUpTo : 0,
- firstSeen: raw.firstSeen && typeof raw.firstSeen === 'object' ? raw.firstSeen : undefined,
- }
- } catch { return empty() }
+ try { return parseFile(JSON.parse(readFileSync(this.file, 'utf-8'))) } catch { return empty() }
}
write(next: DevLogFile): void {
- mkdirSync(join(this.file, '..'), { recursive: true, mode: 0o700 })
- writeFileSync(this.file, JSON.stringify({ ...next, recent: next.recent.slice(-DEVLOG_RECENT) }), { mode: 0o600 })
+ this.writeJson(this.file, trimmed(next))
}
update(change: (current: DevLogFile) => DevLogFile): DevLogFile {
@@ -61,4 +177,71 @@ export class DeviceLogStore {
this.write(next)
return next
}
+
+ /** Keep `file` — the log of an account this machine is leaving — to restore if it comes back. */
+ archive(file: DevLogFile): void {
+ if (!file.state) return
+ const all = this.archived()
+ delete all[file.state.acct]
+ all[file.state.acct] = trimmed(file)
+ const accts = Object.keys(all)
+ for (const acct of accts.slice(0, Math.max(0, accts.length - DEVLOG_ARCHIVED))) delete all[acct]
+ this.writeJson(this.archiveFile, all)
+ }
+
+ /** The kept file of `acct`, made the live one (as `place` has it) and only then taken out of the
+ * archive — a crash in between leaves it in both, never in neither. null when there is none. */
+ restore(acct: string, place: (kept: DevLogFile) => DevLogFile = (kept) => kept): DevLogFile | null {
+ const kept = this.archived()[acct]
+ if (!kept?.state || kept.state.acct !== acct) return null
+ const live = place(kept)
+ this.write(live)
+ const all = this.archived()
+ delete all[acct]
+ this.writeJson(this.archiveFile, all)
+ return live
+ }
+
+ /** The kept file of `acct`, left in the archive; null when there is none. */
+ archivedFile(acct: string): DevLogFile | null {
+ const kept = this.archived()[acct]
+ return kept?.state && kept.state.acct === acct ? kept : null
+ }
+
+ /** A suspension lifted here holds for every kept account too: none of them keeps the key out. */
+ unsuspendArchived(pubs: readonly string[]): void {
+ if (!pubs.length) return
+ const all = this.archived()
+ let changed = false
+ for (const f of Object.values(all)) {
+ const kept = (f.suspended ?? []).filter((k) => !pubs.includes(k))
+ if (kept.length !== (f.suspended ?? []).length) { f.suspended = kept; changed = true }
+ }
+ if (changed) this.writeJson(this.archiveFile, all)
+ }
+
+ /** Every key a fork suspended in an archived account's file: never trusted from another log. */
+ archivedSuspended(): string[] {
+ return [...new Set(Object.values(this.archived()).flatMap((f) => f.suspended ?? []))]
+ }
+
+ private archived(): Record<string, DevLogFile> {
+ try {
+ const raw = JSON.parse(readFileSync(this.archiveFile, 'utf-8')) as unknown
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
+ return Object.fromEntries(Object.entries(raw as Record<string, unknown>).map(([acct, f]) => [acct, parseFile(f)]))
+ } catch { return {} }
+ }
+
+ /** Written whole or not at all: a torn file would read as no file, and start the log over. */
+ private writeJson(path: string, value: unknown): void {
+ mkdirSync(join(path, '..'), { recursive: true, mode: 0o700 })
+ const temp = `${path}.${process.pid}.${Date.now()}.tmp`
+ try {
+ writeFileSync(temp, JSON.stringify(value), { mode: 0o600 })
+ renameSync(temp, path)
+ } finally {
+ try { rmSync(temp, { force: true }) } catch { /* gone with the rename */ }
+ }
+ }
}
diff --git a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts
index 16e39920b..77c9d2bea 100644
--- a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts
+++ b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts
@@ -8,7 +8,8 @@ import {
type DevLogEntry, type DevLogState,
} from './deviceLog.js'
import { DeviceLogStore } from './deviceLogStore.js'
-import { DeviceLogSyncer, type DeviceLogAppendAnswer, type DeviceLogFetched } from './deviceLogSyncer.js'
+import { DeviceLogSyncer, devLogDivergence, type DeviceLogAppendAnswer, type DeviceLogFetched, type DeviceLogRebaseline } from './deviceLogSyncer.js'
+import { ADOPTED_SIGN_IN } from '../authSession.js'
const b64 = (u: Uint8Array): string => Buffer.from(u).toString('base64')
const key = (n: number) => { const priv = new Uint8Array(32).fill(n); return { priv, pub: b64(ed25519.getPublicKey(priv)) } }
@@ -18,8 +19,17 @@ const MID_ME = 'a'.repeat(32), MID2 = 'b'.repeat(32)
/** The backend's side: holds the log, refuses what breaks a rule, can be told to lie. */
class FakeBackend {
+ acct = ACCT
entries: DevLogEntry[] = []
state: DevLogState = emptyDevLogState(ACCT)
+
+ /** Another account's log. */
+ static of(acct: string): FakeBackend {
+ const b = new FakeBackend()
+ b.acct = acct
+ b.state = emptyDevLogState(acct)
+ return b
+ }
/** When set, what `fetch` serves instead of the real log. */
lie: DevLogEntry[] | null = null
offline = false
@@ -45,8 +55,8 @@ class FakeBackend {
fetch = vi.fn(async (since: number): Promise<DeviceLogFetched | null> => {
if (this.offline) return null
const log = this.lie ?? this.entries
- const head = log.length ? applyDevLogEntries(emptyDevLogState(ACCT), log).state.head : emptyDevLogState(ACCT).head
- return { acct: ACCT, head, entries: log.filter((e) => e.seq > since) }
+ const head = log.length ? applyDevLogEntries(emptyDevLogState(this.acct), log).state.head : emptyDevLogState(this.acct).head
+ return { acct: this.acct, head, entries: log.filter((e) => e.seq > since) }
})
append = vi.fn(async (entry: DevLogEntry): Promise<DeviceLogAppendAnswer | null> => {
@@ -57,31 +67,44 @@ class FakeBackend {
})
}
-function setup(opts: { known?: string[]; tombstoned?: string[]; blocked?: string[] } = {}) {
- const backend = new FakeBackend()
- const store = new DeviceLogStore(join(mkdtempSync(join(tmpdir(), 'devlog-')), 'devlog.json'))
+/** `signIn`: the sign-in's epoch (one starting ADOPTED_SIGN_IN is adopted), made at `signInAt` (the
+ * clock's 5_000 by default — just now). */
+function setup(opts: { known?: string[]; tombstoned?: string[]; blocked?: string[]; store?: DeviceLogStore; backend?: FakeBackend; signIn?: () => string | null; signInAt?: number | null } = {}) {
+ const backend = opts.backend ?? new FakeBackend()
+ const store = opts.store ?? new DeviceLogStore(join(mkdtempSync(join(tmpdir(), 'devlog-')), 'devlog.json'))
const calls = {
adopt: vi.fn(), drop: vi.fn(), announce: vi.fn(), signedOut: vi.fn(), changed: vi.fn(),
+ removed: vi.fn(), conflict: vi.fn(), suspend: vi.fn(), resume: vi.fn(),
}
+ /** What this machine trusts "now": tests push into it to play a roster that outran the log. */
+ const trusted: string[] = [...(opts.known ?? [])]
const tombstoned = new Set(opts.tombstoned ?? [])
const syncer = new DeviceLogSyncer({
store,
identity: () => me,
+ signIn: () => {
+ const epoch = opts.signIn?.() ?? null
+ return epoch ? { epoch, adopted: epoch.startsWith(ADOPTED_SIGN_IN), at: opts.signInAt === undefined ? 5_000 : opts.signInAt } : null
+ },
self: () => ({ machineId: MID_ME, label: 'my-mac' }),
fetch: backend.fetch,
append: backend.append,
adopt: calls.adopt,
drop: (pub) => { tombstoned.delete(pub); calls.drop(pub) },
- knownBefore: (pub) => (opts.known ?? []).includes(pub),
+ trustedNow: () => [...trusted],
tombstoned: (pub) => tombstoned.has(pub),
blocked: (pub) => (opts.blocked ?? []).includes(pub),
announce: calls.announce,
+ removed: calls.removed,
+ conflict: calls.conflict,
+ suspend: calls.suspend,
+ resume: calls.resume,
signedOut: calls.signedOut,
changed: calls.changed,
now: () => 5_000,
sleep: async () => {},
})
- return { backend, store, syncer, calls }
+ return { backend, store, syncer, calls, trusted }
}
describe('DeviceLogSyncer', () => {
@@ -244,7 +267,7 @@ describe('DeviceLogSyncer', () => {
t.backend.lie = null
t.backend.add(phone, 'viewer', '', 'phone')
const preview = await t.syncer.rebaseline(false)
- expect(preview?.added.map((m) => m.pub)).toEqual([phone.pub])
+ expect((preview as DeviceLogRebaseline).added.map((m) => m.pub)).toEqual([phone.pub])
expect(t.store.read().frozen).not.toBeNull()
await t.syncer.rebaseline(true)
expect(t.store.read().frozen).toBeNull()
@@ -259,7 +282,8 @@ describe('DeviceLogSyncer', () => {
})
it('sends its head', () => {
- expect(t.syncer.gossip()).toEqual({ head: t.backend.state.head, frozen: false })
+ expect(t.syncer.gossip()).toMatchObject({ head: t.backend.state.head, frozen: false })
+ expect(t.syncer.gossip()?.hashes).toEqual(t.backend.state.hashes.map((hash, i) => ({ seq: i + 1, hash })))
})
it('freezes when a peer holds a different entry at a position it verified', () => {
@@ -284,6 +308,42 @@ describe('DeviceLogSyncer', () => {
expect(t.store.read().frozen?.reason).toBe('rollback')
})
+ /** Hold the next fetch's answer (taken when it is asked) until `release()`. */
+ const holdNextFetch = (): (() => void) => {
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => { release = resolve })
+ const real = t.backend.fetch.getMockImplementation()!
+ t.backend.fetch.mockImplementationOnce(async (since) => { const got = await real(since); await gate; return got })
+ return release
+ }
+ const headAt = (seq: number) => applyDevLogEntries(emptyDevLogState(ACCT), t.backend.entries.slice(0, seq)).state.head
+
+ it('reads a page again when a peer moved the log while it was on its way, rather than calling it a fork', async () => {
+ const viaPeer = t.backend.add(phone, 'viewer', '', 'phone')
+ t.backend.add(key(5), 'viewer', '', 'tablet')
+ const release = holdNextFetch()
+ const refreshed = t.syncer.refresh() // asks for everything after seq 2
+ t.syncer.heard(box2.pub, { head: headAt(3), tail: [viaPeer] })
+ release()
+ await refreshed
+ expect(t.store.read().frozen).toBeNull()
+ expect(t.store.read().state?.head).toEqual(t.backend.state.head)
+ expect(t.calls.announce.mock.calls.map(([m]) => m.label)).toEqual(['phone', 'tablet'])
+ })
+
+ it('reads a page again when a peer moved the log past it, rather than calling it a rollback', async () => {
+ t.backend.add(phone, 'viewer', '', 'phone')
+ const release = holdNextFetch() // the backend's answer stops at seq 3
+ const refreshed = t.syncer.refresh()
+ t.backend.add(key(5), 'viewer', '', 'tablet')
+ t.syncer.heard(box2.pub, { head: t.backend.state.head, tail: t.backend.entries.slice(2) })
+ release()
+ await refreshed
+ expect(t.store.read().frozen).toBeNull()
+ expect(t.store.read().state?.head).toEqual(t.backend.state.head)
+ expect(t.calls.announce.mock.calls.map(([m]) => m.label)).toEqual(['phone', 'tablet'])
+ })
+
it('lists machines that say their log is frozen', () => {
t.syncer.heard(box2.pub, { head: t.backend.state.head, frozen: true })
expect(t.syncer.list().frozenPeers).toEqual(['box2'])
@@ -297,3 +357,1438 @@ describe('DeviceLogSyncer', () => {
expect(t.calls.adopt).not.toHaveBeenCalled()
})
})
+
+const hashesOf = (state: DevLogState) => state.hashes.map((hash, i) => ({ seq: i + 1, hash }))
+const MID_HOLDER = MID_ME
+
+describe('DeviceLogSyncer — what is new, and what stays visible', () => {
+ let t: ReturnType<typeof setup>
+ beforeEach(() => { t = setup() })
+
+ it('announces a key the roster already held before the log read that adds it, once, and keeps it pending', async () => {
+ await t.syncer.register()
+ t.trusted.push(box2.pub) // the trust group spread it before this machine read the entry
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ await t.syncer.refresh()
+ expect(t.calls.announce).toHaveBeenCalledOnce()
+ expect(t.store.read().pending).toEqual([box2.pub])
+ expect(t.syncer.list()).toMatchObject({ pending: [box2.pub] })
+ expect(t.syncer.list().members.find((m) => m.pub === box2.pub)?.pending).toBe(true)
+ })
+
+ it('does the same when the entry arrives in a peer\'s tail, with the roster already ahead', async () => {
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.register()
+ t.trusted.push(box2.pub)
+ const entry = t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.offline = true
+ t.syncer.heard(phone.pub, { head: t.backend.state.head, tail: [entry] })
+ expect(t.calls.announce).toHaveBeenCalledOnce()
+ expect(t.store.read().pending).toEqual([box2.pub])
+ })
+
+ it('a first read of an existing log announces nothing, reports the baseline and the joined point', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ expect(t.calls.announce).not.toHaveBeenCalled()
+ expect(t.syncer.list()).toMatchObject({ baselineSeen: false, joinedSeq: 2, pending: [] })
+ })
+
+ it('an empty first log still announces the first device added later', async () => {
+ await t.syncer.refresh()
+ expect(t.store.read()).toMatchObject({ joinedSeq: 0 })
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ expect(t.calls.announce).toHaveBeenCalledOnce()
+ })
+
+ it('a key trusted when this machine joined never becomes pending', async () => {
+ t = setup({ known: [box2.pub] })
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ expect(t.store.read().pending).toEqual([])
+ expect(t.calls.announce).not.toHaveBeenCalled()
+ })
+
+ it('pending survives a new syncer on the same store; dismiss clears one, all, and the baseline', async () => {
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.register()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.add(evil, 'viewer', '', 'evil')
+ await t.syncer.refresh()
+ const again = setup({ store: t.store, backend: t.backend })
+ expect(again.syncer.list().pending).toEqual([box2.pub, evil.pub])
+ again.syncer.dismiss({ pub: box2.pub })
+ expect(t.store.read().pending).toEqual([evil.pub])
+ expect(again.syncer.list().baselineSeen).toBe(false)
+ again.syncer.dismiss({ baseline: true })
+ expect(t.store.read()).toMatchObject({ pending: [evil.pub], baselineSeen: true })
+ again.syncer.dismiss()
+ expect(t.store.read().pending).toEqual([])
+ expect(again.calls.changed).toHaveBeenCalled()
+ })
+
+ it('a rebaseline replay does not announce what was announced already', async () => {
+ await t.syncer.register()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ t.backend.lie = null
+ await t.syncer.rebaseline(true)
+ expect(t.calls.announce).toHaveBeenCalledOnce()
+ expect(t.store.read().announced).toEqual([box2.pub])
+ })
+
+ it('migrates a file from before the joined point: nothing up to notifiedUpTo is announced again', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.add(phone, 'viewer', '', 'phone')
+ t.backend.add(evil, 'viewer', '', 'evil')
+ await t.syncer.register()
+ const file = t.store.read()
+ // What a client that predates the marks left behind, at seq 3.
+ t.store.write({ state: file.state, recent: file.recent, frozen: null, notifiedUpTo: 3 })
+ expect(t.store.read().joinedSeq).toBeUndefined()
+ t.backend.add(key(7), 'viewer', '', 'late')
+ await t.syncer.refresh()
+ expect(t.calls.announce).toHaveBeenCalledOnce()
+ expect(t.calls.announce).toHaveBeenCalledWith(expect.objectContaining({ label: 'late' }))
+ expect(t.store.read()).toMatchObject({ joinedSeq: 3, baselineSeen: true })
+ })
+
+ it('a downgrade that strips the marks mid-run re-announces nothing it announced before', async () => {
+ await t.syncer.register()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ const file = t.store.read()
+ t.store.write({ state: file.state, recent: file.recent, frozen: null, notifiedUpTo: file.notifiedUpTo })
+ await t.syncer.refresh()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ expect(t.calls.announce).toHaveBeenCalledTimes(2)
+ expect(t.calls.announce.mock.calls.map(([m]) => m.pub)).toEqual([box2.pub, phone.pub])
+ })
+
+ it('a signed-in-to-another-account read starts the marks over', async () => {
+ const who = { user: 'u1' }
+ const s = setup({ signIn: () => who.user })
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ const file = s.store.read()
+ s.store.write({ ...file, state: { ...file.state!, acct: 'other' }, pending: ['x'], suspended: ['y'] })
+ who.user = 'u2'
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ pending: [], suspended: [], baselineSeen: false })
+ })
+
+ it('without a sign-in at hand, an account flip from the backend freezes and never starts over', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ const file = t.store.read()
+ t.store.write({ ...file, state: { ...file.state!, acct: 'other' }, pending: ['x'] })
+ await t.syncer.refresh()
+ expect(t.store.read()).toMatchObject({ pending: ['x'], frozen: { reason: 'invalid' }, state: { acct: 'other' } })
+ })
+
+ describe('the local sign-in decides when the log starts over, never the backend', () => {
+ const wrongAcct = async (): Promise<DeviceLogFetched> => ({ acct: 'x', head: emptyDevLogState('x').head, entries: [] })
+
+ it('a backend that flips the account id and back keeps a fork\'s marks', async () => {
+ let user = 'u1'
+ const s = setup({ signIn: () => user })
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ s.backend.add(phone, 'viewer', '', 'phone')
+ await s.syncer.refresh()
+ s.store.update((f) => ({ ...f, suspended: [phone.pub] }))
+ expect(s.store.read().pending).toContain(phone.pub)
+ s.backend.fetch.mockImplementationOnce(wrongAcct)
+ await s.syncer.refresh()
+ expect(s.store.read().frozen?.reason).toBe('invalid')
+ await s.syncer.refresh() // the real log again
+ expect(s.store.read()).toMatchObject({ suspended: [phone.pub], pending: [phone.pub], frozen: { reason: 'invalid' } })
+ expect(s.store.read().state?.acct).toBe(ACCT)
+ expect(s.syncer.list().members.find((m) => m.pub === phone.pub)).toMatchObject({ suspended: true, pending: true })
+ })
+
+ /** Signed in as `user` on the account the backend at hand serves; `serve` points `fetch` elsewhere. */
+ const signedIn = () => {
+ const who = { user: 'u1' }
+ const s = setup({ signIn: () => who.user })
+ const real = s.backend.fetch.getMockImplementation()!
+ const serve = (b: FakeBackend | null): void => { s.backend.fetch.mockImplementation(b ? b.fetch : real) }
+ return { s, who, serve }
+ }
+ /** A fork suspended `phone`, still pending, and the list is frozen on it. */
+ const forked = async (s: ReturnType<typeof setup>): Promise<void> => {
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ s.backend.add(phone, 'viewer', '', 'phone')
+ await s.syncer.refresh()
+ s.store.update((f) => ({ ...f, suspended: [phone.pub], frozen: { reason: 'fork', at: 1, lastGoodHead: f.state!.head } }))
+ }
+
+ it('a new sign-in id on the same account (a new machine id, a re-login) keeps the file and its marks', async () => {
+ const { s, who } = signedIn()
+ await forked(s)
+ who.user = 'u2'
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ owner: 'u2', suspended: [phone.pub], pending: [phone.pub], frozen: { reason: 'fork' } })
+ expect(s.store.read().joinedSeq).toBe(1)
+ // That sign-in is the file's now: the backend flipping the account freezes, never starts over.
+ s.store.update((f) => ({ ...f, frozen: null }))
+ s.backend.fetch.mockImplementationOnce(wrongAcct)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ suspended: [phone.pub], pending: [phone.pub], frozen: { reason: 'invalid' } })
+ })
+
+ it('a sign-in the backend forced, onto a made-up account and back, gives the first account its marks back', async () => {
+ const { s, who, serve } = signedIn()
+ await forked(s)
+ // Signed out by the backend, signed in again by hand — and told it is another account, whose
+ // log has the suspended key in it.
+ const fake = FakeBackend.of('x')
+ fake.add(phone, 'viewer', '', 'phone')
+ fake.add(evil, 'viewer', '', 'evil')
+ who.user = 'u2'
+ serve(fake)
+ s.calls.adopt.mockClear()
+ await s.syncer.refresh()
+ expect(s.store.read().state?.acct).toBe('x')
+ const adopted = s.calls.adopt.mock.calls.flatMap(([ms]) => ms.map((m: { pub: string }) => m.pub))
+ expect(adopted).toContain(evil.pub)
+ expect(adopted).not.toContain(phone.pub)
+ expect(s.syncer.suspendedKeys()).toContain(phone.pub)
+ // And again, back to the real account.
+ who.user = 'u3'
+ serve(null)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({
+ owner: 'u3', state: { acct: ACCT }, suspended: [phone.pub], pending: [phone.pub], frozen: { reason: 'fork' }, joinedSeq: 1,
+ })
+ })
+
+ it('a sign-in by hand to another account starts it fresh, and switching back restores the first', async () => {
+ const { s, who, serve } = signedIn()
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ s.backend.add(phone, 'viewer', '', 'phone')
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ owner: 'u1', pending: [phone.pub] })
+ const other = FakeBackend.of('acct-2')
+ other.add(key(7), 'machine', 'c'.repeat(32), 'theirs')
+ who.user = 'u2'
+ serve(other)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ owner: 'u2', state: { acct: 'acct-2' }, pending: [], baselineSeen: false })
+ who.user = 'u3'
+ serve(null)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ owner: 'u3', state: { acct: ACCT, head: s.backend.state.head }, pending: [phone.pub] })
+ expect(s.calls.announce).toHaveBeenCalledTimes(1)
+ })
+
+ it('an adopted sign-in (from before epochs) takes the file over but never starts one', async () => {
+ const { s, who } = signedIn()
+ await forked(s)
+ who.user = `${ADOPTED_SIGN_IN}z`
+ s.backend.fetch.mockImplementationOnce(wrongAcct)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ owner: 'u1', state: { acct: ACCT }, suspended: [phone.pub], pending: [phone.pub] })
+ await s.syncer.refresh()
+ expect(s.store.read().owner).toBe(`${ADOPTED_SIGN_IN}z`)
+ })
+
+ it('a file from before it recorded its sign-in starts over for a sign-in by hand to another account', async () => {
+ const { s, serve } = signedIn()
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ s.store.update((f) => { const { owner: _o, ...rest } = f; return { ...rest, pending: ['x'] } })
+ serve(FakeBackend.of('acct-2'))
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ owner: 'u1', state: { acct: 'acct-2' }, pending: [], frozen: null })
+ })
+
+ it('no sign-in id at hand (the daemon reading before its session got one) never starts over on an account flip', async () => {
+ const { s, who } = signedIn()
+ await forked(s)
+ s.store.update((f) => ({ ...f, frozen: null }))
+ const none = who as { user: string | null }
+ none.user = null
+ s.backend.fetch.mockImplementationOnce(wrongAcct)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({
+ owner: 'u1', state: { acct: ACCT }, suspended: [phone.pub], pending: [phone.pub], frozen: { reason: 'invalid' }, joinedSeq: 1,
+ })
+ })
+
+ it('a file from before it recorded its sign-in belongs to the current one', async () => {
+ const s = setup({ signIn: () => 'u1' })
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ s.store.update((f) => { const { owner: _o, ...rest } = f; return { ...rest, pending: ['x'] } })
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ owner: 'u1', pending: ['x'] })
+ })
+ })
+
+ it('a rebaseline during the history walk does not freeze the fresh log', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.register()
+ const alt = new FakeBackend()
+ alt.add(evil, 'viewer', '', 'evil')
+ alt.add(me, 'machine', MID_ME, 'my-mac')
+ const real = t.backend.fetch.getMockImplementation()!
+ t.backend.fetch.mockImplementation(async (since) => {
+ // The person confirms a review while this page is on its way: the file, and what the backend
+ // serves, are another list now.
+ if (since === 0) { t.store.update((f) => ({ ...f, state: alt.state })); t.backend.lie = alt.entries }
+ return real(since)
+ })
+ const h = await t.syncer.history()
+ expect(t.store.read().frozen).toBeNull()
+ expect(h.complete).toBe(false)
+ })
+
+ it('a peer tail that arrives while the first read is still open announces nothing', async () => {
+ const s = setup()
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ s.backend.add(phone, 'viewer', '', 'phone')
+ s.backend.add(evil, 'viewer', '', 'evil')
+ const real = s.backend.fetch.getMockImplementation()!
+ // The first read comes in one entry at a time; between its pages a peer hands over the rest.
+ s.backend.fetch.mockImplementationOnce(async (since) => { const g = await real(since); return g && { ...g, entries: g.entries.slice(0, 1) } })
+ s.backend.fetch.mockImplementationOnce(async (since) => {
+ s.syncer.heard(box2.pub, { head: s.backend.state.head, frozen: false, tail: s.backend.entries.slice(1) })
+ return real(since)
+ })
+ await s.syncer.refresh()
+ expect(s.calls.announce).not.toHaveBeenCalled()
+ expect(s.store.read()).toMatchObject({ joinedSeq: 3, pending: [] })
+ expect(s.store.read().joining).toBeUndefined()
+ s.backend.add(key(7), 'viewer', '', 'later')
+ await s.syncer.refresh()
+ expect(s.calls.announce).toHaveBeenCalledTimes(1)
+ })
+
+ it('a first read the backend cuts short ends the joining: what it held back is news', async () => {
+ const s = setup()
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ s.backend.add(phone, 'viewer', '', 'phone')
+ s.backend.add(evil, 'viewer', '', 'evil')
+ const real = s.backend.fetch.getMockImplementation()!
+ s.backend.fetch.mockImplementationOnce(async (since) => { const g = await real(since); return g && { ...g, entries: g.entries.slice(0, 1) } })
+ s.backend.fetch.mockImplementationOnce(async () => null)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ joinedSeq: 1, pending: [] })
+ expect(s.store.read().joining).toBeUndefined()
+ s.syncer.heard(box2.pub, { head: s.backend.state.head, frozen: false, tail: s.backend.entries.slice(1) })
+ expect(s.calls.announce.mock.calls.map(([m]) => m.pub)).toEqual([phone.pub, evil.pub])
+ expect(s.store.read()).toMatchObject({ joinedSeq: 1, pending: [phone.pub, evil.pub] })
+ })
+
+ it('"Got it" on the already-on-your-account list ends the joining', async () => {
+ const s = setup()
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ s.backend.add(evil, 'viewer', '', 'evil')
+ const real = s.backend.fetch.getMockImplementation()!
+ s.backend.fetch.mockImplementationOnce(async (since) => { const g = await real(since); return g && { ...g, entries: g.entries.slice(0, 1) } })
+ s.backend.fetch.mockImplementationOnce(async (since) => { s.syncer.dismiss({ baseline: true }); return real(since) })
+ await s.syncer.refresh()
+ expect(s.calls.announce).toHaveBeenCalledWith(expect.objectContaining({ pub: evil.pub }))
+ expect(s.store.read()).toMatchObject({ joinedSeq: 1, pending: [evil.pub], baselineSeen: true })
+ })
+
+ it('a key taken into an acknowledged already-on-your-account list shows that list again', async () => {
+ const s = setup()
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ s.backend.add(evil, 'viewer', '', 'evil')
+ const real = s.backend.fetch.getMockImplementation()!
+ s.backend.fetch.mockImplementationOnce(async (since) => { const g = await real(since); return g && { ...g, entries: g.entries.slice(0, 1) } })
+ s.backend.fetch.mockImplementationOnce(async (since) => {
+ // Acknowledged by a client that did not end the joining.
+ s.store.update((f) => ({ ...f, baselineSeen: true }))
+ return real(since)
+ })
+ await s.syncer.refresh()
+ expect(s.calls.announce).not.toHaveBeenCalled()
+ expect(s.store.read()).toMatchObject({ joinedSeq: 2, baselineSeen: false })
+ expect(s.syncer.list().baseline).toContain(evil.pub)
+ })
+
+ describe('every write path keeps the marks', () => {
+ beforeEach(async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ })
+
+ it('accept', async () => {
+ t.store.update((f) => ({ ...f, preLog: ['pre'], baselineSeen: false }))
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ expect(t.store.read()).toMatchObject({ joinedSeq: 1, preLog: ['pre'], baselineSeen: false, pending: [phone.pub] })
+ })
+
+ it('freeze', async () => {
+ t.store.update((f) => ({ ...f, preLog: ['pre'], baselineSeen: false }))
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ expect(t.store.read()).toMatchObject({ joinedSeq: 1, preLog: ['pre'], baselineSeen: false })
+ expect(t.store.read().frozen).not.toBeNull()
+ })
+
+ it('loose removals', async () => {
+ t.store.update((f) => ({ ...f, preLog: ['pre'], baselineSeen: false }))
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ t.backend.lie = null
+ const removal = t.backend.removeBy(box2.pub, me)
+ await t.syncer.refresh()
+ expect(t.store.read()).toMatchObject({ joinedSeq: 1, preLog: ['pre'], baselineSeen: false })
+ expect(t.store.read().looseRemoved).toEqual([removal])
+ expect(t.store.read().recent.map((e) => e.seq)).toEqual([1, 2])
+ })
+
+ it('rebaseline', async () => {
+ t.store.update((f) => ({ ...f, preLog: ['pre'], baselineSeen: false, suspended: [box2.pub] }))
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ await t.syncer.rebaseline(true)
+ expect(t.store.read()).toMatchObject({ joinedSeq: 1, preLog: ['pre'], baselineSeen: false, suspended: [], looseRemoved: [] })
+ expect(t.calls.resume).toHaveBeenCalledOnce()
+ })
+
+ it('register conflict', async () => {
+ const taken = setup()
+ taken.backend.add(box2, 'machine', MID_HOLDER, 'old-install')
+ await taken.syncer.refresh()
+ taken.store.update((f) => ({ ...f, preLog: ['pre'] }))
+ await taken.syncer.register()
+ expect(taken.store.read()).toMatchObject({ joinedSeq: 1, preLog: ['pre'], baselineSeen: false, conflict: { pub: box2.pub } })
+ })
+
+ it('dismiss', () => {
+ t.store.update((f) => ({ ...f, preLog: ['pre'] }))
+ t.syncer.dismiss({ pub: box2.pub })
+ expect(t.store.read()).toMatchObject({ joinedSeq: 1, preLog: ['pre'], baselineSeen: false })
+ })
+ })
+})
+
+describe('DeviceLogSyncer — removal notices', () => {
+ let t: ReturnType<typeof setup>
+ beforeEach(async () => {
+ t = setup()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.register()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ })
+
+ it('says nothing about a removal this device signed, or one before it joined', async () => {
+ t.backend.removeBy(box2.pub, me)
+ await t.syncer.refresh()
+ expect(t.calls.removed).not.toHaveBeenCalled()
+ })
+
+ it('a device that removed itself is "signed out"', async () => {
+ t.syncer.dismiss()
+ t.backend.removeBy(box2.pub, box2)
+ await t.syncer.refresh()
+ expect(t.calls.removed).toHaveBeenCalledWith(expect.objectContaining({ pub: box2.pub, label: 'box2', selfRemoved: true, signerPending: false }))
+ })
+
+ it('a removal by a device that was already trusted is a normal notice naming the signer', async () => {
+ t.syncer.dismiss()
+ t.backend.removeBy(box2.pub, phone)
+ await t.syncer.refresh()
+ expect(t.calls.removed).toHaveBeenCalledWith(expect.objectContaining({
+ pub: box2.pub, signer: phone.pub, signerLabel: 'phone', selfRemoved: false, signerPending: false, kind: 'machine',
+ }))
+ })
+
+ it('is red when the signer is itself a new device nobody looked at', async () => {
+ t.backend.removeBy(phone.pub, box2)
+ await t.syncer.refresh()
+ expect(t.calls.removed).toHaveBeenCalledWith(expect.objectContaining({ pub: phone.pub, signer: box2.pub, signerPending: true, signerLabel: 'box2' }))
+ })
+
+ it('also fires for a removal applied while frozen, and keeps it for the history', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 2)
+ await t.syncer.refresh()
+ t.backend.lie = null
+ t.backend.removeBy(phone.pub, box2)
+ await t.syncer.refresh()
+ expect(t.calls.removed).toHaveBeenCalledWith(expect.objectContaining({ pub: phone.pub, signerPending: true }))
+ expect(t.store.read().looseRemoved?.[0]).toMatchObject({ op: 'remove', pub: phone.pub })
+ })
+})
+
+describe('DeviceLogSyncer — another key holds this machine\'s id', () => {
+ it('records the conflict once (neutral when the holder predates joining), and shows it while the holder is active', async () => {
+ const t = setup()
+ t.backend.add(box2, 'machine', MID_HOLDER, 'old-install')
+ await t.syncer.register()
+ await t.syncer.register()
+ expect(t.calls.conflict).toHaveBeenCalledOnce()
+ expect(t.calls.conflict).toHaveBeenCalledWith(expect.objectContaining({ pub: box2.pub, label: 'old-install', afterJoin: false }))
+ expect(t.syncer.list().conflict).toMatchObject({ pub: box2.pub, afterJoin: false })
+ expect(t.backend.append).not.toHaveBeenCalled()
+ })
+
+ it('is afterJoin when the holder joined after this machine read the log', async () => {
+ const t = setup()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ t.backend.add(box2, 'machine', MID_HOLDER, 'new-install')
+ await t.syncer.register()
+ expect(t.calls.conflict).toHaveBeenCalledWith(expect.objectContaining({ afterJoin: true }))
+ })
+
+ it('clears when the holder is removed, and this machine registers itself', async () => {
+ const t = setup()
+ t.backend.add(box2, 'machine', MID_HOLDER, 'old-install')
+ await t.syncer.register()
+ t.backend.removeBy(box2.pub, box2)
+ await t.syncer.refresh()
+ await vi.waitFor(() => expect(t.backend.state.active[me.pub]).toBeDefined())
+ expect(t.store.read().conflict).toBeUndefined()
+ expect(t.syncer.list().conflict).toBeNull()
+ })
+})
+
+describe('DeviceLogSyncer — a fork', () => {
+ let t: ReturnType<typeof setup>
+ let other: FakeBackend
+ beforeEach(async () => {
+ t = setup()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register() // box2 (1), me (2)
+ t.backend.add(phone, 'viewer', '', 'phone') // 3: new since joining
+ await t.syncer.refresh()
+ other = new FakeBackend()
+ other.add(box2, 'machine', MID2, 'box2')
+ other.add(evil, 'viewer', '', 'evil')
+ other.add(phone, 'viewer', '', 'phone')
+ })
+
+ it('suspends only the new keys at or after the split, and tells the group syncer', () => {
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ expect(t.store.read().frozen?.reason).toBe('fork')
+ expect(t.store.read().suspended).toEqual([phone.pub])
+ expect(t.calls.suspend).toHaveBeenCalledWith([phone.pub])
+ expect(t.syncer.suspendedKeys()).toEqual([phone.pub])
+ expect(t.syncer.list().members.find((m) => m.pub === phone.pub)?.suspended).toBe(true)
+ })
+
+ it('suspends nothing without hashes, outside the window, on bad hashes', () => {
+ t.syncer.heard(box2.pub, { head: other.state.head })
+ expect(t.calls.suspend).not.toHaveBeenCalled()
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: [{ seq: 3, hash: other.state.head.hash }] }) // split not provable
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: 'junk' })
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: [{ seq: 2, hash: 'x' }, { seq: 5, hash: 'y' }] })
+ expect(t.calls.suspend).not.toHaveBeenCalled()
+ expect(t.store.read().suspended).toEqual([])
+ })
+
+ it('a rollback suspends nothing', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ expect(t.store.read().frozen?.reason).toBe('rollback')
+ expect(t.calls.suspend).not.toHaveBeenCalled()
+ })
+
+ it('rebaseline clears the suspension and trusts the log again', async () => {
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ await t.syncer.rebaseline(true)
+ expect(t.store.read().suspended).toEqual([])
+ expect(t.calls.resume).toHaveBeenCalledOnce()
+ expect(t.calls.adopt).toHaveBeenLastCalledWith(expect.arrayContaining([expect.objectContaining({ pub: phone.pub })]))
+ })
+
+ it('rebaseline lifts the suspension only after dropping what the reviewed log removed', async () => {
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ t.backend.removeBy(box2.pub, me)
+ await t.syncer.rebaseline(true)
+ expect(t.calls.drop).toHaveBeenCalledWith(box2.pub)
+ expect(t.calls.resume.mock.invocationCallOrder[0]).toBeGreaterThan(Math.max(...t.calls.drop.mock.invocationCallOrder))
+ })
+
+ it('a log already frozen on a fork still learns the split from a peer that is ahead', async () => {
+ t.backend.lie = other.entries // same length, different entry at 2: a fork the backend showed
+ await t.syncer.refresh()
+ expect(t.store.read().frozen?.reason).toBe('fork')
+ expect(t.calls.suspend).not.toHaveBeenCalled()
+ other.add(key(7), 'viewer', '', 'later')
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ expect(t.store.read().suspended).toEqual([phone.pub])
+ expect(t.calls.suspend).toHaveBeenCalledWith([phone.pub])
+ })
+
+ it('a removal signed by a suspended key does not count while frozen', async () => {
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ t.calls.drop.mockClear()
+ t.backend.removeBy(box2.pub, phone) // the suspended key tries to take out a device trusted here
+ await t.syncer.refresh()
+ expect(t.calls.drop).not.toHaveBeenCalled()
+ expect(t.calls.removed).not.toHaveBeenCalled()
+ expect(t.store.read().state?.active[box2.pub]).toBeDefined()
+ expect(t.store.read().looseRemoved ?? []).toEqual([])
+ })
+
+ it('never adopts a suspended key from the log', async () => {
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ t.calls.adopt.mockClear()
+ t.store.update((f) => ({ ...f, frozen: null }))
+ t.backend.add(evil, 'viewer', '', 'evil')
+ await t.syncer.refresh()
+ expect(t.calls.adopt.mock.calls.flat(2).some((m: { pub: string }) => m.pub === phone.pub)).toBe(false)
+ })
+})
+
+describe('devLogDivergence', () => {
+ const log = new FakeBackend()
+ log.add(box2, 'machine', MID2, 'box2')
+ log.add(phone, 'viewer', '', 'phone')
+ log.add(evil, 'viewer', '', 'evil')
+ const mine = log.state
+ const theirs = (mutate: (h: Array<{ seq: number; hash: string }>) => void) => {
+ const h = hashesOf(mine).map((x) => ({ ...x }))
+ mutate(h)
+ return { head: h.at(-1), hashes: h }
+ }
+
+ it('finds the first position that differs when the one before matches', () => {
+ expect(devLogDivergence(mine, theirs((h) => { h[1].hash = 'x'; h[2].hash = 'y' }))).toBe(2)
+ expect(devLogDivergence(mine, theirs((h) => { h[0].hash = 'x'; h[1].hash = 'y'; h[2].hash = 'z' }))).toBe(1)
+ expect(devLogDivergence(mine, theirs((h) => { h[2].hash = 'z' }))).toBe(3)
+ })
+
+ it('is null when everything matches, or the input is not usable', () => {
+ expect(devLogDivergence(mine, theirs(() => {}))).toBeNull()
+ expect(devLogDivergence(mine, null)).toBeNull()
+ expect(devLogDivergence(mine, { head: mine.head })).toBeNull()
+ expect(devLogDivergence(mine, { head: mine.head, hashes: [{ seq: 1 }] })).toBeNull()
+ expect(devLogDivergence(mine, { head: { seq: 3, hash: 'other' }, hashes: hashesOf(mine) })).toBeNull()
+ })
+
+ it('is null when the window starts at the split (not provable)', () => {
+ const h = hashesOf(mine).slice(1).map((x, i) => (i === 0 ? { ...x, hash: 'x' } : x))
+ expect(devLogDivergence(mine, { head: h.at(-1), hashes: h })).toBeNull()
+ })
+})
+
+describe('DeviceLogSyncer — history', () => {
+ let t: ReturnType<typeof setup>
+ beforeEach(async () => {
+ t = setup()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ t.backend.add(evil, 'viewer', '', 'evil')
+ await t.syncer.refresh()
+ })
+
+ it('lists every entry newest first, with who removed what', async () => {
+ t.backend.removeBy(evil.pub, phone)
+ t.backend.removeBy(phone.pub, phone)
+ const h = await t.syncer.history()
+ expect(h.complete).toBe(true)
+ expect(h.rows.map((r) => [r.seq, r.op])).toEqual([[6, 'signedOut'], [5, 'removed'], [4, 'added'], [3, 'added'], [2, 'added'], [1, 'added']])
+ expect(h.rows[1]).toMatchObject({ pub: evil.pub, label: 'evil', by: { pub: phone.pub, label: 'phone' }, active: false })
+ expect(h.rows.find((r) => r.pub === me.pub)).toMatchObject({ thisDevice: true, afterJoin: true })
+ expect(h.rows.find((r) => r.pub === box2.pub)).toMatchObject({ afterJoin: false, active: true })
+ expect(h.rows.find((r) => r.pub === phone.pub)).toMatchObject({ afterJoin: true })
+ })
+
+ it('shows a rename, and marks pending devices', async () => {
+ const renamed = signDevLogEntry(nextDevLogEntry(t.backend.state, { op: 'add', pub: phone.pub, kind: 'viewer', machineId: '', label: 'pixel', signer: phone.pub }, 3_000), phone.priv)
+ t.backend.entries.push(renamed)
+ t.backend.state = applyDevLogEntries(t.backend.state, [renamed]).state
+ const h = await t.syncer.history()
+ expect(h.rows[0]).toMatchObject({ op: 'renamed', label: 'pixel', previousLabel: 'phone' })
+ expect(h.rows.find((r) => r.op === 'added' && r.pub === phone.pub)?.pending).toBe(true)
+ })
+
+ it('a second call fetches only what is missing', async () => {
+ await t.syncer.history()
+ t.backend.fetch.mockClear()
+ t.backend.add(key(7), 'viewer', '', 'late')
+ await t.syncer.history()
+ const since = t.backend.fetch.mock.calls.map(([s]) => s)
+ expect(since).toEqual([4, 4]) // the refresh, then the one missing entry — never from 0
+ })
+
+ it('freezes when the backend serves a different entry at a verified position', async () => {
+ const forged = new FakeBackend()
+ forged.add(box2, 'machine', MID2, 'box2')
+ forged.add(me, 'machine', MID_ME, 'my-mac', 9_999) // not what this machine verified at 2
+ t.backend.lie = null
+ const real = t.backend.fetch.getMockImplementation()!
+ t.backend.fetch.mockImplementation(async (since) => {
+ const got = await real(since)
+ return got && since < 2 ? { ...got, entries: got.entries.map((e) => ((e as DevLogEntry).seq === 2 ? forged.entries[1] : e)) } : got
+ })
+ const fresh = setup({ store: t.store, backend: t.backend })
+ const h = await fresh.syncer.history()
+ expect(h.complete).toBe(false)
+ expect(t.store.read().frozen?.reason).toBe('fork')
+ })
+
+ it('offline: what is kept locally, not complete', async () => {
+ t.backend.offline = true
+ const fresh = setup({ store: t.store, backend: t.backend })
+ const h = await fresh.syncer.history()
+ expect(h.complete).toBe(false)
+ expect(h.rows.map((r) => r.seq)).toEqual([4, 3, 2, 1])
+ })
+
+ it('removals applied while frozen carry whileFrozen', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 2)
+ await t.syncer.refresh()
+ t.backend.lie = null
+ t.backend.removeBy(evil.pub, phone)
+ await t.syncer.refresh()
+ const h = await t.syncer.history()
+ expect(h.rows.find((r) => r.op === 'removed')).toMatchObject({ whileFrozen: true, pub: evil.pub })
+ })
+})
+
+describe('DeviceLogSyncer — what the backend cannot bend', () => {
+ let t: ReturnType<typeof setup>
+ beforeEach(() => { t = setup() })
+
+ /** A first page whose head claims far more than the entries it carries. */
+ function inflateFirstPage(claim: number): void {
+ const real = t.backend.fetch.getMockImplementation()!
+ let first = true
+ t.backend.fetch.mockImplementation(async (since) => {
+ const got = await real(since)
+ if (!got || !first) return got
+ first = false
+ return { ...got, head: { seq: claim, hash: 'x'.repeat(64) } }
+ })
+ }
+
+ it('the joined point is the VERIFIED head, never the one the backend claims', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.add(phone, 'viewer', '', 'phone')
+ inflateFirstPage(1000)
+ await t.syncer.refresh()
+ expect(t.store.read().frozen).toBeNull()
+ expect(t.store.read().joinedSeq).toBe(2)
+ // A key forged below the claimed 1000 is still new.
+ t.backend.add(evil, 'viewer', '', 'evil')
+ await t.syncer.refresh()
+ expect(t.calls.announce).toHaveBeenCalledWith(expect.objectContaining({ pub: evil.pub }))
+ expect(t.store.read().pending).toEqual([evil.pub])
+ })
+
+ it('a head that is not a position is not read at all', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ for (const seq of [1.5, -1, Number.NaN, 2 ** 60]) {
+ const real = t.backend.fetch.getMockImplementation()!
+ t.backend.fetch.mockImplementationOnce(async (since) => {
+ const got = await real(since)
+ return got && { ...got, head: { seq, hash: 'h' } }
+ })
+ await t.syncer.refresh()
+ expect(t.store.read().state).toBeNull()
+ }
+ })
+
+ it('a first read cut short is verified as far as it went (nothing beyond it hides)', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.add(phone, 'viewer', '', 'phone')
+ const real = t.backend.fetch.getMockImplementation()!
+ let calls = 0
+ t.backend.fetch.mockImplementation(async (since) => {
+ const got = await real(since)
+ if (!got) return got
+ calls++
+ return calls === 1 ? { ...got, entries: got.entries.slice(0, 1) } : got
+ })
+ // The page is short; the run goes on reading from where it verified, still as the join.
+ await t.syncer.refresh()
+ expect(t.store.read().joinedSeq).toBe(2)
+ expect(t.calls.announce).not.toHaveBeenCalled()
+ })
+
+ describe('rebaseline(confirm)', () => {
+ beforeEach(async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh() // frozen (rolled back)
+ t.backend.lie = null
+ })
+
+ it('a key the preview did not show is pending and announced', async () => {
+ const preview = await t.syncer.rebaseline(false) as { head: { seq: number; hash: string } }
+ t.backend.add(evil, 'viewer', '', 'evil') // the backend adds it between preview and confirm
+ const done = await t.syncer.rebaseline(true)
+ expect(done).not.toBeNull()
+ expect(t.store.read().pending).toEqual([evil.pub])
+ expect(t.calls.announce).toHaveBeenCalledWith(expect.objectContaining({ pub: evil.pub }))
+ expect(preview.head.seq).toBeLessThan(t.backend.state.head.seq)
+ })
+
+ it('refuses when the backend head is no longer the one previewed', async () => {
+ const preview = await t.syncer.rebaseline(false) as { head: { seq: number; hash: string } }
+ t.backend.add(evil, 'viewer', '', 'evil')
+ expect(await t.syncer.rebaseline(true, preview.head)).toEqual({ error: 'LOG_CHANGED' })
+ expect(t.store.read().frozen).not.toBeNull()
+ expect(t.store.read().state?.active[evil.pub]).toBeUndefined()
+ expect(t.calls.announce).not.toHaveBeenCalled()
+ const again = await t.syncer.rebaseline(false) as { head: { seq: number; hash: string } }
+ expect(await t.syncer.rebaseline(true, again.head)).toMatchObject({ head: t.backend.state.head })
+ expect(t.store.read().frozen).toBeNull()
+ })
+ })
+
+ describe('a fork does not cost the user the devices they reviewed', () => {
+ let other: FakeBackend
+ beforeEach(async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(phone, 'viewer', '', 'phone') // 3: new since joining, pending
+ await t.syncer.refresh()
+ other = new FakeBackend()
+ other.add(box2, 'machine', MID2, 'box2')
+ other.add(evil, 'viewer', '', 'evil')
+ other.add(phone, 'viewer', '', 'phone')
+ })
+
+ it('a key already marked as seen is not suspended', () => {
+ t.syncer.dismiss({ pubs: [phone.pub] })
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ expect(t.store.read().frozen?.reason).toBe('fork')
+ expect(t.store.read().suspended).toEqual([])
+ expect(t.calls.suspend).not.toHaveBeenCalled()
+ })
+
+ it('a key let in by a review (rebaseline --yes) is not suspended', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ t.backend.lie = null
+ await t.syncer.rebaseline(true)
+ expect(t.store.read().pending).toContain(phone.pub)
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ expect(t.store.read().suspended).toEqual([])
+ })
+
+ it('a key added after the fork was proven is still suspended when it is new here', () => {
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ expect(t.store.read().suspended).toEqual([phone.pub])
+ })
+
+ it('"It\'s mine" on a suspended key lifts its suspension here; a list that was merely viewed does not', () => {
+ t.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ t.syncer.dismiss({ pubs: [phone.pub] })
+ expect(t.store.read().suspended).toEqual([phone.pub])
+ expect(t.store.read().pending).toEqual([phone.pub]) // still flagged
+ t.calls.resume.mockClear()
+ t.calls.adopt.mockClear()
+ t.syncer.dismiss({ pub: phone.pub })
+ expect(t.store.read()).toMatchObject({ suspended: [], pending: [] })
+ expect(t.calls.resume).toHaveBeenCalledOnce()
+ expect(t.calls.adopt).toHaveBeenCalledWith([expect.objectContaining({ pub: phone.pub })])
+ })
+ })
+
+ it('two history() calls at once share one walk and freeze nothing', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ t.backend.add(evil, 'viewer', '', 'evil')
+ await t.syncer.refresh()
+ const fresh = setup({ store: t.store, backend: t.backend })
+ const [a, b] = await Promise.all([fresh.syncer.history(), fresh.syncer.history()])
+ expect(t.store.read().frozen).toBeNull()
+ expect(a.complete).toBe(true)
+ expect(b.rows.map((r) => r.seq)).toEqual([4, 3, 2, 1])
+ })
+
+ it('a second history() while one is walking joins it instead of walking again', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ const once = setup({ store: t.store, backend: t.backend })
+ t.backend.fetch.mockClear()
+ await once.syncer.history()
+ const single = t.backend.fetch.mock.calls.length
+ const twice = setup({ store: t.store, backend: t.backend })
+ t.backend.fetch.mockClear()
+ const [a, b] = await Promise.all([twice.syncer.history(), twice.syncer.history()])
+ expect(t.backend.fetch.mock.calls.length).toBe(single)
+ expect(a).toBe(b)
+ expect(t.store.read().frozen).toBeNull()
+ })
+
+ it('dismiss with a list clears only what it names (a key accepted since the window read stays pending)', async () => {
+ await t.syncer.register()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ t.syncer.dismiss({ pubs: [box2.pub] })
+ expect(t.store.read().pending).toEqual([phone.pub])
+ })
+
+ it('keys this machine trusted at joining, whose entry came after the joined point, are in the baseline', async () => {
+ t = setup({ known: [box2.pub] })
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ t.backend.add(box2, 'machine', MID2, 'box2') // seq 2 > joinedSeq 1, but trusted before joining
+ await t.syncer.refresh()
+ expect(t.syncer.list().baseline.sort()).toEqual([box2.pub, phone.pub].sort())
+ expect(t.syncer.list().pending).toEqual([])
+ })
+
+ it('a removal is described by the label and kind the key had, not the remove entry\'s own', async () => {
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.register()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ t.syncer.dismiss()
+ const lie = signDevLogEntry(nextDevLogEntry(t.backend.state, {
+ op: 'remove', pub: box2.pub, kind: 'viewer', machineId: '', label: 'Totally Fine', signer: phone.pub,
+ }, 2_000), phone.priv)
+ t.backend.entries.push(lie)
+ t.backend.state = applyDevLogEntries(t.backend.state, [lie]).state
+ await t.syncer.refresh()
+ expect(t.calls.removed).toHaveBeenCalledWith(expect.objectContaining({ pub: box2.pub, label: 'box2', kind: 'machine' }))
+ const h = await t.syncer.history()
+ expect(h.rows[0]).toMatchObject({ op: 'removed', pub: box2.pub, label: 'box2', kind: 'machine' })
+ })
+})
+
+describe('DeviceLogSyncer — departed keys, sign-ins and kept accounts', () => {
+ describe('a new key that leaves before anyone looked stays flagged', () => {
+ let t: ReturnType<typeof setup>
+ beforeEach(async () => {
+ t = setup()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register() // box2 (1), me (2)
+ t.backend.add(evil, 'viewer', '', 'evil') // 3: new, pending
+ await t.syncer.refresh()
+ })
+ const departedPubs = (s: ReturnType<typeof setup>): string[] => s.syncer.list().departed.map((d) => d.pub)
+
+ it('removed by itself: departed survives a restart, keeps its history row new, and goes on dismiss', async () => {
+ t.backend.removeBy(evil.pub, evil)
+ await t.syncer.refresh()
+ expect(t.syncer.list().pending).toEqual([])
+ expect(t.syncer.list().departed).toEqual([expect.objectContaining({
+ pub: evil.pub, label: 'evil', kind: 'viewer', addedAt: 1_000, removedAt: 2_000, removedBy: evil.pub, selfRemoved: true,
+ })])
+ // A new daemon (or `harness devices`) over the same file.
+ const again = setup({ store: t.store, backend: t.backend })
+ expect(departedPubs(again)).toEqual([evil.pub])
+ const h = await again.syncer.history()
+ expect(h.rows.filter((r) => r.pub === evil.pub).map((r) => [r.op, r.pending])).toEqual([['signedOut', true], ['added', true]])
+ again.syncer.dismiss({ pub: evil.pub })
+ expect(departedPubs(again)).toEqual([])
+ expect((await again.syncer.history()).rows.some((r) => r.pending)).toBe(false)
+ })
+
+ it('removed by another key: says by whom', async () => {
+ t.backend.removeBy(evil.pub, box2)
+ await t.syncer.refresh()
+ expect(t.syncer.list().departed).toEqual([expect.objectContaining({
+ pub: evil.pub, removedBy: box2.pub, removedByLabel: 'box2', selfRemoved: false,
+ })])
+ })
+
+ it('added and removed within one page: announced, and departed', async () => {
+ t.backend.add(phone, 'viewer', '', 'phone')
+ t.backend.removeBy(phone.pub, phone)
+ await t.syncer.refresh()
+ expect(t.calls.announce).toHaveBeenCalledWith(expect.objectContaining({ pub: phone.pub }))
+ expect(departedPubs(t)).toEqual([phone.pub])
+ })
+
+ it('removed while the list is frozen: departed too', async () => {
+ t.store.update((f) => ({ ...f, frozen: { reason: 'fork', at: 1, lastGoodHead: f.state!.head } }))
+ t.backend.removeBy(evil.pub, box2)
+ await t.syncer.refresh()
+ expect(t.store.read().looseRemoved).toHaveLength(1)
+ expect(departedPubs(t)).toEqual([evil.pub])
+ })
+
+ it('a key already marked as seen is not departed', async () => {
+ t.syncer.dismiss({ pub: evil.pub })
+ t.backend.removeBy(evil.pub, evil)
+ await t.syncer.refresh()
+ expect(departedPubs(t)).toEqual([])
+ })
+
+ it('clears for its own pub, a list naming it, or every one — never for the baseline or another key', async () => {
+ t.backend.removeBy(evil.pub, evil)
+ await t.syncer.refresh()
+ t.syncer.dismiss({ baseline: true })
+ t.syncer.dismiss({ pubs: [box2.pub] })
+ t.syncer.dismiss({ pub: box2.pub })
+ expect(departedPubs(t)).toEqual([evil.pub])
+ t.syncer.dismiss({ pubs: [evil.pub] })
+ expect(departedPubs(t)).toEqual([])
+ t.store.update((f) => ({ ...f, departed: [depOf(evil.pub)] }))
+ t.syncer.dismiss()
+ expect(departedPubs(t)).toEqual([])
+ })
+
+ it('kept newest first-in-last-out up to the cap', async () => {
+ for (let i = 10; i < 10 + 33; i++) {
+ const k = key(i)
+ t.backend.add(k, 'viewer', '', `k${i}`)
+ t.backend.removeBy(k.pub, k)
+ }
+ await t.syncer.refresh()
+ const d = t.syncer.list().departed
+ expect(d).toHaveLength(32)
+ expect(d.at(-1)?.label).toBe('k42')
+ expect(d[0].label).toBe('k11')
+ })
+ })
+
+ const depOf = (pub: string) => ({
+ pub, label: 'x', kind: 'viewer' as const, machineId: '', fingerprint: 'F', addedAt: 1, removedAt: 2, removedBy: pub, removedByLabel: '', selfRemoved: true,
+ })
+
+ describe('a sign-in by hand starts the log over only shortly after it was made', () => {
+ it('one made over 10 minutes ago, with no read of its account yet, only freezes', async () => {
+ const who = { user: 'u1' }
+ const s = setup({ signIn: () => who.user, signInAt: 5_000 - 11 * 60_000 })
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ s.backend.add(phone, 'viewer', '', 'phone')
+ await s.syncer.refresh()
+ who.user = 'u2'
+ s.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ state: { acct: ACCT }, pending: [phone.pub], frozen: { reason: 'invalid' } })
+ expect(s.store.archivedSuspended()).toEqual([])
+ })
+
+ it('one with no time recorded only freezes', async () => {
+ const who = { user: 'u1' }
+ const s = setup({ signIn: () => who.user, signInAt: null })
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ who.user = 'u2'
+ s.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ state: { acct: ACCT }, frozen: { reason: 'invalid' } })
+ })
+
+ it('one made just now starts it over', async () => {
+ const who = { user: 'u1' }
+ const s = setup({ signIn: () => who.user, signInAt: 5_000 - 9 * 60_000 })
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ who.user = 'u2'
+ s.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ state: { acct: 'acct-2' }, frozen: null, owner: 'u2' })
+ })
+ })
+
+ describe('gossip waits for the new sign-in\'s first read', () => {
+ it('neither judges nor says anything while the file is not this sign-in\'s', async () => {
+ const who = { user: 'u1' }
+ const s = setup({ signIn: () => who.user })
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ const other = FakeBackend.of(ACCT)
+ other.add(evil, 'viewer', '', 'evil')
+ other.add(phone, 'viewer', '', 'phone') // another entry at the same position: a fork
+ who.user = 'u2'
+ expect(s.syncer.gossip()).toBeUndefined()
+ expect(s.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state), tail: other.entries })).toBeUndefined()
+ expect(s.store.read().frozen).toBeNull()
+ expect(s.store.read().state?.head).toEqual(s.backend.state.head)
+ await s.syncer.refresh() // same account: the file is this sign-in's now
+ expect(s.syncer.gossip()).toBeDefined()
+ s.syncer.heard(box2.pub, { head: other.state.head, hashes: hashesOf(other.state) })
+ expect(s.store.read().frozen?.reason).toBe('fork')
+ })
+ })
+
+ describe('a suspension kept in another account\'s log shows, and lifts, in this one', () => {
+ /** Signed in to ACCT, where a fork suspended evil; then signed in by hand to acct-2, whose log has evil. */
+ const moved = async () => {
+ const who = { user: 'u1' }
+ const s = setup({ signIn: () => who.user })
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ s.backend.add(evil, 'viewer', '', 'evil')
+ await s.syncer.refresh()
+ s.store.update((f) => ({ ...f, suspended: [evil.pub] }))
+ const b = FakeBackend.of('acct-2')
+ b.add(phone, 'viewer', '', 'phone')
+ b.add(evil, 'viewer', '', 'evil')
+ who.user = 'u2'
+ s.backend.fetch.mockImplementation(b.fetch)
+ s.calls.adopt.mockClear()
+ await s.syncer.refresh()
+ return { s, who, b }
+ }
+
+ it('is suspended and new in the list, never adopted', async () => {
+ const { s } = await moved()
+ expect(s.store.read().state?.acct).toBe('acct-2')
+ expect(s.syncer.list().members.find((m) => m.pub === evil.pub)).toMatchObject({ suspended: true, pending: true })
+ expect(s.calls.adopt.mock.calls.flat(2).some((m: { pub: string }) => m.pub === evil.pub)).toBe(false)
+ })
+
+ it('"It\'s mine" lifts it here and in the kept log', async () => {
+ const { s } = await moved()
+ s.syncer.dismiss({ pub: evil.pub })
+ expect(s.syncer.suspendedKeys()).not.toContain(evil.pub)
+ expect(s.store.archivedSuspended()).not.toContain(evil.pub)
+ expect(s.calls.adopt).toHaveBeenLastCalledWith([expect.objectContaining({ pub: evil.pub })])
+ })
+
+ it('a review does not lift it (it never showed it as suspended): only "It\'s mine" does', async () => {
+ const { s } = await moved()
+ await s.syncer.rebaseline(true)
+ expect(s.syncer.suspendedKeys()).toContain(evil.pub)
+ expect(s.store.archivedSuspended()).toContain(evil.pub)
+ expect(s.syncer.list().members.find((m) => m.pub === evil.pub)).toMatchObject({ suspended: true, pending: true })
+ expect(s.calls.adopt.mock.calls.flat(2).some((m: { pub: string }) => m.pub === evil.pub)).toBe(false)
+ })
+
+ })
+
+ it('a kept log restored is suspended where another kept log says so', async () => {
+ const who = { user: 'u1' }
+ const s = setup({ signIn: () => who.user })
+ const real = s.backend.fetch.getMockImplementation()!
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ s.backend.add(phone, 'viewer', '', 'phone')
+ await s.syncer.refresh()
+ s.syncer.dismiss({ pub: phone.pub })
+ const b = FakeBackend.of('acct-2')
+ b.add(phone, 'viewer', '', 'phone')
+ who.user = 'u2'
+ s.backend.fetch.mockImplementation(b.fetch)
+ await s.syncer.refresh()
+ // A fork in acct-2 suspended phone; then back to ACCT, where phone is on the list.
+ s.store.update((f) => ({ ...f, suspended: [phone.pub] }))
+ who.user = 'u3'
+ s.backend.fetch.mockImplementation(real)
+ await s.syncer.refresh()
+ expect(s.store.read().state?.acct).toBe(ACCT)
+ expect(s.syncer.list().members.find((m) => m.pub === phone.pub)).toMatchObject({ suspended: true, pending: true })
+ })
+
+ it('a review of another account\'s list after a sign-in keeps the one it leaves', async () => {
+ const who = { user: 'u1' }
+ // Made long ago: the new account's list freezes instead of starting over.
+ const t = setup({ signIn: () => who.user, signInAt: 5_000 - 11 * 60_000 })
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.store.update((f) => ({ ...f, suspended: ['k'] }))
+ who.user = 'u2'
+ t.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)
+ await t.syncer.refresh()
+ expect(t.store.read()).toMatchObject({ state: { acct: ACCT }, frozen: { reason: 'invalid' } })
+ await t.syncer.rebaseline(true)
+ expect(t.store.read()).toMatchObject({ state: { acct: 'acct-2' }, frozen: null, owner: 'u2' })
+ expect(t.store.archivedSuspended()).toEqual(['k'])
+ })
+
+ describe('another account\'s list under the sign-in the live log belongs to', () => {
+ /** Signed in to ACCT, a new key K pending; the backend then serves an empty "acct-2" under the same sign-in. */
+ const switched = async (signIn: boolean) => {
+ const t = setup(signIn ? { signIn: () => 'u1' } : {})
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(evil, 'viewer', '', 'K')
+ await t.syncer.refresh()
+ expect(t.store.read().pending).toEqual([evil.pub])
+ t.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)
+ await t.syncer.refresh()
+ expect(t.store.read()).toMatchObject({ state: { acct: ACCT }, frozen: { reason: 'invalid' } })
+ t.calls.adopt.mockClear(); t.calls.drop.mockClear(); t.calls.announce.mockClear(); t.calls.changed.mockClear(); t.calls.resume.mockClear()
+ return t
+ }
+
+ for (const signIn of [true, false]) {
+ it(`refuses the preview and the confirm (OTHER_ACCOUNT), writing nothing${signIn ? '' : ' (no sign-in recorded)'}`, async () => {
+ const t = await switched(signIn)
+ const before = JSON.stringify(t.store.read())
+ expect(await t.syncer.rebaseline(false)).toEqual({ error: 'OTHER_ACCOUNT' })
+ expect(await t.syncer.rebaseline(true)).toEqual({ error: 'OTHER_ACCOUNT' })
+ expect(await t.syncer.rebaseline(true, FakeBackend.of('acct-2').state.head)).toEqual({ error: 'OTHER_ACCOUNT' })
+ // Said before LOG_CHANGED: a confirm on another head is still about another account.
+ expect(await t.syncer.rebaseline(true, { seq: 99, hash: 'x' })).toEqual({ error: 'OTHER_ACCOUNT' })
+ expect(JSON.stringify(t.store.read())).toBe(before)
+ expect(t.store.archivedFile(ACCT)).toBeNull()
+ expect(t.store.archivedFile('acct-2')).toBeNull()
+ expect(t.syncer.list().pending).toEqual([evil.pub])
+ for (const c of [t.calls.adopt, t.calls.drop, t.calls.announce, t.calls.changed, t.calls.resume]) expect(c).not.toHaveBeenCalled()
+ })
+ }
+
+ it('a file stamped by a sign-in, then this machine taken over by an adopted one: neither goes ahead', async () => {
+ const who = { user: 'u1' }
+ const t = setup({ signIn: () => who.user })
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(evil, 'viewer', '', 'K')
+ await t.syncer.refresh()
+ t.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)
+ await t.syncer.refresh()
+ expect(t.store.read()).toMatchObject({ state: { acct: ACCT }, frozen: { reason: 'invalid' }, owner: 'u1', pending: [evil.pub] })
+ who.user = `${ADOPTED_SIGN_IN}x` // an older binary refreshed the token: the sign-in by hand is gone
+ const before = JSON.stringify(t.store.read())
+ expect(await t.syncer.rebaseline(false)).toEqual({ error: 'OTHER_ACCOUNT' })
+ expect(await t.syncer.rebaseline(true)).toEqual({ error: 'OTHER_ACCOUNT' })
+ expect(JSON.stringify(t.store.read())).toBe(before)
+ expect(t.store.archivedFile(ACCT)).toBeNull()
+ expect(t.store.archivedFile('acct-2')).toBeNull()
+ })
+
+ /** A file no sign-in stamped yet (written before sign-ins were recorded, or by an older version after
+ * a downgrade) on ACCT with K pending; then the backend serves an empty "acct-2" under `epoch`. */
+ const unstamped = async (epoch: string) => {
+ const t = setup({ signIn: () => epoch, signInAt: 5_000 - 11 * 60_000 })
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(evil, 'viewer', '', 'K')
+ await t.syncer.refresh()
+ t.store.update((f) => { const { owner: _o, ...rest } = f; return rest })
+ t.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)
+ await t.syncer.refresh()
+ expect(t.store.read()).toMatchObject({ state: { acct: ACCT }, frozen: { reason: 'invalid' }, pending: [evil.pub] })
+ expect(t.store.read().owner).toBeUndefined()
+ return t
+ }
+
+ it('an unstamped file under an adopted sign-in (the session it was written under) refuses too', async () => {
+ const t = await unstamped(`${ADOPTED_SIGN_IN}a`)
+ const before = JSON.stringify(t.store.read())
+ expect(await t.syncer.rebaseline(false)).toEqual({ error: 'OTHER_ACCOUNT' })
+ expect(await t.syncer.rebaseline(true)).toEqual({ error: 'OTHER_ACCOUNT' })
+ expect(JSON.stringify(t.store.read())).toBe(before)
+ expect(t.store.archivedFile(ACCT)).toBeNull()
+ })
+
+ it('an unstamped file under a sign-in by hand is that sign-in moving accounts: the review goes ahead', async () => {
+ const t = await unstamped('u2')
+ expect(await t.syncer.rebaseline(true)).not.toHaveProperty('error')
+ expect(t.store.read()).toMatchObject({ state: { acct: 'acct-2' }, frozen: null, owner: 'u2' })
+ expect(t.store.archivedFile(ACCT)?.pending).toEqual([evil.pub])
+ })
+ })
+})
+
+describe('DeviceLogSyncer — a review (rebaseline --yes)', () => {
+ const k5 = key(5), k6 = key(6), k7 = key(7)
+ let t: ReturnType<typeof setup>
+
+ it('after a sign-in to another account it froze on, a key added below the old joined point is news', async () => {
+ const who = { user: 'u1' }
+ // Every sign-in here was made long ago: the backend held the new account's log back past the window.
+ const s = setup({ signIn: () => who.user, signInAt: 5_000 - 11 * 60_000 })
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ s.backend.add(phone, 'viewer', '', 'phone')
+ s.backend.add(k5, 'viewer', '', 'k5')
+ s.backend.add(k6, 'viewer', '', 'k6')
+ await s.syncer.refresh()
+ expect(s.store.read().joinedSeq).toBe(4)
+ const b = FakeBackend.of('acct-2')
+ b.add(k7, 'viewer', '', 'k7')
+ who.user = 'u2'
+ s.backend.fetch.mockImplementation(b.fetch)
+ await s.syncer.refresh()
+ expect(s.store.read().frozen?.reason).toBe('invalid')
+ await s.syncer.rebaseline(true) // "Trust again"
+ expect(s.store.read()).toMatchObject({ state: { acct: 'acct-2' }, frozen: null, joinedSeq: 0 })
+ s.calls.announce.mockClear()
+ b.add(evil, 'viewer', '', 'evil') // seq 2: below the old account's joined point
+ await s.syncer.refresh()
+ expect(s.calls.announce).toHaveBeenCalledWith(expect.objectContaining({ pub: evil.pub }))
+ expect(s.store.read().pending).toContain(evil.pub)
+ expect(s.syncer.list().baseline).not.toContain(evil.pub)
+ })
+
+ it('after a rollback 4 → 1 it was reviewed on, a key added at 2 is news', async () => {
+ t = setup()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.add(phone, 'viewer', '', 'phone')
+ t.backend.add(k5, 'viewer', '', 'k5')
+ t.backend.add(k6, 'viewer', '', 'k6')
+ await t.syncer.refresh()
+ expect(t.store.read().joinedSeq).toBe(4)
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ expect(t.store.read().frozen?.reason).toBe('rollback')
+ const preview = await t.syncer.rebaseline(false) as DeviceLogRebaseline
+ expect(preview.added).toEqual([])
+ await t.syncer.rebaseline(true, preview.head)
+ expect(t.store.read()).toMatchObject({ frozen: null, joinedSeq: 1 })
+ const rolled = new FakeBackend()
+ rolled.add(box2, 'machine', MID2, 'box2') // the same entry 1
+ rolled.add(evil, 'viewer', '', 'evil')
+ t.backend.lie = null
+ t.backend.fetch.mockImplementation(rolled.fetch)
+ await t.syncer.refresh()
+ expect(t.calls.announce).toHaveBeenCalledWith(expect.objectContaining({ pub: evil.pub }))
+ expect(t.store.read().pending).toEqual([evil.pub])
+ })
+
+ describe('back to an account this machine kept the log of', () => {
+ /** ACCT: phone new and pending, evil suspended by a fork, k7 joined and left before anyone looked;
+ * then a review after a sign-in to acct-2; then the backend serves ACCT again. Every sign-in was made
+ * long ago, so a list of another account freezes rather than starts over. */
+ const away = async () => {
+ const who = { user: 'u1' }
+ const s = setup({ signIn: () => who.user, signInAt: 5_000 - 11 * 60_000 })
+ const real = s.backend.fetch.getMockImplementation()!
+ s.backend.add(box2, 'machine', MID2, 'box2')
+ await s.syncer.register()
+ s.backend.add(phone, 'viewer', '', 'phone')
+ s.backend.add(evil, 'viewer', '', 'evil')
+ s.backend.add(k7, 'viewer', '', 'k7')
+ s.backend.removeBy(k7.pub, box2)
+ await s.syncer.refresh()
+ s.store.update((f) => ({ ...f, suspended: [evil.pub] }))
+ const b = FakeBackend.of('acct-2')
+ b.add(k5, 'viewer', '', 'k5')
+ who.user = 'u2'
+ s.backend.fetch.mockImplementation(b.fetch)
+ await s.syncer.refresh()
+ expect(await s.syncer.rebaseline(true)).not.toHaveProperty('error')
+ expect(s.store.read()).toMatchObject({ state: { acct: 'acct-2' }, frozen: null, owner: 'u2' })
+ s.backend.fetch.mockImplementation(real) // the backend says ACCT
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ state: { acct: 'acct-2' }, frozen: { reason: 'invalid' } })
+ s.calls.announce.mockClear()
+ s.calls.adopt.mockClear()
+ return { s, who }
+ }
+
+ /** …and signed in again (by hand) — the only way back to ACCT. */
+ const back = async () => {
+ const { s, who } = await away()
+ who.user = 'u3'
+ await s.syncer.refresh()
+ expect(s.store.read()).toMatchObject({ state: { acct: 'acct-2' }, frozen: { reason: 'invalid' } })
+ return s
+ }
+
+ it('without a sign-in, neither the preview nor "Trust again" goes back to it', async () => {
+ const { s } = await away()
+ const before = JSON.stringify(s.store.read())
+ expect(await s.syncer.rebaseline(false)).toEqual({ error: 'OTHER_ACCOUNT' })
+ expect(await s.syncer.rebaseline(true)).toEqual({ error: 'OTHER_ACCOUNT' })
+ expect(JSON.stringify(s.store.read())).toBe(before)
+ expect(s.store.archivedFile(ACCT)?.pending).toEqual(expect.arrayContaining([phone.pub, evil.pub]))
+ expect(s.calls.adopt).not.toHaveBeenCalled()
+ })
+
+ it('the preview compares against the kept log, not the account being left', async () => {
+ const s = await back()
+ const preview = await s.syncer.rebaseline(false) as DeviceLogRebaseline
+ expect(preview.added).toEqual([])
+ expect(preview.removed).toEqual([])
+ })
+
+ it('"Trust again" goes on from its marks: pending, departed, suspended, nothing re-announced', async () => {
+ const s = await back()
+ await s.syncer.rebaseline(true)
+ const f = s.store.read()
+ expect(f).toMatchObject({ state: { acct: ACCT }, frozen: null, owner: 'u3' })
+ expect(f.pending).toEqual(expect.arrayContaining([phone.pub, evil.pub]))
+ expect(f.suspended).toEqual([evil.pub])
+ expect(f.departed?.map((d) => d.pub)).toEqual([k7.pub])
+ expect(s.syncer.list().members.find((m) => m.pub === phone.pub)).toMatchObject({ pending: true, suspended: false })
+ expect(s.syncer.list().members.find((m) => m.pub === evil.pub)).toMatchObject({ pending: true, suspended: true })
+ expect(s.syncer.suspendedKeys()).toContain(evil.pub)
+ expect(s.calls.announce).not.toHaveBeenCalled()
+ expect(s.calls.adopt.mock.calls.flat(2).some((m: { pub: string }) => m.pub === evil.pub)).toBe(false)
+ // Taken out of the archive; the account left is kept there instead.
+ expect(s.store.archivedFile(ACCT)).toBeNull()
+ expect(s.store.archivedFile('acct-2')?.state?.active[k5.pub]).toBeDefined()
+ })
+
+ it('goes on from its marks even when keeping the account left pushes it out of the archive', async () => {
+ const s = await back()
+ const live = s.store.read()
+ for (const acct of ['x1', 'x2', 'x3']) s.store.archive({ ...live, state: { ...live.state!, acct } })
+ await s.syncer.rebaseline(true)
+ const f = s.store.read()
+ expect(f.state?.acct).toBe(ACCT)
+ expect(s.store.archivedFile(ACCT)).toBeNull()
+ expect(f.suspended).toEqual([evil.pub])
+ expect(f.pending).toEqual(expect.arrayContaining([phone.pub, evil.pub]))
+ expect(f.departed?.map((d) => d.pub)).toEqual([k7.pub])
+ expect(s.calls.announce).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('what the reviewed list took out', () => {
+ beforeEach(async () => {
+ t = setup()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.add(k5, 'viewer', '', 'k5')
+ await t.syncer.register()
+ t.backend.add(phone, 'viewer', '', 'phone') // 4: new, pending
+ await t.syncer.refresh()
+ expect(t.store.read().pending).toEqual([phone.pub])
+ })
+
+ it('a pending key the reviewed list does not have stays flagged as departed', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 3)
+ await t.syncer.refresh()
+ expect(t.store.read().frozen?.reason).toBe('rollback')
+ await t.syncer.rebaseline(true)
+ expect(t.store.read().pending).toEqual([])
+ expect(t.store.read().departed).toEqual([expect.objectContaining({ pub: phone.pub, label: 'phone', removedBy: '', selfRemoved: false })])
+ })
+
+ it('a pending key removed while frozen is departed, with who removed it', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 3)
+ await t.syncer.refresh()
+ t.backend.lie = null
+ t.backend.removeBy(phone.pub, box2)
+ await t.syncer.rebaseline(true)
+ expect(t.store.read().departed).toEqual([expect.objectContaining({ pub: phone.pub, removedBy: box2.pub, removedByLabel: 'box2' })])
+ })
+
+ it('a key added and removed while frozen is departed; a reviewed-out key nobody flagged is not', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 3)
+ await t.syncer.refresh()
+ t.backend.lie = null
+ t.backend.add(evil, 'viewer', '', 'evil')
+ t.backend.removeBy(evil.pub, box2)
+ t.backend.removeBy(k5.pub, box2) // known since joining: not new
+ await t.syncer.rebaseline(true)
+ expect(t.store.read().departed?.map((d) => d.pub)).toEqual([evil.pub])
+ expect(t.store.read().departed?.[0]).toMatchObject({ label: 'evil', removedBy: box2.pub })
+ })
+
+ it('a key that joined and left before the freeze, and was looked at, is not flagged again', async () => {
+ t.backend.add(k6, 'viewer', '', 'k6')
+ t.backend.removeBy(k6.pub, box2)
+ await t.syncer.refresh()
+ expect(t.store.read().departed?.map((d) => d.pub)).toEqual([k6.pub])
+ t.syncer.dismiss({ pub: k6.pub })
+ t.backend.lie = t.backend.entries.slice(0, 5)
+ await t.syncer.refresh()
+ expect(t.store.read().frozen?.reason).toBe('rollback')
+ t.backend.lie = null
+ await t.syncer.rebaseline(true)
+ expect(t.store.read().departed).toEqual([])
+ })
+ })
+})
diff --git a/cli/src/lib/e2ee/deviceLogSyncer.ts b/cli/src/lib/e2ee/deviceLogSyncer.ts
index 8e163301b..d380b4351 100644
--- a/cli/src/lib/e2ee/deviceLogSyncer.ts
+++ b/cli/src/lib/e2ee/deviceLogSyncer.ts
@@ -11,25 +11,53 @@
* looks at what changed and trusts it again (rebaseline). Removals still take effect.
* - gossip: the head rides every `group_sync`, so two devices shown different logs find out, and a
* device that is behind is handed the entries it is missing (a removal the backend held back).
- * - announce: a key this machine had never trusted before is a "New device: X" — the one way a device
- * added by whoever got hold of the account (or by the backend itself) is seen.
+ * - announce: an `add` past the point this machine joined the log is a "New device: X" and stays
+ * `pending` until someone marks it seen — the one way a device added by whoever got hold of the
+ * account (or by the backend itself) is seen. Decided from the log alone, never from what the trust
+ * group already holds: a roster that outran the log must not hide it.
+ * - history: what the log says about every add and remove, as this machine verified it.
*/
import {
- applyDevLogEntries, compareDevLogHead, DevLogError, devLogMessage, emptyDevLogState, nextDevLogEntry,
+ applyDevLogEntries, compareDevLogHead, DevLogError, devLogHash, devLogMessage, emptyDevLogState, nextDevLogEntry,
parseDevLogEntry, signDevLogEntry, type DevLogEntry, type DevLogHead, type DevLogMember, type DevLogState,
} from './deviceLog.js'
-import { DEVLOG_RECENT, type DevLogFile, type DevLogFreeze, type DeviceLogStore } from './deviceLogStore.js'
+import {
+ DEVLOG_DEPARTED, DEVLOG_RECENT, type DevLogConflict, type DevLogDeparted, type DevLogFile, type DevLogFreeze, type DeviceLogStore,
+} from './deviceLogStore.js'
+import { devLogHistory, type DevLogHistoryRow } from './deviceHistory.js'
import { b64d, fingerprint, verify } from './core.js'
export interface DeviceLogFetched { acct: string; head: DevLogHead; entries: unknown[] }
export type DeviceLogAppendAnswer = { head: DevLogHead } | { error: string; head?: DevLogHead }
+/** A sign-in by hand, as this machine's session records it (authSession `signInOf`) — never anything
+ * the backend sends. */
+export interface DevLogSignIn {
+ /** Which sign-in it is. */
+ epoch: string
+ /** Given to a session from before sign-ins were recorded: nobody saw it being made here, so it never
+ * starts the log over (it may take a file over). */
+ adopted: boolean
+ /** When it was made (ms); null when not known — then it never starts the log over either. */
+ at: number | null
+}
+
+/** How long after a sign-in by hand a read of another account may start the log over: past it, with
+ * no read of that account yet, the backend has had the time to pick when it says so. */
+export const DEVLOG_RESET_WINDOW_MS = 10 * 60_000
+
export interface DeviceLogSyncerDeps {
store: DeviceLogStore
/** This machine's identity: base64 public key and the private key that signs for it. */
identity: () => { pub: string; priv: Uint8Array }
/** How this machine describes itself in the log; no machineId = not signed in, nothing to register. */
self: () => { machineId: string | null; label: string }
+ /** Which sign-in by hand this machine is under; null when not known. The log of another account is
+ * started (or a kept one restored) only when this changed AND the backend's account differs AND it
+ * was made less than DEVLOG_RESET_WINDOW_MS ago — never for an adopted one. Otherwise a different
+ * account id from the backend freezes the log. While the file is not this sign-in's yet (no read of
+ * it so far), what peers gossip is not taken either. */
+ signIn: () => DevLogSignIn | null
/** The log from `since`; null when the backend has none to give (an older backend, or unreachable). */
fetch: (since: number) => Promise<DeviceLogFetched | null>
/** Append one signed entry; null when the backend could not be reached. */
@@ -38,14 +66,23 @@ export interface DeviceLogSyncerDeps {
adopt: (members: DevLogMember[]) => void
/** Stop trusting a key here (and tombstone it in the trust group). */
drop: (pub: string) => void
- /** Whether this machine already trusted `pub` before the log named it — then it is not news. */
- knownBefore: (pub: string) => boolean
+ /** The keys this machine trusts right now: snapshotted once, when it joins the log (or migrates to
+ * this version), so what it already knew then is never news. */
+ trustedNow: () => string[]
/** Whether the trust group holds a removal for `pub` that predates the log. */
tombstoned: (pub: string) => boolean
/** Whether this machine's user unpaired `pub` here — a local override the log never beats. */
blocked: (pub: string) => boolean
- /** A key this machine had never trusted joined the log: "New device: X". */
+ /** A key joined the log after this machine did: "New device: X". */
announce: (member: DevLogMember) => void
+ /** A device was taken out of the log after this machine joined (not by this machine). */
+ removed?: (notice: DeviceRemovalNotice) => void
+ /** Another key holds this machine's id in the log (first time that holder is seen). */
+ conflict?: (conflict: DevLogConflict) => void
+ /** A fork split the lists: stop trusting these keys here until `rebaseline`. */
+ suspend?: (pubs: string[]) => void
+ /** `rebaseline` cleared the suspension: trust the roster again. */
+ resume?: () => void
/** This machine's own key was removed from the log: it is signed out. */
signedOut: () => void
/** Something a window shows changed (the list, the frozen line). */
@@ -59,13 +96,56 @@ export interface DeviceLogListing {
head: DevLogHead | null
frozen: DevLogFreeze | null
self: string
- members: Array<DevLogMember & { fingerprint: string; self: boolean; firstSeen?: number }>
+ members: Array<DevLogMember & { fingerprint: string; self: boolean; firstSeen?: number; pending: boolean; suspended: boolean }>
/** Machines whose own copy of the log is frozen, as their last `group_sync` said. */
frozenPeers: string[]
+ /** Keys that joined after this machine did and nobody has marked as seen. */
+ pending: string[]
+ /** Keys not trusted here after a fork, until `rebaseline`. */
+ suspended: string[]
+ joinedSeq: number
+ /** The keys that were on the account before this machine joined (the "Already on your account" list):
+ * active, not this machine, at or before `joinedSeq` — plus any key this machine already trusted at
+ * joining whose entry came after it (a log cut short at the first read must not hide it). */
+ baseline: string[]
+ /** false until the "already on your account" list was acknowledged. */
+ baselineSeen: boolean
+ /** Another key holds this machine's id (and still does). */
+ conflict: DevLogConflict | null
+ /** New keys removed before anyone marked them as seen: flagged until dismissed (oldest first). */
+ departed: DevLogDeparted[]
+}
+
+/** A device taken out of the account's log after this machine joined it. */
+export interface DeviceRemovalNotice {
+ pub: string
+ label: string
+ kind: DevLogMember['kind']
+ fingerprint: string
+ signer: string
+ signerLabel: string
+ signerFingerprint: string
+ /** The signer is itself a new device nobody has looked at. */
+ signerPending: boolean
+ /** The device removed itself (signed out). */
+ selfRemoved: boolean
+ at: number
+}
+
+export interface DeviceLogHistory {
+ rows: DevLogHistoryRow[]
+ /** false when only part of the log could be read (offline). */
+ complete: boolean
+ frozen: DevLogFreeze | null
}
export type DeviceLogRemoveResult = { ok: true } | { ok: false; error: 'NOT_ACTIVE' | 'NOT_IN_LOG' | 'UNAVAILABLE' | 'REFUSED'; detail?: string }
+/** `rebaseline(confirm, head)` refused: the backend's list is no longer the one that was previewed
+ * (`LOG_CHANGED`), or it is another account's while the log this machine keeps is the one of the
+ * sign-in it is under (`OTHER_ACCOUNT`: only a sign-in switches accounts). */
+export interface DeviceLogRebaselineChanged { error: 'LOG_CHANGED' | 'OTHER_ACCOUNT' }
+
export interface DeviceLogRebaseline {
head: DevLogHead
added: DevLogMember[]
@@ -74,6 +154,45 @@ export interface DeviceLogRebaseline {
const APPEND_ATTEMPTS = 5
const PAGES = 20
+/** The newest hashes a `group_sync` carries, so a fork can be located. */
+const GOSSIP_HASHES = 64
+
+interface Known { label: string; kind: DevLogMember['kind'] }
+
+const fp = (pub: string): string => fingerprint(b64d(pub))
+const uniq = (xs: readonly string[]): string[] => [...new Set(xs)]
+
+/**
+ * Where a peer's log first differs from `state`: the first seq, in the window of hashes the peer sent
+ * (`theirs.hashes`, with `theirs.head` the last of them), whose hash is not ours — only when the entry
+ * before it matches (or it is the first), so the split is proven rather than guessed. null when the peer
+ * sent no usable hashes, nothing in the shared window differs, or the split lies before the window.
+ */
+export function devLogDivergence(state: DevLogState, theirs: unknown): number | null {
+ if (!theirs || typeof theirs !== 'object') return null
+ const { head, hashes } = theirs as { head?: { seq?: unknown; hash?: unknown }; hashes?: unknown }
+ if (!Array.isArray(hashes) || !hashes.length || hashes.length > 4 * GOSSIP_HASHES) return null
+ const window = new Map<number, string>()
+ let prev = 0
+ for (const h of hashes) {
+ if (!h || typeof h !== 'object') return null
+ const { seq, hash } = h as { seq?: unknown; hash?: unknown }
+ if (typeof seq !== 'number' || !Number.isSafeInteger(seq) || seq < 1 || typeof hash !== 'string' || hash.length > 128) return null
+ if (prev !== 0 && seq !== prev + 1) return null
+ prev = seq
+ window.set(seq, hash)
+ }
+ // The window must end where the peer's head is, or it describes some other log.
+ if (!head || head.seq !== prev || head.hash !== window.get(prev)) return null
+ const first = Math.min(...window.keys())
+ for (const [seq, hash] of window) {
+ if (seq > state.head.seq || state.hashes[seq - 1] === hash) continue
+ if (seq === 1) return 1
+ if (seq === first) return null
+ return state.hashes[seq - 2] === window.get(seq - 1) ? seq : null
+ }
+ return null
+}
export class DeviceLogSyncer {
private readonly now: () => number
@@ -82,6 +201,10 @@ export class DeviceLogSyncer {
private readonly frozenPeers = new Map<string, boolean>()
private readonly removing = new Set<string>()
private readonly inFlightRemovals = new Map<string, Promise<DeviceLogRemoveResult>>()
+ /** The history walk in progress, which a second `history()` joins. */
+ private historying: Promise<DeviceLogHistory> | null = null
+ /** Every entry fetched for the history so far (seq 1..n), this run only: never written to disk. */
+ private histCache: { acct: string; entries: DevLogEntry[] } | null = null
constructor(private readonly deps: DeviceLogSyncerDeps) {
this.now = deps.now ?? (() => Date.now())
@@ -96,19 +219,17 @@ export class DeviceLogSyncer {
await this.refresh()
const { pub, priv } = this.deps.identity()
for (let attempt = 0; attempt < APPEND_ATTEMPTS; attempt++) {
- const file = this.deps.store.read()
+ const file = this.marks()
const state = file.state
if (!state || file.frozen) return
if (state.removed.includes(pub)) { this.deps.signedOut(); return }
const mine = state.active[pub]
if (mine) {
+ this.clearConflict()
if (mine.label === self.label || mine.machineId !== self.machineId) return
} else {
const taken = Object.values(state.active).find((m) => m.kind === 'machine' && m.machineId === self.machineId)
- if (taken) {
- this.deps.log?.(`[devlog] this machine's id is held by another key (${fingerprint(b64d(taken.pub))}); remove it from another device to register this one`)
- return
- }
+ if (taken) { this.noteConflict(file, taken); return }
}
const entry = signDevLogEntry(nextDevLogEntry(state, {
op: 'add', pub, kind: 'machine', machineId: self.machineId, label: self.label, signer: pub,
@@ -134,18 +255,202 @@ export class DeviceLogSyncer {
return this.refreshing
}
+ /** The file, with the joined point filled in for one written before it existed (or by a client that
+ * dropped it): everything up to what was already announced is then known, as it was. */
+ private marks(): DevLogFile {
+ const file = this.deps.store.read()
+ if (!file.state || file.joinedSeq !== undefined) return file
+ const next: DevLogFile = {
+ ...file, joinedSeq: file.notifiedUpTo, preLog: this.deps.trustedNow(), pending: [], announced: [], baselineSeen: true,
+ }
+ this.deps.store.write(next)
+ return next
+ }
+
+ /** Whether `local` — a sign-in by hand the file is not yet the log of — may start it over for another
+ * account: never an adopted one, and only shortly after it was made. A backend that holds back the
+ * log after a sign-in must not keep that door open, to name another account days later. */
+ private mayStartOver(local: DevLogSignIn): boolean {
+ return !local.adopted && local.at !== null && Math.abs(this.now() - local.at) <= DEVLOG_RESET_WINDOW_MS
+ }
+
+ /** Whether the file is the log of the sign-in this machine is under (or that cannot be told). Until a
+ * read of it under a new sign-in, it may be another account's: what a peer says is not judged
+ * against it — a peer of the new account would read as a fork of the old one. */
+ private ownsFile(file: DevLogFile): boolean {
+ const local = this.deps.signIn()
+ return local === null || file.owner === local.epoch
+ }
+
+ /** `file`, with every key a fork suspended in another account's kept log, and active in this one,
+ * suspended (and new) here as well: it is not trusted either way, so the list says so — and "It's
+ * mine" lifts it, everywhere (a review of this list does not: it never showed that suspension). */
+ private carrySuspensions(file: DevLogFile): DevLogFile {
+ const state = file.state
+ if (!state) return file
+ const selfPub = this.deps.identity().pub
+ const current = file.suspended ?? []
+ const carried = this.deps.store.archivedSuspended().filter((k) => !!state.active[k] && k !== selfPub && !current.includes(k))
+ if (!carried.length) return file
+ return { ...file, suspended: [...current, ...carried], pending: uniq([...(file.pending ?? []), ...carried]) }
+ }
+
+ /** `gone`, just taken out by `e`, kept flagged: it was new here and nobody had looked at it yet. */
+ private departedOf(gone: DevLogMember, e: DevLogEntry, signerLabel: string): DevLogDeparted {
+ return {
+ pub: gone.pub, label: gone.label, kind: gone.kind, machineId: gone.machineId, fingerprint: fp(gone.pub), addedAt: gone.addedAt,
+ removedAt: e.at, removedBy: e.signer, removedByLabel: signerLabel, selfRemoved: e.signer === gone.pub,
+ }
+ }
+
+ /** `prev` plus `more` (a key once, at its newest), the oldest dropped past DEVLOG_DEPARTED. */
+ private withDeparted(prev: DevLogDeparted[] | undefined, more: readonly DevLogDeparted[]): { departed?: DevLogDeparted[] } {
+ if (!more.length) return prev ? { departed: prev } : {}
+ const pubs = new Set(more.map((d) => d.pub))
+ return { departed: [...(prev ?? []).filter((d) => !pubs.has(d.pub)), ...more].slice(-DEVLOG_DEPARTED) }
+ }
+
+ /** What a review (`rebaseline --yes`) takes out that was new here and never looked at: a key pending
+ * in `base` that the reviewed list does not keep — and a key the list added and removed again at
+ * entries this machine never verified (while it was frozen) — stays flagged as departed. */
+ private reviewDeparted(
+ base: DevLogFile, next: DevLogState, parsed: readonly DevLogEntry[], removed: readonly DevLogMember[], selfPub: string, preLog: ReadonlySet<string>,
+ ): DevLogDeparted[] {
+ const verified = base.state
+ if (!verified) return []
+ const pending = base.pending ?? []
+ const known = new Map<string, Known>()
+ const adds = new Map<string, DevLogEntry>()
+ const out = new Map<string, DevLogDeparted>()
+ for (const e of [...parsed].sort((a, b) => a.seq - b.seq)) {
+ if (e.op === 'add') {
+ if (!known.has(e.pub)) adds.set(e.pub, e) // added (not renamed)
+ known.set(e.pub, { label: e.label, kind: e.kind })
+ continue
+ }
+ const was = removed.find((m) => m.pub === e.pub)
+ const add = adds.get(e.pub)
+ const label = known.get(e.pub)?.label
+ known.delete(e.pub)
+ if (e.pub === selfPub || next.active[e.pub]) continue
+ // Added at an entry this machine never verified, and gone again before it could see it.
+ const unseen = !was && !!add && verified.hashes[add.seq - 1] !== devLogHash(add) && !preLog.has(e.pub) && !this.deps.blocked(e.pub)
+ if ((was && pending.includes(e.pub)) || unseen) {
+ const member: DevLogMember = was ?? { pub: e.pub, kind: add!.kind, machineId: add!.machineId, label: label ?? add!.label, addedAt: add!.at, seq: add!.seq }
+ out.set(e.pub, this.departedOf(member, e, known.get(e.signer)?.label ?? ''))
+ }
+ }
+ // Pending here, and not on the reviewed list at all (a branch the backend no longer serves).
+ for (const m of removed) {
+ if (out.has(m.pub) || m.pub === selfPub || !pending.includes(m.pub)) continue
+ out.set(m.pub, {
+ pub: m.pub, label: m.label, kind: m.kind, machineId: m.machineId, fingerprint: fp(m.pub), addedAt: m.addedAt,
+ removedAt: this.now(), removedBy: '', removedByLabel: '', selfRemoved: false,
+ })
+ }
+ return [...out.values()]
+ }
+
+ /** The first read of the log has reached its head (or stopped): what is verified from here on is news. */
+ private endJoin(): void {
+ const file = this.deps.store.read()
+ if (!file.joining) return
+ const { joining: _j, ...rest } = file
+ this.deps.store.write(rest)
+ }
+
+ /** Another key holds this machine's id: remember it, and say so the first time that holder is seen. */
+ private noteConflict(file: DevLogFile, holder: DevLogMember): void {
+ if (file.conflict?.pub === holder.pub) return
+ const conflict: DevLogConflict = {
+ pub: holder.pub, label: holder.label, machineId: holder.machineId, addedAt: holder.addedAt, seq: holder.seq,
+ fingerprint: fp(holder.pub), afterJoin: holder.seq > (file.joinedSeq ?? 0),
+ }
+ this.deps.store.write({ ...file, conflict })
+ const who = `${conflict.label || '(no name)'} (${conflict.fingerprint})`
+ this.deps.log?.(conflict.afterJoin
+ ? `[devlog] ⚠ another key took this computer's place on your account after it joined: ${who} — if you did not set up Harness here again, remove that key from another device now`
+ : `[devlog] this computer is held by another key on your account: ${who} — if that was an earlier install of this computer, remove it from another device; this computer joins on its own once it is gone`)
+ this.deps.conflict?.(conflict)
+ this.deps.changed?.()
+ }
+
+ private clearConflict(): void {
+ const file = this.deps.store.read()
+ if (!file.conflict) return
+ const { conflict: _gone, ...rest } = file
+ this.deps.store.write(rest)
+ this.deps.changed?.()
+ }
+
private async doRefresh(): Promise<void> {
+ try {
+ await this.readPages()
+ } finally {
+ // However the read ended — at the head, on a freeze, or cut short (no answer, the page cap) — the
+ // first read of a log is over: what is verified from here on is news. Held open, a backend that
+ // stalls the second page would have every key it adds later taken for one there at joining.
+ this.endJoin()
+ }
+ }
+
+ private async readPages(): Promise<void> {
+ this.marks()
// The first read of a log (a new install, or an existing sign-in from before the log existed) only
- // learns what is there: nothing in it is news, every page of it.
+ // learns what is there: every key it adopts, and none of it is news (it is before `joinedSeq`).
let bootstrap = !this.deps.store.read().state?.head.seq
for (let page = 0; page < PAGES; page++) {
const file = this.deps.store.read()
const since = file.state?.head.seq ?? 0
const got = await this.deps.fetch(since)
if (!got) return
- if (!file.state || file.state.acct !== got.acct) {
- // First read, or signed in to another account: that account's log starts from nothing here.
- const fresh: DevLogFile = { state: emptyDevLogState(got.acct), recent: [], frozen: null, notifiedUpTo: 0 }
+ // A head that is not a position is the backend lying (or broken): nothing to verify it against.
+ if (!Number.isSafeInteger(got.head.seq) || got.head.seq < 0) return
+ const latest = this.deps.store.read()
+ const now = latest.state
+ if (file.state && now && now.acct === got.acct
+ && (file.state.acct !== now.acct || file.state.head.seq !== now.head.seq || file.state.head.hash !== now.head.hash)) {
+ // The log moved here while this page was on its way (a peer handed over its tail): judged
+ // against the newer head the page would read as a rollback, or as entries out of order. Ask
+ // again from where the log is now.
+ continue
+ }
+ const local = this.deps.signIn()
+ let reset = !now
+ if (now) {
+ const signedInAgain = local !== null && latest.owner !== local.epoch
+ if (now.acct !== got.acct) {
+ // Another account only right after a sign-in by hand here. Otherwise it is the backend saying
+ // so — and starting over would clear every mark a fork put on the list, the real log then
+ // adopted whole.
+ if (!signedInAgain || !this.mayStartOver(local)) {
+ this.freeze('invalid')
+ return
+ }
+ reset = true
+ } else if (signedInAgain) {
+ // Signed in again to the same account: the same list, now this sign-in's.
+ this.deps.store.write({ ...latest, owner: local.epoch })
+ }
+ }
+ if (reset) {
+ if (now) this.deps.store.archive(latest)
+ // Back to an account this machine was signed in to before: its log as verified then, and every
+ // mark on it (frozen, suspended, pending), go on from where they were.
+ const kept = this.deps.store.restore(got.acct, (k) => this.carrySuspensions({ ...k, ...(local ? { owner: local.epoch } : {}) }))
+ if (kept) {
+ bootstrap = !kept.state?.head.seq
+ continue
+ }
+ // First read, or signed in to another account here: that account's log starts from nothing.
+ // `joinedSeq` starts at 0 and follows the head of each page this machine VERIFIES (accept):
+ // never the head the backend merely claims, or it could park it far ahead and have every key
+ // it forges below that adopted without a word. `preLog` is what was trusted already.
+ const fresh: DevLogFile = {
+ state: emptyDevLogState(got.acct), recent: [], frozen: null, notifiedUpTo: 0,
+ joinedSeq: 0, preLog: this.deps.trustedNow(), pending: [], announced: [], suspended: [], baselineSeen: false,
+ joining: true, ...(local ? { owner: local.epoch } : {}),
+ }
this.deps.store.write(fresh)
bootstrap = true
if (got.head.seq === 0) return
@@ -176,9 +481,36 @@ export class DeviceLogSyncer {
return out
}
+ /** `keys` cut to the ones still active — the marks never outlive the key. */
+ private prune(keys: readonly string[] | undefined, state: DevLogState): string[] {
+ return uniq(keys ?? []).filter((k) => state.active[k] !== undefined)
+ }
+
+ /** The notice for a `remove` that took `gone` out, or null when there is nothing to say: this
+ * machine's own removal, this machine's own key, or a removal from before it joined. `known` says
+ * what each key was called, and what kind it was, BEFORE this removal — the remove entry's own label
+ * and kind are the signer's to pick, so they are never what the person is told. */
+ private removalNotice(e: DevLogEntry, joinedSeq: number, selfPub: string, pending: readonly string[], known: ReadonlyMap<string, Known>): DeviceRemovalNotice | null {
+ if (e.op !== 'remove' || e.seq <= joinedSeq || e.pub === selfPub || e.signer === selfPub) return null
+ const was = known.get(e.pub)
+ return {
+ pub: e.pub, label: was?.label ?? e.label, kind: was?.kind ?? e.kind, fingerprint: fp(e.pub),
+ signer: e.signer, signerLabel: known.get(e.signer)?.label ?? '', signerFingerprint: fp(e.signer),
+ signerPending: pending.includes(e.signer), selfRemoved: e.signer === e.pub, at: this.now(),
+ }
+ }
+
+ /** What each active key in `state` is called now, to be walked forward through entries. */
+ private knownOf(state: DevLogState): Map<string, Known> {
+ return new Map(Object.values(state.active).map((m) => [m.pub, { label: m.label, kind: m.kind }] as const))
+ }
+
/** Apply entries that continue this machine's log; freeze on anything that does not. */
private accept(entries: readonly unknown[], bootstrap: boolean): boolean {
- const file = this.deps.store.read()
+ const file = this.marks()
+ // While the first read of this log is open (a peer's tail can arrive between its pages too):
+ // whatever is verified before it reaches the head is what was there at joining.
+ const joining = file.joining === true
let applied
try {
applied = applyDevLogEntries(file.state!, entries)
@@ -188,29 +520,74 @@ export class DeviceLogSyncer {
return false
}
const selfPub = this.deps.identity().pub
- // Decided before anything is adopted: afterwards every one of them is "known".
- const news = bootstrap ? [] : applied.added.filter((m) =>
- m.seq > file.notifiedUpTo && m.pub !== selfPub && !this.deps.knownBefore(m.pub) && !this.deps.blocked(m.pub))
+ // While joining, everything this page verified is what was there before: the joined point moves up
+ // to the verified head (never past it), and none of it is news.
+ const joinedSeq = joining ? applied.state.head.seq : file.joinedSeq ?? 0
+ const preLog = new Set(file.preLog ?? [])
const parsed = entries.map((e) => parseDevLogEntry(e)).filter((e): e is DevLogEntry => e !== null)
- this.deps.store.write({
+ // News is decided from the log alone: an `add` past the point this machine joined, for a key it
+ // did not already trust then. What the roster or the pins hold now says nothing — a key can reach
+ // them (over `group_sync`) before this machine reads the entry that adds it.
+ const news = applied.added.filter((m) =>
+ m.seq > joinedSeq && m.pub !== selfPub && !preLog.has(m.pub) && !this.deps.blocked(m.pub))
+ const pendingBefore = file.pending ?? []
+ const announced = file.announced ?? []
+ const newHere = [...pendingBefore, ...news.map((m) => m.pub)]
+ const pending = this.prune(newHere, applied.state)
+ const toAnnounce = news.filter((m) => !announced.includes(m.pub))
+ // Walk the entries in order: a removal is described by what the key was called when it was removed.
+ const known = this.knownOf(file.state!)
+ const notices: DeviceRemovalNotice[] = []
+ const gone = new Map(applied.removed.map((m) => [m.pub, m] as const))
+ const departed: DevLogDeparted[] = []
+ for (const e of [...parsed].sort((a, b) => a.seq - b.seq)) {
+ if (e.op === 'add') known.set(e.pub, { label: e.label, kind: e.kind })
+ else {
+ const n = this.removalNotice(e, joinedSeq, selfPub, newHere, known)
+ if (n) notices.push(n)
+ // A new key nobody looked at, gone again (even within this page): it stays flagged.
+ const member = gone.get(e.pub)
+ if (member && newHere.includes(e.pub) && e.pub !== selfPub) departed.push(this.departedOf(member, e, known.get(e.signer)?.label ?? ''))
+ known.delete(e.pub)
+ }
+ }
+ // The holder of this machine's id left, or this machine got its own key in: the conflict is over.
+ const conflictOver = !!file.conflict && (!!applied.state.active[selfPub] || !applied.state.active[file.conflict.pub])
+ // A key taken into the "already on your account" list after that list was acknowledged: show it.
+ const unseen = joining && file.baselineSeen !== false && applied.added.some((m) => m.pub !== selfPub)
+ const { conflict: _c, ...rest } = file
+ this.deps.store.write(this.carrySuspensions({
+ ...rest,
+ ...(unseen ? { baselineSeen: false } : {}),
+ ...(file.conflict && !conflictOver ? { conflict: file.conflict } : {}),
state: applied.state,
+ joinedSeq,
recent: [...file.recent, ...parsed].slice(-DEVLOG_RECENT),
frozen: null,
notifiedUpTo: applied.state.head.seq,
- firstSeen: bootstrap ? file.firstSeen : this.stamp(file.firstSeen, applied.added, applied.state),
- })
+ firstSeen: this.stamp(file.firstSeen, applied.added.filter((m) => m.seq > joinedSeq), applied.state),
+ pending,
+ announced: this.prune([...announced, ...toAnnounce.map((m) => m.pub)], applied.state),
+ suspended: this.prune(file.suspended, applied.state),
+ ...this.withDeparted(file.departed, departed),
+ }))
this.trustState(applied.state, bootstrap ? Object.values(applied.state.active) : [...applied.added, ...applied.relabeled])
for (const m of applied.removed) this.deps.drop(m.pub)
- for (const m of news) this.deps.announce(m)
+ for (const m of toAnnounce) this.deps.announce(m)
+ for (const n of notices) this.deps.removed?.(n)
if (applied.state.removed.includes(selfPub)) this.deps.signedOut()
void this.carryOverTombstones(applied.state)
this.deps.changed?.()
+ // Its holder gone, this machine takes its own place in the account.
+ if (conflictOver && !applied.state.active[selfPub]) void this.register()
return true
}
private trustState(state: DevLogState, members: DevLogMember[]): void {
const selfPub = this.deps.identity().pub
- const adopt = members.filter((m) => m.pub !== selfPub && state.active[m.pub] && !this.deps.blocked(m.pub) && !this.deps.tombstoned(m.pub))
+ const suspended = this.suspendedKeys()
+ const adopt = members.filter((m) => m.pub !== selfPub && state.active[m.pub] && !suspended.includes(m.pub)
+ && !this.deps.blocked(m.pub) && !this.deps.tombstoned(m.pub))
if (adopt.length) this.deps.adopt(adopt)
}
@@ -224,28 +601,47 @@ export class DeviceLogSyncer {
}
}
- /** While frozen, a removal still counts — if a key this machine trusts signed it. */
+ /** While frozen, a removal still counts — if a key this machine trusts signed it. A key a fork
+ * suspended is not trusted here, so what it signs does not count either. */
private looseRemovals(entries: readonly unknown[]): void {
- const file = this.deps.store.read()
+ const file = this.marks()
const state = file.state
if (!state) return
- let changed = false
+ const selfPub = this.deps.identity().pub
+ const joinedSeq = file.joinedSeq ?? 0
+ const suspended = new Set(file.suspended ?? [])
+ const loose: DevLogEntry[] = []
+ const notices: DeviceRemovalNotice[] = []
+ const departed: DevLogDeparted[] = []
+ const known = this.knownOf(state)
for (const raw of entries) {
const e = parseDevLogEntry(raw)
- if (!e || e.op !== 'remove' || !state.active[e.signer] || !state.active[e.pub]) continue
+ if (!e || e.op !== 'remove' || !state.active[e.signer] || suspended.has(e.signer) || !state.active[e.pub]) continue
if (!verify(b64d(e.signer), devLogMessage(e), b64d(e.sig))) continue
+ const notice = this.removalNotice(e, joinedSeq, selfPub, file.pending ?? [], known)
+ if ((file.pending ?? []).includes(e.pub) && e.pub !== selfPub) departed.push(this.departedOf(state.active[e.pub], e, known.get(e.signer)?.label ?? ''))
delete state.active[e.pub]
state.removed.push(e.pub)
this.deps.drop(e.pub)
- changed = true
+ loose.push(e)
+ if (notice) notices.push(notice)
}
- if (changed) { this.deps.store.write({ ...file, state }); this.deps.changed?.() }
+ if (!loose.length) return
+ this.deps.store.write({
+ ...file, state,
+ looseRemoved: [...(file.looseRemoved ?? []), ...loose],
+ pending: this.prune(file.pending, state), announced: this.prune(file.announced, state), suspended: this.prune(file.suspended, state),
+ ...this.withDeparted(file.departed, departed),
+ })
+ for (const n of notices) this.deps.removed?.(n)
+ this.deps.changed?.()
}
private freeze(reason: DevLogFreeze['reason']): void {
const file = this.deps.store.read()
if (file.frozen || !file.state) return
- this.deps.store.write({ ...file, frozen: { reason, at: this.now(), lastGoodHead: file.state.head } })
+ const { joining: _j, ...rest } = file
+ this.deps.store.write({ ...rest, frozen: { reason, at: this.now(), lastGoodHead: file.state.head } })
this.deps.log?.(`[devlog] FROZEN (${reason}): the device list the backend serves does not match what this machine verified — no device is added from it until someone reviews it (harness devices rebaseline)`)
this.deps.changed?.()
}
@@ -286,14 +682,19 @@ export class DeviceLogSyncer {
return { ok: false, error: 'UNAVAILABLE' }
}
- /** What trusting the backend's log again would change; with `confirm`, do it. */
- async rebaseline(confirm: boolean): Promise<DeviceLogRebaseline | null> {
+ /**
+ * What trusting the backend's log again would change; with `confirm`, do it. `expected` is the head
+ * the person was shown in the preview: if the backend's log is not that one any more, nothing is
+ * done (`LOG_CHANGED`) — what gets trusted is what was reviewed.
+ */
+ async rebaseline(confirm: boolean, expected?: DevLogHead): Promise<DeviceLogRebaseline | DeviceLogRebaselineChanged | null> {
const entries: unknown[] = []
let acct = ''
let head: DevLogHead = emptyDevLogState('').head
for (let page = 0; page < PAGES; page++) {
const got = await this.deps.fetch(entries.length)
if (!got) return null
+ if (!Number.isSafeInteger(got.head.seq) || got.head.seq < 0) return null
acct = got.acct
head = got.head
entries.push(...got.entries)
@@ -304,18 +705,66 @@ export class DeviceLogSyncer {
next = applyDevLogEntries(emptyDevLogState(acct), entries).state
} catch { return null }
if (next.head.seq !== head.seq || next.head.hash !== head.hash) return null
- const file = this.deps.store.read()
- const before = file.state?.active ?? {}
+ const file = this.marks()
+ const same = !!file.state && file.state.acct === next.acct
+ // Another account's list while the live log is the one of the sign-in this machine is under: the
+ // backend switched accounts on its own. A review must not move this machine there (the account it
+ // is signed in to, and every mark on it, would go out of sight): only a sign-in switches accounts.
+ // Only a sign-in by hand the file is not stamped with is that switch: none recorded, an adopted one
+ // (a session this machine took over — whatever stamp the file has, or lacks, from an older version),
+ // or the sign-in the file is stamped with is not.
+ const local = this.deps.signIn()
+ if (file.state && !same && (local === null || local.adopted || file.owner === local.epoch)) return { error: 'OTHER_ACCOUNT' }
+ if (confirm && expected && (expected.seq !== next.head.seq || expected.hash !== next.head.hash)) return { error: 'LOG_CHANGED' }
+ // The list under review is judged against this account's own log as this machine verified it:
+ // the live file, or — for another account — the one kept when this machine left it (its marks go
+ // on), or else nothing (every key on it is new here). Never against the account being left.
+ const kept = same ? null : this.deps.store.archivedFile(next.acct)
+ const base: DevLogFile = same ? file : kept ?? {
+ state: null, recent: [], frozen: null, notifiedUpTo: 0, joinedSeq: 0, preLog: file.preLog ?? [],
+ pending: [], announced: [], suspended: [], baselineSeen: true,
+ }
+ const before = base.state?.active ?? {}
const added = Object.values(next.active).filter((m) => !before[m.pub])
const removed = Object.values(before).filter((m) => !next.active[m.pub])
if (confirm) {
const parsed = entries.map((e) => parseDevLogEntry(e)).filter((e): e is DevLogEntry => e !== null)
- this.deps.store.write({
- state: next, recent: parsed.slice(-DEVLOG_RECENT), frozen: null, notifiedUpTo: next.head.seq,
- firstSeen: this.stamp(file.firstSeen, added, next),
+ const selfPub = this.deps.identity().pub
+ const signIn = this.deps.signIn()
+ const preLog = new Set(base.preLog ?? [])
+ const announced = base.announced ?? []
+ // Every key the review let in is new here — however the preview and this read differ — unless
+ // this machine knew it already or its user unpaired it.
+ const news = added.filter((m) => m.pub !== selfPub && !preLog.has(m.pub) && !this.deps.blocked(m.pub))
+ const toAnnounce = news.filter((m) => !announced.includes(m.pub))
+ // The joined point never moves up past the reviewed head: a shorter list (rolled back, or
+ // another account's) must leave every key added to it from here on news.
+ const joinedSeq = Math.min(base.joinedSeq ?? base.notifiedUpTo, next.head.seq)
+ // The reviewed list is another account's: the one this machine leaves is kept, as on a sign-in
+ // (and what a fork suspended in it stays suspended here) — and a kept one of the reviewed account
+ // goes on from where it was.
+ if (file.state && !same) this.deps.store.archive(file)
+ const { joining: _j, ...rest } = base
+ const reviewed: DevLogFile = this.carrySuspensions({
+ ...rest,
+ state: next, recent: parsed.slice(-DEVLOG_RECENT), frozen: null, notifiedUpTo: next.head.seq, joinedSeq,
+ firstSeen: this.stamp(base.firstSeen, added, next),
+ pending: this.prune([...(base.pending ?? []), ...news.map((m) => m.pub)], next),
+ announced: this.prune([...announced, ...toAnnounce.map((m) => m.pub)], next),
+ // A review lifts what a fork suspended in this list; a kept list's suspensions were never in
+ // the preview, so they stay.
+ suspended: same ? [] : this.prune(base.suspended, next),
+ looseRemoved: [], reviewedSeq: next.head.seq,
+ ...this.withDeparted(base.departed, this.reviewDeparted(base, next, parsed, removed, selfPub, preLog)),
+ ...(signIn ? { owner: signIn.epoch } : {}),
})
+ if (!kept || !this.deps.store.restore(next.acct, () => reviewed)) this.deps.store.write(reviewed)
this.trustState(next, Object.values(next.active))
for (const m of removed) this.deps.drop(m.pub)
+ // The review is done: what a fork suspended is trusted again, along with the rest of the log —
+ // after the drops, so a key the reviewed log removed is not pinned again on the way out.
+ this.deps.resume?.()
+ for (const m of toAnnounce) this.deps.announce(m)
this.deps.changed?.()
}
return { head: next.head, added, removed }
@@ -324,8 +773,11 @@ export class DeviceLogSyncer {
/** What rides this machine's side of a `group_sync`. */
gossip(): Record<string, unknown> | undefined {
const file = this.deps.store.read()
- if (!file.state) return undefined
- return { head: file.state.head, frozen: file.frozen !== null }
+ // Not this sign-in's log yet (it may be the account this machine just left): nothing to say.
+ if (!file.state || !this.ownsFile(file)) return undefined
+ // The newest hashes let a peer that finds the logs forked say where they split.
+ const hashes = file.state.hashes.slice(-GOSSIP_HASHES).map((hash, i, all) => ({ seq: file.state!.head.seq - (all.length - 1 - i), hash }))
+ return { head: file.state.head, frozen: file.frozen !== null, hashes }
}
/**
@@ -333,8 +785,11 @@ export class DeviceLogSyncer {
* the entries the peer is missing if it is behind).
*/
heard(peerPub: string, raw: unknown): Record<string, unknown> | undefined {
- const file = this.deps.store.read()
+ const file = this.marks()
const state = file.state
+ // A sign-in waiting for its first read: the file may be the account left behind, and a peer of the
+ // new one would freeze it as a fork. Nothing is judged until the log is this sign-in's.
+ if (!this.ownsFile(file)) return undefined
const mine = this.gossip()
if (!state || !raw || typeof raw !== 'object') return mine
const p = raw as { head?: unknown; frozen?: unknown; tail?: unknown }
@@ -343,10 +798,12 @@ export class DeviceLogSyncer {
if (!head || typeof head.seq !== 'number' || !Number.isSafeInteger(head.seq) || head.seq < 0 || typeof head.hash !== 'string') return mine
const theirs: DevLogHead = { seq: head.seq, hash: head.hash }
const relation = compareDevLogHead(state, theirs)
- if (relation === 'fork') { this.freeze('fork'); return this.gossip() }
+ if (relation === 'fork') { this.freeze('fork'); this.suspendAfterFork(state, raw); return this.gossip() }
if (relation === 'behind') {
const tail = Array.isArray(p.tail) ? p.tail.filter((e) => (parseDevLogEntry(e)?.seq ?? 0) > state.head.seq) : []
- if (tail.length && !file.frozen) this.accept(tail, false)
+ // A tail that does not continue this log is a fork; and a log already frozen on one can still
+ // learn from this peer's hashes where it split.
+ if (file.frozen || (tail.length && !this.accept(tail, false))) this.suspendAfterFork(state, raw)
// Either way ask the backend too: if it will not serve what a peer already verified, that is a
// rollback, and the next refresh freezes on it.
void this.refresh()
@@ -359,17 +816,162 @@ export class DeviceLogSyncer {
return mine
}
+ /**
+ * A fork a peer proved with its hashes: the keys added at or after the split — and new here — are
+ * not trusted until the list is reviewed (rebaseline). Only locally: nothing is tombstoned or
+ * written to the log. Without usable hashes (an older peer, a split outside the window, a rollback)
+ * the freeze alone stands.
+ */
+ private suspendAfterFork(state: DevLogState, theirs: unknown): void {
+ const file = this.deps.store.read()
+ if (file.frozen?.reason !== 'fork') return
+ const split = devLogDivergence(state, theirs)
+ if (split === null) return
+ const selfPub = this.deps.identity().pub
+ const pending = file.pending ?? []
+ // Only keys nobody here has marked as seen — and not one a review (`rebaseline --yes`) already let
+ // in: another device's old branch must not cost this one the devices its user just looked at.
+ const reviewed = file.reviewedSeq ?? -1
+ const keys = Object.values(state.active)
+ .filter((m) => m.seq >= split && m.pub !== selfPub && pending.includes(m.pub) && m.seq > reviewed)
+ .map((m) => m.pub)
+ const fresh = keys.filter((k) => !(file.suspended ?? []).includes(k))
+ if (!fresh.length) return
+ this.deps.store.write({ ...file, suspended: uniq([...(file.suspended ?? []), ...fresh]) })
+ this.deps.suspend?.(fresh)
+ this.deps.log?.(`[devlog] this computer's and another device's lists split at entry ${split}: not trusting ${fresh.length} key(s) added after it until you review the list (harness devices rebaseline)`)
+ this.deps.changed?.()
+ }
+
+ /** Keys not trusted here after a fork, until `rebaseline` — and every key a fork suspended in the
+ * kept log of another account, which no other account's log can bring back in. */
+ suspendedKeys(): string[] {
+ return [...new Set([...(this.deps.store.read().suspended ?? []), ...this.deps.store.archivedSuspended()])]
+ }
+
+ /**
+ * Mark new devices as seen: the ones in `pubs` (what a window displayed), one (`pub`), every one
+ * (nothing named — only the explicit `harness devices dismiss`), and/or the "already on your account"
+ * list (`baseline`). Persisted, so it holds across restarts. A key a fork suspended stays flagged
+ * when it is only part of a list that was looked at; `pub` — "It's mine" on that very device — is the
+ * person vouching for it, and lifts its suspension here (and in every kept account's log). A key that
+ * joined and left before anyone looked (`departed`) is cleared the same way: named, or every one.
+ */
+ dismiss(opts: { pub?: string; pubs?: string[]; baseline?: boolean } = {}): void {
+ const file = this.marks()
+ if (!file.state) return
+ const suspended = file.suspended ?? []
+ const named = opts.pub !== undefined || opts.pubs !== undefined
+ const gone = new Set([...(opts.pubs ?? []), ...(opts.pub !== undefined ? [opts.pub] : [])])
+ const keep = (k: string): boolean => (named ? !gone.has(k) : !!opts.baseline) || (suspended.includes(k) && k !== opts.pub)
+ const pending = (file.pending ?? []).filter(keep)
+ const departed = (file.departed ?? []).filter((d) => (named ? !gone.has(d.pub) : !!opts.baseline))
+ const lift = opts.pub !== undefined && suspended.includes(opts.pub)
+ // The "already on your account" list was looked at: the first read is over, whatever comes after is
+ // news — or a backend that stalls that read could add a key to a list nobody will look at again.
+ const { joining: _j, ...rest } = file
+ this.deps.store.write({
+ ...(opts.baseline ? { ...rest, baselineSeen: true } : file), pending,
+ ...(file.departed ? { departed } : {}),
+ ...(lift ? { suspended: suspended.filter((k) => k !== opts.pub) } : {}),
+ })
+ if (lift) {
+ this.deps.store.unsuspendArchived([opts.pub!])
+ const member = file.state.active[opts.pub!]
+ if (member) this.trustState(file.state, [member])
+ this.deps.resume?.()
+ }
+ this.deps.changed?.()
+ }
+
+ /**
+ * Every add and remove in the log, newest first, as this machine verified it: the entries come from
+ * the backend but each must hash to what this machine already verified, or the log freezes. Offline,
+ * what is kept locally (`complete: false`).
+ */
+ history(): Promise<DeviceLogHistory> {
+ // One walk at a time: two interleaved on the same cache would each read the other's entries as a
+ // gap in the log and freeze it.
+ this.historying ??= this.historyOnce().finally(() => { this.historying = null })
+ return this.historying
+ }
+
+ private async historyOnce(): Promise<DeviceLogHistory> {
+ await this.refresh()
+ const file = this.marks()
+ const state = file.state
+ if (!state) return { rows: [], complete: false, frozen: file.frozen }
+ const cache = this.histCache && this.histCache.acct === state.acct ? this.histCache : { acct: state.acct, entries: [] as DevLogEntry[] }
+ const last = cache.entries.at(-1)
+ if (last && (last.seq > state.head.seq || devLogHash(last) !== state.hashes[last.seq - 1])) cache.entries = []
+ this.histCache = cache
+ for (let page = 0; page < PAGES && cache.entries.length < state.head.seq; page++) {
+ const since = cache.entries.length
+ const got = await this.deps.fetch(since)
+ if (!got || got.acct !== state.acct) break
+ let progressed = false
+ for (const raw of got.entries) {
+ const e = parseDevLogEntry(raw)
+ const rawSeq = (raw as { seq?: unknown } | null)?.seq
+ const seq = e?.seq ?? (typeof rawSeq === 'number' ? rawSeq : 0)
+ if (seq <= cache.entries.length || seq > state.head.seq) continue
+ // At a position this machine verified, anything unreadable or off-hash means the backend is
+ // lying about the past: freeze, and show only what was already checked.
+ if (!e || e.seq !== cache.entries.length + 1 || devLogHash(e) !== state.hashes[e.seq - 1]) {
+ // Only against the log this walk started from: if the file was rebaselined (or moved to
+ // another account) while the pages were on their way, the mismatch is with a log that is
+ // gone, and says nothing about the backend.
+ const now = this.deps.store.read().state
+ if (!now || now.acct !== state.acct || now.head.seq !== state.head.seq || now.head.hash !== state.head.hash) {
+ this.histCache = null
+ return this.historyOf([], false)
+ }
+ this.freeze('fork')
+ return this.historyOf(cache.entries, false)
+ }
+ cache.entries.push(e)
+ progressed = true
+ }
+ if (!progressed) break
+ }
+ return this.historyOf(cache.entries, cache.entries.length >= state.head.seq)
+ }
+
+ private historyOf(fetched: readonly DevLogEntry[], complete: boolean): DeviceLogHistory {
+ const file = this.deps.store.read()
+ const state = file.state
+ if (!state) return { rows: [], complete: false, frozen: file.frozen }
+ // Offline, the newest entries kept locally fill in what could not be fetched.
+ const entries = complete ? fetched : [...fetched, ...file.recent.filter((e) => e.seq > (fetched.at(-1)?.seq ?? 0))]
+ const rows = devLogHistory(entries, {
+ // A key that joined and left before anyone looked is still new, in its rows too.
+ selfPub: this.deps.identity().pub, joinedSeq: file.joinedSeq, active: state.active, loose: file.looseRemoved,
+ pending: [...(file.pending ?? []), ...(file.departed ?? []).map((d) => d.pub)],
+ })
+ return { rows, complete, frozen: file.frozen }
+ }
+
/** The account's devices as this machine's log has them, for the Devices list. */
list(): DeviceLogListing {
- const file = this.deps.store.read()
+ const file = this.marks()
const selfPub = this.deps.identity().pub
+ const pending = file.pending ?? []
+ const suspended = file.suspended ?? []
const members = Object.values(file.state?.active ?? {})
.sort((a, b) => a.seq - b.seq)
- .map((m) => ({ ...m, fingerprint: fingerprint(b64d(m.pub)), self: m.pub === selfPub }))
+ .map((m) => ({ ...m, fingerprint: fp(m.pub), self: m.pub === selfPub, pending: pending.includes(m.pub), suspended: suspended.includes(m.pub) }))
const labels = new Map(members.map((m) => [m.pub, m.label]))
- const frozenPeers = [...this.frozenPeers].filter(([, frozen]) => frozen).map(([pub]) => labels.get(pub) ?? fingerprint(b64d(pub)))
+ const frozenPeers = [...this.frozenPeers].filter(([, frozen]) => frozen).map(([pub]) => labels.get(pub) ?? fp(pub))
// Each row carries when this machine first applied it (never the entry's self-chosen `at`).
const withSeen = members.map((m) => (file.firstSeen?.[m.pub] === undefined ? m : { ...m, firstSeen: file.firstSeen[m.pub] }))
- return { head: file.state?.head ?? null, frozen: file.frozen, self: selfPub, members: withSeen, frozenPeers }
+ const joinedSeq = file.joinedSeq ?? 0
+ const preLog = new Set(file.preLog ?? [])
+ const baseline = withSeen.filter((m) => !m.self && (m.seq <= joinedSeq || preLog.has(m.pub))).map((m) => m.pub)
+ const holder = file.conflict
+ const conflict = holder && file.state?.active[holder.pub] && !file.state.active[selfPub] ? holder : null
+ return {
+ head: file.state?.head ?? null, frozen: file.frozen, self: selfPub, members: withSeen, frozenPeers,
+ pending, suspended, joinedSeq, baseline, baselineSeen: file.baselineSeen ?? true, conflict, departed: file.departed ?? [],
+ }
}
}
diff --git a/cli/src/lib/e2ee/groupSyncer.spec.ts b/cli/src/lib/e2ee/groupSyncer.spec.ts
index 6bc4f1191..9bcd4e519 100644
--- a/cli/src/lib/e2ee/groupSyncer.spec.ts
+++ b/cli/src/lib/e2ee/groupSyncer.spec.ts
@@ -356,6 +356,42 @@ describe('GroupSyncer', () => {
})
})
+describe('GroupSyncer — suspended keys', () => {
+ it('never pins, trusts or dials a suspended key; suspend() unlinks it, resume() puts it back', async () => {
+ vi.useFakeTimers()
+ const f = fleet()
+ const [a, b] = [f.add('a'), f.add('b')]
+ f.link(a, b)
+ expect(a.peers.get(b.machineId!)).not.toBeNull()
+ const suspended = new Set<string>()
+ ;(a.syncer as unknown as { deps: { suspended?: () => Set<string> } }).deps.suspended = () => suspended
+ suspended.add(b.pub)
+ a.syncer.suspend([b.pub])
+ expect(a.peers.get(b.machineId!)).toBeNull()
+ expect(a.trusted.has(b.pub)).toBe(false)
+ expect(a.droppedSessions).toContain(b.machineId)
+ a.syncer.resume()
+ expect(a.peers.get(b.machineId!)).toBeNull() // still suspended: not re-pinned
+ suspended.clear()
+ a.syncer.resume()
+ expect(a.peers.get(b.machineId!)?.pub).toBe(b.pub)
+ expect(a.trusted.has(b.pub)).toBe(true)
+ for (const n of f.nodes) n.syncer.stop()
+ })
+
+ it('a suspended member is not a syncAll target', async () => {
+ vi.useFakeTimers()
+ const f = fleet()
+ const [a, b] = [f.add('a'), f.add('b')]
+ f.link(a, b)
+ ;(a.syncer as unknown as { deps: { suspended?: () => Set<string> } }).deps.suspended = () => new Set([b.pub])
+ const spy = vi.spyOn(a.syncer, 'syncWith')
+ await a.syncer.syncAll()
+ expect(spy).not.toHaveBeenCalled()
+ for (const n of f.nodes) n.syncer.stop()
+ })
+})
+
describe('relayRequester', () => {
it('resolves with the matching _result and detaches; null on timeout', async () => {
let detached = 0
diff --git a/cli/src/lib/e2ee/groupSyncer.ts b/cli/src/lib/e2ee/groupSyncer.ts
index f1af4ee33..d5d3f6e29 100644
--- a/cli/src/lib/e2ee/groupSyncer.ts
+++ b/cli/src/lib/e2ee/groupSyncer.ts
@@ -54,6 +54,8 @@ export interface GroupSyncerDeps {
/** Close every open relay session to a machine the group removed — a lingering one would otherwise
* keep working after its pin is gone, since a pooled session is reused without looking again. */
dropSessions?: (machineId: string) => void
+ /** Keys a fork put out of trust here until reviewed (deviceLogSyncer.ts): never pinned, trusted or dialed. */
+ suspended?: () => ReadonlySet<string>
/** Machines worth dialing now; null = unknown, try every member. */
reachable?: () => Set<string> | null
now?: () => number
@@ -118,6 +120,17 @@ export class GroupSyncer {
return known || result.dropped.length > 0
}
+ /** A fork put these keys out of trust here: unpin, untrust and stop dialing them — locally only (no
+ * tombstone, so nothing is removed for anyone else) until `resume`. */
+ suspend(pubs: readonly string[]): void {
+ for (const pub of pubs) this.forget(pub)
+ }
+
+ /** The suspension was lifted (a review): pin and trust the roster again. */
+ resume(): void {
+ this.applyAll()
+ }
+
/** This machine's user unpaired `pub` (`harness unpair`): stop trusting and dialing it HERE, and keep
* it that way — without this the next round would put back what the roster still names. */
unpaired(pub: string): void {
@@ -198,8 +211,9 @@ export class GroupSyncer {
const reachable = this.deps.reachable?.() ?? null
const self = this.deps.self().machineId
const targets = new Set<string>()
- for (const m of this.deps.store.read().members) if (m.kind === 'machine' && m.machineId) targets.add(m.machineId)
- for (const p of this.deps.peers.list()) targets.add(p.machineId)
+ const suspended = this.deps.suspended?.() ?? new Set<string>()
+ for (const m of this.deps.store.read().members) if (m.kind === 'machine' && m.machineId && !suspended.has(m.pub)) targets.add(m.machineId)
+ for (const p of this.deps.peers.list()) if (!suspended.has(p.pub)) targets.add(p.machineId)
if (self) targets.delete(self)
// All at once: one machine that never answers (offline, or too old to know the frame) must not
// hold up the rest for its whole timeout.
@@ -286,8 +300,9 @@ export class GroupSyncer {
private apply(result: MergeResult): void {
const selfMachine = this.deps.self().machineId
const blocked = this.deps.store.blocked()
+ const suspended = this.deps.suspended?.() ?? new Set<string>()
for (const m of result.upserted) {
- if (blocked.has(m.pub)) continue
+ if (blocked.has(m.pub) || suspended.has(m.pub)) continue
try {
if (m.kind === 'machine' && m.machineId && m.machineId !== selfMachine) {
const pin = this.deps.peers.get(m.machineId)
diff --git a/cli/src/lib/remoteRelay.spec.ts b/cli/src/lib/remoteRelay.spec.ts
index 899c37bd2..e06910cfa 100644
--- a/cli/src/lib/remoteRelay.spec.ts
+++ b/cli/src/lib/remoteRelay.spec.ts
@@ -627,6 +627,20 @@ describe('RemoteRelayPool shares one upstream between every local client selecte
clearTimeout(entry.lingerTimer!)
})
+ it.each(['device_key_added', 'device_key_removed', 'device_conflict', 'device_keys_changed'])(
+ 'a %s frame from the remote machine never reaches the local app: those notices are this daemon\'s own', async (type) => {
+ const { pool, entry } = poolWithEntry()
+ const app = sink()
+ await pool.acquire('m1', 'env', { type: 'machine_select', payload: {} }, app, vi.fn())
+ app.sendFrame.mockClear()
+ // Delivered as far as the sender knows (the client is not dropped for it), but not forwarded.
+ expect(entry.sink!.sendFrame({ type, payload: { pub: 'evil' } })).toBe(true)
+ expect(app.sendFrame).not.toHaveBeenCalled()
+ expect(entry.attached.size).toBe(1)
+ entry.sink!.sendFrame({ type: 'agent_created', payload: {} })
+ expect(app.sendFrame).toHaveBeenCalledWith({ type: 'agent_created', payload: {} })
+ })
+
it('a client whose socket refuses a frame is dropped; the rest keep receiving', async () => {
const { pool, entry } = poolWithEntry()
const live = sink()
diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.ts
index 2ec16a9bb..3cefab2a3 100644
--- a/cli/src/lib/remoteRelay.ts
+++ b/cli/src/lib/remoteRelay.ts
@@ -106,6 +106,14 @@ function binaryBytes(raw: RawData): Uint8Array {
return new Uint8Array()
}
+/**
+ * Frames only THIS machine's own daemon says to its own windows (the device key log's notices). A
+ * remote machine is not that daemon: if its frame reached the local app as-is, the app would show a
+ * "new device" / "removed by" band as though this machine had verified it. Dropped on the way in,
+ * sealed or not.
+ */
+export const DAEMON_LOCAL_ONLY_TYPES: ReadonlySet<string> = new Set(['device_key_added', 'device_key_removed', 'device_conflict', 'device_keys_changed'])
+
/** One local client attached to a pooled upstream: where its frames go, and what to tell it on close. */
interface AttachedClient {
sink: LocalClientSink
@@ -122,6 +130,8 @@ function bindAttached(entry: Entry): void {
if (clients.size === 0) { entry.sink = null; entry.onClosed = null; return }
entry.sink = {
sendFrame: (frame) => {
+ // Not delivered, and not a refusal either: nobody is dropped for a frame that never goes out.
+ if (typeof frame.type === 'string' && DAEMON_LOCAL_ONLY_TYPES.has(frame.type)) return true
let delivered = false
for (const client of [...clients]) {
if (client.sink.sendFrame(frame)) delivered = true
diff --git a/cli/src/loginForceRace.spec.ts b/cli/src/loginForceRace.spec.ts
index b8494d37b..c850bfc3e 100644
--- a/cli/src/loginForceRace.spec.ts
+++ b/cli/src/loginForceRace.spec.ts
@@ -210,6 +210,6 @@ describe('login --force beside a start that lands mid-sign-in', () => {
.filter((line) => line.type === 'result')
expect(results).toEqual([expect.objectContaining({ type: 'result', status: 'success' })])
expect(JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')))
- .toMatchObject({ accessToken: 'tok_new', machineId: 'm_new' })
+ .toMatchObject({ accessToken: 'tok_new', machineId: 'm_new', signInEpoch: expect.stringMatching(/^[0-9a-f]{32}@\d+$/) })
}, 30_000)
})
diff --git a/cli/src/sharing/relay.spec.ts b/cli/src/sharing/relay.spec.ts
index 64a2e3134..7bc0937b0 100644
--- a/cli/src/sharing/relay.spec.ts
+++ b/cli/src/sharing/relay.spec.ts
@@ -71,6 +71,16 @@ describe('recipient relay', () => {
await session.send({ type: 'terminal_alive' })
expect(ws.send).toHaveBeenCalledTimes(count)
})
+ it('never forwards the daemon-local device notices a share owner sends', async () => {
+ const { ws, owner } = await ready()
+ sink.sendFrame.mockClear()
+ for (const type of ['device_key_added', 'device_key_removed', 'device_conflict', 'device_keys_changed']) {
+ frame(ws, 'observer_frame', owner.cipher.seal({ type, payload: { pub: 'x' } }))
+ }
+ expect(sink.sendFrame).not.toHaveBeenCalled()
+ frame(ws, 'observer_frame', owner.cipher.seal({ type: 'observer_viewer', payload: { state: 'live' } }))
+ expect(sink.sendFrame).toHaveBeenCalledTimes(1)
+ })
it('refuses unpublished or wrong-machine grants before opening a socket', async () => {
discover.mockResolvedValue([])
await expect(relay.acquire('machine', 'share', sink as never, closed)).rejects.toBeInstanceOf(SharingEndedError)
diff --git a/cli/src/sharing/relay.ts b/cli/src/sharing/relay.ts
index 668a21016..09c8bf5e9 100644
--- a/cli/src/sharing/relay.ts
+++ b/cli/src/sharing/relay.ts
@@ -2,7 +2,7 @@ import { WebSocket } from 'ws'
import { b64e, newEphemeral } from '../lib/e2ee/core.js'
import type { AuthSessionManager } from '../lib/authSession.js'
import type { Frame, LocalClientSink } from '../backendSocket.js'
-import type { RelaySession } from '../lib/remoteRelay.js'
+import { DAEMON_LOCAL_ONLY_TYPES, type RelaySession } from '../lib/remoteRelay.js'
import { recipientHandshake, type ObserverCipher } from './crypto.js'
import { BACKEND_IDLE_DEADLINE_MS, watchSocketLiveness } from '../lib/wsLiveness.js'
@@ -67,7 +67,7 @@ export class HarnessShareRelay {
if (clear.type === 'observer_binary') {
const bytes = (clear.payload as { bytes?: unknown })?.bytes
if (typeof bytes === 'string') sink.sendBinary(Buffer.from(bytes, 'base64'))
- } else sink.sendFrame(clear)
+ } else if (!(typeof clear.type === 'string' && DAEMON_LOCAL_ONLY_TYPES.has(clear.type))) sink.sendFrame(clear)
}
} catch {
clearTimeout(timeout)
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 9f10a3334..bf69e89e9 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -374,16 +374,50 @@ class ApiClient {
}
}
+ /// `GET /api/devices/history` — every add and remove, as the daemon verified it. Null when the
+ /// daemon predates the route (404); throws when it cannot answer.
+ Future<Map<String, dynamic>?> daemonDeviceHistory() async {
+ final res = await _dio.get(
+ '/api/devices/history',
+ options: Options(headers: {'x-adapter-local': '1'}),
+ );
+ if (res.statusCode == 404) return null;
+ final data = res.data;
+ if (res.statusCode == 200 && data is Map<String, dynamic>) return data;
+ throw StateError('HTTP_${res.statusCode}');
+ }
+
+ /// `POST /api/devices/dismiss` — new devices marked as seen: [pub] one, neither argument every
+ /// one, [pubs] exactly those (what the person was shown), [baseline] the "Already on your account"
+ /// list. False when the daemon predates the route (an old one answers a `pubs` body with an error).
+ Future<bool> daemonDismissDevices({String? pub, List<String>? pubs, bool baseline = false}) async {
+ try {
+ final res = await _dio.post(
+ '/api/devices/dismiss',
+ data: {'pub': ?pub, 'pubs': ?pubs, if (baseline) 'baseline': true},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ );
+ return res.statusCode == 200;
+ } catch (_) {
+ return false;
+ }
+ }
+
/// `POST /api/devices/rebaseline` — what trusting the backend's list again changes; [confirm]
- /// does it. Null when the daemon could not read a valid list.
- Future<Map<String, dynamic>?> daemonRebaselineDevices({required bool confirm}) async {
+ /// does it, for the list whose [head] (`{seq, hash}`) the preview showed. Null when the daemon could
+ /// not read a valid list; `{'error': 'LOG_CHANGED'}` when the list is not the one that was previewed;
+ /// `{'error': 'OTHER_ACCOUNT'}` when it is another account's than the one this computer is signed in to.
+ Future<Map<String, dynamic>?> daemonRebaselineDevices({required bool confirm, Map<String, Object?>? head}) async {
try {
final res = await _dio.post(
'/api/devices/rebaseline',
- data: {'confirm': confirm},
+ data: {'confirm': confirm, 'head': ?head},
options: Options(headers: {'x-adapter-local': '1'}),
);
final data = res.data;
+ if (res.statusCode == 409) {
+ return {'error': data is Map && data['error'] == 'OTHER_ACCOUNT' ? 'OTHER_ACCOUNT' : 'LOG_CHANGED'};
+ }
return res.statusCode == 200 && data is Map<String, dynamic> ? data : null;
} catch (_) {
return null;
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dart
index 13e233f01..da647d110 100644
--- a/desktop/lib/app_shell.dart
+++ b/desktop/lib/app_shell.dart
@@ -374,6 +374,8 @@ class _RootShellState extends ConsumerState<RootShell>
// overlay it landed on the rail's head — covering the wordmark and the
// three buttons beside it, which is the one strip of this window that
// must stay reachable.
+ // Device bands, most urgent first: a removal (red before neutral), a key that joined and left,
+ // a new device, a held computer id. The mobile app stacks them in the same order.
return Column(
children: [
// The app's commands as a menu strip (Linux only; macOS carries
@@ -384,9 +386,18 @@ class _RootShellState extends ConsumerState<RootShell>
app.status != AppStatus.checkingEnvironment &&
app.status != AppStatus.preparingEnvironment)
UpdateNotice(notifier: app),
+ if (app.visibleDeviceRemovals.isNotEmpty &&
+ app.status == AppStatus.authenticated)
+ DeviceRemovalNoticeBand(notifier: app),
+ if (app.departedDevices.isNotEmpty &&
+ app.status == AppStatus.authenticated)
+ DeviceDepartedNoticeBand(notifier: app),
if (app.newDevices.isNotEmpty &&
app.status == AppStatus.authenticated)
NewDeviceNotice(notifier: app),
+ if (app.deviceConflict != null &&
+ app.status == AppStatus.authenticated)
+ DeviceConflictNoticeBand(notifier: app),
Expanded(child: framed),
],
);
diff --git a/desktop/lib/settings/sections/account_device_detail.dart b/desktop/lib/settings/sections/account_device_detail.dart
index aac7d45d6..9bb9d05fb 100644
--- a/desktop/lib/settings/sections/account_device_detail.dart
+++ b/desktop/lib/settings/sections/account_device_detail.dart
@@ -8,6 +8,7 @@ import '../../shared/widgets/app_dialog.dart';
import '../../shared/widgets/fingerprint_text.dart';
import '../../state/account_devices.dart';
import '../../state/app_state.dart';
+import '../../theme/app_theme.dart';
/// What removing a device does, said in the confirm and nowhere else so the two entry points (the list
/// row and the detail) cannot word it differently.
@@ -161,12 +162,17 @@ class _AccountDeviceDetailState extends State<_AccountDeviceDetail> {
}
setState(() {
_removing = false;
- _error = "Couldn't remove $name ($error). Try again.";
+ _error = 'Couldn’t remove $name ($error). Try again.';
});
}
void _mine() {
- widget.app.dismissNewDevice(widget.pub);
+ // Only a suspension this dialog SHOWS is lifted. Before the device has loaded (opened from the
+ // banner or a notification) it dismisses the way the banner's own button does, which keeps it.
+ widget.app.dismissNewDevice(
+ widget.pub,
+ liftSuspension: _device?.suspended == true,
+ );
widget.onMine?.call();
Navigator.pop(context);
}
@@ -245,12 +251,25 @@ class _AccountDeviceDetailState extends State<_AccountDeviceDetail> {
),
),
],
+ if (device?.suspended ?? false) ...[
+ const SizedBox(height: 12),
+ Text(
+ 'Not trusted here: added after this device’s list and another’s split. '
+ 'Review the list to trust it again.',
+ key: const Key('device-detail-suspended'),
+ style: grid.AppType.body(
+ color: grid.AppPalette.warn,
+ height: 1.4,
+ ),
+ ),
+ ],
if (_error case final error?) ...[
const SizedBox(height: 12),
Text(
error,
key: const Key('device-detail-error'),
- style: grid.AppType.body(color: grid.AppPalette.warn),
+ // A failure to remove is red; only a state to review again is amber.
+ style: grid.AppType.body(color: AppColors.danger),
),
],
],
@@ -259,7 +278,9 @@ class _AccountDeviceDetailState extends State<_AccountDeviceDetail> {
),
actions: [
closeButton,
- if (widget.isNew)
+ // New by the caller's word, or by the list's own once it has loaded (a notification's click can
+ // land before the banner has been rebuilt from the log).
+ if (widget.isNew || device?.pending == true)
TextButton(
key: const Key('device-detail-mine'),
onPressed: _removing ? null : _mine,
diff --git a/desktop/lib/settings/sections/account_device_history.dart b/desktop/lib/settings/sections/account_device_history.dart
new file mode 100644
index 000000000..e7ecc21ea
--- /dev/null
+++ b/desktop/lib/settings/sections/account_device_history.dart
@@ -0,0 +1,234 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../../core/relative_time.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/app_dialog.dart';
+import '../../state/app_state.dart';
+import '../../theme/app_theme.dart';
+import '../../viewer/device_history.dart';
+import 'account_device_detail.dart';
+
+/// Settings ▸ Your devices ▸ History… — every device added to or removed from the account, newest
+/// first, as this end verified the log. A device that was removed stays in it, named as it was.
+Future<void> showAccountDeviceHistory(BuildContext context, AppNotifier app) =>
+ showAppDialog<void>(
+ context: context,
+ builder: (context) => _AccountDeviceHistory(app: app),
+ );
+
+class _AccountDeviceHistory extends StatefulWidget {
+ const _AccountDeviceHistory({required this.app});
+
+ final AppNotifier app;
+
+ @override
+ State<_AccountDeviceHistory> createState() => _AccountDeviceHistoryState();
+}
+
+class _AccountDeviceHistoryState extends State<_AccountDeviceHistory> {
+ DeviceLogHistory? _history;
+ bool _loading = true;
+ bool _failed = false;
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_load());
+ }
+
+ Future<void> _load() async {
+ setState(() {
+ _loading = true;
+ _failed = false;
+ });
+ DeviceLogHistory? history;
+ var failed = false;
+ try {
+ history = await widget.app.loadDeviceHistory();
+ } catch (_) {
+ failed = true;
+ }
+ if (!mounted) return;
+ setState(() {
+ _history = history;
+ _failed = failed || history == null;
+ _loading = false;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final history = _history;
+ final Widget body;
+ if (_loading) {
+ body = Text(
+ 'Loading…',
+ style: grid.AppType.body(color: grid.AppPalette.textSecondary),
+ );
+ } else if (history == null || _failed) {
+ body = Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Couldn’t load the history. Try again.',
+ key: const Key('device-history-error'),
+ style: grid.AppType.body(color: AppColors.danger),
+ ),
+ const SizedBox(height: 8),
+ OutlinedButton(
+ key: const Key('device-history-retry'),
+ onPressed: () => unawaited(_load()),
+ child: const Text('Try again'),
+ ),
+ ],
+ );
+ } else {
+ body = Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final row in history.rows)
+ _HistoryRow(
+ key: ValueKey('device-history-${row.seq}'),
+ row: row,
+ onOpen: row.active
+ ? () => unawaited(
+ showAccountDeviceDetail(
+ context,
+ widget.app,
+ pub: row.pub,
+ isNew: row.pending,
+ ),
+ )
+ : null,
+ ),
+ if (history.rows.isEmpty && history.complete)
+ Text(
+ 'No history yet.',
+ key: const Key('device-history-empty'),
+ style: grid.AppType.body(color: grid.AppPalette.textSecondary),
+ ),
+ if (!history.complete)
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Text(
+ 'Older history needs a connection.',
+ key: const Key('device-history-incomplete'),
+ style: grid.AppType.body(color: grid.AppPalette.textSecondary),
+ ),
+ ),
+ ],
+ );
+ }
+ return AlertDialog(
+ title: const Text('Device history'),
+ content: SizedBox(
+ width: 460,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ 'Every device added to or removed from your account, newest first, as this device verified it.',
+ style: grid.AppType.body(
+ color: grid.AppPalette.textSecondary,
+ height: 1.4,
+ ),
+ ),
+ const SizedBox(height: 14),
+ body,
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ key: const Key('device-history-close'),
+ onPressed: () => Navigator.pop(context),
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ overlayColor: grid.AppSurface.hoverFill,
+ ),
+ child: const Text('Close'),
+ ),
+ ],
+ );
+ }
+}
+
+class _HistoryRow extends StatelessWidget {
+ const _HistoryRow({super.key, required this.row, required this.onOpen});
+
+ final DevLogHistoryRow row;
+ final VoidCallback? onOpen;
+
+ @override
+ Widget build(BuildContext context) {
+ final when = fullDateTime(DateTime.fromMillisecondsSinceEpoch(row.at));
+ final what = row.kind == 'machine' ? 'Computer' : 'App';
+ final detail =
+ '$when · $what${row.fingerprint.isEmpty ? '' : ' · ${row.fingerprint}'}';
+ final content = Padding(
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Flexible(
+ child: Text(
+ historySentence(row),
+ style: grid.AppType.body(color: grid.AppPalette.textPrimary),
+ ),
+ ),
+ if (row.thisDevice) ...[
+ const SizedBox(width: 6),
+ Text(
+ '(this device)',
+ style: grid.AppType.caption(
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ ],
+ if (row.pending) ...[
+ const SizedBox(width: 6),
+ DecoratedBox(
+ decoration: BoxDecoration(
+ color: grid.AppPalette.warn.withValues(alpha: 0.12),
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6,
+ vertical: 1,
+ ),
+ child: Text(
+ // A key that was new and is gone again: its flag stays until dismissed.
+ row.active ? 'New' : 'Left before you looked',
+ style: grid.AppType.caption(color: grid.AppPalette.warn),
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ Text(
+ detail,
+ style: grid.AppType.caption(color: grid.AppPalette.textSecondary),
+ ),
+ ],
+ ),
+ );
+ if (onOpen == null) return content;
+ // A device still on the account opens its page — by keyboard too (Tab, then Enter or Space).
+ return InkWell(
+ onTap: onOpen,
+ borderRadius: BorderRadius.circular(4),
+ hoverColor: grid.AppSurface.hoverFill,
+ child: content,
+ );
+ }
+}
diff --git a/desktop/lib/settings/sections/account_devices_section.dart b/desktop/lib/settings/sections/account_devices_section.dart
index 14d183a69..68a0dc942 100644
--- a/desktop/lib/settings/sections/account_devices_section.dart
+++ b/desktop/lib/settings/sections/account_devices_section.dart
@@ -11,7 +11,14 @@ import '../../shared/widgets/setting_row.dart';
import '../../shared/widgets/skeleton.dart';
import '../../state/account_devices.dart';
import '../../state/app_state.dart';
+import '../../theme/app_theme.dart';
import 'account_device_detail.dart';
+import 'account_device_history.dart';
+
+/// What "Trust again" says when the list it would trust is another account's than the one signed in to.
+const otherAccountMessage =
+ 'The device list now belongs to a different account than the one you signed in with. '
+ 'Sign in again to switch accounts.';
/// Settings ▸ Your devices — every computer and app signed in to this account. Signing in on one is
/// what makes the others trust it (the device key log), so this list is also the one place to see a
@@ -32,10 +39,17 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
final Set<String> _removing = {};
String? _error;
+ /// The error is a state to review again (another account, a list that changed), not a failure: amber.
+ /// Every other error is red.
+ bool _errorIsNotice = false;
+
/// The devices that were new when this list opened: they keep their `New` badge for the visit, though
/// opening the list clears the banner that announced them.
late final Set<String> _newPubs;
+ /// "Got it" was pressed on the baseline panel: hidden at once, whatever the write takes.
+ bool _baselineDone = false;
+
AppNotifier get _app => widget.notifier;
@override
@@ -44,10 +58,6 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
_app.addListener(_changed);
_newPubs = {for (final d in _app.newDevices) d.pub};
unawaited(_load());
- // Looking at the list IS reviewing the new devices: the banner that pointed here is done.
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) _app.seenNewDevices();
- });
}
@override
@@ -62,12 +72,33 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
Future<void> _load() async {
_revision = _app.devicesRevision;
- final devices = await _app.loadDevices();
+ final first = !_loaded;
+ List<String>? banner;
+ final devices = await _app.loadDevices(onListed: (b) => banner = b);
if (!mounted) return;
setState(() {
_devices = devices;
_loaded = true;
+ // What the log kept as new (it outlives the banner and a restart) badges alongside the banner's —
+ // on every read, so a device that turns up while the list is open is badged too (it stays pending:
+ // only the first read of a visit is marked seen below).
+ if (devices != null) _newPubs.addAll(devices.pending);
+ if (!first) _newPubs.addAll(_app.newDevices.map((d) => d.pub));
});
+ // Looking at the list IS reviewing the new devices: the banner that pointed here is done. After
+ // the first read, so the pending keys are in [_newPubs] before they are marked seen.
+ if (first) {
+ _app.seenNewDevices(
+ pending: devices?.pending ?? const [],
+ shown: banner,
+ departed: devices?.departed ?? const [],
+ );
+ }
+ }
+
+ Future<void> _gotIt() async {
+ setState(() => _baselineDone = true);
+ await _app.seeDeviceBaseline();
}
Future<void> _remove(AccountDevice device) async {
@@ -83,12 +114,14 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
setState(() {
_removing.add(device.pub);
_error = null;
+ _errorIsNotice = false;
});
final error = await _app.removeDevice(device.pub);
if (!mounted) return;
setState(() {
_removing.remove(device.pub);
- _error = error == null ? null : "Couldn't remove $name ($error). Try again.";
+ _error = error == null ? null : 'Couldn’t remove $name ($error). Try again.';
+ _errorIsNotice = false;
});
}
@@ -106,6 +139,7 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
setState(() {
_removingUnused = true;
_error = null;
+ _errorIsNotice = false;
});
final failed = <String>[];
for (final d in unused) {
@@ -114,7 +148,8 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
if (!mounted) return;
setState(() {
_removingUnused = false;
- _error = failed.isEmpty ? null : "Couldn't remove ${failed.join(', ')}. Try again.";
+ _error = failed.isEmpty ? null : 'Couldn’t remove ${failed.join(', ')}. Try again.';
+ _errorIsNotice = false;
});
}
@@ -122,7 +157,17 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
final preview = await _app.rebaselineDevices(confirm: false);
if (!mounted) return;
if (preview == null) {
- setState(() => _error = "Couldn't read a valid device list. Try again later.");
+ setState(() {
+ _error = 'Couldn’t read a valid device list. Try again later.';
+ _errorIsNotice = false;
+ });
+ return;
+ }
+ if (preview.otherAccount) {
+ setState(() {
+ _error = otherAccountMessage;
+ _errorIsNotice = true;
+ });
return;
}
final lines = [
@@ -136,9 +181,35 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
? 'It changes no device. Continue only if you expected this.'
: 'Only if every device added below is yours:\n\n${lines.join('\n')}',
'Trust again',
+ // Trusting a list the backend served is the cautionary action: the same red as Remove.
+ destructive: true,
);
if (!confirmed || !mounted) return;
- await _app.rebaselineDevices(confirm: true);
+ final done = await _app.rebaselineDevices(confirm: true, head: preview.head);
+ if (!mounted) return;
+ if (done == null) {
+ setState(() {
+ _error = 'Couldn’t trust the device list again. Try again later.';
+ _errorIsNotice = false;
+ });
+ } else if (done.otherAccount) {
+ setState(() {
+ _error = otherAccountMessage;
+ _errorIsNotice = true;
+ });
+ } else if (!done.logChanged) {
+ setState(() {
+ _error = null;
+ _errorIsNotice = false;
+ });
+ } else {
+ // What was reviewed is no longer what the backend serves: nothing was trusted. Show it again.
+ setState(() {
+ _error = 'The device list changed while you were reviewing it. Review it again.';
+ _errorIsNotice = true;
+ });
+ unawaited(_trustAgain());
+ }
}
void _open(AccountDevice device) => unawaited(
@@ -165,10 +236,16 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (devices != null && devices.frozen) _FrozenLine(devices: devices, onTrustAgain: _trustAgain),
+ if (devices != null && !devices.baselineSeen && !_baselineDone && !_app.baselineSeenLocally && devices.baseline.isNotEmpty)
+ _BaselinePanel(devices: devices.baseline, onGotIt: () => unawaited(_gotIt())),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(bottom: 12),
- child: Text(error, style: grid.AppType.body(color: grid.AppPalette.warn)),
+ child: Text(
+ error,
+ key: const Key('account-devices-error'),
+ style: grid.AppType.body(color: _errorIsNotice ? AppColors.warning : AppColors.danger),
+ ),
),
if (devices != null && devices.unused(DateTime.now()).isNotEmpty)
Padding(
@@ -214,7 +291,11 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
child: SettingRow(
key: ValueKey('account-device-${device.pub}'),
title: device.label.trim().isEmpty ? 'Unnamed device' : device.label,
- badge: _newPubs.contains(device.pub) ? 'New' : null,
+ badge: device.suspended
+ ? 'Suspended'
+ : _newPubs.contains(device.pub)
+ ? 'New'
+ : null,
detail: deviceDetailLine(
device,
now: DateTime.now(),
@@ -239,6 +320,23 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
),
),
),
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: devices.historyAvailable
+ ? Align(
+ alignment: Alignment.centerLeft,
+ child: OutlinedButton(
+ key: const Key('account-devices-history'),
+ onPressed: () => unawaited(showAccountDeviceHistory(context, _app)),
+ child: const Text('History…'),
+ ),
+ )
+ : Text(
+ 'Update Harness on this computer to see history.',
+ key: const Key('account-devices-history-hint'),
+ style: grid.AppType.body(color: grid.AppPalette.textSecondary),
+ ),
+ ),
],
],
),
@@ -247,6 +345,56 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {
}
}
+/// The devices that were already on the account when this one joined: never announced, so said once.
+class _BaselinePanel extends StatelessWidget {
+ const _BaselinePanel({required this.devices, required this.onGotIt});
+
+ final List<AccountDevice> devices;
+ final VoidCallback onGotIt;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: DecoratedBox(
+ key: const Key('account-devices-baseline'),
+ decoration: BoxDecoration(
+ color: grid.AppPalette.warn.withValues(alpha: 0.10),
+ borderRadius: BorderRadius.circular(8),
+ border: Border.all(color: grid.AppPalette.warn.withValues(alpha: 0.28)),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text('Already on your account', style: Theme.of(context).textTheme.titleSmall),
+ const SizedBox(height: 4),
+ Text(
+ 'These were on your account before this device joined. If one isn’t yours, remove it.',
+ style: grid.AppType.body(color: grid.AppPalette.textPrimary),
+ ),
+ const SizedBox(height: 8),
+ for (final d in devices)
+ Text(
+ '${d.label.trim().isEmpty ? 'A device' : d.label.trim()} · ${d.isMachine ? 'Computer' : 'App'} · ${d.fingerprint}',
+ style: grid.AppType.caption(color: grid.AppPalette.textSecondary),
+ ),
+ const SizedBox(height: 8),
+ Align(
+ alignment: Alignment.centerRight,
+ child: OutlinedButton(
+ key: const Key('account-devices-baseline-gotit'),
+ onPressed: onGotIt,
+ child: const Text('Got it'),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+}
+
class _FrozenLine extends StatelessWidget {
const _FrozenLine({required this.devices, required this.onTrustAgain});
diff --git a/desktop/lib/state/account_devices.dart b/desktop/lib/state/account_devices.dart
index 9706a9dbe..794e9b806 100644
--- a/desktop/lib/state/account_devices.dart
+++ b/desktop/lib/state/account_devices.dart
@@ -17,6 +17,9 @@ class AccountDevice {
required this.fingerprint,
required this.self,
this.lastSeen,
+ this.seq,
+ this.pending = false,
+ this.suspended = false,
});
final String pub;
@@ -34,11 +37,20 @@ class AccountDevice {
/// When this key last opened an E2EE session, as the backend saw it; null when it does not know.
final DateTime? lastSeen;
+ /// The log entry that added it; null when the daemon predates the field.
+ final int? seq;
+
+ /// Joined after this end did and nobody marked it as seen.
+ final bool pending;
+
+ /// Not trusted here after a fork, until the list is reviewed.
+ final bool suspended;
+
bool get isMachine => kind == 'machine';
AccountDevice withLastSeen(DateTime? at) => AccountDevice(
pub: pub, label: label, kind: kind, machineId: machineId, addedAt: addedAt,
- fingerprint: fingerprint, self: self, lastSeen: at,
+ fingerprint: fingerprint, self: self, lastSeen: at, seq: seq, pending: pending, suspended: suspended,
);
static AccountDevice? fromDaemon(Object? raw) {
@@ -49,18 +61,67 @@ class AccountDevice {
return AccountDevice(
pub: pub, label: label, kind: kind, machineId: machineId is String ? machineId : '',
addedAt: DateTime.fromMillisecondsSinceEpoch(addedAt), fingerprint: fp, self: self == true,
+ seq: raw['seq'] is int ? raw['seq'] as int : null,
+ pending: raw['pending'] == true,
+ suspended: raw['suspended'] == true,
);
}
static AccountDevice fromRow(DeviceLogRow row) => AccountDevice(
pub: row.member.pub, label: row.member.label, kind: row.member.kind, machineId: row.member.machineId,
addedAt: DateTime.fromMillisecondsSinceEpoch(row.member.addedAt), fingerprint: row.fingerprint, self: row.self,
+ seq: row.member.seq, pending: row.pending, suspended: row.suspended,
);
}
+/// Another key holds this computer's id on the account, so this computer cannot register (a desktop
+/// build's daemon says so; `device_conflict`).
+class DeviceConflict {
+ const DeviceConflict({
+ required this.pub,
+ required this.label,
+ required this.fingerprint,
+ required this.addedAt,
+ required this.afterJoin,
+ });
+
+ final String pub;
+ final String label;
+ final String fingerprint;
+ final DateTime addedAt;
+
+ /// The holder was added after this computer joined: someone took its place.
+ final bool afterJoin;
+
+ /// The listing's `conflict` and the `device_conflict` frame's payload are the same object.
+ static DeviceConflict? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'], label = raw['label'], fp = raw['fingerprint'], addedAt = raw['addedAt'];
+ if (pub is! String || fp is! String || addedAt is! int) return null;
+ return DeviceConflict(
+ pub: pub,
+ label: label is String ? label : '',
+ fingerprint: fp,
+ addedAt: DateTime.fromMillisecondsSinceEpoch(addedAt),
+ afterJoin: raw['afterJoin'] == true,
+ );
+ }
+}
+
/// The account's devices and whether the list can be trusted as it stands.
class AccountDevices {
- const AccountDevices({required this.devices, this.frozenReason, this.frozenPeers = const []});
+ const AccountDevices({
+ required this.devices,
+ this.frozenReason,
+ this.frozenPeers = const [],
+ this.pending = const [],
+ this.joinedSeq,
+ this.baselineSeen = true,
+ this.baselineKeys,
+ this.conflict,
+ this.historyAvailable = true,
+ this.departed = const [],
+ });
final List<AccountDevice> devices;
@@ -74,6 +135,45 @@ class AccountDevices {
bool get frozen => frozenReason != null || frozenPeers.isNotEmpty;
+ /// Keys that joined after this end did and nobody marked as seen.
+ final List<String> pending;
+
+ /// The log's head when this end joined; null when the daemon predates it.
+ final int? joinedSeq;
+
+ /// false until the "Already on your account" list was acknowledged.
+ final bool baselineSeen;
+ final DeviceConflict? conflict;
+
+ /// Whether the history can be read from here: false for a daemon that predates it.
+ final bool historyAvailable;
+
+ /// Keys that joined and left before anyone looked, as this listing read them: the list is not where
+ /// they are cleared (their own "Got it" is), so opening it must not mark them seen.
+ final List<String> departed;
+
+ /// The keys the log's own listing named as the baseline panel's (`baseline`), when it sent them; null
+ /// from a daemon that predates it, which falls back to the `seq <= joinedSeq` rule.
+ final List<String>? baselineKeys;
+
+ /// The devices that were on the account before this end joined it, which it never announced.
+ List<AccountDevice> get baseline {
+ final keys = baselineKeys;
+ if (keys != null) {
+ final set = keys.toSet();
+ return [
+ for (final d in devices)
+ if (!d.self && set.contains(d.pub)) d,
+ ];
+ }
+ final joined = joinedSeq;
+ if (joined == null) return const [];
+ return [
+ for (final d in devices)
+ if (!d.self && d.seq != null && d.seq! <= joined) d,
+ ];
+ }
+
/// Apps not seen in [unusedAfter]: most likely a browser whose data was cleared, which never signs
/// its own removal. Offered for removal together; never this app, never a computer (whose
/// absence is visible in the machine list anyway), never one the backend has no record of.
@@ -126,6 +226,13 @@ class AccountDevices {
],
frozenReason: frozenReason,
frozenPeers: frozenPeers,
+ pending: pending,
+ joinedSeq: joinedSeq,
+ baselineSeen: baselineSeen,
+ baselineKeys: baselineKeys,
+ conflict: conflict,
+ historyAvailable: historyAvailable,
+ departed: departed,
);
static AccountDevices? fromDaemon(Map<String, dynamic>? raw) {
@@ -133,10 +240,19 @@ class AccountDevices {
final members = raw['members'];
final frozen = raw['frozen'];
final peers = raw['frozenPeers'];
+ final pending = raw['pending'];
return AccountDevices(
devices: members is List ? members.map(AccountDevice.fromDaemon).whereType<AccountDevice>().toList() : const [],
frozenReason: frozen is Map && frozen['reason'] is String ? frozen['reason'] as String : null,
frozenPeers: peers is List ? peers.whereType<String>().toList() : const [],
+ // An older daemon sends none of these: no `pending` array is how this end knows.
+ pending: pending is List ? pending.whereType<String>().toList() : const [],
+ joinedSeq: raw['joinedSeq'] is int ? raw['joinedSeq'] as int : null,
+ baselineSeen: raw['baselineSeen'] is bool ? raw['baselineSeen'] as bool : true,
+ baselineKeys: raw['baseline'] is List ? (raw['baseline'] as List).whereType<String>().toList() : null,
+ conflict: DeviceConflict.fromJson(raw['conflict']),
+ historyAvailable: pending is List,
+ departed: [for (final d in DeviceLogDeparted.listFromJson(raw['departed'])) d.pub],
).withLastSeen(parseLastSeen(raw['lastSeen']));
}
@@ -144,40 +260,94 @@ class AccountDevices {
devices: listing.members.map(AccountDevice.fromRow).toList(),
frozenReason: listing.frozen?.reason,
frozenPeers: listing.frozenPeers,
+ pending: listing.pending,
+ joinedSeq: listing.joinedSeq,
+ baselineSeen: listing.baselineSeen,
+ baselineKeys: listing.baseline,
+ departed: [for (final d in listing.departed) d.pub],
);
}
/// What trusting the backend's list again would change.
class DevicesRebaseline {
- const DevicesRebaseline({required this.added, required this.removed});
+ const DevicesRebaseline({
+ required this.added,
+ required this.removed,
+ this.head,
+ this.logChanged = false,
+ this.otherAccount = false,
+ });
+
+ /// The "the list changed under the review" answer: nothing was trusted, review again.
+ const DevicesRebaseline.changed()
+ : added = const [],
+ removed = const [],
+ head = null,
+ logChanged = true,
+ otherAccount = false;
+
+ /// The list is another account's than the one signed in to: nothing was trusted, and a review never
+ /// switches accounts — signing in again does.
+ const DevicesRebaseline.otherAccount()
+ : added = const [],
+ removed = const [],
+ head = null,
+ logChanged = false,
+ otherAccount = true;
final List<String> added;
final List<String> removed;
+ /// The head of the list this preview describes; handed back with the confirm so what gets trusted
+ /// is what was shown.
+ final DevLogHead? head;
+ final bool logChanged;
+ final bool otherAccount;
+
+ /// Nothing was trusted ([logChanged] or [otherAccount]).
+ bool get refused => logChanged || otherAccount;
+
static DevicesRebaseline? fromDaemon(Map<String, dynamic>? raw) {
if (raw == null) return null;
+ if (raw['error'] == 'LOG_CHANGED') return const DevicesRebaseline.changed();
+ if (raw['error'] == 'OTHER_ACCOUNT') return const DevicesRebaseline.otherAccount();
String name(Object? m) => m is Map && m['label'] is String && (m['label'] as String).isNotEmpty ? m['label'] as String : 'A device';
final added = raw['added'], removed = raw['removed'];
return DevicesRebaseline(
added: added is List ? added.map(name).toList() : const [],
removed: removed is List ? removed.map(name).toList() : const [],
+ head: DevLogHead.fromJson(raw['head']),
);
}
- static DevicesRebaseline fromViewer(DeviceLogRebaseline r) => DevicesRebaseline(
- added: [for (final m in r.added) m.label.isEmpty ? 'A device' : m.label],
- removed: [for (final m in r.removed) m.label.isEmpty ? 'A device' : m.label],
- );
+ static DevicesRebaseline fromViewer(DeviceLogRebaseline r) => r.otherAccount
+ ? const DevicesRebaseline.otherAccount()
+ : DevicesRebaseline(
+ added: [for (final m in r.added) m.label.isEmpty ? 'A device' : m.label],
+ removed: [for (final m in r.removed) m.label.isEmpty ? 'A device' : m.label],
+ head: r.logChanged ? null : r.head,
+ logChanged: r.logChanged,
+ );
}
/// A device that joined the account and this end had never trusted: "New device: X".
class NewDeviceNotice {
- const NewDeviceNotice({required this.pub, required this.label, required this.kind, this.frameFingerprint});
+ const NewDeviceNotice({
+ required this.pub,
+ required this.label,
+ required this.kind,
+ this.frameFingerprint,
+ this.suspended = false,
+ });
final String pub;
final String label;
final String kind;
+ /// A fork's suspension is on it (this app does not trust it until the list is reviewed): the banner's
+ /// "It's mine" cannot settle it, so it opens the device instead.
+ final bool suspended;
+
/// The key code the `device_key_added` frame carried, when it did.
final String? frameFingerprint;
@@ -199,7 +369,8 @@ class NewDeviceNotice {
: '$name signed in to your account and can reach your machines.';
}
- static NewDeviceNotice fromMember(DevLogMember m) => NewDeviceNotice(pub: m.pub, label: m.label, kind: m.kind);
+ static NewDeviceNotice fromMember(DevLogMember m, {bool suspended = false}) =>
+ NewDeviceNotice(pub: m.pub, label: m.label, kind: m.kind, suspended: suspended);
}
/// `{pub: ms}` as the backend answers `GET /api/device-keys/seen`; anything else is dropped.
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 56b119024..b8a3261f7 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -113,7 +113,9 @@ import '../notify/alert_sounds.dart';
import '../notify/system_notifications.dart';
import '../notify/system_notifications.dart' as notify_system;
import 'account_devices.dart';
+import '../viewer/device_log.dart' show DevLogHead;
import '../viewer/device_log_sync.dart';
+import '../viewer/device_history.dart' show DeviceLogHistory;
enum AppStatus {
bootstrapping,
@@ -982,7 +984,16 @@ class AppNotifier extends ChangeNotifier {
onChanged: _applyLocalGitProjects,
);
- AppStatus status = AppStatus.bootstrapping;
+ AppStatus _status = AppStatus.bootstrapping;
+ AppStatus get status => _status;
+ set status(AppStatus value) {
+ _status = value;
+ // Device notices the log raised while the app was still starting are said now (and dropped for good
+ // once the person is signed out).
+ if (value == AppStatus.authenticated) _flushDeviceNotices();
+ if (value == AppStatus.unauthenticated) _queuedDeviceNotices.clear();
+ }
+
CurrentUserProfile? _currentUser;
CurrentUserProfile? get currentUser => _currentUser;
set currentUser(CurrentUserProfile? profile) {
@@ -3294,6 +3305,7 @@ class AppNotifier extends ChangeNotifier {
/// What a machine hears the moment its socket is up — first connect, or a
/// reconnect after its daemon restarted, which has forgotten all of it.
void _onMachineConnected(String machineId, MachineState machine) {
+ _rereadDevicesAfterDaemonReconnect(machineId);
// A viewer build keeps its own trust group (a CLI build's daemon keeps one for it): any session
// that comes up is the moment to compare it with this machine.
unawaited(_syncGroup(machineId));
@@ -4231,6 +4243,10 @@ class AppNotifier extends ChangeNotifier {
Future<void> _finishBootstrapSignedIn() async {
final revision = _authRevision;
if (!_authWorkCurrent(revision)) return;
+ // Which sign-in this app is under is the device log's to know before anything below can read it
+ // (a restored pane, the dial, the pool, a connection's push): synchronous, ahead of the first await.
+ // A sign-in by hand just now is `fresh`; a stored session (the app opening) is not.
+ if (signedIn) _deviceLog?.beginSignIn(fresh: viewer?.auth.consumeFreshSignIn() ?? false);
// Stays on the pre-navigation `bootstrapping` screen (main.dart) until the daemon is
// confirmed reachable — flipping to `authenticated` any earlier is what let the home UI
// race `harness start`'s own backend handshake and surface a bogus 30s "Could not load
@@ -4291,9 +4307,12 @@ class AppNotifier extends ChangeNotifier {
// the log existed), and every machine it names is trusted with no password.
if (signedIn) {
if (_deviceLog case final log?) {
- unawaited(
- log.register(freshSignIn: viewer?.auth.consumeFreshSignIn() ?? false),
- );
+ // Which sign-in by hand this log's marks belong to is the log's own (minted at the start of
+ // this boot by `beginSignIn`), never the profile's id — nothing to wait for.
+ unawaited(log.register().whenComplete(_syncPendingDevices));
+ } else {
+ // A desktop build: the daemon's own copy says which devices are still waiting to be seen.
+ unawaited(_syncPendingDevices());
}
}
try {
@@ -4822,7 +4841,8 @@ class AppNotifier extends ChangeNotifier {
/// Remove the old account's live objects without overwriting its saved desk.
/// In particular, multiple emptied tabs must not prevent the next restore.
- void _clearAccountWorkspace() {
+ void _clearAccountWorkspace({bool notices = true}) {
+ if (notices) _clearDeviceNoticeState();
experimentalFeatures.bind(null);
_agentChanges.clear();
++_layoutRevision;
@@ -5405,6 +5425,8 @@ class AppNotifier extends ChangeNotifier {
pendingAuthorizeUrl = null;
_closedHistory.clear();
_monitorHarnesses.clear();
+ // What was said about the account's devices was about this account's.
+ _clearDeviceNoticeState();
// A VIEWER goes back to its login screen; a desktop window stays on the desk
// and becomes a guest — the daemon comes back signed out and keeps serving
// this computer, so signing out of the account is not a reason to take the
@@ -5422,7 +5444,7 @@ class AppNotifier extends ChangeNotifier {
? Future<bool>.value(true)
: Future<void>.sync(cliLogin.logout)
.then((_) => true, onError: (Object _) => false);
- _clearAccountWorkspace();
+ _clearAccountWorkspace(notices: false);
notifyListeners();
await _workspaceCleanup;
final didClear = await cleared;
@@ -6395,6 +6417,72 @@ class AppNotifier extends ChangeNotifier {
/// Devices that joined the account and this end had never trusted, not yet dismissed.
final List<NewDeviceNotice> newDevices = [];
+ /// Devices taken out of the account by another device, not yet dismissed. Not persisted: the
+ /// history is the durable record.
+ final List<DeviceRemovalNotice> deviceRemovals = [];
+
+ /// The removal notices the band shows. A key that signed itself out and is also on the departed list
+ /// (it joined and left before anyone looked) is told once, by the departed band: that band's "Got it"
+ /// is its one dismissal, so the removal notice for the same key is left out, not dismissed.
+ List<DeviceRemovalNotice> get visibleDeviceRemovals => [
+ for (final n in deviceRemovals)
+ if (!(n.selfRemoved && departedDevices.any((d) => d.pub == n.pub))) n,
+ ];
+
+ /// Keys that joined the account and were taken out again before anyone looked at them, not yet
+ /// dismissed ("<label> joined your account and left before you looked."). The log keeps them (the
+ /// daemon's, or this app's own), so they outlast a restart; only "Got it" clears one.
+ final List<DeviceLogDeparted> departedDevices = [];
+
+ /// Whether [departed] was removed by a key that is itself new and unlooked-at (or one that left that
+ /// way): someone who just got in clearing up after themselves. A key's own sign-out is never red.
+ bool departedIsRed(DeviceLogDeparted departed) {
+ if (departed.selfRemoved || departed.removedBy == departed.pub) return false;
+ return newDevices.any((d) => d.pub == departed.removedBy) ||
+ departedDevices.any((d) => d.pub == departed.removedBy);
+ }
+
+ /// Another key holds this computer's id on the account (a desktop build's daemon says so); null
+ /// when none does.
+ DeviceConflict? deviceConflict;
+
+ /// The conflict holder the band was dismissed for; the daemon keeps saying it until it is resolved.
+ String? _dismissedConflict;
+
+ /// New devices marked as seen here but not (yet) persisted — an in-flight write, or a daemon that
+ /// predates `POST /api/devices/dismiss`. The pending sync leaves them out.
+ final Set<String> _dismissedDevices = {};
+
+ /// The "Already on your account" list was acknowledged here, whether or not it could be persisted.
+ bool _baselineSeenLocally = false;
+ bool get baselineSeenLocally => _baselineSeenLocally;
+
+ /// Everything this window said about the account's devices belongs to the account that is leaving
+ /// (logout and a runtime sign-out both): the banners, the unsaved dismissals, and any read still in
+ /// flight, which must not write the old account's listing under the next one.
+ void _clearDeviceNoticeState() {
+ newDevices.clear();
+ departedDevices.clear();
+ deviceRemovals.clear();
+ _queuedDeviceNotices.clear();
+ deviceConflict = null;
+ _dismissedConflict = null;
+ _dismissedDevices.clear();
+ _baselineSeenLocally = false;
+ _pendingBootReadDone = false;
+ _pendingSyncGeneration++;
+ }
+
+ /// Whether [machineId] is this computer's own daemon, as local discovery reported it — NOT
+ /// `isLocalMachine`, which follows a backend-supplied computer id. Every machine's frames reach the
+ /// app through that daemon, but only its own `device_*` frames are the daemon's word; a relayed
+ /// machine's are anyone's.
+ bool _isOwnDaemonMachine(String machineId) {
+ if (viewer != null) return false;
+ final own = _cliEndpoint?.machineId;
+ return own != null && own.isNotEmpty && own == machineId;
+ }
+
/// Bumped whenever the account's devices may have changed; the Devices list re-reads on it.
int devicesRevision = 0;
@@ -6406,16 +6494,54 @@ class AppNotifier extends ChangeNotifier {
fetch: (since) => api.deviceKeys(since),
append: (entry) => api.appendDeviceKey(entry),
label: _deviceLabel,
- onAnnounce: (m) => _announceDevice(NewDeviceNotice.fromMember(m)),
+ onAnnounce: (m) => _whenSignedIn(() {
+ // A key the person has already dismissed (while this waited) is not news any more.
+ if (_dismissedDevices.contains(m.pub)) return;
+ // The log says each key once, so the notification goes out even when the banner (rebuilt from
+ // the log's pending list meanwhile) already holds it.
+ _announceDevice(NewDeviceNotice.fromMember(m), always: true);
+ // The replay can name a key that has since left the pending list (removed, or dismissed on
+ // another device): the log's own list says who is still new, so the banner follows it.
+ unawaited(_syncPendingDevices());
+ }),
+ onRemoved: (n) => _whenSignedIn(() => _announceRemoval(n)),
onSignedOut: _deviceRemovedHere,
onChanged: () {
devicesRevision++;
+ unawaited(_syncPendingDevices());
if (!_disposed) notifyListeners();
},
);
services.links.deviceLog = log;
}
+ /// What the device log announced while the app was not yet signed in (starting up): the log has
+ /// already recorded it as announced, so it is said once the app is authenticated — never lost to the
+ /// startup order, and dropped only when the person is signed out.
+ final List<void Function()> _queuedDeviceNotices = [];
+
+ void _whenSignedIn(void Function() say) {
+ switch (_status) {
+ case AppStatus.authenticated:
+ say();
+ case AppStatus.unauthenticated:
+ break;
+ case AppStatus.bootstrapping:
+ case AppStatus.checkingEnvironment:
+ case AppStatus.preparingEnvironment:
+ _queuedDeviceNotices.add(say);
+ }
+ }
+
+ void _flushDeviceNotices() {
+ if (_queuedDeviceNotices.isEmpty) return;
+ final queued = [..._queuedDeviceNotices];
+ _queuedDeviceNotices.clear();
+ for (final say in queued) {
+ say();
+ }
+ }
+
/// How this app names itself in the account's devices.
String _deviceLabel() {
// A browser has no computer name to give: "Chrome on macOS". An existing "Browser" entry is
@@ -6441,9 +6567,19 @@ class AppNotifier extends ChangeNotifier {
unawaited(log.refresh());
}
- void _announceDevice(NewDeviceNotice notice) {
- if (newDevices.any((d) => d.pub == notice.pub)) return;
- newDevices.add(notice);
+ /// A desktop build's link to its own daemon came back: a conflict, a new device or a departed key
+ /// that arose while it was down was only said in frames nobody heard, so the daemon's listing is
+ /// read again rather than waiting for the next change to the log.
+ void _rereadDevicesAfterDaemonReconnect(String machineId) {
+ if (_deviceLog != null || !_isOwnDaemonMachine(machineId)) return;
+ unawaited(_syncPendingDevices());
+ }
+
+ void _announceDevice(NewDeviceNotice notice, {bool always = false}) {
+ final shown = newDevices.any((d) => d.pub == notice.pub);
+ // A daemon's frame can repeat; the viewer's log says each key once ([always]).
+ if (shown && !always) return;
+ if (!shown) newDevices.add(notice);
devicesRevision++;
systemNotifications.postNotice(
id: 'harness-device:${notice.pub}',
@@ -6455,15 +6591,258 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
- /// The devices list was opened: every device announced so far has been seen.
- void seenNewDevices() {
- if (newDevices.isEmpty) return;
- newDevices.clear();
+ /// Rebuilds [newDevices] from the copy of the log that persists them — this app's (viewer) or the
+ /// daemon's (desktop) — so a restart, or a device the log read before this window opened, still
+ /// shows. A daemon that predates `pending` sends none: the in-memory notices stay as they are.
+ Future<void> _syncPendingDevices() async {
+ // Reads can overlap (a `device_keys_changed` and the `device_key_added` that follows it): only the
+ // latest one started may write, or an older listing could take back a device just announced.
+ final generation = ++_pendingSyncGeneration;
+ try {
+ final List<String> pending;
+ final List<NewDeviceNotice> known;
+ final List<DeviceLogDeparted> departed;
+ DeviceConflict? conflict;
+ var daemon = false;
+ var legacyDaemon = false;
+ if (_deviceLog case final log?) {
+ final listing = await log.list();
+ pending = listing.pending;
+ departed = listing.departed;
+ known = [for (final r in listing.members) NewDeviceNotice.fromMember(r.member, suspended: r.suspended)];
+ } else {
+ final raw = await api.daemonDevices();
+ if (raw == null) return;
+ // A daemon that predates the persisted marks answers without `pending` (and without `departed`):
+ // it has nothing to say about them, and asking again every recovery tick would not change that.
+ legacyDaemon = raw['pending'] is! List;
+ final devices = legacyDaemon ? null : AccountDevices.fromDaemon(raw);
+ if (!legacyDaemon && devices == null) return;
+ daemon = true;
+ pending = devices?.pending ?? const [];
+ departed = DeviceLogDeparted.listFromJson(raw['departed']);
+ conflict = devices?.conflict;
+ known = [
+ for (final d in devices?.devices ?? const <AccountDevice>[])
+ NewDeviceNotice(
+ pub: d.pub,
+ label: d.label,
+ kind: d.kind,
+ frameFingerprint: d.fingerprint,
+ suspended: d.suspended,
+ ),
+ ];
+ }
+ // No account check: at boot the profile (which sets [currentUser]) and this read race, so one taken
+ // before it would drop the listing for good. A sign-out bumps the generation instead
+ // ([_clearDeviceNoticeState]), and a daemon's listing is the daemon's current account.
+ // Nor after a sign-out: a read already in flight must not put the old account's banner back.
+ if (_disposed || generation != _pendingSyncGeneration || status == AppStatus.unauthenticated) return;
+ _pendingBootReadDone = true;
+ if (legacyDaemon) return;
+ // Oldest first: the band names the first, and "(+n more)" the rest.
+ final order = {for (var i = 0; i < pending.length; i++) pending[i]: i};
+ final next = [
+ for (final n in known)
+ if (order.containsKey(n.pub) && !_dismissedDevices.contains(n.pub)) n,
+ ]..sort((a, b) => order[a.pub]!.compareTo(order[b.pub]!));
+ var changed = !_samePubs(newDevices, next);
+ if (changed) {
+ newDevices
+ ..clear()
+ ..addAll(next);
+ }
+ final nextDeparted = [
+ for (final d in departed)
+ if (!_dismissedDevices.contains(d.pub)) d,
+ ];
+ if (!_sameDeparted(departedDevices, nextDeparted)) {
+ departedDevices
+ ..clear()
+ ..addAll(nextDeparted);
+ changed = true;
+ }
+ if (conflict == null) _dismissedConflict = null;
+ if (daemon && deviceConflict?.pub != (conflict?.pub == _dismissedConflict ? null : conflict?.pub)) {
+ deviceConflict = conflict?.pub == _dismissedConflict ? null : conflict;
+ changed = true;
+ }
+ if (changed) notifyListeners();
+ } catch (_) {
+ // Unreadable now; the next change retries.
+ }
+ }
+
+ int _pendingSyncGeneration = 0;
+
+ /// Whether the pending list has been read once under this sign-in. Until it has, a recovery tick
+ /// reads it again (the first read may have found nothing yet, or been dropped); after, the log's own
+ /// changes and the daemon's frames say when to read, so a recovery tick every few seconds does not.
+ bool _pendingBootReadDone = false;
+
+ static bool _sameDeparted(List<DeviceLogDeparted> a, List<DeviceLogDeparted> b) {
+ if (a.length != b.length) return false;
+ for (var i = 0; i < a.length; i++) {
+ if (a[i].pub != b[i].pub || a[i].removedAt != b[i].removedAt) return false;
+ }
+ return true;
+ }
+
+ static bool _samePubs(List<NewDeviceNotice> a, List<NewDeviceNotice> b) {
+ if (a.length != b.length) return false;
+ for (var i = 0; i < a.length; i++) {
+ if (a[i].pub != b[i].pub || a[i].suspended != b[i].suspended) return false;
+ }
+ return true;
+ }
+
+ /// Persists "seen" for [pub] (one), every device (neither) or the baseline panel, in whichever copy
+ /// of the log this end keeps. Only when that cannot be — a daemon that predates it — does it stay
+ /// in memory ([_dismissedDevices]).
+ Future<void> _persistSeen({String? pub, List<String>? pubs, bool baseline = false}) async {
+ // Which dismissals this write settles; the baseline panel's "Got it" settles none of them.
+ void settled() {
+ if (baseline) return;
+ _dismissedDevices.removeWhere((p) => pub != null ? p == pub : (pubs?.contains(p) ?? true));
+ }
+
+ try {
+ if (_deviceLog case final log?) {
+ if (baseline) {
+ await log.seeBaseline();
+ } else {
+ await log.dismiss(pub: pub, pubs: pubs);
+ }
+ settled();
+ return;
+ }
+ if (await api.daemonDismissDevices(pub: pub, pubs: pubs, baseline: baseline)) {
+ settled();
+ }
+ } catch (_) {}
+ }
+
+ /// The devices list was opened: every device announced so far has been seen. [pending] is what the
+ /// list itself read as still new, which is written back even when no banner was up for it (a seen
+ /// that could not be written before, or a listing read before the banner's). Only the devices that
+ /// were shown are marked: one that joined after the read stays new.
+ ///
+ /// [shown] is the banner's set as it was when the list was READ: the read can wait on the network,
+ /// and a device announced meanwhile was never on screen. Without it, whatever the banner holds now.
+ ///
+ /// [departed] is what that same read listed as joined-and-left: at startup the app may not have read
+ /// them as departed yet (a replayed "New device" put one in the banner), and the list did.
+ void seenNewDevices({
+ Iterable<String> pending = const [],
+ Iterable<String>? shown,
+ Iterable<String> departed = const [],
+ }) {
+ final banner = (shown ?? newDevices.map((d) => d.pub)).toSet();
+ // A key that joined and left unseen is cleared by its own "Got it" only: opening the list must
+ // not mark it seen (a startup replay can have put it in the banner set meanwhile).
+ final gone = {for (final d in departedDevices) d.pub, ...departed};
+ final seen = banner.difference(gone);
+ final seenPending = pending.where((p) => !gone.contains(p)).toSet();
+ if (banner.isEmpty && pending.isEmpty && _dismissedDevices.isEmpty) return;
+ final marked = {...seen, ...seenPending, ..._dismissedDevices}.toList();
+ if (marked.isEmpty) {
+ // Only departed keys were up: nothing is marked, so a read of the list under way (the one a
+ // startup replay starts, which takes their stale "New device" down) is not stale — let it land.
+ final before = newDevices.length;
+ newDevices.removeWhere((d) => banner.contains(d.pub));
+ if (newDevices.length != before) notifyListeners();
+ return;
+ }
+ _dismissedDevices
+ ..addAll(seen)
+ ..addAll(seenPending);
+ newDevices.removeWhere((d) => banner.contains(d.pub));
+ _pendingSyncGeneration++;
notifyListeners();
+ unawaited(_persistSeen(pubs: marked));
}
- void dismissNewDevice(String pub) {
+ ///
+ /// [pub] alone (the device's own page, where a suspension is shown) also lifts a suspension on it;
+ /// the banner's "It's mine" does not — it dismisses through [pubs], which leaves a fork's
+ /// suspension in place.
+ void dismissNewDevice(String pub, {bool liftSuspension = false}) {
newDevices.removeWhere((d) => d.pub == pub);
+ // A key that joined and left before anyone looked: a "New device" for it is a stale replay, and its
+ // flag is cleared by its own "Got it" only ([dismissDeparted]) — "It's mine" here takes the banner
+ // down and marks nothing.
+ if (departedDevices.any((d) => d.pub == pub)) {
+ notifyListeners();
+ return;
+ }
+ _dismissedDevices.add(pub);
+ _pendingSyncGeneration++;
+ notifyListeners();
+ unawaited(liftSuspension ? _persistSeen(pub: pub) : _persistSeen(pubs: [pub]));
+ }
+
+ /// "Got it" on a key that joined and left before anyone looked: the one way its flag goes away (the
+ /// removal band's own "Got it" and opening the list leave it). Persisted where the log lives.
+ void dismissDeparted(String pub) => dismissDepartedAll([pub]);
+
+ /// "Got it" on the departed band: the key it shows and the "+N more" behind it, cleared together in
+ /// one persisted write (the History still lists each of them).
+ void dismissDepartedAll(Iterable<String> pubs) {
+ final cleared = pubs.toSet();
+ if (cleared.isEmpty) return;
+ _dismissedDevices.addAll(cleared);
+ departedDevices.removeWhere((d) => cleared.contains(d.pub));
+ // The departed band was the one telling of a key's own sign-out ([visibleDeviceRemovals] holds the
+ // removal notice back for it): once it is read, that notice must not surface in its place.
+ deviceRemovals.removeWhere((n) => n.selfRemoved && cleared.contains(n.pub));
+ _pendingSyncGeneration++;
+ notifyListeners();
+ unawaited(_persistSeen(pubs: cleared.toList()));
+ }
+
+ /// "Got it" on the "Already on your account" panel.
+ Future<void> seeDeviceBaseline() async {
+ _baselineSeenLocally = true;
+ await _persistSeen(baseline: true);
+ devicesRevision++;
+ notifyListeners();
+ }
+
+ /// Every add and remove on the account, newest first, as this end verified the log. Null when the
+ /// daemon predates it; throws when it cannot be read.
+ Future<DeviceLogHistory?> loadDeviceHistory() async {
+ if (_deviceLog case final log?) return log.history();
+ final raw = await api.daemonDeviceHistory();
+ if (raw == null) return null;
+ return DeviceLogHistory.fromJson(raw) ?? (throw StateError('BAD_HISTORY'));
+ }
+
+ /// Another device took [notice]'s device out of the account (or it signed itself out).
+ void _announceRemoval(DeviceRemovalNotice notice) {
+ // A red notice (a new device nobody looked at removed it) is never softened by a later one for the
+ // same key — only the person's own dismissal takes it down.
+ if (!notice.red && deviceRemovals.any((n) => n.pub == notice.pub && n.red)) return;
+ deviceRemovals.removeWhere((n) => n.pub == notice.pub);
+ deviceRemovals.add(notice);
+ devicesRevision++;
+ systemNotifications.postNotice(
+ id: 'harness-device-removed:${notice.pub}',
+ title: notice.title,
+ body: notice.sentence,
+ // Red: a click opens the new device that did it.
+ devicePub: notice.red ? notice.signer : null,
+ );
+ notifyListeners();
+ }
+
+ void dismissDeviceConflict() {
+ _dismissedConflict = deviceConflict?.pub;
+ deviceConflict = null;
+ notifyListeners();
+ }
+
+ void dismissDeviceRemoval(String pub) {
+ deviceRemovals.removeWhere((n) => n.pub == pub);
notifyListeners();
}
@@ -6478,12 +6857,18 @@ class AppNotifier extends ChangeNotifier {
}
/// The account's devices, from whichever end verified the log. Null when it cannot be read.
- Future<AccountDevices?> loadDevices() async {
+ ///
+ /// [onListed] hears the banner's devices the moment the listing is read — before the last-seen
+ /// request, which the backend can delay — so the list marks as seen only what was shown with it.
+ Future<AccountDevices?> loadDevices({void Function(List<String> banner)? onListed}) async {
if (_deviceLog case final log?) {
final listing = AccountDevices.fromListing(await log.list());
+ onListed?.call([for (final d in newDevices) d.pub]);
return listing.withLastSeen(await api.deviceKeysSeen());
}
- return AccountDevices.fromDaemon(await api.daemonDevices());
+ final raw = await api.daemonDevices();
+ onListed?.call([for (final d in newDevices) d.pub]);
+ return AccountDevices.fromDaemon(raw);
}
/// Take [pub] out of the account on every device. Null when done, else why not.
@@ -6499,17 +6884,22 @@ class AppNotifier extends ChangeNotifier {
/// What trusting the backend's device list again would change; [confirm] does it — the one way
/// out of a frozen list. Null when no valid list could be read.
- Future<DevicesRebaseline?> rebaselineDevices({required bool confirm}) async {
+ ///
+ /// A confirm names the [head] the preview showed: if the backend's list is another by now, nothing is
+ /// trusted and the answer is [DevicesRebaseline.logChanged]. Another account's list than the one
+ /// signed in to is never trusted by a review ([DevicesRebaseline.otherAccount]): signing in again is.
+ Future<DevicesRebaseline?> rebaselineDevices({required bool confirm, DevLogHead? head}) async {
final DevicesRebaseline? result;
if (_deviceLog case final log?) {
- final r = await log.rebaseline(confirm: confirm);
+ final r = await log.rebaseline(confirm: confirm, expectedHead: confirm ? head : null);
+ // Null is a log that could not be read; a head that moved is a result of its own.
result = r == null ? null : DevicesRebaseline.fromViewer(r);
} else {
result = DevicesRebaseline.fromDaemon(
- await api.daemonRebaselineDevices(confirm: confirm),
+ await api.daemonRebaselineDevices(confirm: confirm, head: confirm ? head?.toJson() : null),
);
}
- if (confirm) {
+ if (confirm && result != null && !result.refused) {
devicesRevision++;
notifyListeners();
}
@@ -6915,7 +7305,12 @@ class AppNotifier extends ChangeNotifier {
if (signedIn && currentUser == null) unawaited(_loadProfile());
// A boot that found the daemon still connecting finishes THROUGH here (see
// `_loadProfile`), so the desk is joined here as well — once.
- if (signedIn) _deskEnsure(revision);
+ if (signedIn) {
+ _deskEnsure(revision);
+ // The first boot's read may have found nothing to say yet (or been dropped); read again —
+ // until one has succeeded.
+ if (!_pendingBootReadDone) unawaited(_syncPendingDevices());
+ }
try {
if (!await refreshMachines() || !_authWorkCurrent(revision)) return;
if (!automatic) _lastError = null;
@@ -11703,6 +12098,7 @@ class AppNotifier extends ChangeNotifier {
// A `reconnecting` status that was never followed by `connected` stopped the minute's agent
// sync; the socket being live again is the connect it was waiting for.
_startAgentSyncTimer(machine.machine.machineId);
+ _rereadDevicesAfterDaemonReconnect(machine.machine.machineId);
_logLocalMachine(
machine,
'restored ($why${restoredEndpoint != null ? ', endpoint' : ''})',
@@ -14740,14 +15136,31 @@ class AppNotifier extends ChangeNotifier {
case 'device_keys_changed':
// The account's device key log grew. A viewer re-reads and verifies it itself; a desktop
// build's daemon already did, and the Devices list re-reads it from there.
- if (_deviceLog case final log?) unawaited(log.refresh());
+ if (_deviceLog case final log?) {
+ unawaited(log.refresh());
+ } else {
+ unawaited(_syncPendingDevices());
+ }
devicesRevision++;
notifyListeners();
break;
+ case 'device_key_removed':
+ // Only this computer's own daemon says this (see [_isOwnDaemonMachine]).
+ if (_isOwnDaemonMachine(machineId)) {
+ if (DeviceRemovalNotice.fromJson(payload) case final notice?) _announceRemoval(notice);
+ }
+ break;
+ case 'device_conflict':
+ // A hint: the conflict itself is re-read from the daemon's listing, never taken from the frame.
+ if (_isOwnDaemonMachine(machineId)) {
+ devicesRevision++;
+ unawaited(_syncPendingDevices());
+ }
+ break;
case 'device_key_added':
// Only this computer's own daemon says this (a viewer build has no daemon, and a machine's
// frame must not be able to raise a notice here).
- if (viewer == null) {
+ if (_isOwnDaemonMachine(machineId)) {
final pub = payload['pub'],
label = payload['label'],
kind = payload['kind'];
@@ -14761,6 +15174,7 @@ class AppNotifier extends ChangeNotifier {
frameFingerprint: fp is String ? fp : null,
),
);
+ unawaited(_syncPendingDevices());
}
}
break;
@@ -15211,6 +15625,26 @@ class AppNotifier extends ChangeNotifier {
Map<String, dynamic> event,
) => _handleEvent(machineId, event);
+ @visibleForTesting
+ void clearDeviceNoticeStateForTest() => _clearDeviceNoticeState();
+
+ @visibleForTesting
+ bool get pendingBootReadDoneForTest => _pendingBootReadDone;
+
+ /// Local discovery having found this computer's own daemon, which serves [machineId].
+ @visibleForTesting
+ void ownDaemonMachineIdForTest(String? machineId) {
+ _cliEndpoint = machineId == null
+ ? null
+ : LocalCliEndpoint(
+ computerId: 'test-computer',
+ wsUri: Uri.parse('ws://127.0.0.1:1/ws'),
+ protocolVersion: localWsProtocolVersion,
+ terminalProtocolVersion: localTerminalProtocolVersion,
+ machineId: machineId,
+ );
+ }
+
/// The supervisor's five-second "daemon ready" snapshot, without a supervisor.
@visibleForTesting
void daemonSnapshotForTest(LocalCliEndpoint endpoint) =>
diff --git a/desktop/lib/viewer/device_history.dart b/desktop/lib/viewer/device_history.dart
new file mode 100644
index 000000000..540a23a4b
--- /dev/null
+++ b/desktop/lib/viewer/device_history.dart
@@ -0,0 +1,459 @@
+import '../e2ee/bytes.dart';
+import '../e2ee/keys.dart';
+import 'device_log.dart';
+
+/// The device key log read as a history — the Dart port of cli/src/lib/e2ee/deviceHistory.ts. The rows
+/// are the wire format of the daemon's `GET /api/devices/history`, so [DevLogHistoryRow.fromJson]
+/// reads exactly what the CLI's `devLogHistory` writes. Change both together.
+
+/// A key that was new here and was removed before anyone marked it as seen: it stays flagged — "joined
+/// your account and left before you looked" — until it is dismissed. The same JSON as an item of the
+/// daemon's `GET /api/devices` `departed` (cli deviceLogStore.ts `DevLogDeparted`).
+class DeviceLogDeparted {
+ const DeviceLogDeparted({
+ required this.pub,
+ required this.label,
+ required this.kind,
+ required this.machineId,
+ required this.fingerprint,
+ required this.addedAt,
+ required this.removedAt,
+ required this.removedBy,
+ required this.removedByLabel,
+ required this.selfRemoved,
+ });
+
+ final String pub;
+ final String label;
+
+ /// `machine` | `viewer`.
+ final String kind;
+ final String machineId;
+ final String fingerprint;
+
+ /// The `at` of the entry that added it (picked by that device).
+ final int addedAt;
+
+ /// The `at` of the entry that removed it (picked by its signer).
+ final int removedAt;
+
+ /// The key that signed the removal, and what it was called then ('' when not known).
+ final String removedBy;
+ final String removedByLabel;
+
+ /// It removed itself (signed out).
+ final bool selfRemoved;
+
+ Map<String, Object?> toJson() => {
+ 'pub': pub,
+ 'label': label,
+ 'kind': kind,
+ 'machineId': machineId,
+ 'fingerprint': fingerprint,
+ 'addedAt': addedAt,
+ 'removedAt': removedAt,
+ 'removedBy': removedBy,
+ 'removedByLabel': removedByLabel,
+ 'selfRemoved': selfRemoved,
+ };
+
+ static DeviceLogDeparted? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'],
+ label = raw['label'],
+ kind = raw['kind'],
+ machineId = raw['machineId'];
+ final fp = raw['fingerprint'],
+ addedAt = raw['addedAt'],
+ removedAt = raw['removedAt'];
+ final by = raw['removedBy'],
+ byLabel = raw['removedByLabel'],
+ self = raw['selfRemoved'];
+ if (pub is! String ||
+ pub.isEmpty ||
+ label is! String ||
+ (kind != 'machine' && kind != 'viewer')) {
+ return null;
+ }
+ if (machineId is! String ||
+ fp is! String ||
+ addedAt is! int ||
+ removedAt is! int) {
+ return null;
+ }
+ if (by is! String || byLabel is! String || self is! bool) return null;
+ return DeviceLogDeparted(
+ pub: pub,
+ label: label,
+ kind: kind as String,
+ machineId: machineId,
+ fingerprint: fp,
+ addedAt: addedAt,
+ removedAt: removedAt,
+ removedBy: by,
+ removedByLabel: byLabel,
+ selfRemoved: self,
+ );
+ }
+
+ /// A `departed` list as the daemon (or a stored file) has it: what cannot be read is left out.
+ static List<DeviceLogDeparted> listFromJson(Object? raw) => [
+ if (raw is List)
+ for (final d in raw) ?DeviceLogDeparted.fromJson(d),
+ ];
+}
+
+/// A device taken out of the account after this app joined it — the same JSON as the daemon's
+/// `device_key_removed` frame (cli deviceLogSyncer.ts `DeviceRemovalNotice`).
+class DeviceRemovalNotice {
+ const DeviceRemovalNotice({
+ required this.pub,
+ required this.label,
+ required this.kind,
+ required this.fingerprint,
+ required this.signer,
+ required this.signerLabel,
+ required this.signerFingerprint,
+ required this.signerPending,
+ required this.selfRemoved,
+ required this.at,
+ });
+
+ final String pub;
+ final String label;
+ final String kind;
+ final String fingerprint;
+ final String signer;
+ final String signerLabel;
+ final String signerFingerprint;
+
+ /// The signer is itself a new device nobody has looked at.
+ final bool signerPending;
+
+ /// The device removed itself (signed out).
+ final bool selfRemoved;
+ final int at;
+
+ Map<String, Object?> toJson() => {
+ 'pub': pub,
+ 'label': label,
+ 'kind': kind,
+ 'fingerprint': fingerprint,
+ 'signer': signer,
+ 'signerLabel': signerLabel,
+ 'signerFingerprint': signerFingerprint,
+ 'signerPending': signerPending,
+ 'selfRemoved': selfRemoved,
+ 'at': at,
+ };
+
+ static DeviceRemovalNotice? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'],
+ label = raw['label'],
+ kind = raw['kind'],
+ fp = raw['fingerprint'];
+ final signer = raw['signer'],
+ signerLabel = raw['signerLabel'],
+ signerFp = raw['signerFingerprint'];
+ if (pub is! String ||
+ label is! String ||
+ kind is! String ||
+ fp is! String) {
+ return null;
+ }
+ if (signer is! String || signerLabel is! String || signerFp is! String) {
+ return null;
+ }
+ return DeviceRemovalNotice(
+ pub: pub,
+ label: label,
+ kind: kind,
+ fingerprint: fp,
+ signer: signer,
+ signerLabel: signerLabel,
+ signerFingerprint: signerFp,
+ signerPending: raw['signerPending'] == true,
+ selfRemoved: raw['selfRemoved'] == true,
+ at: raw['at'] is int ? raw['at'] as int : 0,
+ );
+ }
+}
+
+class DevLogHistoryBy {
+ const DevLogHistoryBy({
+ required this.pub,
+ required this.label,
+ required this.fingerprint,
+ });
+
+ final String pub;
+ final String label;
+ final String fingerprint;
+
+ static DevLogHistoryBy? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'], label = raw['label'], fp = raw['fingerprint'];
+ if (pub is! String || label is! String || fp is! String) return null;
+ return DevLogHistoryBy(pub: pub, label: label, fingerprint: fp);
+ }
+}
+
+class DevLogHistoryRow {
+ const DevLogHistoryRow({
+ required this.seq,
+ required this.op,
+ required this.pub,
+ required this.kind,
+ required this.machineId,
+ required this.label,
+ this.previousLabel,
+ required this.fingerprint,
+ this.by,
+ required this.at,
+ required this.thisDevice,
+ required this.afterJoin,
+ required this.pending,
+ required this.active,
+ required this.whileFrozen,
+ });
+
+ final int seq;
+
+ /// `added` | `renamed` | `removed` | `signedOut`.
+ final String op;
+ final String pub;
+ final String kind;
+ final String machineId;
+ final String label;
+
+ /// For `renamed`: the name it had before, when known.
+ final String? previousLabel;
+ final String fingerprint;
+
+ /// For `removed`: the key that signed the removal.
+ final DevLogHistoryBy? by;
+ final int at;
+ final bool thisDevice;
+
+ /// Added after this device joined.
+ final bool afterJoin;
+
+ /// Still new: nobody marked it as seen here.
+ final bool pending;
+
+ /// The key is active in the log now.
+ final bool active;
+
+ /// A removal applied while the list was frozen (unchained, so unverified).
+ final bool whileFrozen;
+
+ static DevLogHistoryRow? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final seq = raw['seq'],
+ op = raw['op'],
+ pub = raw['pub'],
+ kind = raw['kind'];
+ final machineId = raw['machineId'], label = raw['label'];
+ final fp = raw['fingerprint'], at = raw['at'];
+ if (seq is! int || op is! String || pub is! String || kind is! String) {
+ return null;
+ }
+ if (machineId is! String || label is! String || fp is! String) return null;
+ if (at is! int) return null;
+ final previous = raw['previousLabel'];
+ return DevLogHistoryRow(
+ seq: seq,
+ op: op,
+ pub: pub,
+ kind: kind,
+ machineId: machineId,
+ label: label,
+ previousLabel: previous is String ? previous : null,
+ fingerprint: fp,
+ by: DevLogHistoryBy.fromJson(raw['by']),
+ at: at,
+ thisDevice: raw['thisDevice'] == true,
+ afterJoin: raw['afterJoin'] == true,
+ pending: raw['pending'] == true,
+ active: raw['active'] == true,
+ whileFrozen: raw['whileFrozen'] == true,
+ );
+ }
+}
+
+class DeviceLogHistory {
+ const DeviceLogHistory({required this.rows, required this.complete});
+
+ final List<DevLogHistoryRow> rows;
+
+ /// false when only part of the log could be read (offline).
+ final bool complete;
+
+ static DeviceLogHistory? fromJson(Object? raw) {
+ if (raw is! Map || raw['rows'] is! List) return null;
+ return DeviceLogHistory(
+ rows: [
+ for (final r in raw['rows'] as List) ?DevLogHistoryRow.fromJson(r),
+ ],
+ complete: raw['complete'] == true,
+ );
+ }
+}
+
+String _fp(String pub) {
+ try {
+ return fingerprint(b64d(pub));
+ } catch (_) {
+ return '';
+ }
+}
+
+/// Newest first. [entries] may have gaps at the front (offline: only the recent tail is known).
+/// [loose] are removals applied while frozen: they are not part of the chain, and are shown as such.
+List<DevLogHistoryRow> devLogHistory(
+ List<DevLogEntry> entries, {
+ required String selfPub,
+ int? joinedSeq,
+ required List<String> pending,
+ required Map<String, DevLogMember> active,
+ List<DevLogEntry> loose = const [],
+}) {
+ final seen = <String>{};
+ final ordered = <(DevLogEntry, bool)>[];
+ final sorted = [...entries]..sort((a, b) => a.seq.compareTo(b.seq));
+ for (final e in sorted) {
+ if (seen.add('${e.seq}:${e.sig}')) ordered.add((e, false));
+ }
+ for (final e in loose) {
+ if (seen.add('${e.seq}:${e.sig}')) ordered.add((e, true));
+ }
+ // The name each key last went by, to say "renamed from" and to name a signer that is gone.
+ final labels = {for (final m in active.values) m.pub: m.label};
+ final known = <String, ({String label, String kind, String machineId})>{};
+ final rows = <DevLogHistoryRow>[];
+ for (final (e, isLoose) in ordered) {
+ // A removal names the key as the log had it BEFORE: the remove entry's own label, kind and machine
+ // id are chosen by whoever signed it, and say nothing checked. When the add is outside what is
+ // known (offline, the newest entries only) the key is named by its fingerprint alone: an empty
+ // label, shown as "A device", and no kind or machine id of the signer's.
+ final prior = e.op == 'remove' ? known[e.pub] : null;
+ DevLogHistoryRow row(
+ String op, {
+ String? previousLabel,
+ DevLogHistoryBy? by,
+ }) => DevLogHistoryRow(
+ seq: e.seq,
+ op: op,
+ pub: e.pub,
+ kind: e.op == 'remove' ? prior?.kind ?? 'viewer' : e.kind,
+ machineId: e.op == 'remove' ? prior?.machineId ?? '' : e.machineId,
+ label: e.op == 'remove' ? prior?.label ?? '' : e.label,
+ previousLabel: previousLabel,
+ fingerprint: _fp(e.pub),
+ by: by,
+ at: e.at,
+ thisDevice: e.pub == selfPub,
+ afterJoin: joinedSeq != null && e.seq > joinedSeq,
+ pending: pending.contains(e.pub),
+ active: active.containsKey(e.pub),
+ whileFrozen: isLoose,
+ );
+ if (e.op == 'add') {
+ final before = known[e.pub];
+ final member = active[e.pub];
+ if (before != null || (member != null && member.seq < e.seq)) {
+ rows.add(row('renamed', previousLabel: before?.label));
+ } else {
+ rows.add(row('added'));
+ }
+ known[e.pub] = (label: e.label, kind: e.kind, machineId: e.machineId);
+ labels[e.pub] = e.label;
+ } else if (e.signer == e.pub) {
+ rows.add(row('signedOut'));
+ known.remove(e.pub);
+ } else {
+ final label = known[e.signer]?.label ?? labels[e.signer] ?? '';
+ rows.add(
+ row(
+ 'removed',
+ by: DevLogHistoryBy(
+ pub: e.signer,
+ label: label,
+ fingerprint: _fp(e.signer),
+ ),
+ ),
+ );
+ known.remove(e.pub);
+ }
+ }
+ rows.sort((a, b) => b.seq.compareTo(a.seq));
+ return rows;
+}
+
+String _name(String label) => label.trim().isEmpty ? 'A device' : label.trim();
+
+/// How the apps word a [DeviceRemovalNotice], so the band and the notification say the same thing.
+extension DeviceRemovalCopy on DeviceRemovalNotice {
+ /// Removed by a new device nobody has looked at (a signed-out device is never red: it is its own act).
+ bool get red => signerPending && !selfRemoved;
+
+ String get title => selfRemoved
+ ? 'Device signed out'
+ : red
+ ? 'Removed by a new device'
+ : 'Device removed';
+
+ String get sentence {
+ final name = _name(label);
+ if (selfRemoved) return '$name signed out of your account.';
+ final signerName = signerLabel.trim().isEmpty
+ ? 'another device'
+ : signerLabel.trim();
+ if (!red) return '$name was removed from your account by $signerName.';
+ final groups = signerFingerprint
+ .split('·')
+ .take(2)
+ .where((g) => g.isNotEmpty)
+ .join('·');
+ final short = groups.isEmpty ? '' : ' · $groups…';
+ return '$name was removed from your account by a new device you haven’t looked at ($signerName$short).';
+ }
+}
+
+/// How the apps word a [DeviceLogDeparted]: "`label` joined your account and left before you looked."
+/// and, unless it signed itself out or nothing took it out (a review of the list), who took it out: " Removed by `signer`." With [red] — the signer is
+/// itself a device nobody has looked at — the sentence says so too, not the colour alone.
+extension DeviceDepartedCopy on DeviceLogDeparted {
+ String sentence({required bool red}) {
+ final head =
+ '${_name(label)} joined your account and left before you looked.';
+ if (selfRemoved || removedBy.isEmpty || removedBy == pub) return head;
+ final signer = removedByLabel.trim().isEmpty
+ ? 'another device'
+ : removedByLabel.trim();
+ return red
+ ? '$head Removed by $signer, a new device you haven’t looked at.'
+ : '$head Removed by $signer.';
+ }
+}
+
+/// What the row says happened, in words: `iPad added`, `Old Mac renamed to Mac`, `iPad removed by Mac`.
+/// A signer with no known name is "another device".
+String historySentence(DevLogHistoryRow row) {
+ final name = _name(row.label);
+ final signer = row.by?.label.trim() ?? '';
+ final text = switch (row.op) {
+ 'renamed' =>
+ row.previousLabel == null || row.previousLabel!.trim().isEmpty
+ ? '$name renamed'
+ : '${row.previousLabel!.trim()} renamed to $name',
+ 'removed' =>
+ row.by == null
+ ? '$name removed'
+ : '$name removed by ${signer.isEmpty ? 'another device' : signer}',
+ 'signedOut' => '$name signed out',
+ _ => '$name added',
+ };
+ return row.whileFrozen ? '$text · applied while the list was frozen' : text;
+}
diff --git a/desktop/lib/viewer/device_log_sync.dart b/desktop/lib/viewer/device_log_sync.dart
index 8057241ca..9248b9c1a 100644
--- a/desktop/lib/viewer/device_log_sync.dart
+++ b/desktop/lib/viewer/device_log_sync.dart
@@ -3,17 +3,22 @@ import 'dart:math';
import '../e2ee/bytes.dart';
import '../e2ee/keys.dart';
+import 'device_history.dart';
import 'device_log.dart';
import 'group_sync.dart';
import 'viewer_key_store.dart';
+export 'device_history.dart'
+ show DeviceDepartedCopy, DeviceLogDeparted, DeviceRemovalCopy, DeviceRemovalNotice, historySentence;
+
/// The account's device key log, on a device with no harness CLI — the viewer's half of
/// cli/src/lib/e2ee/deviceLogSyncer.ts.
///
/// Signing in is what puts this app's key into the log ([register]); every machine the log names is
/// then pinned here with no password, and every machine trusts this app. A backend that rewrites the
/// log or rolls it back FREEZES it here: nothing more is pinned from it until someone reviews what
-/// changed ([rebaseline]). A machine this app had never trusted is announced ("New device: X").
+/// changed ([rebaseline]). A key added after this app joined the log is announced ("New device: X") and
+/// stays pending until it is marked seen; what the log says is never read against what the roster holds.
/// What `GET /api/device-keys?since=` answered; null from the fetcher when there is no log to read.
typedef DeviceLogFetched = ({String acct, DevLogHead head, List<Object?> entries});
@@ -43,47 +48,165 @@ class DeviceLogFreeze {
}
class _File {
- _File(this.state, this.recent, this.frozen, this.notifiedUpTo);
+ _File(
+ this.state,
+ this.recent,
+ this.frozen,
+ this.notifiedUpTo, {
+ this.joinedSeq,
+ this.preLog = const [],
+ this.pending = const [],
+ this.announced = const [],
+ this.suspended = const [],
+ this.baselineSeen = true,
+ this.looseRemoved = const [],
+ this.reviewedSeq,
+ this.owner,
+ this.joining = false,
+ this.departed = const [],
+ });
DevLogState? state;
List<DevLogEntry> recent;
DeviceLogFreeze? frozen;
int notifiedUpTo;
+ /// The head seq this app's first read ended at: only an `add` past it is news. Null in a file from
+ /// before this existed (migrated on first use).
+ int? joinedSeq;
+
+ /// Keys this app trusted when it joined (or migrated): never news.
+ List<String> preLog;
+
+ /// New keys nobody has marked as seen yet.
+ List<String> pending;
+
+ /// Keys already announced — never twice.
+ List<String> announced;
+
+ /// Keys not trusted here after a fork, until [ViewerDeviceLog.rebaseline].
+ List<String> suspended;
+
+ /// false until the "Already on your account" panel was dismissed.
+ bool baselineSeen;
+
+ /// Removals applied while frozen: never in [recent], which is handed to peers as a chained tail.
+ List<DevLogEntry> looseRemoved;
+
+ /// The head seq of the list a person last reviewed ([ViewerDeviceLog.rebaseline]): a key at or
+ /// before it was looked at, so a later fork never suspends it.
+ int? reviewedSeq;
+
+ /// Which sign-in by hand this file belongs to (see [ViewerDeviceLog.register]). Null in a file from
+ /// before this existed.
+ String? owner;
+
+ /// true from the fresh write of a log until the first read of it reaches the head (or stops on a
+ /// freeze): while set, whatever is verified is what was there at joining — none of it is news.
+ bool joining;
+
+ /// New keys removed before anyone looked (oldest first, at most [_departedKept]).
+ List<DeviceLogDeparted> departed;
+
Map<String, Object?> toJson() => {
'state': state?.toJson(),
'recent': [for (final e in recent.skip(max(0, recent.length - _recentKept))) e.toJson()],
'frozen': frozen?.toJson(),
'notifiedUpTo': notifiedUpTo,
+ if (joinedSeq != null) ...{
+ 'joinedSeq': joinedSeq,
+ 'preLog': preLog,
+ 'pending': pending,
+ 'announced': announced,
+ 'baselineSeen': baselineSeen,
+ },
+ if (suspended.isNotEmpty) 'suspended': suspended,
+ if (reviewedSeq != null) 'reviewedSeq': reviewedSeq,
+ if (owner != null) 'owner': owner,
+ if (joining) 'joining': true,
+ if (looseRemoved.isNotEmpty)
+ 'looseRemoved': [for (final e in looseRemoved.skip(max(0, looseRemoved.length - _recentKept))) e.toJson()],
+ if (departed.isNotEmpty)
+ 'departed': [for (final d in departed.skip(max(0, departed.length - _departedKept))) d.toJson()],
};
+ static List<String> _strings(Object? raw) => raw is List ? [for (final v in raw) if (v is String) v] : <String>[];
+
static _File parse(Object? raw) {
if (raw is! Map) return _File(null, [], null, 0);
final recent = raw['recent'];
+ final loose = raw['looseRemoved'];
return _File(
DevLogState.fromJson(raw['state']),
recent is List ? recent.map(DevLogEntry.parse).whereType<DevLogEntry>().toList() : [],
DeviceLogFreeze.fromJson(raw['frozen']),
raw['notifiedUpTo'] is int ? raw['notifiedUpTo'] as int : 0,
+ joinedSeq: raw['joinedSeq'] is int && (raw['joinedSeq'] as int) >= 0 ? raw['joinedSeq'] as int : null,
+ preLog: _strings(raw['preLog']),
+ pending: _strings(raw['pending']),
+ announced: _strings(raw['announced']),
+ suspended: _strings(raw['suspended']),
+ baselineSeen: raw['baselineSeen'] is bool ? raw['baselineSeen'] as bool : true,
+ looseRemoved: loose is List ? loose.map(DevLogEntry.parse).whereType<DevLogEntry>().toList() : [],
+ reviewedSeq: raw['reviewedSeq'] is int && (raw['reviewedSeq'] as int) >= 0 ? raw['reviewedSeq'] as int : null,
+ owner: raw['owner'] is String && (raw['owner'] as String).isNotEmpty ? raw['owner'] as String : null,
+ joining: raw['joining'] == true,
+ departed: DeviceLogDeparted.listFromJson(raw['departed']),
);
}
}
const _recentKept = 64;
+
+/// How many departed keys are kept ([_File.departed]); the oldest goes first.
+const _departedKept = 32;
+
+/// How long after a sign-in by hand a read of another account may start the log over: past it, with no
+/// read of that account yet, the backend has had the time to pick when it says so.
+const _resetWindowMs = 10 * 60 * 1000;
const _appendAttempts = 5;
const _pages = 20;
+/// How many other accounts' logs are kept ([ViewerKeyStore.deviceLogArchive]); the oldest goes first.
+const _archivedKept = 4;
+
+/// How a sign-in id given to a session from before sign-in ids existed starts: nobody saw that
+/// sign-in being made here, so it may take a file over but never starts one over.
+const _adoptedSignIn = 'adopted:';
+
/// One device on the account, for the Devices list.
class DeviceLogRow {
- const DeviceLogRow(this.member, {required this.fingerprint, required this.self});
+ const DeviceLogRow(
+ this.member, {
+ required this.fingerprint,
+ required this.self,
+ this.pending = false,
+ this.suspended = false,
+ });
final DevLogMember member;
final String fingerprint;
final bool self;
+
+ /// Joined after this app did and nobody marked it as seen.
+ final bool pending;
+
+ /// Not trusted here after a fork, until the list is reviewed.
+ final bool suspended;
}
class DeviceLogListing {
- const DeviceLogListing({required this.members, required this.frozen, required this.frozenPeers});
+ const DeviceLogListing({
+ required this.members,
+ required this.frozen,
+ required this.frozenPeers,
+ this.pending = const [],
+ this.suspended = const [],
+ this.joinedSeq = 0,
+ this.baseline = const [],
+ this.baselineSeen = true,
+ this.departed = const [],
+ });
static const empty = DeviceLogListing(members: [], frozen: null, frozenPeers: []);
@@ -92,14 +215,98 @@ class DeviceLogListing {
/// Machines whose own copy of the log is frozen, as their last `group_sync` said.
final List<String> frozenPeers;
+
+ /// Keys that joined after this app did and nobody marked as seen.
+ final List<String> pending;
+
+ /// Keys not trusted here after a fork, until the list is reviewed.
+ final List<String> suspended;
+ final int joinedSeq;
+
+ /// The keys that were on the account before this app joined (the "Already on your account" list):
+ /// active, not this app, at or before [joinedSeq] — plus any key this app already trusted at joining
+ /// whose entry came after it (a log cut short at the first read must not hide it).
+ final List<String> baseline;
+
+ /// false until the "already on your account" list was acknowledged.
+ final bool baselineSeen;
+
+ /// New keys removed before anyone marked them as seen (oldest first): flagged until [ViewerDeviceLog.dismiss]
+ /// names them (`pub`, or `pubs`) or clears every one.
+ final List<DeviceLogDeparted> departed;
+}
+
+/// The newest hashes a `group_sync` carries, so a fork can be located.
+const _gossipHashes = 64;
+
+/// Where a peer's log first differs from [state]: the first seq, in the window of hashes the peer sent
+/// (`theirs['hashes']`, the last of which is `theirs['head']`), whose hash is not ours — only when the
+/// entry before it matches (or it is the first), so the split is proven rather than guessed. Null when
+/// the peer sent no usable hashes, nothing in the shared window differs, or the split lies before it.
+int? devLogDivergence(DevLogState state, Object? theirs) {
+ if (theirs is! Map) return null;
+ final hashes = theirs['hashes'];
+ if (hashes is! List || hashes.isEmpty || hashes.length > 4 * _gossipHashes) return null;
+ final window = <int, String>{};
+ var prev = 0;
+ for (final h in hashes) {
+ if (h is! Map) return null;
+ final seq = h['seq'], hash = h['hash'];
+ if (seq is! int || seq < 1 || hash is! String || hash.length > 128) return null;
+ if (prev != 0 && seq != prev + 1) return null;
+ prev = seq;
+ window[seq] = hash;
+ }
+ // The window must end where the peer's head is, or it describes some other log.
+ final head = DevLogHead.fromJson(theirs['head']);
+ if (head == null || head.seq != prev || head.hash != window[prev]) return null;
+ final first = window.keys.reduce(min);
+ for (final e in window.entries) {
+ if (e.key > state.head.seq || state.hashes[e.key - 1] == e.value) continue;
+ if (e.key == 1) return 1;
+ if (e.key == first) return null;
+ return state.hashes[e.key - 2] == window[e.key - 1] ? e.key : null;
+ }
+ return null;
+}
+
+
+/// What a step under the file lock found to tell the app — said once the lock is let go, since a
+/// listener may well read the log again (and signing out waits on the app).
+class _Effects {
+ final announce = <DevLogMember>[];
+ final removed = <DeviceRemovalNotice>[];
+ bool signOut = false;
+ bool changed = false;
}
class DeviceLogRebaseline {
- const DeviceLogRebaseline(this.head, this.added, this.removed);
+ const DeviceLogRebaseline(this.head, this.added, this.removed) : logChanged = false, otherAccount = false;
+
+ /// The backend's list is no longer the one that was previewed: nothing was done. Branch on
+ /// [logChanged]; [head], [added] and [removed] are empty placeholders then.
+ const DeviceLogRebaseline.changed()
+ : head = const DevLogHead(0, ''),
+ added = const [],
+ removed = const [],
+ logChanged = true,
+ otherAccount = false;
+
+ /// The backend's list is another account's while the live log is the one of the sign-in this app is
+ /// under: nothing was done — only a sign-in switches accounts. Branch on [otherAccount]; [head],
+ /// [added] and [removed] are empty placeholders then.
+ const DeviceLogRebaseline.otherAccount()
+ : head = const DevLogHead(0, ''),
+ added = const [],
+ removed = const [],
+ logChanged = false,
+ otherAccount = true;
final DevLogHead head;
final List<DevLogMember> added;
final List<DevLogMember> removed;
+ final bool logChanged;
+ final bool otherAccount;
}
class ViewerDeviceLog {
@@ -109,6 +316,7 @@ class ViewerDeviceLog {
required this.append,
required this.label,
this.onAnnounce,
+ this.onRemoved,
this.onSignedOut,
this.onChanged,
int Function()? now,
@@ -123,9 +331,12 @@ class ViewerDeviceLog {
/// How this app calls itself in the account's list of devices.
final String Function() label;
- /// A machine this app had never trusted joined the account: "New device: X".
+ /// A key joined the account after this app did: "New device: X".
final void Function(DevLogMember member)? onAnnounce;
+ /// A device was taken out of the account after this app joined it (not by this app).
+ final void Function(DeviceRemovalNotice notice)? onRemoved;
+
/// This app's own key was removed from the account: it is signed out.
final Future<void> Function()? onSignedOut;
@@ -139,11 +350,34 @@ class ViewerDeviceLog {
final _random = Random();
final Set<String> _removing = {};
+ /// Every entry fetched for the history so far (seq 1..n), this run only: never written to disk.
+ List<DevLogEntry> _histCache = [];
+ String? _histAcct;
+
/// Set while a sign-in by hand registers: this app's old key being removed is then expected, and is
/// replaced rather than signed out over.
bool _signingInAgain = false;
bool _signedOut = false;
+ /// Set while [register] runs.
+ bool _registering = false;
+
+ /// Moves on with each [beginSignIn]: a read that began after one, outside [register], ends what it
+ /// set — a sign-in by hand that never registers must not keep this app's own removal from signing
+ /// it out for good.
+ int _signInRound = 0;
+
+ /// Which sign-in by hand this app is under ([ViewerKeyStore.signInEpoch]), once known: minted by
+ /// [beginSignIn] (or [register] with `freshSignIn`), never anything the backend sends (not the
+ /// profile's id either).
+ String? _epoch;
+
+ /// Set by [beginSignIn] until [register] takes it: a sign-in by hand waiting to be registered.
+ bool _freshPending = false;
+
+ /// The write of the sign-in id [beginSignIn] minted; [register] waits for it.
+ Future<void>? _epochSaving;
+
/// This app's key is gone from the log: sign out, once.
Future<void> _signOut() async {
if (_signedOut) return;
@@ -161,10 +395,19 @@ class ViewerDeviceLog {
/// a reason to sign out — this app may have been signed out by the removal before it could read it
/// (a revoked session answers 401 first), and signing in again must not end in a second sign-out.
/// A stored session (the app opening) under a removed key signs out, as it always did.
+ ///
+ /// A sign-in by hand is also what lets this app's copy of the log move to another account (keeping
+ /// the one it leaves, to restore if it comes back) — for a short while after it ([_resetWindowMs]).
+ /// Its id is minted by [beginSignIn], which [register] calls itself when it was not called before.
Future<void> register({bool freshSignIn = false}) async {
- _signingInAgain = freshSignIn;
+ if (freshSignIn && !_freshPending) beginSignIn(fresh: true);
+ final fresh = _freshPending;
+ _freshPending = false;
+ _signingInAgain = fresh;
_signedOut = false;
+ _registering = true;
try {
+ await _epochSaving;
await refresh();
var identity = await keys.identity();
var pub = b64e(identity.pub);
@@ -174,7 +417,7 @@ class ViewerDeviceLog {
final state = file.state;
if (state == null || file.frozen != null) return;
if (state.removed.contains(pub)) {
- if (!freshSignIn) {
+ if (!fresh) {
await _signOut();
return;
}
@@ -204,80 +447,531 @@ class ViewerDeviceLog {
// The next sign-in, resume or push tries again.
} finally {
_signingInAgain = false;
+ _registering = false;
}
}
+ /// The app knows who is signed in — call it synchronously, before anything that reads the log (a
+ /// restored pane, a machine list, a connection) can start, then [register]. [fresh]: the person
+ /// signed in by hand just now (`DirectAuth.consumeFreshSignIn()`); its id is minted here, so a read
+ /// already on its way judges by this sign-in, not the one before. A stored session (the app opening)
+ /// is not fresh: nothing is minted.
+ void beginSignIn({required bool fresh}) {
+ _signedOut = false;
+ _freshPending = fresh;
+ // A removal of this app's old key read before [register] runs is then expected, not a sign-out —
+ // for the read that comes first ([_doRefresh] ends it), or until [register] takes over.
+ _signingInAgain = fresh;
+ _signInRound++;
+ if (!fresh) return;
+ final previous = _epoch;
+ final minted = _mintEpoch();
+ _epoch = minted;
+ _epochSaving = keys.writeSignInEpoch(minted).then(
+ (_) {},
+ onError: (Object _) {
+ // Not kept, not used: after a restart the file would be another sign-in's than the store's.
+ if (_epoch == minted) _epoch = previous;
+ },
+ );
+ }
+
/// Read and verify whatever the log gained. Concurrent calls share one read. Never throws.
Future<void> refresh() => _refreshing ??= _doRefresh().catchError((Object _) {}).whenComplete(() => _refreshing = null);
+ /// The tail of the queue every read-modify-write of the file waits in. A refresh, a peer's tail, a
+ /// dismissal and a review each read the file, change it and write it back; two of them interleaved
+ /// would write the older read over the newer one — a head rolled back, an announcement forgotten
+ /// and made twice, a dismissal undone.
+ Future<void> _fileQueue = Future.value();
+
+ /// Run [body] alone against the file — within this instance: two instances over one store (two web
+ /// tabs) do not see each other's lock and can still interleave. [body] must not wait on anything
+ /// that takes the lock itself (and nothing the app is told runs inside it: see [_Effects]).
+ Future<T> _locked<T>(Future<T> Function() body) {
+ final before = _fileQueue;
+ final done = Completer<void>();
+ _fileQueue = done.future;
+ return before.then((_) => body()).whenComplete(() => done.complete());
+ }
+
+ /// Tell the app what a step under the lock decided, once the lock is let go.
+ Future<void> _fire(_Effects e) async {
+ for (final m in e.announce) {
+ onAnnounce?.call(m);
+ }
+ for (final n in e.removed) {
+ onRemoved?.call(n);
+ }
+ if (e.signOut) await _signOut();
+ if (e.changed) onChanged?.call();
+ }
+
+ /// A sign-in id: random, then `@` and when it was made (ms) — see [_mayStartOver].
+ String _mintEpoch() =>
+ '${[for (var i = 0; i < 16; i++) _secure.nextInt(256).toRadixString(16).padLeft(2, '0')].join()}@${_now()}';
+ static final _secure = Random.secure();
+
+ /// Whether [local] — a sign-in by hand the file is not yet the log of — may start it over for another
+ /// account: never an adopted one, and only shortly after it was made. A backend that holds the log
+ /// back after a sign-in must not keep that door open, to name another account days later.
+ bool _mayStartOver(String local) {
+ if (local.startsWith(_adoptedSignIn)) return false;
+ final made = RegExp(r'@(\d{1,15})$').firstMatch(local);
+ if (made == null) return false;
+ return (_now() - int.parse(made.group(1)!)).abs() <= _resetWindowMs;
+ }
+
+ /// Whether [file] is the log of the sign-in this app is under (or that cannot be told). Until a read
+ /// of it under a new sign-in it may be the account just left: what a machine gossips is not judged
+ /// against it — a machine of the new account would read as a fork of the old one.
+ Future<bool> _ownsFile(_File file) async {
+ final local = await _localOwner();
+ return local == null || file.owner == local;
+ }
+
+ /// The sign-in by hand this app is under; a session from before sign-in ids existed is given one,
+ /// adopted ([_adoptedSignIn]). Null when the store cannot be read.
+ Future<String?> _localOwner() async {
+ if (_epoch case final epoch?) return epoch;
+ try {
+ final stored = await keys.signInEpoch();
+ if (stored != null && stored.isNotEmpty) return _epoch ??= stored;
+ final adopted = '$_adoptedSignIn${_mintEpoch()}';
+ await keys.writeSignInEpoch(adopted);
+ return _epoch ??= adopted;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// The first read of the log is over, however it ended: what is verified from here on is news.
+ Future<void> _endJoin() => _locked(() async {
+ final file = await _read();
+ if (!file.joining) return;
+ file.joining = false;
+ await _write(file);
+ });
+
+ /// The logs of accounts this app was signed in to before, by account id.
+ Future<Map<String, Object?>> _archived() async {
+ try {
+ return await keys.deviceLogArchive();
+ } catch (_) {
+ return {};
+ }
+ }
+
+ /// Keep [file] — the log of an account this app is leaving — to restore if it comes back. Under the lock.
+ Future<void> _archiveIn(_File file) async {
+ final acct = file.state?.acct;
+ if (acct == null) return;
+ final all = await _archived()
+ ..remove(acct);
+ all[acct] = file.toJson();
+ while (all.length > _archivedKept) {
+ all.remove(all.keys.first);
+ }
+ await keys.writeDeviceLogArchive(all);
+ }
+
+ /// The kept log of [acct], made the live file (this sign-in's: [owner]) and only then taken out of
+ /// the archive — a crash in between leaves it in both, never in neither. Null when there is none.
+ /// Under the lock.
+ Future<_File?> _restoreIn(String acct, String? owner) async {
+ final kept = _File.parse((await _archived())[acct]);
+ if (kept.state?.acct != acct) return null;
+ kept.owner = owner ?? kept.owner;
+ await _carrySuspensionsIn(kept);
+ await _write(kept);
+ final all = await _archived()
+ ..remove(acct);
+ await keys.writeDeviceLogArchive(all);
+ return kept;
+ }
+
+ /// [file], with every key a fork suspended in another account's kept log, and active in this one,
+ /// suspended (and new) here as well: it is not trusted either way, so the list says so — and "It's
+ /// mine" lifts it, everywhere (a review of this list does not: it never showed that suspension).
+ /// Under the lock.
+ Future<void> _carrySuspensionsIn(_File file) async {
+ final state = file.state;
+ if (state == null) return;
+ final selfPub = await _selfPub();
+ final carried = [
+ for (final k in await _archivedSuspended())
+ if (state.active.containsKey(k) && k != selfPub && !file.suspended.contains(k)) k,
+ ];
+ if (carried.isEmpty) return;
+ file
+ ..suspended = [...file.suspended, ...carried]
+ ..pending = {...file.pending, ...carried}.toList();
+ }
+
+ /// A suspension lifted here holds for every kept account too: none of them keeps [pubs] out. Under
+ /// the lock.
+ Future<void> _unsuspendArchivedIn(Iterable<String> pubs) async {
+ final lift = pubs.toSet();
+ final all = await _archived();
+ var changed = false;
+ for (final e in all.entries.toList()) {
+ final f = _File.parse(e.value);
+ if (!f.suspended.any(lift.contains)) continue;
+ f.suspended = [for (final k in f.suspended) if (!lift.contains(k)) k];
+ all[e.key] = f.toJson();
+ changed = true;
+ }
+ if (changed) await keys.writeDeviceLogArchive(all);
+ }
+
+ /// [gone], just taken out by [e], kept flagged: it was new here and nobody had looked at it yet.
+ DeviceLogDeparted _departedOf(DevLogMember gone, DevLogEntry e, String signerLabel) => DeviceLogDeparted(
+ pub: gone.pub,
+ label: gone.label,
+ kind: gone.kind,
+ machineId: gone.machineId,
+ fingerprint: fingerprint(b64d(gone.pub)),
+ addedAt: gone.addedAt,
+ removedAt: e.at,
+ removedBy: e.signer,
+ removedByLabel: signerLabel,
+ selfRemoved: e.signer == gone.pub,
+ );
+
+ /// [prev] plus [more] (a key once, at its newest), the oldest dropped past [_departedKept].
+ List<DeviceLogDeparted> _withDeparted(List<DeviceLogDeparted> prev, List<DeviceLogDeparted> more) {
+ if (more.isEmpty) return prev;
+ final pubs = {for (final d in more) d.pub};
+ final all = [for (final d in prev) if (!pubs.contains(d.pub)) d, ...more];
+ return all.skip(max(0, all.length - _departedKept)).toList();
+ }
+
+ /// The kept log of [acct], left in the archive; null when there is none.
+ Future<_File?> _archivedFileIn(String acct) async {
+ final kept = _File.parse((await _archived())[acct]);
+ return kept.state?.acct == acct ? kept : null;
+ }
+
+ /// What a review ([rebaseline]) takes out that was new here and never looked at: a key pending in
+ /// [base] that the reviewed list does not keep — and a key the list added and removed again at
+ /// entries this app never verified (while it was frozen) — stays flagged as departed.
+ List<DeviceLogDeparted> _reviewDeparted(
+ _File base,
+ DevLogState next,
+ List<DevLogEntry> parsed,
+ List<DevLogMember> removed,
+ String selfPub,
+ Set<String> pre,
+ ) {
+ final verified = base.state;
+ if (verified == null) return [];
+ final known = <String, ({String label, String kind})>{};
+ final adds = <String, DevLogEntry>{};
+ final out = <String, DeviceLogDeparted>{};
+ for (final e in [...parsed]..sort((a, b) => a.seq.compareTo(b.seq))) {
+ if (e.op == 'add') {
+ if (!known.containsKey(e.pub)) adds[e.pub] = e; // added (not renamed)
+ known[e.pub] = (label: e.label, kind: e.kind);
+ continue;
+ }
+ final was = removed.where((m) => m.pub == e.pub).firstOrNull;
+ final add = adds[e.pub];
+ final label = known[e.pub]?.label;
+ known.remove(e.pub);
+ if (e.pub == selfPub || next.active[e.pub] != null) continue;
+ // Added at an entry this app never verified, and gone again before it could see it.
+ final unseen = was == null &&
+ add != null &&
+ (add.seq > verified.hashes.length || verified.hashes[add.seq - 1] != devLogHash(add)) &&
+ !pre.contains(e.pub);
+ if ((was != null && base.pending.contains(e.pub)) || unseen) {
+ final member = was ??
+ DevLogMember(pub: e.pub, kind: add!.kind, machineId: add.machineId, label: label ?? add.label, addedAt: add.at, seq: add.seq);
+ out[e.pub] = _departedOf(member, e, known[e.signer]?.label ?? '');
+ }
+ }
+ // Pending here, and not on the reviewed list at all (a branch the backend no longer serves).
+ for (final m in removed) {
+ if (out.containsKey(m.pub) || m.pub == selfPub || !base.pending.contains(m.pub)) continue;
+ out[m.pub] = DeviceLogDeparted(
+ pub: m.pub,
+ label: m.label,
+ kind: m.kind,
+ machineId: m.machineId,
+ fingerprint: fingerprint(b64d(m.pub)),
+ addedAt: m.addedAt,
+ removedAt: _now(),
+ removedBy: '',
+ removedByLabel: '',
+ selfRemoved: false,
+ );
+ }
+ return [...out.values];
+ }
+
+ /// Every key a fork suspended in another account's kept log: no other account's log brings it back.
+ Future<Set<String>> _archivedSuspended() async => {
+ for (final f in (await _archived()).values) ..._File.parse(f).suspended,
+ };
+
+ Future<_File> _marks() => _locked(_marksIn);
+
+ /// [_marks], for a caller already holding the lock: the file, with the joined point filled in for one
+ /// written before it existed (or by a client that dropped it) — everything up to what was already
+ /// announced is then known, as it was.
+ Future<_File> _marksIn() async {
+ final file = await _read();
+ if (file.state == null || file.joinedSeq != null) return file;
+ file.joinedSeq = file.notifiedUpTo;
+ file.preLog = (await _knownPubs()).toList();
+ file.pending = [];
+ file.announced = [];
+ file.baselineSeen = true;
+ await _write(file);
+ return file;
+ }
+
Future<void> _doRefresh() async {
+ // A sign-in by hand waiting for [register]: this read is the one its old key's removal is expected
+ // in. After it, with no [register] under way, a removal of this app's key signs out again.
+ final round = _signInRound;
+ final expecting = _signingInAgain;
+ try {
+ await _readPages();
+ } finally {
+ // However the read ended — at the head, on a freeze, or cut short (no answer, the page cap) — the
+ // first read of a log is over: what is verified from here on is news. Held open, a backend that
+ // stalls the second page would have every key it adds later taken for one there at joining.
+ await _endJoin();
+ if (expecting && !_registering && round == _signInRound) _signingInAgain = false;
+ }
+ }
+
+ Future<void> _readPages() async {
+ await _marks();
var bootstrap = ((await _read()).state?.head.seq ?? 0) == 0;
for (var page = 0; page < _pages; page++) {
- final file = await _read();
- final since = file.state?.head.seq ?? 0;
+ final seen = (await _read()).state;
+ final since = seen?.head.seq ?? 0;
final got = await fetch(since);
if (got == null) return;
- if (file.state == null || file.state!.acct != got.acct) {
- // First read, or signed in to another account: that account's log starts from nothing here.
- await _write(_File(DevLogState.empty(got.acct), [], null, 0));
- bootstrap = true;
- if (got.head.seq == 0) return;
- if (since != 0) continue;
- }
- final current = await _read();
- final state = current.state!;
- if (current.frozen != null) {
- await _looseRemovals(got.entries);
- return;
- }
- if (got.head.seq < state.head.seq) return _freeze('rollback');
- if (got.head.seq == state.head.seq) {
- if (got.head.hash != state.head.hash) await _freeze('fork');
- return;
- }
- if (got.entries.isEmpty) return _freeze('invalid');
- if (!await _accept(got.entries, bootstrap)) return;
- if ((await _read()).state!.head.seq >= got.head.seq) return;
+ // A head that is not a position is the backend lying (or broken): nothing to verify it against.
+ if (!_isPosition(got.head.seq)) return;
+ final effects = _Effects();
+ // Whether to read another page.
+ final more = await _locked(() async {
+ var file = await _marksIn();
+ final local = await _localOwner();
+ var reset = file.state == null;
+ if (!reset) {
+ final signedInAgain = local != null && file.owner != local;
+ if (file.state!.acct != got.acct) {
+ // Another account only after a sign-in by hand here. Otherwise it is the backend saying so
+ // — and starting over would clear every mark a fork put on the list, the real log then
+ // adopted whole.
+ if (local == null || !signedInAgain || !_mayStartOver(local)) {
+ await _freezeIn(file, 'invalid', effects);
+ return false;
+ }
+ reset = true;
+ } else if (signedInAgain) {
+ // Signed in again to the same account: the same list, now this sign-in's.
+ file.owner = local;
+ await _write(file);
+ }
+ }
+ if (reset) {
+ if (file.state != null) await _archiveIn(file);
+ // Back to an account this app was signed in to before: its log as verified then, and every
+ // mark on it (frozen, suspended, pending), go on from where they were.
+ final kept = await _restoreIn(got.acct, local);
+ if (kept != null) {
+ bootstrap = (kept.state?.head.seq ?? 0) == 0;
+ return true;
+ }
+ // First read, or signed in to another account here: that account's log starts from nothing.
+ // `joinedSeq` starts at 0 and follows the head of each page this app VERIFIES ([_acceptIn]):
+ // never the head the backend merely claims, or it could park it far ahead and have every key
+ // it forges below that adopted without a word. `preLog` is what was trusted already.
+ file = _File(
+ DevLogState.empty(got.acct),
+ [],
+ null,
+ 0,
+ joinedSeq: 0,
+ preLog: (await _knownPubs()).toList(),
+ baselineSeen: false,
+ joining: true,
+ owner: local,
+ );
+ await _write(file);
+ bootstrap = true;
+ if (got.head.seq == 0) return false;
+ if (since != 0) return true;
+ } else if (seen == null || seen.acct != file.state!.acct || seen.head != file.state!.head) {
+ // The log moved here while this page was on its way (a peer handed over its tail): the page
+ // answers a question nobody is asking any more — judged against the newer head it would read
+ // as a rollback, or as entries out of order. Ask again from where the log is now.
+ return true;
+ }
+ final state = file.state!;
+ if (file.frozen != null) {
+ await _looseRemovalsIn(file, got.entries, effects);
+ return false;
+ }
+ if (got.head.seq < state.head.seq) {
+ await _freezeIn(file, 'rollback', effects);
+ return false;
+ }
+ if (got.head.seq == state.head.seq) {
+ if (got.head.hash != state.head.hash) await _freezeIn(file, 'fork', effects);
+ return false;
+ }
+ if (got.entries.isEmpty) {
+ await _freezeIn(file, 'invalid', effects);
+ return false;
+ }
+ if (!await _acceptIn(file, got.entries, bootstrap, effects)) return false;
+ return file.state!.head.seq < got.head.seq;
+ });
+ await _fire(effects);
+ if (!more) return;
}
}
- Future<bool> _accept(List<Object?> entries, bool bootstrap) async {
- final file = await _read();
+ /// [keys] cut to the ones still active — the marks never outlive the key.
+ List<String> _prune(List<String> keys, DevLogState state) => [
+ for (final k in keys.toSet())
+ if (state.active.containsKey(k)) k,
+ ];
+
+ /// What each active key in [state] is called now, to be walked forward through entries.
+ Map<String, ({String label, String kind})> _knownOf(DevLogState state) => {
+ for (final m in state.active.values) m.pub: (label: m.label, kind: m.kind),
+ };
+
+ /// The notice for a `remove`, or null when there is nothing to say: this app's own removal, its own
+ /// key, or a removal from before it joined. [known] says what each key was called, and what kind it
+ /// was, BEFORE this removal — the remove entry's own label and kind are the signer's to pick, so they
+ /// are never what the person is told.
+ DeviceRemovalNotice? _removalNotice(
+ DevLogEntry e,
+ int joinedSeq,
+ String selfPub,
+ List<String> pending,
+ Map<String, ({String label, String kind})> known,
+ ) {
+ if (e.op != 'remove' || e.seq <= joinedSeq || e.pub == selfPub || e.signer == selfPub) return null;
+ final was = known[e.pub];
+ return DeviceRemovalNotice(
+ pub: e.pub,
+ label: was?.label ?? e.label,
+ kind: was?.kind ?? e.kind,
+ fingerprint: fingerprint(b64d(e.pub)),
+ signer: e.signer,
+ signerLabel: known[e.signer]?.label ?? '',
+ signerFingerprint: fingerprint(b64d(e.signer)),
+ signerPending: pending.contains(e.signer),
+ selfRemoved: e.signer == e.pub,
+ at: _now(),
+ );
+ }
+
+ /// The entries a peer handed over that this app lacks, applied under the lock — judged against the
+ /// head the file has by then, which a refresh may have moved since the peer was heard.
+ Future<bool> _acceptFromPeer(List<Object?> entries) async {
+ final effects = _Effects();
+ final ok = await _locked(() async {
+ final file = await _marksIn();
+ final state = file.state;
+ if (state == null || file.frozen != null) return false;
+ final missing = [
+ for (final e in entries)
+ if ((DevLogEntry.parse(e)?.seq ?? 0) > state.head.seq) e,
+ ];
+ if (missing.isEmpty) return true;
+ return _acceptIn(file, missing, false, effects);
+ });
+ await _fire(effects);
+ return ok;
+ }
+
+ /// Apply [entries] to [file] and write it; under the lock. What the app is told goes in [effects].
+ Future<bool> _acceptIn(_File file, List<Object?> entries, bool bootstrap, _Effects effects) async {
+ // While the first read of this log is open (a peer's tail can arrive between its pages too):
+ // whatever is verified before it reaches the head is what was there at joining.
+ final joining = file.joining;
final DevLogApplied applied;
try {
applied = await applyDevLogEntries(file.state!, entries);
} on DevLogError catch (err) {
- await _freeze(err.code == 'BROKEN_CHAIN' || err.code == 'OUT_OF_ORDER' ? 'fork' : 'invalid');
+ await _freezeIn(file, err.code == 'BROKEN_CHAIN' || err.code == 'OUT_OF_ORDER' ? 'fork' : 'invalid', effects);
return false;
}
final selfPub = await _selfPub();
- final known = await _knownPubs();
- final news = bootstrap
- ? const <DevLogMember>[]
- : [
- for (final m in applied.added)
- if (m.seq > file.notifiedUpTo && m.pub != selfPub && !known.contains(m.pub)) m,
- ];
- await _write(_File(
- applied.state,
- [...file.recent, ...entries.map(DevLogEntry.parse).whereType<DevLogEntry>()],
- null,
- applied.state.head.seq,
- ));
+ // While joining, everything this page verified is what was there before: the joined point moves up
+ // to the verified head (never past it), and none of it is news.
+ final joinedSeq = joining ? applied.state.head.seq : file.joinedSeq ?? 0;
+ final pre = file.preLog.toSet();
+ final parsed = entries.map(DevLogEntry.parse).whereType<DevLogEntry>().toList();
+ // News is decided from the log alone: an `add` past the point this app joined, for a key it did not
+ // already trust then. What the roster or the pins hold now says nothing — a key can reach them
+ // (over `group_sync`) before this app reads the entry that adds it.
+ final news = [
+ for (final m in applied.added)
+ if (m.seq > joinedSeq && m.pub != selfPub && !pre.contains(m.pub)) m,
+ ];
+ final pendingNow = [...file.pending, for (final m in news) m.pub];
+ // Walk the entries in order: a removal is described by what the key was called when it was removed.
+ final known = _knownOf(file.state!);
+ final notices = <DeviceRemovalNotice>[];
+ final gone = {for (final m in applied.removed) m.pub: m};
+ final departed = <DeviceLogDeparted>[];
+ for (final e in [...parsed]..sort((a, b) => a.seq.compareTo(b.seq))) {
+ if (e.op == 'add') {
+ known[e.pub] = (label: e.label, kind: e.kind);
+ } else {
+ final n = _removalNotice(e, joinedSeq, selfPub, pendingNow, known);
+ if (n != null) notices.add(n);
+ // A new key nobody looked at, gone again (even within this page): it stays flagged.
+ final member = gone[e.pub];
+ if (member != null && pendingNow.contains(e.pub) && e.pub != selfPub) {
+ departed.add(_departedOf(member, e, known[e.signer]?.label ?? ''));
+ }
+ known.remove(e.pub);
+ }
+ }
+ final toAnnounce = [
+ for (final m in news)
+ if (!file.announced.contains(m.pub)) m,
+ ];
+ // A key taken into the "already on your account" list after that list was acknowledged: show it.
+ if (joining && applied.added.any((m) => m.pub != selfPub)) file.baselineSeen = false;
+ file
+ ..state = applied.state
+ ..joinedSeq = joinedSeq
+ ..recent = [...file.recent, ...parsed]
+ ..frozen = null
+ ..notifiedUpTo = applied.state.head.seq
+ ..pending = _prune(pendingNow, applied.state)
+ ..announced = _prune([...file.announced, for (final m in toAnnounce) m.pub], applied.state)
+ ..suspended = _prune(file.suspended, applied.state)
+ ..departed = _withDeparted(file.departed, departed);
+ await _carrySuspensionsIn(file);
+ await _write(file);
await _trust(bootstrap ? applied.state.active.values.toList() : [...applied.added, ...applied.relabeled]);
for (final m in applied.removed) {
await _drop(m);
}
- for (final m in news) {
- onAnnounce?.call(m);
- }
- if (applied.state.removed.contains(selfPub) && !_signingInAgain) await _signOut();
- onChanged?.call();
+ effects.announce.addAll(toAnnounce);
+ effects.removed.addAll(notices);
+ if (applied.state.removed.contains(selfPub) && !_signingInAgain) effects.signOut = true;
+ effects.changed = true;
return true;
}
- /// What this app already trusted — its pins and its trust group — so a key the log adds that is
- /// among them is not news.
+ /// What this app trusts right now — its pins and its trust group — snapshotted once, when it joins
+ /// the log (or migrates), so what it already knew then is never news.
Future<Set<String>> _knownPubs() async {
final roster = GroupRoster.parse(await keys.groupRoster());
return {
@@ -293,10 +987,11 @@ class ViewerDeviceLog {
final stored = GroupRoster.parse(await keys.groupRoster());
final inRoster = {for (final m in stored.members) m.pub};
final tombstoned = {for (final t in stored.removed) if (!inRoster.contains(t.pub)) t.pub};
+ final suspended = await suspendedPubs();
final now = _now();
final adopt = [
for (final m in members)
- if (m.pub != selfPub && !tombstoned.contains(m.pub)) m,
+ if (m.pub != selfPub && !tombstoned.contains(m.pub) && !suspended.contains(m.pub)) m,
];
final incoming = [
for (final m in adopt)
@@ -340,35 +1035,58 @@ class ViewerDeviceLog {
}
}
- /// While frozen, a removal still counts — if a key this app trusts signed it.
- Future<void> _looseRemovals(List<Object?> entries) async {
- final file = await _read();
+ /// While frozen, a removal still counts — if a key this app trusts signed it. A key a fork suspended
+ /// is not trusted here, so what it signs does not count either.
+ /// Under the lock.
+ Future<void> _looseRemovalsIn(_File file, List<Object?> entries, _Effects effects) async {
final state = file.state;
if (state == null) return;
- var changed = false;
+ final selfPub = await _selfPub();
+ final joinedSeq = file.joinedSeq ?? 0;
+ final suspended = file.suspended.toSet();
+ final known = _knownOf(state);
+ final loose = <DevLogEntry>[];
+ final notices = <DeviceRemovalNotice>[];
+ final departed = <DeviceLogDeparted>[];
for (final raw in entries) {
final e = DevLogEntry.parse(raw);
- if (e == null || e.op != 'remove' || state.active[e.signer] == null) continue;
+ if (e == null || e.op != 'remove' || state.active[e.signer] == null || suspended.contains(e.signer)) continue;
final target = state.active[e.pub];
if (target == null) continue;
if (!await verifySignature(b64d(e.signer), devLogMessage(e), b64d(e.sig))) continue;
+ final notice = _removalNotice(e, joinedSeq, selfPub, file.pending, known);
+ if (file.pending.contains(e.pub) && e.pub != selfPub) departed.add(_departedOf(target, e, known[e.signer]?.label ?? ''));
state.active.remove(e.pub);
state.removed.add(e.pub);
await _drop(target);
- changed = true;
- }
- if (changed) {
- await _write(file);
- onChanged?.call();
+ loose.add(e);
+ if (notice != null) notices.add(notice);
}
+ if (loose.isEmpty) return;
+ file
+ ..looseRemoved = [...file.looseRemoved, ...loose]
+ ..pending = _prune(file.pending, state)
+ ..announced = _prune(file.announced, state)
+ ..suspended = _prune(file.suspended, state)
+ ..departed = _withDeparted(file.departed, departed);
+ await _write(file);
+ effects.removed.addAll(notices);
+ effects.changed = true;
}
Future<void> _freeze(String reason) async {
- final file = await _read();
+ final effects = _Effects();
+ await _locked(() async => _freezeIn(await _read(), reason, effects));
+ await _fire(effects);
+ }
+
+ /// [_freeze], for a caller already holding the lock.
+ Future<void> _freezeIn(_File file, String reason, _Effects effects) async {
if (file.frozen != null || file.state == null) return;
file.frozen = DeviceLogFreeze(reason, _now(), file.state!.head);
+ file.joining = false;
await _write(file);
- onChanged?.call();
+ effects.changed = true;
}
/// Remove a device from the account, signed by this app. It stops being trusted here at once.
@@ -418,14 +1136,19 @@ class ViewerDeviceLog {
} catch (_) {}
}
- /// What trusting the backend's log again would change; with [confirm], do it.
- Future<DeviceLogRebaseline?> rebaseline({required bool confirm}) async {
+ /// What trusting the backend's log again would change; with [confirm], do it. [expectedHead] is the
+ /// head the person was shown in the preview: if the backend's log is not that one any more, nothing is
+ /// done and the result has [DeviceLogRebaseline.logChanged] set — what gets trusted is what was
+ /// reviewed. Another account's list under the sign-in the live log belongs to is refused, preview and
+ /// confirm alike ([DeviceLogRebaseline.otherAccount]). Null: the backend's list could not be read or
+ /// did not verify.
+ Future<DeviceLogRebaseline?> rebaseline({required bool confirm, DevLogHead? expectedHead}) async {
final entries = <Object?>[];
var acct = '';
DevLogHead? head;
for (var page = 0; page < _pages; page++) {
final got = await fetch(entries.length);
- if (got == null) return null;
+ if (got == null || !_isPosition(got.head.seq)) return null;
acct = got.acct;
head = got.head;
entries.addAll(got.entries);
@@ -438,69 +1161,347 @@ class ViewerDeviceLog {
return null;
}
if (head == null || next.head != head) return null;
- final file = await _read();
- final before = file.state?.active ?? const <String, DevLogMember>{};
- final added = [for (final m in next.active.values) if (before[m.pub] == null) m];
- final removed = [for (final m in before.values) if (next.active[m.pub] == null) m];
- if (confirm) {
- await _write(_File(next, entries.map(DevLogEntry.parse).whereType<DevLogEntry>().toList(), null, next.head.seq));
- await _trust(next.active.values.toList());
- for (final m in removed) {
- await _drop(m);
+ final effects = _Effects();
+ final result = await _locked(() async {
+ final file = await _marksIn();
+ final same = file.state != null && file.state!.acct == next.acct;
+ // Another account's list while the live log is the one of the sign-in this app is under: the
+ // backend switched accounts on its own. A review must not move this app there (the account it is
+ // signed in to, and every mark on it, would go out of sight): only a sign-in switches accounts.
+ // Only a sign-in by hand the list is not stamped with is that switch: none recorded, an adopted one
+ // (a session this app took over — whatever stamp the list has, or lacks, from an older version), or
+ // the sign-in the list is stamped with is not.
+ if (file.state != null && !same) {
+ final local = await _localOwner();
+ if (local == null || local.startsWith(_adoptedSignIn) || file.owner == local) {
+ return const DeviceLogRebaseline.otherAccount();
+ }
}
- onChanged?.call();
- }
- return DeviceLogRebaseline(next.head, added, removed);
+ if (confirm && expectedHead != null && next.head != expectedHead) return const DeviceLogRebaseline.changed();
+ // The list under review is judged against this account's own log as this app verified it: the
+ // live file, or — for another account — the one kept when this app left it (its marks go on), or
+ // else nothing (every key on it is new here). Never against the account being left.
+ final kept = same ? null : await _archivedFileIn(next.acct);
+ final base = same ? file : kept ?? _File(null, [], null, 0, joinedSeq: 0, preLog: [...file.preLog]);
+ final before = base.state?.active ?? const <String, DevLogMember>{};
+ final added = [for (final m in next.active.values) if (before[m.pub] == null) m];
+ final removed = [for (final m in before.values) if (next.active[m.pub] == null) m];
+ if (confirm) {
+ final selfPub = await _selfPub();
+ final pre = base.preLog.toSet();
+ // Every key the review let in is new here — however the preview and this read differ — unless
+ // this app knew it already.
+ final news = [
+ for (final m in added)
+ if (m.pub != selfPub && !pre.contains(m.pub)) m,
+ ];
+ final toAnnounce = [
+ for (final m in news)
+ if (!base.announced.contains(m.pub)) m,
+ ];
+ final parsed = entries.map(DevLogEntry.parse).whereType<DevLogEntry>().toList();
+ final departed = _reviewDeparted(base, next, parsed, removed, selfPub, pre);
+ // The reviewed list is another account's: the one this app leaves is kept, as on a sign-in (and
+ // what a fork suspended in it stays suspended here) — and a kept one of the reviewed account
+ // goes on from where it was.
+ if (file.state != null && !same) await _archiveIn(file);
+ base
+ ..state = next
+ ..recent = parsed
+ ..frozen = null
+ ..notifiedUpTo = next.head.seq
+ // The joined point never moves up past the reviewed head: a shorter list (rolled back, or
+ // another account's) must leave every key added to it from here on news.
+ ..joinedSeq = min(base.joinedSeq ?? base.notifiedUpTo, next.head.seq)
+ ..pending = _prune([...base.pending, for (final m in news) m.pub], next)
+ ..announced = _prune([...base.announced, for (final m in toAnnounce) m.pub], next)
+ // A review lifts what a fork suspended in this list; a kept list's suspensions were never in
+ // the preview, so they stay.
+ ..suspended = same ? [] : _prune(base.suspended, next)
+ ..looseRemoved = []
+ ..joining = false
+ ..reviewedSeq = next.head.seq
+ ..departed = _withDeparted(base.departed, departed)
+ ..owner = await _localOwner() ?? base.owner;
+ await _carrySuspensionsIn(base);
+ // Live first, then out of the archive: a crash in between leaves it in both, never in neither.
+ await _write(base);
+ if (kept != null) {
+ final all = await _archived();
+ if (all.remove(next.acct) != null) await keys.writeDeviceLogArchive(all);
+ }
+ await _trust(next.active.values.toList());
+ for (final m in removed) {
+ await _drop(m);
+ }
+ effects.announce.addAll(toAnnounce);
+ effects.changed = true;
+ }
+ return DeviceLogRebaseline(next.head, added, removed);
+ });
+ await _fire(effects);
+ return result;
}
/// What rides this app's side of a `group_sync`.
Future<Map<String, Object?>?> gossip() async {
final file = await _read();
final state = file.state;
- if (state == null) return null;
- return {'head': state.head.toJson(), 'frozen': file.frozen != null};
+ // Not this sign-in's log yet (it may be the account this app just left): nothing to say.
+ if (state == null || !await _ownsFile(file)) return null;
+ // The newest hashes let a peer that finds the logs forked say where they split.
+ final from = max(0, state.hashes.length - _gossipHashes);
+ return {
+ 'head': state.head.toJson(),
+ 'frozen': file.frozen != null,
+ 'hashes': [
+ for (var i = from; i < state.hashes.length; i++) {'seq': i + 1, 'hash': state.hashes[i]},
+ ],
+ };
}
/// A machine's answer to this app's `group_sync`: its head, whether it is frozen, and the entries
/// this app lacks if it is behind.
Future<void> heard(String machinePub, Object? raw) async {
- final file = await _read();
+ final file = await _marks();
final state = file.state;
if (state == null || raw is! Map) return;
+ // A sign-in waiting for its first read: the file may be the account left behind, and a machine of
+ // the new one would freeze it as a fork. Nothing is judged until the log is this sign-in's.
+ if (!await _ownsFile(file)) return;
_frozenPeers[machinePub] = raw['frozen'] == true;
final theirs = DevLogHead.fromJson(raw['head']);
if (theirs == null) return;
final relation = compareDevLogHead(state, theirs);
- if (relation == 'fork') return _freeze('fork');
+ if (relation == 'fork') {
+ await _freeze('fork');
+ return _suspendAfterFork(raw);
+ }
if (relation == 'behind') {
final tail = raw['tail'];
final missing = tail is List
? [for (final e in tail) if ((DevLogEntry.parse(e)?.seq ?? 0) > state.head.seq) e]
: const <Object?>[];
- if (missing.isNotEmpty && file.frozen == null) await _accept(missing, false);
+ // A tail that does not continue this log is a fork; and a log already frozen on one can still
+ // learn from this machine's hashes where it split.
+ if (file.frozen != null || (missing.isNotEmpty && !await _acceptFromPeer(missing))) {
+ await _suspendAfterFork(raw);
+ }
unawaited(refresh());
}
}
+ /// A fork a peer proved with its hashes: the keys added at or after the split — and new here — are
+ /// not trusted until the list is reviewed ([rebaseline]). Only locally: nothing is tombstoned or
+ /// written to the log. Without usable hashes the freeze alone stands.
+ Future<void> _suspendAfterFork(Object? theirs) async {
+ final changed = await _locked(() async {
+ final file = await _read();
+ final state = file.state;
+ if (state == null || file.frozen?.reason != 'fork') return false;
+ final split = devLogDivergence(state, theirs);
+ if (split == null) return false;
+ final selfPub = await _selfPub();
+ // Only keys nobody here has marked as seen — and not one a review (`rebaseline`) already let in:
+ // another device's old branch must not cost this one the devices its user just looked at.
+ final reviewed = file.reviewedSeq ?? -1;
+ final fresh = [
+ for (final m in state.active.values)
+ if (m.seq >= split &&
+ m.pub != selfPub &&
+ file.pending.contains(m.pub) &&
+ m.seq > reviewed &&
+ !file.suspended.contains(m.pub))
+ m,
+ ];
+ if (fresh.isEmpty) return false;
+ file.suspended = [...file.suspended, for (final m in fresh) m.pub];
+ await _write(file);
+ for (final m in fresh) {
+ if (m.kind != 'machine') continue;
+ final current = await keys.peer(m.machineId);
+ if (current != null && b64e(current.pub) == m.pub) await keys.unlink(m.machineId);
+ }
+ return true;
+ });
+ if (changed) onChanged?.call();
+ }
+
+ /// Keys not trusted here after a fork, until [rebaseline] — and every key a fork suspended in another
+ /// account's kept log, which no other account's log can bring back in.
+ Future<Set<String>> suspendedPubs() async => {...(await _read()).suspended, ...await _archivedSuspended()};
+
+ /// Mark new devices as seen: the ones in [pubs] (what a window displayed), one ([pub]), or every one
+ /// (neither). The "already on your account" list is [seeBaseline]. Persisted, so it holds across
+ /// restarts. A key a fork suspended stays flagged when it is only part of a list that was looked at;
+ /// [pub] — "It's mine" on that very device — is the person vouching for it, and lifts its suspension
+ /// (here and in every kept account's log). A key that joined and left before anyone looked
+ /// ([DeviceLogListing.departed]) is cleared the same way: named, or every one.
+ Future<void> dismiss({String? pub, List<String>? pubs}) async {
+ final lifted = <DevLogMember>[];
+ final changed = await _locked(() async {
+ final file = await _marksIn();
+ if (file.state == null) return false;
+ final named = pub != null || pubs != null;
+ final gone = {...?pubs, ?pub};
+ file.pending = [
+ for (final k in file.pending)
+ if ((named ? !gone.contains(k) : false) || (file.suspended.contains(k) && k != pub)) k,
+ ];
+ file.departed = [
+ for (final d in file.departed)
+ if (named && !gone.contains(d.pub)) d,
+ ];
+ final lifting = pub != null && file.suspended.contains(pub) ? pub : null;
+ if (lifting != null) {
+ file.suspended = [for (final k in file.suspended) if (k != lifting) k];
+ final m = file.state!.active[lifting];
+ if (m != null) lifted.add(m);
+ }
+ await _write(file);
+ if (lifting != null) await _unsuspendArchivedIn([lifting]);
+ if (lifted.isNotEmpty) await _trust(lifted);
+ return true;
+ });
+ if (changed) onChanged?.call();
+ }
+
+ /// The "Already on your account" list was acknowledged: the first read is over, whatever comes after
+ /// is news — or a backend that stalls that read could add a key to a list nobody looks at again.
+ Future<void> seeBaseline() => _change((file) {
+ file
+ ..baselineSeen = true
+ ..joining = false;
+ });
+
+ /// Read the file, [edit] it and write it back, under the lock; nothing when there is no log yet.
+ Future<void> _change(void Function(_File file) edit) async {
+ final changed = await _locked(() async {
+ final file = await _marksIn();
+ if (file.state == null) return false;
+ edit(file);
+ await _write(file);
+ return true;
+ });
+ if (changed) onChanged?.call();
+ }
+
+ /// Every add and remove in the log, newest first, as this app verified it: the entries come from the
+ /// backend but each must hash to what this app already verified, or the log freezes. Offline, what
+ /// is kept locally (`complete: false`).
+ Future<DeviceLogHistory> history() => _historying ??= _historyOnce().whenComplete(() => _historying = null);
+
+ /// One walk at a time: two interleaved on the same cache would each read the other's entries as a
+ /// gap in the log and freeze it.
+ Future<DeviceLogHistory>? _historying;
+
+ Future<DeviceLogHistory> _historyOnce() async {
+ await refresh();
+ final file = await _marks();
+ final state = file.state;
+ if (state == null) return const DeviceLogHistory(rows: [], complete: false);
+ if (_histAcct != state.acct) {
+ _histAcct = state.acct;
+ _histCache = [];
+ }
+ final last = _histCache.isEmpty ? null : _histCache.last;
+ if (last != null && (last.seq > state.head.seq || devLogHash(last) != state.hashes[last.seq - 1])) {
+ _histCache = [];
+ }
+ for (var page = 0; page < _pages && _histCache.length < state.head.seq; page++) {
+ final since = _histCache.length;
+ final got = await fetch(since);
+ if (got == null || got.acct != state.acct) break;
+ var progressed = false;
+ for (final raw in got.entries) {
+ final e = DevLogEntry.parse(raw);
+ final rawSeq = raw is Map ? raw['seq'] : null;
+ final seq = e?.seq ?? (rawSeq is int ? rawSeq : 0);
+ if (seq <= _histCache.length || seq > state.head.seq) continue;
+ // At a position this app verified, anything unreadable or off-hash means the backend is lying
+ // about the past: freeze, and show only what was already checked.
+ if (e == null || e.seq != _histCache.length + 1 || devLogHash(e) != state.hashes[e.seq - 1]) {
+ // Only against the log this walk started from: if the file was rebaselined (or moved to
+ // another account) while the pages were on their way, the mismatch is with a log that is
+ // gone, and says nothing about the backend.
+ final now = (await _read()).state;
+ if (now == null || now.acct != state.acct || now.head != state.head) {
+ _histCache = [];
+ _histAcct = null;
+ return _historyOf(const [], false);
+ }
+ await _freeze('fork');
+ return _historyOf(_histCache, false);
+ }
+ _histCache.add(e);
+ progressed = true;
+ }
+ if (!progressed) break;
+ }
+ return _historyOf(_histCache, _histCache.length >= state.head.seq);
+ }
+
+ Future<DeviceLogHistory> _historyOf(List<DevLogEntry> fetched, bool complete) async {
+ final file = await _read();
+ final state = file.state;
+ if (state == null) return const DeviceLogHistory(rows: [], complete: false);
+ // Offline, the newest entries kept locally fill in what could not be fetched.
+ final from = fetched.isEmpty ? 0 : fetched.last.seq;
+ final entries = complete ? fetched : [...fetched, for (final e in file.recent) if (e.seq > from) e];
+ return DeviceLogHistory(
+ rows: devLogHistory(
+ entries,
+ selfPub: await _selfPub(),
+ joinedSeq: file.joinedSeq,
+ // A key that joined and left before anyone looked is still new, in its rows too.
+ pending: [...file.pending, for (final d in file.departed) d.pub],
+ active: state.active,
+ loose: file.looseRemoved,
+ ),
+ complete: complete,
+ );
+ }
+
/// The account's devices as this app's log has them.
Future<DeviceLogListing> list() async {
- final file = await _read();
+ final file = await _marks();
final selfPub = await _selfPub();
final members = (file.state?.active.values.toList() ?? [])..sort((a, b) => a.seq.compareTo(b.seq));
final labels = {for (final m in members) m.pub: m.label};
+ final joinedSeq = file.joinedSeq ?? 0;
+ final pre = file.preLog.toSet();
return DeviceLogListing(
members: [
- for (final m in members) DeviceLogRow(m, fingerprint: fingerprint(b64d(m.pub)), self: m.pub == selfPub),
+ for (final m in members)
+ DeviceLogRow(
+ m,
+ fingerprint: fingerprint(b64d(m.pub)),
+ self: m.pub == selfPub,
+ pending: file.pending.contains(m.pub),
+ suspended: file.suspended.contains(m.pub),
+ ),
],
frozen: file.frozen,
frozenPeers: [
for (final e in _frozenPeers.entries)
if (e.value) labels[e.key] ?? fingerprint(b64d(e.key)),
],
+ pending: file.pending,
+ suspended: file.suspended,
+ joinedSeq: joinedSeq,
+ baseline: [
+ for (final m in members)
+ if (m.pub != selfPub && (m.seq <= joinedSeq || pre.contains(m.pub))) m.pub,
+ ],
+ baselineSeen: file.baselineSeen,
+ departed: file.departed,
);
}
}
+/// Whether [seq] can be a log position: a whole number, not negative, not past what a double holds.
+bool _isPosition(int seq) => seq >= 0 && seq <= 9007199254740991;
+
String _clip(String label) {
final clean = label.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim();
return clean.length > devLogLabelMax ? clean.substring(0, devLogLabelMax) : clean;
diff --git a/desktop/lib/viewer/direct_link.dart b/desktop/lib/viewer/direct_link.dart
index 165f5816f..92983ca5e 100644
--- a/desktop/lib/viewer/direct_link.dart
+++ b/desktop/lib/viewer/direct_link.dart
@@ -93,6 +93,7 @@ class DirectLink implements PeerLinkClient {
label: label,
socket: socket,
devlog: await log?.gossip(),
+ suspended: log?.suspendedPubs,
onDevlog: log?.heard,
);
}
diff --git a/desktop/lib/viewer/group_sync.dart b/desktop/lib/viewer/group_sync.dart
index bbab7a8f0..fb33b4127 100644
--- a/desktop/lib/viewer/group_sync.dart
+++ b/desktop/lib/viewer/group_sync.dart
@@ -217,6 +217,10 @@ Future<GroupSyncOutcome> syncTrustGroup({
Duration timeout = const Duration(seconds: 20),
Map<String, Object?>? devlog,
Future<void> Function(String machinePub, Object? devlog)? onDevlog,
+
+ /// Keys a fork put out of trust here until reviewed (device_log_sync.dart): never pinned or seeded.
+ /// Asked again after [onDevlog], which can suspend a key in this very exchange.
+ Future<Set<String>> Function()? suspended,
}) async {
WebSocketChannel? channel;
try {
@@ -224,7 +228,7 @@ Future<GroupSyncOutcome> syncTrustGroup({
if (pin == null) return GroupSyncOutcome.none;
final identity = await keys.identity();
final selfPub = b64e(identity.pub);
- final local = await _seeded(keys, selfPub);
+ final local = await _seeded(keys, selfPub, await suspended?.call() ?? const {});
final self = GroupMember(
pub: selfPub,
kind: 'viewer',
@@ -268,7 +272,7 @@ Future<GroupSyncOutcome> syncTrustGroup({
selfPub,
);
await keys.writeGroupRoster(merged.roster.toJson());
- return await _apply(keys, merged);
+ return await _apply(keys, merged, await suspended?.call() ?? const {});
} catch (_) {
return GroupSyncOutcome.none;
} finally {
@@ -278,7 +282,11 @@ Future<GroupSyncOutcome> syncTrustGroup({
/// This phone's roster, with every machine it has pinned folded in — how a machine this phone linked
/// by password reaches the rest of the group, and how links made before the group existed join it.
-Future<GroupRoster> _seeded(ViewerKeyStore keys, String selfPub) async {
+Future<GroupRoster> _seeded(
+ ViewerKeyStore keys,
+ String selfPub,
+ Set<String> suspended,
+) async {
final stored = GroupRoster.parse(await keys.groupRoster());
// Only pins the roster does not name yet: a pin's `linkedAt` is when THIS device pinned it (the
// group's own pins included), and folding that in again would restamp the member as new on every
@@ -286,7 +294,7 @@ Future<GroupRoster> _seeded(ViewerKeyStore keys, String selfPub) async {
final known = {for (final m in stored.members) m.pub};
final pins = [
for (final p in await keys.peers())
- if (!known.contains(b64e(p.pub)))
+ if (!known.contains(b64e(p.pub)) && !suspended.contains(b64e(p.pub)))
?GroupMember.tryParse({
'pub': b64e(p.pub),
'machineId': p.machineId,
@@ -298,11 +306,15 @@ Future<GroupRoster> _seeded(ViewerKeyStore keys, String selfPub) async {
return mergeGroupRoster(stored, GroupRoster(pins, const []), selfPub).roster;
}
-Future<GroupSyncOutcome> _apply(ViewerKeyStore keys, GroupMerge merged) async {
+Future<GroupSyncOutcome> _apply(
+ ViewerKeyStore keys,
+ GroupMerge merged,
+ Set<String> suspended,
+) async {
final pinned = <String>[], unpinned = <String>[];
for (final m in merged.upserted) {
final id = m.machineId;
- if (!m.isMachine || id == null) continue;
+ if (!m.isMachine || id == null || suspended.contains(m.pub)) continue;
final current = await keys.peer(id);
if (current != null && b64e(current.pub) == m.pub) continue;
await keys.pin(id, b64d(m.pub), label: m.label);
diff --git a/desktop/lib/viewer/viewer_key_store.dart b/desktop/lib/viewer/viewer_key_store.dart
index c9b40e7e1..ff42aa699 100644
--- a/desktop/lib/viewer/viewer_key_store.dart
+++ b/desktop/lib/viewer/viewer_key_store.dart
@@ -64,6 +64,8 @@ class ViewerKeyStore {
static const _peersKey = 'viewer_e2ee_machine_peers';
static const _groupKey = 'viewer_e2ee_group';
static const _devLogKey = 'viewer_e2ee_devlog';
+ static const _devLogArchiveKey = 'viewer_e2ee_devlog_archive';
+ static const _signInKey = 'viewer_e2ee_sign_in';
/// Minted on first use and kept: every linked machine has pinned it.
Future<E2eeIdentity> identity() => _identity ??= _loadOrMintIdentity();
@@ -155,13 +157,36 @@ class ViewerKeyStore {
Future<void> writeDeviceLog(Map<String, Object?> log) =>
_storage.write(_devLogKey, jsonEncode(log));
+ /// The device key logs of accounts this device was signed in to before, by account id, as stored
+ /// JSON; empty when there are none or they cannot be read.
+ Future<Map<String, Object?>> deviceLogArchive() async {
+ final raw = await _storage.read(_devLogArchiveKey);
+ if (raw == null) return {};
+ try {
+ final decoded = jsonDecode(raw);
+ return decoded is Map ? decoded.cast<String, Object?>() : {};
+ } on FormatException {
+ return {};
+ }
+ }
+
+ Future<void> writeDeviceLogArchive(Map<String, Object?> archive) =>
+ _storage.write(_devLogArchiveKey, jsonEncode(archive));
+
+ /// Which sign-in by hand this device is under (`device_log_sync.dart` keeps its marks per sign-in);
+ /// null when none was recorded.
+ Future<String?> signInEpoch() => _storage.read(_signInKey);
+
+ Future<void> writeSignInEpoch(String epoch) =>
+ _storage.write(_signInKey, epoch);
+
/// This device was removed from the account's device key log: its identity is spent. The next one
- /// minted is a new device, which every other device announces as one.
+ /// minted is a new device, which every other device announces as one. The log as this device
+ /// verified it stays, with every mark on it: signing in again to the same account goes on from there.
Future<void> forgetIdentity() =>
_storage.synchronized('viewer_identity', () async {
_identity = null;
await _storage.delete(_seedKey);
- await _storage.delete(_devLogKey);
});
Future<void> _write(List<MachinePeer> peers) => _storage.write(
diff --git a/desktop/lib/widgets/new_device_notice.dart b/desktop/lib/widgets/new_device_notice.dart
index 331abdc34..61e2fdd4d 100644
--- a/desktop/lib/widgets/new_device_notice.dart
+++ b/desktop/lib/widgets/new_device_notice.dart
@@ -4,10 +4,13 @@ import 'package:flutter/material.dart';
import 'package:harness/shared/theme/app_icons.dart';
import '../settings/sections/account_device_detail.dart';
+import '../settings/sections/account_device_history.dart';
import '../settings/settings_screen.dart';
import '../settings/settings_section.dart';
import '../shared/theme/app_theme.dart' as grid;
+import '../state/account_devices.dart' show DeviceConflict;
import '../state/app_state.dart';
+import '../viewer/device_log_sync.dart' show DeviceDepartedCopy, DeviceRemovalCopy, DeviceRemovalNotice;
import 'window_chrome.dart';
/// The band across the top of the window when a device this end had never trusted joined the
@@ -52,7 +55,11 @@ class NewDeviceNotice extends StatelessWidget {
const SizedBox(width: 12),
TextButton(
key: const Key('new-device-dismiss'),
- onPressed: () => notifier.dismissNewDevice(notice.pub),
+ // A fork's suspension is not the banner's to lift (it would be back on the next read):
+ // that device's own page shows it, and lifts it there.
+ onPressed: notice.suspended
+ ? () => unawaited(showAccountDeviceDetail(context, notifier, pub: notice.pub, isNew: true))
+ : () => notifier.dismissNewDevice(notice.pub),
child: const Text('It’s mine'),
),
const SizedBox(width: 6),
@@ -79,3 +86,192 @@ class NewDeviceNotice extends StatelessWidget {
);
}
}
+
+/// The same band, for the other things about the account's devices worth a line across the window
+/// (a removal, a departed key, a held computer id): [text], and one or two buttons. [red] is for what looks like someone else acting.
+class _DeviceBand extends StatelessWidget {
+ const _DeviceBand({
+ required this.red,
+ required this.text,
+ required this.textKey,
+ required this.actions,
+ this.maxLines = 2,
+ });
+
+ final bool red;
+ final String text;
+ final Key textKey;
+ final List<Widget> actions;
+
+ /// Lines the text may take before it is cut with an ellipsis; null: as many as it needs.
+ final int? maxLines;
+
+ @override
+ Widget build(BuildContext context) {
+ final accent = red ? grid.AppPalette.dangerFill : grid.AppPalette.warn;
+ final tint = Color.alphaBlend(accent.withValues(alpha: 0.10), grid.AppPalette.windowBg);
+ return WindowDragArea(
+ child: Material(
+ color: Colors.transparent,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: tint,
+ border: Border(bottom: BorderSide(color: accent.withValues(alpha: 0.28))),
+ ),
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(14 + trafficLightClearance, 7, 10, 7),
+ child: Row(
+ children: [
+ Icon(AppIcons.shield, size: 16, color: accent),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ text,
+ key: textKey,
+ maxLines: maxLines,
+ // An ellipsis needs a line cap to mean "wrap, then cut": uncapped text just wraps.
+ overflow: maxLines == null ? TextOverflow.clip : TextOverflow.ellipsis,
+ style: grid.AppType.body(color: grid.AppPalette.textPrimary),
+ ),
+ ),
+ for (final a in actions) ...[const SizedBox(width: 8), a],
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// A device was taken out of the account by another device, or signed itself out. Normal for the
+/// account's owner doing it; red when the one that did it is itself a new device nobody has looked at.
+class DeviceRemovalNoticeBand extends StatelessWidget {
+ const DeviceRemovalNoticeBand({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final all = notifier.visibleDeviceRemovals;
+ if (all.isEmpty) return const SizedBox.shrink();
+ // A red one first: one that looks like someone else acting must not sit behind an older neutral one.
+ final DeviceRemovalNotice notice = all.firstWhere((n) => n.red, orElse: () => all.first);
+ final more = all.length - 1;
+ return _DeviceBand(
+ red: notice.red,
+ textKey: const Key('device-removal-notice'),
+ text: '${notice.title}. ${notice.sentence}${more > 0 ? ' (+$more more)' : ''}',
+ actions: [
+ TextButton(
+ key: const Key('device-removal-dismiss'),
+ onPressed: () => notifier.dismissDeviceRemoval(notice.pub),
+ child: const Text('Got it'),
+ ),
+ if (notice.red)
+ OutlinedButton(
+ key: const Key('device-removal-review'),
+ onPressed: () => unawaited(
+ showAccountDeviceDetail(context, notifier, pub: notice.signer, isNew: true),
+ ),
+ child: const Text('Review'),
+ ),
+ ],
+ );
+ }
+}
+
+/// A device joined the account and was taken out again before anyone looked at it. The log keeps the
+/// flag until "Got it": the new-device banner it would have had is gone with the key, and this is what
+/// says so. Red when the key that took it out is itself a new device nobody has looked at. With
+/// several, a red one is the one shown, "(+N more)" counts the rest, and "Got it" clears them all.
+class DeviceDepartedNoticeBand extends StatelessWidget {
+ const DeviceDepartedNoticeBand({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final all = notifier.departedDevices;
+ if (all.isEmpty) return const SizedBox.shrink();
+ // "Got it" clears every one, so the one read is the one that matters most.
+ final notice = all.firstWhere(notifier.departedIsRed, orElse: () => all.first);
+ final more = all.length - 1;
+ final shown = [for (final d in all) d.pub];
+ final red = notifier.departedIsRed(notice);
+ // A new device that did it is still on the account: its own page is what to look at. Otherwise
+ // the History says who did what and when.
+ final signerStillNew = red && notifier.newDevices.any((d) => d.pub == notice.removedBy);
+ return _DeviceBand(
+ red: red,
+ textKey: const Key('device-departed-notice'),
+ text: '${notice.sentence(red: red)}${more > 0 ? ' (+$more more)' : ''}',
+ actions: [
+ TextButton(
+ key: const Key('device-departed-dismiss'),
+ onPressed: () => notifier.dismissDepartedAll(shown),
+ child: const Text('Got it'),
+ ),
+ OutlinedButton(
+ key: const Key('device-departed-review'),
+ onPressed: () => unawaited(
+ signerStillNew
+ ? showAccountDeviceDetail(context, notifier, pub: notice.removedBy, isNew: true)
+ : showAccountDeviceHistory(context, notifier),
+ ),
+ child: Text(signerStillNew ? 'Review' : 'History'),
+ ),
+ ],
+ );
+ }
+}
+
+/// Another key holds this computer's id on the account, so this computer is not registered under its
+/// own key. Red when that key was added after this computer joined.
+class DeviceConflictNoticeBand extends StatelessWidget {
+ const DeviceConflictNoticeBand({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final DeviceConflict? conflict = notifier.deviceConflict;
+ if (conflict == null) return const SizedBox.shrink();
+ final holder =
+ '${conflict.label.trim().isEmpty ? 'A device' : conflict.label.trim()} · ${conflict.fingerprint}';
+ return _DeviceBand(
+ red: conflict.afterJoin,
+ textKey: const Key('device-conflict-notice'),
+ // The longest copy of the bands: it wraps rather than being cut, since its second sentence is the advice.
+ maxLines: null,
+ text: conflict.afterJoin
+ ? 'Another key took this computer’s place on your account after it joined: $holder. '
+ 'If you did not set up Harness here again, remove that key from another device now (Your devices).'
+ : 'This computer is held by another key on your account: $holder. If that was an earlier '
+ 'install of this computer, remove it from another device (Your devices) — this computer '
+ 'joins on its own once it is gone.',
+ actions: [
+ TextButton(
+ key: const Key('device-conflict-dismiss'),
+ onPressed: notifier.dismissDeviceConflict,
+ child: const Text('Got it'),
+ ),
+ OutlinedButton(
+ key: const Key('device-conflict-review'),
+ onPressed: () => unawaited(
+ showSettingsScreen(
+ context,
+ notifier,
+ initialSection: SettingsSection.accountDevices,
+ source: 'device-conflict-notice',
+ ),
+ ),
+ child: const Text('Your devices'),
+ ),
+ ],
+ );
+ }
+}
diff --git a/desktop/test/account_device_detail_test.dart b/desktop/test/account_device_detail_test.dart
index f6e3235ea..9d5b88b53 100644
--- a/desktop/test/account_device_detail_test.dart
+++ b/desktop/test/account_device_detail_test.dart
@@ -7,6 +7,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/settings/sections/account_device_detail.dart';
import 'package:harness/shared/widgets/fingerprint_text.dart';
import 'package:harness/state/account_devices.dart';
+import 'package:harness/theme/app_theme.dart' show AppColors;
import 'support/devices_app.dart';
@@ -53,6 +54,27 @@ void main() {
return mine;
}
+ testWidgets(
+ 'a device the log still has as new offers It’s mine even when the caller did not say so',
+ (tester) async {
+ // A notification's click lands before the banner has been rebuilt from the log.
+ final mine = await open(
+ tester,
+ pub: 'p1',
+ device: fakeDevice('p1', pending: true),
+ );
+ await tester.tap(find.byKey(const Key('device-detail-mine')));
+ await tester.pump();
+ expect(app.dismissCalls, [('p1', false)]);
+ expect(mine, ['p1']);
+ },
+ );
+
+ testWidgets('a device that is not new offers no It’s mine', (tester) async {
+ await open(tester, pub: 'p1', device: fakeDevice('p1'));
+ expect(find.byKey(const Key('device-detail-mine')), findsNothing);
+ });
+
testWidgets(
'an app: kind, added, last active, the code and how to check it on the app',
(tester) async {
@@ -126,9 +148,62 @@ void main() {
await tester.pump();
expect(app.newDevices, isEmpty);
expect(mine, ['p1']);
+ // Nothing here said the key is suspended, so "mine" lifts nothing.
+ expect(app.dismissCalls, [('p1', false)]);
expect(find.text(fp), findsNothing);
});
+ testWidgets(
+ 'It’s mine on a suspended device, whose Suspended text is shown, lifts the suspension',
+ (tester) async {
+ app.newDevices.add(
+ const NewDeviceNotice(
+ pub: 'sus',
+ label: 'Odd Mac',
+ kind: 'viewer',
+ suspended: true,
+ ),
+ );
+ await open(
+ tester,
+ pub: 'sus',
+ device: fakeDevice('sus', suspended: true),
+ isNew: true,
+ );
+ expect(find.byKey(const Key('device-detail-suspended')), findsOneWidget);
+ await tester.tap(find.byKey(const Key('device-detail-mine')));
+ await tester.pump();
+ expect(app.dismissCalls, [('sus', true)]);
+ },
+ );
+
+ testWidgets(
+ 'It’s mine before the device has loaded (so no Suspended text) keeps the suspension',
+ (tester) async {
+ // Opened from the banner's Review: the list that says the key is suspended has not answered, and
+ // whoever delays it must not get the suspension lifted for a page that never showed it.
+ app.loadGate = Completer<void>();
+ app.newDevices.add(
+ const NewDeviceNotice(
+ pub: 'sus',
+ label: 'Odd Mac',
+ kind: 'viewer',
+ suspended: true,
+ ),
+ );
+ app.devices = AccountDevices(
+ devices: [fakeDevice('sus', suspended: true)],
+ );
+ await open(tester, pub: 'sus', isNew: true);
+ expect(find.byKey(const Key('device-detail-suspended')), findsNothing);
+ await tester.tap(find.byKey(const Key('device-detail-mine')));
+ await tester.pump();
+ expect(app.dismissCalls, [('sus', false)]);
+ app.loadGate!.complete();
+ await tester.pump();
+ },
+ );
+
testWidgets('Remove asks first; a no leaves the device alone', (
tester,
) async {
@@ -169,11 +244,19 @@ void main() {
await tester.pump();
expect(app.removed, ['p1']);
expect(
- find.text("Couldn't remove iPad (UNAVAILABLE). Try again."),
+ find.text('Couldn’t remove iPad (UNAVAILABLE). Try again.'),
findsOneWidget,
);
expect(find.text(fp), findsOneWidget);
expect(find.text('Remove'), findsOneWidget);
+ // A failure, not a state to review again: red.
+ expect(
+ tester
+ .widget<Text>(find.byKey(const Key('device-detail-error')))
+ .style
+ ?.color,
+ AppColors.danger,
+ );
});
testWidgets(
diff --git a/desktop/test/account_device_history_test.dart b/desktop/test/account_device_history_test.dart
new file mode 100644
index 000000000..48e6174d8
--- /dev/null
+++ b/desktop/test/account_device_history_test.dart
@@ -0,0 +1,199 @@
+// Settings ▸ Your devices ▸ History…: the log's adds and removes, newest first.
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/settings/sections/account_device_history.dart';
+import 'package:harness/state/account_devices.dart';
+import 'package:harness/theme/app_theme.dart' show AppColors;
+import 'package:harness/viewer/device_history.dart';
+
+import 'support/devices_app.dart';
+
+DevLogHistoryRow _row(
+ int seq,
+ String op,
+ String label, {
+ String pub = 'p',
+ String kind = 'viewer',
+ String? previous,
+ DevLogHistoryBy? by,
+ bool thisDevice = false,
+ bool pending = false,
+ bool active = false,
+ bool whileFrozen = false,
+}) => DevLogHistoryRow(
+ seq: seq,
+ op: op,
+ pub: pub,
+ kind: kind,
+ machineId: '',
+ label: label,
+ previousLabel: previous,
+ fingerprint: 'AAAA·BBBB',
+ by: by,
+ at: DateTime(2026, 10, 1, 14, 5).millisecondsSinceEpoch,
+ thisDevice: thisDevice,
+ afterJoin: false,
+ pending: pending,
+ active: active,
+ whileFrozen: whileFrozen,
+);
+
+void main() {
+ late FakeDevicesApp app;
+
+ setUp(() => app = FakeDevicesApp());
+ tearDown(() => app.dispose());
+
+ Future<void> open(WidgetTester tester) async {
+ tester.view.physicalSize = const Size(1200, 1600);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showAccountDeviceHistory(context, app),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pump();
+ await tester.pump();
+ }
+
+ testWidgets(
+ 'each row says what happened, in order, with the date and the key code',
+ (tester) async {
+ app.history = DeviceLogHistory(
+ complete: true,
+ rows: [
+ _row(
+ 5,
+ 'removed',
+ 'Old iPad',
+ by: const DevLogHistoryBy(
+ pub: 'm',
+ label: 'MacBook',
+ fingerprint: 'X',
+ ),
+ whileFrozen: true,
+ ),
+ _row(4, 'signedOut', 'Phone'),
+ _row(3, 'renamed', 'Mac', previous: 'Old Mac', kind: 'machine'),
+ _row(
+ 2,
+ 'added',
+ 'Test iPad',
+ pub: 'new',
+ pending: true,
+ active: true,
+ ),
+ _row(1, 'added', 'MacBook', thisDevice: true),
+ ],
+ );
+ await open(tester);
+ expect(find.text('Device history'), findsOneWidget);
+ expect(
+ find.text(
+ 'Every device added to or removed from your account, newest first, as this device verified it.',
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.text(
+ 'Old iPad removed by MacBook · applied while the list was frozen',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Phone signed out'), findsOneWidget);
+ expect(find.text('Old Mac renamed to Mac'), findsOneWidget);
+ expect(find.text('Test iPad added'), findsOneWidget);
+ expect(find.text('MacBook added'), findsOneWidget);
+ expect(find.text('(this device)'), findsOneWidget);
+ expect(find.text('New'), findsOneWidget);
+ expect(
+ find.text('1 Oct 2026, 14:05 · App · AAAA·BBBB'),
+ findsNWidgets(4),
+ );
+ double top(int seq) =>
+ tester.getTopLeft(find.byKey(ValueKey('device-history-$seq'))).dy;
+ expect(top(5), lessThan(top(4)));
+ expect(top(2), lessThan(top(1)));
+ expect(find.byKey(const Key('device-history-incomplete')), findsNothing);
+ },
+ );
+
+ testWidgets(
+ 'an active row opens that device, offering It’s mine when it is still new',
+ (tester) async {
+ app.history = DeviceLogHistory(
+ complete: true,
+ rows: [
+ _row(
+ 2,
+ 'added',
+ 'Test iPad',
+ pub: 'new',
+ pending: true,
+ active: true,
+ ),
+ ],
+ );
+ app.devices = AccountDevices(
+ devices: [fakeDevice('new', label: 'Test iPad')],
+ );
+ await open(tester);
+ await tester.tap(find.text('Test iPad added'));
+ await tester.pump();
+ await tester.pump();
+ await tester.pump();
+ expect(find.byKey(const Key('device-detail-mine')), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'offline: what is kept, and the line that says it is not all of it',
+ (tester) async {
+ app.history = DeviceLogHistory(
+ complete: false,
+ rows: [_row(2, 'added', 'Test iPad')],
+ );
+ await open(tester);
+ expect(find.text('Test iPad added'), findsOneWidget);
+ expect(find.text('Older history needs a connection.'), findsOneWidget);
+ },
+ );
+
+ testWidgets('an empty log says so', (tester) async {
+ app.history = const DeviceLogHistory(complete: true, rows: []);
+ await open(tester);
+ expect(find.text('No history yet.'), findsOneWidget);
+ });
+
+ testWidgets('a read that fails says so and can be tried again', (
+ tester,
+ ) async {
+ await open(tester);
+ expect(find.text('Couldn’t load the history. Try again.'), findsOneWidget);
+ expect(
+ tester
+ .widget<Text>(find.byKey(const Key('device-history-error')))
+ .style
+ ?.color,
+ AppColors.danger,
+ );
+ app.history = DeviceLogHistory(
+ complete: true,
+ rows: [_row(1, 'added', 'MacBook')],
+ );
+ await tester.tap(find.byKey(const Key('device-history-retry')));
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('MacBook added'), findsOneWidget);
+ expect(find.byKey(const Key('device-history-error')), findsNothing);
+ });
+}
diff --git a/desktop/test/account_devices_section_test.dart b/desktop/test/account_devices_section_test.dart
index 885e0fe1c..a46f79c95 100644
--- a/desktop/test/account_devices_section_test.dart
+++ b/desktop/test/account_devices_section_test.dart
@@ -1,26 +1,51 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/auth/auth_session.dart';
-import 'package:harness/core/config.dart';
import 'package:harness/settings/sections/account_devices_section.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/account_devices.dart';
+import 'package:harness/theme/app_theme.dart' show AppColors;
import 'package:harness/shared/widgets/fingerprint_text.dart';
-import 'package:harness/state/app_state.dart';
+import 'package:harness/viewer/device_log.dart' show DevLogHead;
+import 'package:harness/viewer/device_log_sync.dart' show DeviceLogRebaseline;
import 'support/devices_app.dart';
/// Settings ▸ Your devices: opening it is reviewing the devices the banner announced.
void main() {
+ test('the daemon\'s OTHER_ACCOUNT answer and the viewer\'s are a refusal of another account\'s list', () {
+ final daemon = DevicesRebaseline.fromDaemon({'error': 'OTHER_ACCOUNT'})!;
+ expect([daemon.otherAccount, daemon.logChanged, daemon.refused], [true, false, true]);
+ expect(DevicesRebaseline.fromDaemon({'error': 'LOG_CHANGED'})!.otherAccount, isFalse);
+ final viewer = DevicesRebaseline.fromViewer(const DeviceLogRebaseline.otherAccount());
+ expect([viewer.otherAccount, viewer.logChanged, viewer.head], [true, false, null]);
+ });
+ test('a listing carries its departed keys, from the daemon and from the viewer alike', () {
+ final fromDaemon = AccountDevices.fromDaemon({
+ 'members': <Object>[],
+ 'pending': <Object>[],
+ 'departed': [
+ {
+ 'pub': 'gone', 'label': 'Phone', 'kind': 'viewer', 'machineId': '', 'fingerprint': 'AAAA',
+ 'addedAt': 1, 'removedAt': 2, 'removedBy': 'gone', 'removedByLabel': 'Phone', 'selfRemoved': true,
+ },
+ ],
+ })!;
+ expect(fromDaemon.departed, ['gone']);
+ expect(AccountDevices.fromDaemon({'members': <Object>[], 'pending': <Object>[]})!.departed, isEmpty);
+ expect(fromDaemon.withLastSeen(const {}).departed, ['gone']);
+ });
testWidgets('opening the devices list takes the new-device banner down', (tester) async {
- final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null);
+ final app = FakeDevicesApp();
addTearDown(app.dispose);
app.newDevices.add(const NewDeviceNotice(pub: 'p1', label: 'Test iPad', kind: 'viewer'));
app.newDevices.add(const NewDeviceNotice(pub: 'p2', label: 'box9', kind: 'machine'));
await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));
await tester.pump();
+ // Marking the devices seen waits for the list's read, so the pending keys it holds are badged first.
+ await tester.pump();
expect(app.newDevices, isEmpty);
- // Let the list's read (no daemon in a test) run out before the tree goes.
- await tester.runAsync(() => Future<void>.delayed(const Duration(milliseconds: 100)));
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
});
@@ -152,4 +177,284 @@ void main() {
expect(find.byKey(const ValueKey('account-device-old')), findsNothing);
});
});
+
+ group('what the log kept', () {
+ late FakeDevicesApp app;
+ tearDown(() => app.dispose());
+
+ Future<void> open(WidgetTester tester, AccountDevices devices) async {
+ app = FakeDevicesApp()..devices = devices;
+ tester.view.physicalSize = const Size(1200, 1600);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));
+ await tester.pump();
+ await tester.pump();
+ }
+
+ testWidgets('a device the daemon kept as pending is badged New though no banner is up', (tester) async {
+ await open(tester, AccountDevices(
+ devices: [fakeDevice('me', self: true), fakeDevice('old'), fakeDevice('late', label: 'Late iPad')],
+ pending: const ['late'],
+ ));
+ expect(find.descendant(of: find.byKey(const ValueKey('account-device-late')), matching: find.text('New')), findsOneWidget);
+ expect(find.descendant(of: find.byKey(const ValueKey('account-device-old')), matching: find.text('New')), findsNothing);
+ // Looking at the list is seeing them: what it read as pending is written back, once.
+ expect(app.seenPending, [['late']]);
+ });
+
+ testWidgets('a device that turns up while the list is open is badged New too (it is pending)', (tester) async {
+ // E2E 2026-10-01: a forged key added while Your devices was open stayed pending (the banner came
+ // back on leaving) but its row had no badge — `New` must follow `pending`, as on the phone.
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true), fakeDevice('old')], pending: const []));
+ app.devices = AccountDevices(
+ devices: [fakeDevice('me', self: true), fakeDevice('old'), fakeDevice('evil', label: 'Evil Chrome')],
+ pending: const ['evil'],
+ );
+ app.devicesRevision++;
+ app.notifyListeners();
+ await tester.pump();
+ await tester.pump();
+ expect(find.descendant(of: find.byKey(const ValueKey('account-device-evil')), matching: find.text('New')), findsOneWidget);
+ expect(find.descendant(of: find.byKey(const ValueKey('account-device-old')), matching: find.text('New')), findsNothing);
+ // Only the first read of the visit is written back as seen.
+ expect(app.seenPending, [<String>[]]);
+ });
+
+ testWidgets('the baseline panel names what was there before this device joined; Got it persists and hides it', (tester) async {
+ await open(tester, AccountDevices(
+ devices: [
+ AccountDevice(pub: 'me', label: 'MacBook', kind: 'machine', machineId: 'm', addedAt: DateTime(2026, 9, 1), fingerprint: 'AAAA·1', self: true, seq: 1),
+ AccountDevice(pub: 'old', label: 'Old iPad', kind: 'viewer', machineId: '', addedAt: DateTime(2026, 9, 1), fingerprint: 'BBBB·2', self: false, seq: 2),
+ AccountDevice(pub: 'later', label: 'Later', kind: 'viewer', machineId: '', addedAt: DateTime(2026, 9, 2), fingerprint: 'CCCC·3', self: false, seq: 5),
+ ],
+ joinedSeq: 3,
+ baselineSeen: false,
+ ));
+ final panel = find.byKey(const Key('account-devices-baseline'));
+ expect(find.descendant(of: panel, matching: find.text('Already on your account')), findsOneWidget);
+ expect(find.descendant(of: panel, matching: find.text('These were on your account before this device joined. If one isn’t yours, remove it.')), findsOneWidget);
+ expect(find.descendant(of: panel, matching: find.text('Old iPad · App · BBBB·2')), findsOneWidget);
+ expect(find.descendant(of: panel, matching: find.textContaining('Later')), findsNothing);
+ await tester.tap(find.byKey(const Key('account-devices-baseline-gotit')));
+ await tester.pump();
+ expect(app.baselineSeenCalls, 1);
+ expect(panel, findsNothing);
+ });
+
+ testWidgets('no panel once the baseline was seen, or when the daemon sends no joined point', (tester) async {
+ await open(tester, AccountDevices(
+ devices: [fakeDevice('me', self: true), fakeDevice('old')],
+ joinedSeq: 3,
+ ));
+ expect(find.byKey(const Key('account-devices-baseline')), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true), fakeDevice('old')], baselineSeen: false));
+ expect(find.byKey(const Key('account-devices-baseline')), findsNothing);
+ });
+
+ testWidgets('a suspended device wears Suspended instead of New, and its detail says why', (tester) async {
+ await open(tester, AccountDevices(
+ devices: [
+ fakeDevice('me', self: true),
+ AccountDevice(pub: 'sus', label: 'Odd Mac', kind: 'machine', machineId: 'abcdef0123456789', addedAt: DateTime(2026, 9, 1), fingerprint: 'DDDD·4', self: false, suspended: true, pending: true),
+ ],
+ pending: const ['sus'],
+ ));
+ final row = find.byKey(const ValueKey('account-device-sus'));
+ expect(find.descendant(of: row, matching: find.text('Suspended')), findsOneWidget);
+ expect(find.descendant(of: row, matching: find.text('New')), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('account-device-details-sus')));
+ await tester.pump();
+ await tester.pump();
+ expect(
+ find.text('Not trusted here: added after this device’s list and another’s split. Review the list to trust it again.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('Trust again confirms the previewed head; a list that changed meanwhile says so and is previewed again', (tester) async {
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'fork'));
+ app.previews
+ ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')))
+ ..add(const DevicesRebaseline(added: ['iPad', 'Mac'], removed: [], head: DevLogHead(8, 'h8')));
+ app.confirmAnswer = const DevicesRebaseline.changed();
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pump();
+ await tester.pump();
+ expect(app.confirmedHeads.single?.seq, 7);
+ expect(find.text('The device list changed while you were reviewing it. Review it again.'), findsOneWidget);
+ // The new preview is up, with the extra device.
+ expect(find.textContaining('+ Mac'), findsOneWidget);
+ });
+
+ group('Trust again on another account\'s list says to sign in again', () {
+ const message =
+ 'The device list now belongs to a different account than the one you signed in with. Sign in again to switch accounts.';
+
+ testWidgets('at the preview: nothing to confirm', (tester) async {
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'invalid'));
+ app.previews.add(const DevicesRebaseline.otherAccount());
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ expect(find.text(message), findsOneWidget);
+ expect(find.byKey(const Key('account-device-confirm')), findsNothing);
+ expect(app.confirmedHeads, isEmpty);
+ });
+
+ testWidgets('at the confirm: said once, not previewed again', (tester) async {
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'invalid'));
+ app.previews.add(const DevicesRebaseline(added: [], removed: [], head: DevLogHead(7, 'h7')));
+ app.confirmAnswer = const DevicesRebaseline.otherAccount();
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pump();
+ await tester.pump();
+ expect(find.text(message), findsOneWidget);
+ expect(find.text('The device list changed while you were reviewing it. Review it again.'), findsNothing);
+ expect(find.byKey(const Key('account-device-confirm')), findsNothing);
+ expect(app.confirmedHeads, hasLength(1));
+ });
+ });
+
+ // One convention: what is only a state to review again (another account's list, a list that changed
+ // while it was reviewed) is the warning amber; every other failure is red.
+ testWidgets('error colours: unreadable list, a failed trust and a failed remove are red; a list that changed is amber', (tester) async {
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true), fakeDevice('b')], frozenReason: 'fork'));
+ Color? colourOf(String text) => tester.widget<Text>(find.text(text)).style?.color;
+ // The preview cannot be read.
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ expect(colourOf('Couldn’t read a valid device list. Try again later.'), AppColors.danger);
+ // The trust is refused for another reason than the list changing.
+ app.previews.add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')));
+ app.confirmAnswer = null;
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pump();
+ await tester.pump();
+ expect(colourOf('Couldn’t trust the device list again. Try again later.'), AppColors.danger);
+ // A removal that fails.
+ app.removeError = 'UNAVAILABLE';
+ await tester.tap(find.descendant(of: find.byKey(const ValueKey('account-device-b')), matching: find.text('Remove')));
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pump();
+ await tester.pump();
+ expect(colourOf('Couldn’t remove iPad (UNAVAILABLE). Try again.'), AppColors.danger);
+ // LOG_CHANGED: amber, and the colour does not stick to the next error.
+ app.previews
+ ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')))
+ ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(8, 'h8')));
+ app.confirmAnswer = const DevicesRebaseline.changed();
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pump();
+ await tester.pump();
+ expect(colourOf('The device list changed while you were reviewing it. Review it again.'), AppColors.warning);
+ });
+
+ testWidgets('Trust again: an unreadable list says so; a later success clears the message', (tester) async {
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'fork'));
+ app.previews
+ ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')))
+ ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')));
+ app.confirmAnswer = null;
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('Couldn’t trust the device list again. Try again later.'), findsOneWidget);
+ expect(find.text('The device list changed while you were reviewing it. Review it again.'), findsNothing);
+
+ app.confirmAnswer = const DevicesRebaseline(added: [], removed: [], head: DevLogHead(7, 'h7'));
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('Couldn’t trust the device list again. Try again later.'), findsNothing);
+ });
+
+ testWidgets('opening the list marks seen only the banner as it was when the list was read', (tester) async {
+ final gate = Completer<void>();
+ app = FakeDevicesApp()
+ ..devices = AccountDevices(devices: [fakeDevice('me', self: true)])
+ ..newDevices.add(const NewDeviceNotice(pub: 'new', label: 'N', kind: 'viewer'));
+ app.loadGate = gate;
+ // The banner holds `new` when the listing is read.
+ app.bannerAtRead = () => ['new'];
+ tester.view.physicalSize = const Size(1200, 1600);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));
+ await tester.pump();
+ // A device announced while the read waits.
+ app.newDevices.add(const NewDeviceNotice(pub: 'late', label: 'L', kind: 'viewer'));
+ gate.complete();
+ await tester.pump();
+ await tester.pump();
+ expect(app.seenShown.single, ['new']);
+ expect(app.newDevices.map((d) => d.pub), ['late']);
+ });
+
+ testWidgets('the departed keys the listing read are handed over, so a banner that still names one does not mark it seen', (tester) async {
+ app = FakeDevicesApp()
+ ..devices = AccountDevices(devices: [fakeDevice('me', self: true)], departed: ['gone'])
+ ..newDevices.add(const NewDeviceNotice(pub: 'gone', label: 'G', kind: 'viewer'));
+ tester.view.physicalSize = const Size(1200, 1600);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));
+ await tester.pump();
+ await tester.pump();
+ expect(app.seenDeparted.single, ['gone']);
+ });
+
+ testWidgets('Trust again is confirmed with the destructive (red) button, like Remove', (tester) async {
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'fork'));
+ app.previews.add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')));
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ final confirm = tester.widget<FilledButton>(find.byKey(const Key('account-device-confirm')));
+ expect(confirm.style?.backgroundColor?.resolve(const {}), grid.AppPalette.dangerFill);
+ });
+
+ testWidgets('the OTHER_ACCOUNT message is the warning amber', (tester) async {
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'invalid'));
+ app.previews.add(const DevicesRebaseline.otherAccount());
+ await tester.tap(find.text('Review…'));
+ await tester.pump();
+ await tester.pump();
+ final text = tester.widget<Text>(find.text(otherAccountMessage));
+ expect(text.style?.color, grid.AppPalette.warn);
+ });
+
+ testWidgets('History… opens the history; a daemon that predates it gets the update hint instead', (tester) async {
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)]));
+ expect(find.byKey(const Key('account-devices-history-hint')), findsNothing);
+ expect(find.text('History…'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], historyAvailable: false));
+ expect(find.text('History…'), findsNothing);
+ expect(find.text('Update Harness on this computer to see history.'), findsOneWidget);
+ });
+ });
}
diff --git a/desktop/test/account_devices_test.dart b/desktop/test/account_devices_test.dart
index 0f2290002..45aa4b884 100644
--- a/desktop/test/account_devices_test.dart
+++ b/desktop/test/account_devices_test.dart
@@ -109,4 +109,44 @@ void main() {
expect(NewDeviceNotice(pub: pub, label: 'iPad', kind: 'viewer', frameFingerprint: '').fingerprint, computed);
expect(const NewDeviceNotice(pub: '%%not base64%%', label: '', kind: 'viewer').fingerprint, '');
});
+
+ test('a daemon listing with pending reads the joined point, baseline, conflict and per-device flags', () {
+ final devices = AccountDevices.fromDaemon({
+ 'members': [
+ {...row('old'), 'seq': 2},
+ {...row('me', self: true), 'seq': 3},
+ {...row('late'), 'seq': 7, 'pending': true},
+ {...row('sus'), 'seq': 8, 'suspended': true},
+ ],
+ 'pending': ['late', 5],
+ 'joinedSeq': 3,
+ 'baselineSeen': false,
+ 'conflict': {
+ 'pub': 'holder', 'label': 'Old install', 'fingerprint': 'AAAA·BBBB', 'addedAt': 1000, 'afterJoin': true,
+ },
+ })!;
+ expect(devices.pending, ['late']);
+ expect(devices.joinedSeq, 3);
+ expect(devices.baselineSeen, isFalse);
+ expect(devices.historyAvailable, isTrue);
+ expect(devices.baseline.map((d) => d.pub), ['old'], reason: 'not this device, not one added after it joined');
+ expect(devices.devices[2].pending, isTrue);
+ expect(devices.devices[3].suspended, isTrue);
+ expect(devices.conflict?.pub, 'holder');
+ expect(devices.conflict?.afterJoin, isTrue);
+ expect(devices.conflict?.addedAt, DateTime.fromMillisecondsSinceEpoch(1000));
+ // The flags survive a last-seen pass.
+ expect(devices.withLastSeen({}).devices[2].pending, isTrue);
+ expect(devices.withLastSeen({}).conflict, isNotNull);
+ });
+
+ test('a listing from an older daemon has no pending array: no history, nothing pending, baseline already seen', () {
+ final devices = AccountDevices.fromDaemon({'members': [row('old'), row('me', self: true)]})!;
+ expect(devices.historyAvailable, isFalse);
+ expect(devices.pending, isEmpty);
+ expect(devices.joinedSeq, isNull);
+ expect(devices.baselineSeen, isTrue);
+ expect(devices.baseline, isEmpty);
+ expect(devices.conflict, isNull);
+ });
}
diff --git a/desktop/test/daemon_readiness_test.dart b/desktop/test/daemon_readiness_test.dart
index a997dd7aa..b1ab2af3f 100644
--- a/desktop/test/daemon_readiness_test.dart
+++ b/desktop/test/daemon_readiness_test.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/auth/cli_login.dart';
import 'package:harness/core/config.dart';
@@ -110,6 +111,41 @@ class _Notifier extends AppNotifier {
}
}
+/// A daemon whose copy of the device log still has one device nobody looked at.
+class _PendingDevicesApi extends ApiClient {
+ _PendingDevicesApi() : super(config: AppConfig.dev, session: AuthSession());
+
+ int reads = 0;
+
+ /// Whether the daemon has its listing ready (null otherwise: still connecting).
+ bool ready = true;
+
+ /// A daemon that predates the persisted marks: it answers, with no `pending`.
+ bool legacy = false;
+
+ @override
+ Future<Map<String, dynamic>?> daemonDevices() async {
+ reads++;
+ if (!ready) return null;
+ if (legacy) return {'members': <Object?>[]};
+ return {
+ 'members': [
+ {
+ 'pub': 'a',
+ 'label': 'Phone',
+ 'kind': 'viewer',
+ 'machineId': '',
+ 'addedAt': 1000,
+ 'fingerprint': 'FPA',
+ 'self': false,
+ 'seq': 2,
+ },
+ ],
+ 'pending': ['a'],
+ };
+ }
+}
+
final _endpoint = LocalCliEndpoint(
computerId: '0123456789abcdef0123456789abcdef',
wsUri: Uri.parse('ws://127.0.0.1:18473/api/local-ws'),
@@ -345,4 +381,79 @@ void main() {
reason: 'one supervisor for the app, not one per attempt',
);
});
+
+ test('a retry that gets through reads again which devices are still waiting to be seen', () async {
+ // The boot found the daemon still connecting, so its own read of the pending devices never ran
+ // (or found nothing yet): the retry that finishes the boot reads them.
+ final notifier = _Notifier(
+ _ScriptedDiscovery([LocalCliProbe.ready(_endpoint)]),
+ )..status = AppStatus.authenticated;
+ addTearDown(notifier.dispose);
+ final api = _PendingDevicesApi();
+ notifier.api = api;
+
+ await notifier.retryMachines();
+ for (var i = 0; i < 5; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+
+ expect(api.reads, greaterThanOrEqualTo(1));
+ expect(notifier.newDevices.map((d) => d.pub), ['a']);
+ });
+
+ test(
+ 'recovery ticks read the pending devices only until one read has succeeded',
+ () async {
+ final notifier = _Notifier(
+ _ScriptedDiscovery([LocalCliProbe.ready(_endpoint)]),
+ )..status = AppStatus.authenticated;
+ addTearDown(notifier.dispose);
+ final api = _PendingDevicesApi()..ready = false;
+ notifier.api = api;
+ Future<void> tick() async {
+ await notifier.retryMachines();
+ for (var i = 0; i < 5; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+ }
+
+ // The daemon has nothing to say yet: the next tick asks again.
+ await tick();
+ expect(api.reads, 1);
+ await tick();
+ expect(api.reads, 2);
+
+ api.ready = true;
+ await tick();
+ expect(api.reads, 3);
+ expect(notifier.newDevices.map((d) => d.pub), ['a']);
+
+ // It has been read: the log's own changes and the daemon's frames say when to read again.
+ await tick();
+ await tick();
+ expect(api.reads, 3);
+ },
+ );
+
+ test('a daemon that predates the pending list is asked once, not on every recovery tick', () async {
+ final notifier = _Notifier(
+ _ScriptedDiscovery([LocalCliProbe.ready(_endpoint)]),
+ )..status = AppStatus.authenticated;
+ addTearDown(notifier.dispose);
+ final api = _PendingDevicesApi()..legacy = true;
+ notifier.api = api;
+ Future<void> tick() async {
+ await notifier.retryMachines();
+ for (var i = 0; i < 5; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+ }
+
+ await tick();
+ expect(api.reads, 1);
+ await tick();
+ await tick();
+ expect(api.reads, 1, reason: 'it answered; it has nothing more to say');
+ expect(notifier.newDevices, isEmpty);
+ });
}
diff --git a/desktop/test/desktop_account_transition_test.dart b/desktop/test/desktop_account_transition_test.dart
index d121b6a00..a48b1ed9f 100644
--- a/desktop/test/desktop_account_transition_test.dart
+++ b/desktop/test/desktop_account_transition_test.dart
@@ -8,9 +8,11 @@ import 'package:harness/auth/cli_login.dart';
import 'package:harness/auth/sign_in_provider.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
+import 'package:harness/state/account_devices.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/pane_layout_store.dart';
import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/viewer/device_log_sync.dart' show DeviceLogDeparted;
import 'swarm_state_test.dart' show MemoryStore;
@@ -198,6 +200,45 @@ void main() {
);
}
+ test(
+ 'a runtime sign-out forgets what was said about the old account’s devices',
+ () async {
+ final app = _Desktop(MemoryStore(), _Login());
+ addTearDown(app.dispose);
+ await app.arrange();
+ app.newDevices.add(
+ const NewDeviceNotice(pub: 'p', label: 'iPad', kind: 'viewer'),
+ );
+ app.departedDevices.add(
+ const DeviceLogDeparted(
+ pub: 'g',
+ label: 'Phone',
+ kind: 'viewer',
+ machineId: '',
+ fingerprint: 'AAAA',
+ addedAt: 1,
+ removedAt: 2,
+ removedBy: 'x',
+ removedByLabel: 'Mac',
+ selfRemoved: false,
+ ),
+ );
+ app.deviceConflict = DeviceConflict(
+ pub: 'h',
+ label: 'H',
+ fingerprint: 'AAAA',
+ addedAt: DateTime.fromMillisecondsSinceEpoch(1),
+ afterJoin: true,
+ );
+ app.expireSessionForTest('Session expired.');
+ await _settle();
+ expect(app.newDevices, isEmpty);
+ expect(app.departedDevices, isEmpty);
+ expect(app.deviceConflict, isNull);
+ expect(app.deviceRemovals, isEmpty);
+ },
+ );
+
test(
'expiry hides remote panes even when the guest daemon is unavailable',
() async {
diff --git a/desktop/test/device_daemon_wire_test.dart b/desktop/test/device_daemon_wire_test.dart
new file mode 100644
index 000000000..3ed3161d8
--- /dev/null
+++ b/desktop/test/device_daemon_wire_test.dart
@@ -0,0 +1,377 @@
+// The daemon's device payloads, exactly as the CLI writes them (cli/src/lib/e2ee/deviceLogSyncer.ts
+// `list()` / `history()` / the `removed` and `conflict` hooks, cli/src/cli.ts `onDevicesList` /
+// `onDevicesHistory` and the `device_key_removed` / `device_conflict` frames), read by this app's
+// parsers. Each JSON below was dumped from the real CLI code — a listing with a new device and a
+// removal it signed, a history, a conflict — so a field renamed on one side fails here. Regenerate
+// from the CLI when its wire format changes on purpose.
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/account_devices.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/viewer/device_history.dart';
+
+/// `GET /api/devices` (`{...list(), lastSeen}`): this computer, plus a phone added after it joined
+/// that is still new; box2 (on the account before) was removed by that phone.
+const _listing = r'''
+{
+ "head": {
+ "seq": 4,
+ "hash": "KGA6L7o4dLJXflHfMrNvQApIFzGCiv9+vBD/YpG2Ezg="
+ },
+ "frozen": null,
+ "self": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "members": [
+ {
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "my-mac",
+ "addedAt": 5000,
+ "seq": 2,
+ "fingerprint": "3475·0F98·BD59·FCFC",
+ "self": true,
+ "pending": false,
+ "suspended": false,
+ "firstSeen": 5000
+ },
+ {
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "Phone",
+ "addedAt": 1000,
+ "seq": 3,
+ "fingerprint": "B62E·867F·A2F3·3AFE",
+ "self": false,
+ "pending": true,
+ "suspended": false,
+ "firstSeen": 5000
+ }
+ ],
+ "frozenPeers": [],
+ "pending": [
+ "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E="
+ ],
+ "suspended": [],
+ "joinedSeq": 1,
+ "baselineSeen": false,
+ "conflict": null,
+ "lastSeen": {
+ "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=": 4000
+ }
+}
+''';
+
+/// `GET /api/devices` on a computer whose id another key holds.
+const _conflictListing = r'''
+{
+ "head": {
+ "seq": 2,
+ "hash": "eCj7fh11xqlaccjtoufCZTZjmCxcY6uv61jBNLJ687U="
+ },
+ "frozen": null,
+ "self": "iodf/x6zhFFXes1a/uQFRWVo3XyJ4JCGOgVXvHr0nxc=",
+ "members": [
+ {
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "addedAt": 1000,
+ "seq": 1,
+ "fingerprint": "6A38·03D5·F059·902A",
+ "self": false,
+ "pending": false,
+ "suspended": false
+ },
+ {
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "machine",
+ "machineId": "cccccccccccccccccccccccccccccccc",
+ "label": "old-install",
+ "addedAt": 1000,
+ "seq": 2,
+ "fingerprint": "C5B9·40ED·3F65·C391",
+ "self": false,
+ "pending": true,
+ "suspended": false,
+ "firstSeen": 5000
+ }
+ ],
+ "frozenPeers": [],
+ "pending": [
+ "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw="
+ ],
+ "suspended": [],
+ "joinedSeq": 1,
+ "baselineSeen": false,
+ "conflict": {
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "label": "old-install",
+ "machineId": "cccccccccccccccccccccccccccccccc",
+ "addedAt": 1000,
+ "seq": 2,
+ "fingerprint": "C5B9·40ED·3F65·C391",
+ "afterJoin": true
+ }
+}
+''';
+
+/// `GET /api/devices/history` for the first listing.
+const _history = r'''
+{
+ "rows": [
+ {
+ "seq": 4,
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "fingerprint": "6A38·03D5·F059·902A",
+ "at": 2000,
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false,
+ "op": "removed",
+ "by": {
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "label": "Phone",
+ "fingerprint": "B62E·867F·A2F3·3AFE"
+ }
+ },
+ {
+ "seq": 3,
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "Phone",
+ "fingerprint": "B62E·867F·A2F3·3AFE",
+ "at": 1000,
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": true,
+ "whileFrozen": false,
+ "op": "added"
+ },
+ {
+ "seq": 2,
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "my-mac",
+ "fingerprint": "3475·0F98·BD59·FCFC",
+ "at": 5000,
+ "thisDevice": true,
+ "afterJoin": true,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false,
+ "op": "added"
+ },
+ {
+ "seq": 1,
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "fingerprint": "6A38·03D5·F059·902A",
+ "at": 1000,
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false,
+ "op": "added"
+ }
+ ],
+ "complete": true,
+ "frozen": null
+}
+''';
+
+/// The frames the daemon sent the app (`backend.sendLocal`).
+const _removedFrame = r'''
+{
+ "type": "device_key_removed",
+ "payload": {
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "label": "box2",
+ "kind": "machine",
+ "fingerprint": "6A38·03D5·F059·902A",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "signerLabel": "Phone",
+ "signerFingerprint": "B62E·867F·A2F3·3AFE",
+ "signerPending": true,
+ "selfRemoved": false,
+ "at": 5000
+ }
+}
+''';
+const _conflictFrame = r'''
+{
+ "type": "device_conflict",
+ "payload": {
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "label": "old-install",
+ "fingerprint": "C5B9·40ED·3F65·C391",
+ "addedAt": 1000,
+ "afterJoin": true
+ }
+}
+''';
+
+Map<String, dynamic> _json(String s) => jsonDecode(s) as Map<String, dynamic>;
+
+const _phone = '7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=';
+const _box2 = 'gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=';
+const _holder = 'ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=';
+
+class _DaemonApi extends ApiClient {
+ _DaemonApi() : super(config: AppConfig.dev, session: AuthSession());
+
+ bool conflicted = false;
+
+ @override
+ Future<Map<String, dynamic>?> daemonDevices() async =>
+ _json(conflicted ? _conflictListing : _listing);
+
+ @override
+ Future<Map<String, dynamic>?> daemonDeviceHistory() async => _json(_history);
+}
+
+const _machine = Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'Mac',
+);
+
+void main() {
+ test('the listing reads every field the daemon sends', () {
+ final devices = AccountDevices.fromDaemon(_json(_listing))!;
+ expect(
+ devices.devices.map(
+ (d) => (d.label, d.self, d.seq, d.pending, d.suspended),
+ ),
+ [('my-mac', true, 2, false, false), ('Phone', false, 3, true, false)],
+ );
+ final phone = devices.devices[1];
+ expect(phone.kind, 'viewer');
+ expect(phone.fingerprint, 'B62E·867F·A2F3·3AFE');
+ expect(phone.addedAt, DateTime.fromMillisecondsSinceEpoch(1000));
+ expect(phone.lastSeen, DateTime.fromMillisecondsSinceEpoch(4000));
+ expect(devices.devices[0].machineId, 'a' * 32);
+ expect(devices.pending, [_phone]);
+ expect(devices.joinedSeq, 1);
+ expect(devices.baselineSeen, isFalse);
+ expect(devices.historyAvailable, isTrue);
+ expect(devices.frozen, isFalse);
+ expect(devices.conflict, isNull);
+ });
+
+ test('a conflict in the listing and in the frame reads the same', () {
+ final listed = AccountDevices.fromDaemon(_json(_conflictListing))!
+ .conflict!;
+ final framed = DeviceConflict.fromJson(_json(_conflictFrame)['payload'])!;
+ for (final c in [listed, framed]) {
+ expect(
+ (c.pub, c.label, c.fingerprint, c.afterJoin),
+ (_holder, 'old-install', 'C5B9·40ED·3F65·C391', true),
+ );
+ expect(c.addedAt, DateTime.fromMillisecondsSinceEpoch(1000));
+ }
+ });
+
+ test('every history row parses, with who did it and the flags', () {
+ final raw = _json(_history);
+ final history = DeviceLogHistory.fromJson(raw)!;
+ expect(history.rows, hasLength((raw['rows'] as List).length));
+ expect(history.complete, isTrue);
+ expect(history.rows.map((r) => (r.seq, r.op, r.label)), [
+ (4, 'removed', 'box2'),
+ (3, 'added', 'Phone'),
+ (2, 'added', 'my-mac'),
+ (1, 'added', 'box2'),
+ ]);
+ final removal = history.rows.first;
+ expect(
+ (
+ removal.pub,
+ removal.by?.pub,
+ removal.by?.label,
+ removal.by?.fingerprint,
+ ),
+ (_box2, _phone, 'Phone', 'B62E·867F·A2F3·3AFE'),
+ );
+ expect((removal.afterJoin, removal.active), (true, false));
+ expect(history.rows[1].pending, isTrue);
+ expect(history.rows[2].thisDevice, isTrue);
+ expect(history.rows[3].afterJoin, isFalse);
+ expect(
+ history.rows.every((r) => r.machineId.isNotEmpty || r.kind == 'viewer'),
+ isTrue,
+ );
+ });
+
+ test('the removal frame parses whole: signer, its name and code, and that it is still new', () {
+ final n = DeviceRemovalNotice.fromJson(_json(_removedFrame)['payload'])!;
+ expect(
+ (n.pub, n.label, n.kind, n.fingerprint),
+ (_box2, 'box2', 'machine', '6A38·03D5·F059·902A'),
+ );
+ expect(
+ (n.signer, n.signerLabel, n.signerFingerprint),
+ (_phone, 'Phone', 'B62E·867F·A2F3·3AFE'),
+ );
+ expect((n.signerPending, n.selfRemoved, n.at), (true, false, 5000));
+ // The Dart side writes back the same object.
+ expect(n.toJson(), _json(_removedFrame)['payload']);
+ });
+
+ test('a desktop build turns the daemon’s payloads into its banner, bands and history', () async {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ addTearDown(app.dispose);
+ final api = _DaemonApi();
+ app.api = api;
+ app.machines = [_machine];
+ app.machineStates['m'] = MachineState(_machine);
+ app.ownDaemonMachineIdForTest('m');
+ await app.handleEventForTest('m', {
+ 'type': 'device_keys_changed',
+ 'payload': <String, dynamic>{},
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices.map((d) => (d.pub, d.label, d.fingerprint)), [
+ (_phone, 'Phone', 'B62E·867F·A2F3·3AFE'),
+ ]);
+
+ await app.handleEventForTest('m', _json(_removedFrame));
+ expect(app.deviceRemovals.single.red, isTrue);
+ expect(
+ app.deviceRemovals.single.sentence,
+ startsWith(
+ 'box2 was removed from your account by a new device you haven’t looked at (Phone · ',
+ ),
+ );
+
+ // The frame is a hint; the daemon's listing is what says who holds the id.
+ api.conflicted = true;
+ await app.handleEventForTest('m', _json(_conflictFrame));
+ await Future<void>.delayed(Duration.zero);
+ expect(app.deviceConflict?.pub, _holder);
+
+ final history = (await app.loadDeviceHistory())!;
+ expect(history.rows.first.op, 'removed');
+ });
+}
diff --git a/desktop/test/device_notice_bands_shell_test.dart b/desktop/test/device_notice_bands_shell_test.dart
new file mode 100644
index 000000000..d939a263d
--- /dev/null
+++ b/desktop/test/device_notice_bands_shell_test.dart
@@ -0,0 +1,233 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/app_shell.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/account_devices.dart'
+ as model
+ show DeviceConflict, NewDeviceNotice;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/viewer/device_history.dart';
+
+/// The window's device bands are mounted by the shell itself (app_shell.dart), above whatever screen
+/// is showing — a band that is built but never mounted would leave a departed key unseen.
+class _SignedOutCli extends CliLogin {
+ @override
+ Future<void> logout() async {}
+
+ @override
+ Future<CliAuthStatus> checkStatus() async => CliAuthStatus(loggedIn: false);
+}
+
+/// "Got it" writes the dismissal to the daemon; nothing here should reach a network.
+class _QuietApi extends ApiClient {
+ _QuietApi() : super(config: AppConfig.dev, session: AuthSession());
+
+ @override
+ Future<bool> daemonDismissDevices({
+ String? pub,
+ List<String>? pubs,
+ bool baseline = false,
+ }) async => true;
+}
+
+AppNotifier _app(AppStatus status) {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLogin: _SignedOutCli(),
+ );
+ app.status = status;
+ app.currentUser = const CurrentUserProfile(
+ id: 'user-1',
+ name: 'Sam',
+ email: '[email protected]',
+ );
+ return app;
+}
+
+const _departed = DeviceLogDeparted(
+ pub: 'gone',
+ label: 'Phone',
+ kind: 'viewer',
+ machineId: '',
+ fingerprint: 'AAAA',
+ addedAt: 1,
+ removedAt: 2,
+ removedBy: 'gone',
+ removedByLabel: 'Phone',
+ selfRemoved: true,
+);
+
+Future<void> _pump(WidgetTester tester, AppNotifier app) async {
+ await tester.pumpWidget(
+ ProviderScope(
+ overrides: [appStateProvider.overrideWithValue(app)],
+ child: HarnessApp(
+ authenticatedScreen: (_) => const SizedBox(key: Key('screen')),
+ ),
+ ),
+ );
+ await tester.pump();
+}
+
+void main() {
+ DeviceRemovalNotice removal(String pub, {required bool self}) =>
+ DeviceRemovalNotice(
+ pub: pub,
+ label: 'Phone',
+ kind: 'viewer',
+ fingerprint: 'AAAA',
+ signer: self ? pub : 'signer',
+ signerLabel: self ? 'Phone' : 'MacBook',
+ signerFingerprint: 'E2FB',
+ signerPending: false,
+ selfRemoved: self,
+ at: 1,
+ );
+
+ testWidgets(
+ 'a key that signed itself out and also left unseen is told once: only the departed band shows',
+ (tester) async {
+ final app = _app(AppStatus.authenticated)
+ ..deviceRemovals.add(removal('gone', self: true))
+ ..departedDevices.add(_departed)
+ ..api = _QuietApi();
+ addTearDown(app.dispose);
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await _pump(tester, app);
+ expect(find.byKey(const Key('device-departed-notice')), findsOneWidget);
+ expect(find.byKey(const Key('device-removal-notice')), findsNothing);
+ // Held back, not dismissed: the departed band's Got it is the one dismissal — and it takes the held
+ // sign-out notice with it, so that notice does not surface in its place.
+ expect(app.deviceRemovals, hasLength(1));
+ await tester.tap(find.byKey(const Key('device-departed-dismiss')));
+ await tester.pump();
+ expect(app.deviceRemovals, isEmpty);
+ expect(find.byKey(const Key('device-departed-notice')), findsNothing);
+ expect(find.byKey(const Key('device-removal-notice')), findsNothing);
+ },
+ );
+
+ testWidgets(
+ 'the removal band still shows another key\'s sign-out and a removal by someone else of a departed key',
+ (tester) async {
+ final app = _app(AppStatus.authenticated)
+ ..deviceRemovals.addAll([
+ removal('other', self: true),
+ removal('gone', self: false),
+ ])
+ ..departedDevices.add(_departed)
+ ..api = _QuietApi();
+ addTearDown(app.dispose);
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await _pump(tester, app);
+ expect(find.byKey(const Key('device-removal-notice')), findsOneWidget);
+ expect(find.textContaining('(+1 more)'), findsOneWidget);
+ expect(find.byKey(const Key('device-departed-notice')), findsOneWidget);
+ // The departed band's Got it takes only a key's own sign-out notice with it: someone else's removal
+ // of that key is its own news.
+ await tester.tap(find.byKey(const Key('device-departed-dismiss')));
+ await tester.pump();
+ expect(app.deviceRemovals.map((n) => n.pub), ['other', 'gone']);
+ expect(find.textContaining('(+1 more)'), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'a key that joined and left before anyone looked is shown by the window itself',
+ (tester) async {
+ final app = _app(AppStatus.authenticated)..departedDevices.add(_departed);
+ addTearDown(app.dispose);
+ await _pump(tester, app);
+ expect(find.byKey(const Key('screen')), findsOneWidget);
+ expect(find.byKey(const Key('device-departed-notice')), findsOneWidget);
+ expect(find.byKey(const Key('device-departed-dismiss')), findsOneWidget);
+ },
+ );
+
+ testWidgets('the departed band waits for the signed-in window', (
+ tester,
+ ) async {
+ final app = _app(AppStatus.bootstrapping)..departedDevices.add(_departed);
+ addTearDown(app.dispose);
+ await _pump(tester, app);
+ expect(find.byKey(const Key('device-departed-notice')), findsNothing);
+
+ app.status = AppStatus.authenticated;
+ app.notifyListeners();
+ await tester.pump();
+ expect(find.byKey(const Key('device-departed-notice')), findsOneWidget);
+ });
+
+ testWidgets('nothing departed: no band', (tester) async {
+ final app = _app(AppStatus.authenticated);
+ addTearDown(app.dispose);
+ await _pump(tester, app);
+ expect(find.byKey(const Key('screen')), findsOneWidget);
+ expect(find.byKey(const Key('device-departed-notice')), findsNothing);
+ });
+
+ testWidgets(
+ 'the bands stack removal → departed → new device → conflict, top to bottom',
+ (tester) async {
+ final app = _app(AppStatus.authenticated)
+ ..deviceRemovals.add(
+ const DeviceRemovalNotice(
+ pub: 'rm',
+ label: 'Old iPad',
+ kind: 'viewer',
+ fingerprint: 'AAAA',
+ signer: 'signer',
+ signerLabel: 'MacBook',
+ signerFingerprint: 'E2FB',
+ signerPending: false,
+ selfRemoved: false,
+ at: 1,
+ ),
+ )
+ ..departedDevices.add(_departed)
+ ..newDevices.add(
+ const model.NewDeviceNotice(
+ pub: 'new',
+ label: 'Evil Phone',
+ kind: 'viewer',
+ ),
+ )
+ ..deviceConflict = model.DeviceConflict(
+ pub: 'holder',
+ label: 'Old install',
+ fingerprint: 'AAAA·BBBB',
+ addedAt: DateTime(2026, 9, 1),
+ afterJoin: false,
+ );
+ addTearDown(app.dispose);
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await _pump(tester, app);
+ double top(String key) => tester.getTopLeft(find.byKey(Key(key))).dy;
+ final order = [
+ top('device-removal-notice'),
+ top('device-departed-notice'),
+ top('new-device-notice'),
+ top('device-conflict-notice'),
+ ];
+ expect(
+ order,
+ orderedEquals([...order]..sort()),
+ reason: 'top to bottom: $order',
+ );
+ expect(order.toSet(), hasLength(4));
+ },
+ );
+}
diff --git a/desktop/test/device_pending_sync_test.dart b/desktop/test/device_pending_sync_test.dart
new file mode 100644
index 000000000..48182ed32
--- /dev/null
+++ b/desktop/test/device_pending_sync_test.dart
@@ -0,0 +1,844 @@
+// A desktop build keeps no device log of its own: which devices are still new, and whether this
+// computer's id is held by another key, are read from the daemon — and "seen" is written back to it.
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/account_devices.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/viewer/device_history.dart' show DeviceDepartedCopy;
+import 'package:harness/viewer/device_log.dart' show DevLogHead;
+import 'package:harness/ws/ws_conn.dart';
+
+/// A socket that answers every request with nothing: connecting a machine loads its data, and only
+/// what that does to the device notices is under test.
+class _QuietConn extends WsConn {
+ _QuietConn()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) => Future.value({});
+}
+
+/// A socket that is up: the local machine's link is live, so a frame from it heals an "offline" mark.
+class _ReadyConn extends _QuietConn {
+ @override
+ bool get isReady => true;
+}
+
+class _DaemonApi extends ApiClient {
+ _DaemonApi() : super(config: AppConfig.dev, session: AuthSession());
+
+ Map<String, dynamic>? listing;
+ Map<String, dynamic>? history;
+
+ /// Whether marking DEVICES seen succeeds; "Got it" on the baseline panel is a write of its own.
+ bool dismissWorks = true;
+ bool baselineWorks = true;
+ final dismissed = <({String? pub, List<String>? pubs, bool baseline})>[];
+ final rebaselines = <({bool confirm, Map<String, Object?>? head})>[];
+ Map<String, dynamic>? rebaselineAnswer;
+
+ /// When set, each read waits on the next of these, so reads can be made to answer out of order.
+ List<Completer<Map<String, dynamic>?>>? held;
+
+ @override
+ Future<Map<String, dynamic>?> daemonDevices() async {
+ if (held case final queue?) {
+ final gate = Completer<Map<String, dynamic>?>();
+ queue.add(gate);
+ return gate.future;
+ }
+ return listing;
+ }
+
+ @override
+ Future<bool> daemonDismissDevices({
+ String? pub,
+ List<String>? pubs,
+ bool baseline = false,
+ }) async {
+ dismissed.add((pub: pub, pubs: pubs, baseline: baseline));
+ if (dismissWorks && !baseline && listing?['pending'] is List) {
+ listing!['pending'] = [
+ for (final p in listing!['pending'] as List)
+ if (pub != p && !(pubs?.contains(p) ?? false)) p,
+ ];
+ // The daemon clears a departed key the same way it clears a pending one.
+ if (listing!['departed'] is List) {
+ listing!['departed'] = [
+ for (final d in listing!['departed'] as List)
+ if (d is Map &&
+ pub != d['pub'] &&
+ !(pubs?.contains(d['pub']) ?? false))
+ d,
+ ];
+ }
+ }
+ return baseline ? baselineWorks : dismissWorks;
+ }
+
+ @override
+ Future<Map<String, dynamic>?> daemonRebaselineDevices({
+ required bool confirm,
+ Map<String, Object?>? head,
+ }) async {
+ rebaselines.add((confirm: confirm, head: head));
+ return rebaselineAnswer;
+ }
+
+ @override
+ Future<Map<String, dynamic>?> daemonDeviceHistory() async => history;
+}
+
+Map<String, Object?> _member(
+ String pub,
+ int seq, {
+ String kind = 'viewer',
+ bool self = false,
+ bool suspended = false,
+}) => {
+ 'pub': pub,
+ 'label': pub.toUpperCase(),
+ 'kind': kind,
+ 'machineId': '',
+ 'addedAt': 1000 + seq,
+ 'fingerprint': 'FP$seq',
+ 'self': self,
+ 'seq': seq,
+ 'suspended': suspended,
+};
+
+const _machine = Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'Mac',
+);
+
+void main() {
+ late AppNotifier app;
+ late _DaemonApi api;
+
+ setUp(() {
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (_) => _QuietConn(),
+ );
+ api = _DaemonApi();
+ app.api = api;
+ app.machines = [_machine];
+ app.machineStates['m'] = MachineState(_machine);
+ app.ownDaemonMachineIdForTest('m');
+ });
+ tearDown(() => app.dispose());
+
+ Future<void> frame(String type) => app.handleEventForTest('m', {
+ 'type': type,
+ 'payload': <String, dynamic>{},
+ });
+
+ test('what the daemon kept as pending becomes the new devices, oldest first, with their key codes', () async {
+ api.listing = {
+ 'members': [
+ _member('me', 1, self: true),
+ _member('b', 4),
+ _member('a', 3),
+ _member('old', 2),
+ ],
+ 'pending': ['a', 'b', 'gone'],
+ 'conflict': {
+ 'pub': 'holder',
+ 'label': 'H',
+ 'fingerprint': 'HH',
+ 'addedAt': 9,
+ 'afterJoin': false,
+ },
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices.map((d) => d.pub), ['a', 'b']);
+ expect(app.newDevices.first.fingerprint, 'FP3');
+ expect(app.deviceConflict?.pub, 'holder');
+ // Once the daemon stops reporting the holder, the band goes.
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ 'pending': <String>[],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ expect(app.deviceConflict, isNull);
+ });
+
+ test('a daemon without pending leaves the in-memory notices exactly as they were', () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ };
+ await app.handleEventForTest('m', {
+ 'type': 'device_key_added',
+ 'payload': {'pub': 'p', 'label': 'iPad', 'kind': 'viewer'},
+ });
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices.map((d) => d.pub), ['p']);
+ });
+
+ Map<String, Object?> departed(
+ String pub, {
+ String by = 'box',
+ bool self = false,
+ int removedAt = 50,
+ }) => {
+ 'pub': pub,
+ 'label': 'Phone',
+ 'kind': 'viewer',
+ 'machineId': '',
+ 'fingerprint': 'FP·$pub',
+ 'addedAt': 10,
+ 'removedAt': removedAt,
+ 'removedBy': self ? pub : by,
+ 'removedByLabel': self ? 'Phone' : 'Box',
+ 'selfRemoved': self,
+ };
+
+ test('the link to this computer\'s own daemon coming back reads the listing again: what arose while it was down shows', () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ 'pending': <String>[],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ expect(app.departedDevices, isEmpty);
+ expect(app.deviceConflict, isNull);
+
+ // While the link was down the daemon found a held computer id, a new key and a departed one; the
+ // frames that said so reached nobody.
+ api.listing = {
+ 'members': [_member('me', 1, self: true), _member('p', 2)],
+ 'pending': ['p'],
+ 'departed': [departed('gone')],
+ 'conflict': {
+ 'pub': 'holder',
+ 'label': 'H',
+ 'fingerprint': 'HH',
+ 'addedAt': 9,
+ 'afterJoin': false,
+ },
+ };
+ app.onMachineConnectedForTest('m');
+ await Future<void>.delayed(Duration.zero);
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices.map((d) => d.pub), ['p']);
+ expect(app.departedDevices.map((d) => d.pub), ['gone']);
+ expect(app.deviceConflict?.pub, 'holder');
+ });
+
+ test('this computer\'s machine healed from "offline" by a live local socket reads the listing again too', () async {
+ // The other way the daemon's link comes back: no reconnect, the socket was live all along and a
+ // frame from it restores the machine (_healLocalMachine).
+ app.dispose();
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (_) => _ReadyConn(),
+ );
+ app.api = api;
+ app.machines = [_machine];
+ app.machineStates['m'] = MachineState(_machine)
+ ..localOnly = true
+ ..nodeOnline = false
+ ..localEndpoint = null;
+ app.ownDaemonMachineIdForTest('m');
+ api.listing = {
+ 'members': [_member('me', 1, self: true), _member('p', 2)],
+ 'pending': ['p'],
+ 'conflict': {
+ 'pub': 'holder',
+ 'label': 'H',
+ 'fingerprint': 'HH',
+ 'addedAt': 9,
+ 'afterJoin': false,
+ },
+ };
+ await frame('test_unrelated_frame');
+ await Future<void>.delayed(Duration.zero);
+ await Future<void>.delayed(Duration.zero);
+ expect(app.machineStates['m']!.nodeOnline, isTrue);
+ expect(app.newDevices.map((d) => d.pub), ['p']);
+ expect(app.deviceConflict?.pub, 'holder');
+ });
+
+ test('another machine connecting is not the daemon: it reads nothing (its frames are anyone\'s)', () async {
+ const other = Machine(
+ machineId: 'other',
+ authMode: MachineAuthMode.remote,
+ name: 'Box',
+ );
+ app.machines = [_machine, other];
+ app.machineStates['other'] = MachineState(other);
+ api.listing = {
+ 'members': [_member('me', 1, self: true), _member('p', 2)],
+ 'pending': ['p'],
+ };
+ app.onMachineConnectedForTest('other');
+ await Future<void>.delayed(Duration.zero);
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ });
+
+ test('a key that joined and left before anyone looked is read from the daemon, and outlasts a restart', () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ 'pending': <String>[],
+ 'departed': [
+ departed('gone'),
+ {'garbage': true},
+ ],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.departedDevices.map((d) => d.pub), ['gone']);
+ expect(
+ app.departedDevices.single.sentence(red: false),
+ 'Phone joined your account and left before you looked. Removed by Box.',
+ );
+ expect(app.departedIsRed(app.departedDevices.single), isFalse);
+
+ // Another read says the same: nothing changes (no rebuild churn), and the flag stays.
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.departedDevices.map((d) => d.pub), ['gone']);
+ });
+
+ test('a daemon that predates the field has no departed keys', () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ 'pending': <String>[],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.departedDevices, isEmpty);
+ });
+
+ test('red when the key that took it out is itself new, or itself left unseen; never for its own sign-out', () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true), _member('new', 5)],
+ 'pending': ['new'],
+ 'departed': [
+ departed('a', by: 'new'),
+ departed('b', by: 'a'),
+ departed('c', by: 'known'),
+ departed('d', self: true),
+ ],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ final red = {
+ for (final d in app.departedDevices) d.pub: app.departedIsRed(d),
+ };
+ expect(red, {'a': true, 'b': true, 'c': false, 'd': false});
+ expect(
+ app.departedDevices[0].sentence(red: true),
+ 'Phone joined your account and left before you looked. Removed by Box, a new device you haven’t looked at.',
+ );
+ expect(
+ app.departedDevices[3].sentence(red: false),
+ 'Phone joined your account and left before you looked.',
+ );
+ });
+
+ test('Got it on a departed key is written to the daemon as seen, and a read from before cannot bring it back', () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ 'pending': <String>[],
+ 'departed': [departed('gone')],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ app.dismissDeparted('gone');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.departedDevices, isEmpty);
+ expect(api.dismissed.single.pubs, ['gone']);
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.departedDevices, isEmpty);
+ expect(
+ (api.listing!['departed'] as List),
+ isEmpty,
+ reason: 'the daemon cleared it',
+ );
+ });
+
+ test(
+ 'Got it on a band of several clears them all in one write to the daemon',
+ () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ 'pending': <String>[],
+ 'departed': [departed('gone'), departed('gone2')],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ app.dismissDepartedAll(['gone', 'gone2']);
+ await Future<void>.delayed(Duration.zero);
+ expect(app.departedDevices, isEmpty);
+ expect(api.dismissed.single.pubs, unorderedEquals(['gone', 'gone2']));
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.departedDevices, isEmpty);
+ },
+ );
+
+ test(
+ 'a dismissal the daemon could not write stays dismissed in memory',
+ () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ 'pending': <String>[],
+ 'departed': [departed('gone')],
+ };
+ api.dismissWorks = false;
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ app.dismissDeparted('gone');
+ await Future<void>.delayed(Duration.zero);
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.departedDevices, isEmpty);
+ },
+ );
+
+ test('signing out forgets the departed keys of the old account', () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ 'pending': <String>[],
+ 'departed': [departed('gone')],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ app.clearDeviceNoticeStateForTest();
+ expect(app.departedDevices, isEmpty);
+ });
+
+ test('a daemon without pending counts as read: the recovery tick does not ask again', () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true)],
+ };
+ expect(app.pendingBootReadDoneForTest, isFalse);
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.pendingBootReadDoneForTest, isTrue);
+ });
+
+ test(
+ 'a daemon that cannot answer leaves the boot read to be tried again',
+ () async {
+ api.listing = null;
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.pendingBootReadDoneForTest, isFalse);
+ },
+ );
+
+ test('seen is written to the daemon, one device or all; a daemon that cannot keeps it in memory', () async {
+ api.listing = {
+ 'members': [
+ _member('me', 1, self: true),
+ _member('a', 3),
+ _member('b', 4),
+ ],
+ 'pending': ['a', 'b'],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ app.dismissNewDevice('a');
+ await Future<void>.delayed(Duration.zero);
+ // The banner's "It's mine" goes through `pubs`: a fork's suspension on the key is kept.
+ expect(api.dismissed.single.pub, isNull);
+ expect(api.dismissed.single.pubs, ['a']);
+ expect(app.newDevices.map((d) => d.pub), ['b']);
+
+ // The daemon predates dismiss: it still lists both as pending, but what was seen stays seen.
+ api.dismissWorks = false;
+ app.seenNewDevices();
+ await Future<void>.delayed(Duration.zero);
+ expect(api.dismissed.last.pubs, ['b']);
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ });
+
+ test('a fork-suspended entry is marked so on the banner, and follows the listing', () async {
+ api.listing = {
+ 'members': [
+ _member('me', 1, self: true),
+ _member('a', 3, suspended: true),
+ _member('b', 4),
+ ],
+ 'pending': ['a', 'b'],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices.map((d) => (d.pub, d.suspended)), [
+ ('a', true),
+ ('b', false),
+ ]);
+ // Reviewed and lifted elsewhere: the same pending pubs, but no longer suspended.
+ api.listing = {
+ 'members': [
+ _member('me', 1, self: true),
+ _member('a', 3),
+ _member('b', 4),
+ ],
+ 'pending': ['a', 'b'],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices.map((d) => (d.pub, d.suspended)), [
+ ('a', false),
+ ('b', false),
+ ]);
+ });
+
+ test(
+ 'the device page lifts a suspension (single pub); the banner does not',
+ () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true), _member('a', 3)],
+ 'pending': ['a'],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ app.dismissNewDevice('a', liftSuspension: true);
+ await Future<void>.delayed(Duration.zero);
+ expect(api.dismissed.single.pub, 'a');
+ expect(api.dismissed.single.pubs, isNull);
+ },
+ );
+
+ test(
+ 'the boot read is kept when the profile arrives while it is in flight',
+ () async {
+ api.held = [];
+ await frame('device_keys_changed');
+ expect(app.currentUser, isNull);
+ // /api/auth/me answers before the daemon's listing does.
+ app.currentUser = const CurrentUserProfile(id: 'u1', email: '[email protected]');
+ api.held![0].complete({
+ 'members': [_member('me', 1, self: true), _member('a', 3)],
+ 'pending': ['a'],
+ 'conflict': {
+ 'pub': 'holder',
+ 'label': 'H',
+ 'fingerprint': 'HH',
+ 'addedAt': 9,
+ 'afterJoin': false,
+ },
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices.map((d) => d.pub), ['a']);
+ expect(app.deviceConflict?.pub, 'holder');
+ },
+ );
+
+ test('a read in flight when the account signs out does not write the old listing', () async {
+ api.held = [];
+ await frame('device_keys_changed');
+ app.clearDeviceNoticeStateForTest();
+ api.held![0].complete({
+ 'members': [_member('me', 1, self: true), _member('a', 3)],
+ 'pending': ['a'],
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ });
+
+ test('an older read answering last cannot take back a device the newer read reported', () async {
+ api.held = [];
+ // The log grew (a read starts), then the daemon announced what it read (a second read starts).
+ await frame('device_keys_changed');
+ await app.handleEventForTest('m', {
+ 'type': 'device_key_added',
+ 'payload': {'pub': 'a', 'label': 'A', 'kind': 'viewer'},
+ });
+ expect(api.held!.length, 2);
+ final members = [_member('me', 1, self: true), _member('a', 3)];
+ api.held![1].complete({
+ 'members': members,
+ 'pending': ['a'],
+ });
+ await Future<void>.delayed(Duration.zero);
+ // The first read, from before the daemon accepted it, answers last.
+ api.held![0].complete({
+ 'members': [members.first],
+ 'pending': <String>[],
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices.map((d) => d.pub), ['a']);
+ });
+
+ test('opening the list writes back what it read as pending even with no banner up', () async {
+ api.listing = {
+ 'members': [_member('me', 1, self: true), _member('a', 3)],
+ 'pending': ['a'],
+ };
+ app.seenNewDevices(pending: ['a']);
+ await Future<void>.delayed(Duration.zero);
+ // Exactly what was shown — never "everything".
+ expect(api.dismissed.single.pubs, ['a']);
+ expect(api.dismissed.single.pub, isNull);
+ // And nothing to write back is no write at all.
+ final fresh = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ addTearDown(fresh.dispose);
+ final other = _DaemonApi();
+ fresh.api = other;
+ fresh.seenNewDevices();
+ await Future<void>.delayed(Duration.zero);
+ expect(other.dismissed, isEmpty);
+ });
+
+ test('"Got it" on the baseline panel is written to the daemon', () async {
+ await app.seeDeviceBaseline();
+ expect(api.dismissed.single, (pub: null, pubs: null, baseline: true));
+ expect(app.baselineSeenLocally, isTrue);
+ });
+
+ test(
+ 'a device that joined after the list was read is not marked seen with it',
+ () async {
+ api.listing = {
+ 'members': [
+ _member('me', 1, self: true),
+ _member('a', 3),
+ _member('late', 4),
+ ],
+ 'pending': ['a'],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ app.seenNewDevices(pending: ['a']);
+ await Future<void>.delayed(Duration.zero);
+ expect(api.dismissed.single.pubs, ['a']);
+ expect(api.dismissed.single.pubs, isNot(contains('late')));
+ },
+ );
+
+ test(
+ '"Got it" on the baseline panel keeps an unsaved "It’s mine" dismissal',
+ () async {
+ api.dismissWorks = false;
+ api.listing = {
+ 'members': [_member('me', 1, self: true), _member('a', 3)],
+ 'pending': ['a'],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ app.dismissNewDevice('a');
+ await Future<void>.delayed(Duration.zero);
+ await app.seeDeviceBaseline();
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ },
+ );
+
+ test(
+ 'a read that started before "It’s mine" cannot bring the device back',
+ () async {
+ api.held = [];
+ final members = [_member('me', 1, self: true), _member('a', 3)];
+ await app.handleEventForTest('m', {
+ 'type': 'device_key_added',
+ 'payload': {'pub': 'a', 'label': 'A', 'kind': 'viewer'},
+ });
+ expect(app.newDevices.map((d) => d.pub), ['a']);
+ app.dismissNewDevice('a');
+ api.dismissWorks = false;
+ // The read from before the dismissal answers still listing it as pending.
+ api.held![0].complete({
+ 'members': members,
+ 'pending': ['a'],
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ },
+ );
+
+ test('a read that started before the list was opened cannot bring a seen device back', () async {
+ api.held = [];
+ final members = [_member('me', 1, self: true), _member('a', 3)];
+ await app.handleEventForTest('m', {
+ 'type': 'device_key_added',
+ 'payload': {'pub': 'a', 'label': 'A', 'kind': 'viewer'},
+ });
+ expect(app.newDevices.map((d) => d.pub), ['a']);
+ app.seenNewDevices(pending: ['a']);
+ // The seen is written (so nothing is held back in memory any more)…
+ await Future<void>.delayed(Duration.zero);
+ expect(api.dismissed.single.pubs, ['a']);
+ // …and only then does the read from before it answer, still listing it as pending.
+ api.held![0].complete({
+ 'members': members,
+ 'pending': ['a'],
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ });
+
+ test('a read answering after the account was left is dropped', () async {
+ api.held = [];
+ await frame('device_keys_changed');
+ expect(api.held!.length, 1);
+ app.ownDaemonMachineIdForTest('m');
+ app.clearDeviceNoticeStateForTest();
+ api.held![0].complete({
+ 'members': [_member('me', 1, self: true), _member('a', 3)],
+ 'pending': ['a'],
+ 'conflict': {
+ 'pub': 'h',
+ 'label': 'H',
+ 'fingerprint': 'HH',
+ 'addedAt': 9,
+ 'afterJoin': false,
+ },
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ expect(app.deviceConflict, isNull);
+ });
+
+ test('the baseline panel lists what the daemon says, not what seq <= joinedSeq would', () async {
+ final raw = {
+ 'members': [
+ _member('me', 1, self: true),
+ _member('a', 2),
+ _member('b', 5),
+ ],
+ 'pending': <String>[],
+ 'joinedSeq': 3,
+ 'baseline': ['b'],
+ };
+ expect(AccountDevices.fromDaemon(raw)!.baseline.map((d) => d.pub), ['b']);
+ raw.remove('baseline');
+ expect(AccountDevices.fromDaemon(raw)!.baseline.map((d) => d.pub), ['a']);
+ });
+
+ test('Trust again hands the previewed head to the confirm; a changed list is reported, not applied', () async {
+ api.rebaselineAnswer = {
+ 'head': {'seq': 7, 'hash': 'h7'},
+ 'added': <Object?>[],
+ 'removed': <Object?>[],
+ };
+ final preview = (await app.rebaselineDevices(confirm: false))!;
+ expect(preview.head?.seq, 7);
+ api.rebaselineAnswer = {'error': 'LOG_CHANGED'};
+ final before = app.devicesRevision;
+ final done = await app.rebaselineDevices(confirm: true, head: preview.head);
+ expect(api.rebaselines.last.head, {'seq': 7, 'hash': 'h7'});
+ expect(done?.logChanged, isTrue);
+ expect(app.devicesRevision, before);
+ });
+
+ test('the daemon\'s 409 says which refusal it is: OTHER_ACCOUNT, else LOG_CHANGED', () async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ addTearDown(() => server.close(force: true));
+ var answer = '{"error":"OTHER_ACCOUNT"}';
+ server.listen((req) async {
+ await req.drain<void>();
+ req.response
+ ..statusCode = 409
+ ..headers.contentType = ContentType.json
+ ..write(answer);
+ await req.response.close();
+ });
+ final client = ApiClient(
+ config: AppConfig(
+ apiBaseUrl: 'http://127.0.0.1:1',
+ localCliBaseUrl: 'http://127.0.0.1:${server.port}',
+ ),
+ session: AuthSession(),
+ );
+ expect(await client.daemonRebaselineDevices(confirm: false), {
+ 'error': 'OTHER_ACCOUNT',
+ });
+ answer = '{"error":"LOG_CHANGED"}';
+ expect(
+ await client.daemonRebaselineDevices(
+ confirm: true,
+ head: {'seq': 1, 'hash': 'h'},
+ ),
+ {'error': 'LOG_CHANGED'},
+ );
+ answer = '{}';
+ expect(await client.daemonRebaselineDevices(confirm: true), {
+ 'error': 'LOG_CHANGED',
+ });
+ });
+
+ test('Trust again on another account\'s list (OTHER_ACCOUNT) is reported, not applied', () async {
+ api.rebaselineAnswer = {'error': 'OTHER_ACCOUNT'};
+ final before = app.devicesRevision;
+ final preview = (await app.rebaselineDevices(confirm: false))!;
+ expect([preview.otherAccount, preview.logChanged], [true, false]);
+ final done = (await app.rebaselineDevices(
+ confirm: true,
+ head: const DevLogHead(7, 'h7'),
+ ))!;
+ expect([done.otherAccount, done.logChanged], [true, false]);
+ expect(app.devicesRevision, before);
+ });
+
+ test(
+ 'the history is the daemon’s; a daemon that predates it answers null',
+ () async {
+ expect(await app.loadDeviceHistory(), isNull);
+ api.history = {
+ 'complete': true,
+ 'rows': [
+ {
+ 'seq': 2,
+ 'op': 'added',
+ 'pub': 'p',
+ 'kind': 'viewer',
+ 'machineId': '',
+ 'label': 'iPad',
+ 'fingerprint': 'FP',
+ 'at': 5,
+ 'thisDevice': false,
+ 'afterJoin': true,
+ 'pending': true,
+ 'active': true,
+ 'whileFrozen': false,
+ },
+ ],
+ };
+ final history = (await app.loadDeviceHistory())!;
+ expect(history.complete, isTrue);
+ expect(history.rows.single.label, 'iPad');
+ },
+ );
+}
diff --git a/desktop/test/device_viewer_notices_test.dart b/desktop/test/device_viewer_notices_test.dart
new file mode 100644
index 000000000..2b0c33a67
--- /dev/null
+++ b/desktop/test/device_viewer_notices_test.dart
@@ -0,0 +1,970 @@
+// A viewer build (web) keeps the account's device key log itself: the new-device banner is rebuilt
+// from what that log kept as pending (so it survives a restart), "seen" is written back to it, and a
+// removal it reads becomes a band — red when a device nobody has looked at did it.
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/notify/system_notifications.dart';
+import 'package:harness/state/pane_layout_store.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/state/account_devices.dart' show NewDeviceNotice;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/viewer/device_log.dart';
+import 'package:harness/viewer/device_log_sync.dart';
+import 'package:harness/viewer/direct_auth_api.dart' show IssuedTokens;
+import 'package:harness/viewer/viewer_key_store.dart';
+import 'package:harness/viewer/viewer_services.dart';
+
+import 'swarm_state_test.dart' show MemoryStore;
+
+const _acct = 'acct-1';
+
+/// Records the device notices that would have reached the operating system.
+class _Posts extends SystemNotifications {
+ _Posts() : super(notifier: const NoSystemNotifier());
+
+ final ids = <String>[];
+
+ @override
+ void postNotice({
+ required String id,
+ required String title,
+ required String body,
+ String? devicePub,
+ }) => ids.add(id);
+}
+
+/// A key-value store that tells the test when the app reads it (the boot's pane restore).
+class _HookedStore extends MemoryStore {
+ Future<void> Function()? onRead;
+
+ @override
+ Future<String?> read(String key) async {
+ final hook = onRead;
+ onRead = null;
+ await hook?.call();
+ return super.read(key);
+ }
+}
+
+/// A backend that keeps the log honestly.
+class _Backend {
+ _Backend([this.acct = _acct]) : state = DevLogState.empty(acct);
+
+ final String acct;
+ final entries = <DevLogEntry>[];
+ DevLogState state;
+
+ Future<void> add(
+ E2eeIdentity who,
+ String kind,
+ String machineId,
+ String label,
+ ) async {
+ final pub = b64e(who.pub);
+ await _push(
+ await signDevLogEntry(
+ nextDevLogEntry(
+ state,
+ op: 'add',
+ pub: pub,
+ kind: kind,
+ machineId: machineId,
+ label: label,
+ signer: pub,
+ at: 1000,
+ ),
+ who,
+ ),
+ );
+ }
+
+ Future<void> removeBy(String target, E2eeIdentity by) async {
+ final t = state.active[target]!;
+ await _push(
+ await signDevLogEntry(
+ nextDevLogEntry(
+ state,
+ op: 'remove',
+ pub: t.pub,
+ kind: t.kind,
+ machineId: t.machineId,
+ label: t.label,
+ signer: b64e(by.pub),
+ at: 2000,
+ ),
+ by,
+ ),
+ );
+ }
+
+ Future<void> _push(DevLogEntry e) async {
+ state = (await applyDevLogEntries(state, [e.toJson()])).state;
+ entries.add(e);
+ }
+
+ DeviceLogFetched fetch(int since) => (
+ acct: acct,
+ head: state.head,
+ entries: [
+ for (final e in entries)
+ if (e.seq > since) e.toJson(),
+ ],
+ );
+
+ Future<DeviceLogAppendAnswer> append(DevLogEntry entry) async {
+ if (entry.seq != state.head.seq + 1 || entry.prev != state.head.hash) {
+ return (head: state.head, error: 'STALE_HEAD');
+ }
+ await _push(entry);
+ return (head: state.head, error: null);
+ }
+}
+
+class _Api extends ApiClient {
+ _Api(this.backend) : super(config: AppConfig.dev, session: AuthSession());
+
+ final _Backend backend;
+
+ /// The backend cannot be reached.
+ bool offline = false;
+
+ /// When set, the last-seen request waits on it (the backend can delay it as long as it likes).
+ Completer<void>? seenGate;
+
+ @override
+ Future<DeviceLogFetched?> deviceKeys(int since) async =>
+ offline ? null : backend.fetch(since);
+
+ @override
+ Future<DeviceLogAppendAnswer?> appendDeviceKey(DevLogEntry entry) =>
+ backend.append(entry);
+
+ @override
+ Future<Map<String, int>> deviceKeysSeen() async {
+ await seenGate?.future;
+ return const {};
+ }
+
+ @override
+ Future<Map<String, dynamic>?> daemonDevices() async =>
+ throw StateError('a viewer build has no daemon');
+
+ /// Who `/api/auth/me` says is signed in (null: no profile).
+ String? user;
+
+ @override
+ Future<Map<String, dynamic>?> me() async {
+ final id = user;
+ return id == null
+ ? null
+ : {
+ 'user': {'id': id, 'email': '[email protected]'},
+ };
+ }
+
+ @override
+ Future<List<Machine>> machines() async => const [];
+}
+
+/// A viewer that is already signed in when it opens.
+class _SignedIn extends CliLogin {
+ @override
+ Future<CliAuthStatus> checkStatus() async =>
+ const CliAuthStatus(loggedIn: true);
+
+ @override
+ Future<void> logout() async {}
+}
+
+void main() {
+ late _Backend backend;
+ late ViewerKeyStore keys;
+ late E2eeIdentity box2, phone, intruder;
+
+ AppNotifier start({SystemNotifications? notices}) {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(storage: MemoryStore()),
+ configStore: null,
+ systemNotifications: notices,
+ viewer: ViewerServices(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ keys: keys,
+ ),
+ );
+ app.api = _Api(backend);
+ // Signed in: the boot's announcements are only taken from a signed-in app.
+ app.status = AppStatus.authenticated;
+ return app;
+ }
+
+ ViewerDeviceLog logOf(AppNotifier app) => app.viewer!.links.deviceLog!;
+
+ /// Lets the listeners the log fired (`onChanged` → the pending sync) finish.
+ Future<void> settle() async {
+ for (var i = 0; i < 20; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+ }
+
+ setUp(() async {
+ backend = _Backend();
+ // Whatever this app persists — its key, the log's copy — lives here, across "restarts".
+ keys = ViewerKeyStore(storage: MemoryStore());
+ box2 = await E2eeIdentity.fromSeed(List.filled(32, 2));
+ phone = await E2eeIdentity.fromSeed(List.filled(32, 3));
+ intruder = await E2eeIdentity.fromSeed(List.filled(32, 4));
+ });
+
+ test('opening signed in registers with the log and brings back what is still pending — nothing else asked', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ Future<AppNotifier> open() async {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(storage: MemoryStore()),
+ configStore: null,
+ cliLogin: _SignedIn(),
+ viewer: ViewerServices(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ keys: keys,
+ ),
+ );
+ app.api = _Api(backend);
+ addTearDown(app.dispose);
+ await app.bootstrap();
+ await settle();
+ expect(app.status, AppStatus.authenticated);
+ return app;
+ }
+
+ final first = await open();
+ final me = b64e((await keys.identity()).pub);
+ expect(
+ backend.state.active[me]?.kind,
+ 'viewer',
+ reason: 'the boot itself put this app into the log',
+ );
+ expect(first.newDevices, isEmpty);
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await logOf(first).refresh();
+ await settle();
+ expect(first.newDevices.map((d) => d.label), ['Phone']);
+
+ // A restart: the banner is back from the boot alone, before the log reads anything new.
+ final again = await open();
+ expect(again.newDevices.map((d) => d.label), ['Phone']);
+ });
+
+ Future<AppNotifier> openAs(
+ _Backend on,
+ String user, {
+ bool byHand = false,
+ }) async {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(storage: MemoryStore()),
+ configStore: null,
+ cliLogin: _SignedIn(),
+ viewer: ViewerServices(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ keys: keys,
+ ),
+ );
+ app.api = _Api(on)..user = user;
+ // A sign-in by hand is what the boot reads as fresh; a restored session never is.
+ if (byHand) {
+ await app.viewer!.auth.signIn(const IssuedTokens(token: 'token'));
+ }
+ addTearDown(app.dispose);
+ await app.bootstrap();
+ await settle();
+ return app;
+ }
+
+ test('signing in by hand as another account starts that account\'s list over', () async {
+ // Account A: this browser joined its log.
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ await openAs(backend, 'user-a', byHand: true);
+ final me = b64e((await keys.identity()).pub);
+ expect(backend.state.active[me]?.kind, 'viewer');
+
+ // Signed in as B in the same browser, by hand: B's log is another account's, and this sign-in is
+ // new — a new list, not a backend that lies. The profile is not waited for.
+ final other = _Backend('acct-2');
+ await other.add(phone, 'viewer', '', 'Phone');
+ final b = await openAs(other, 'user-b', byHand: true);
+ final listing = await logOf(b).list();
+ expect(
+ listing.frozen,
+ isNull,
+ reason: 'a new local sign-in is a new list, not a backend that lies',
+ );
+ expect(
+ other.state.active[me]?.kind,
+ 'viewer',
+ reason: 'this browser joined B\'s log',
+ );
+ expect(listing.members.map((m) => m.member.label), contains('Phone'));
+ });
+
+ test('a restored session whose /me id differs does not reset the list', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ await openAs(backend, 'user-a', byHand: true);
+ await backend.add(phone, 'viewer', '', 'Phone');
+ final first = await openAs(backend, 'user-a');
+ expect(first.newDevices.map((d) => d.label), ['Phone']);
+
+ // The backend now says another person is signed in (the profile is the backend's word): the log
+ // is the same account's, so nothing is reset — the marks and the list stay.
+ final again = await openAs(backend, 'user-evil');
+ expect((await logOf(again).list()).frozen, isNull);
+ expect(again.newDevices.map((d) => d.label), ['Phone']);
+
+ // And a restored session on another ACCOUNT's log is frozen, not started over.
+ final other = _Backend('acct-2');
+ await other.add(intruder, 'viewer', '', 'Chrome');
+ final lied = await openAs(other, 'user-b');
+ expect((await logOf(lied).list()).frozen, isNotNull);
+ expect(
+ other.state.active.keys,
+ isNot(contains(b64e((await keys.identity()).pub))),
+ reason: 'it did not join',
+ );
+ expect(lied.newDevices.map((d) => d.label), [
+ 'Phone',
+ ], reason: 'the marks are still the old account\'s');
+ });
+
+ test(
+ 'a device that joins later is banner-worthy, and still is after a restart',
+ () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ // What was there before this app joined is not news.
+ expect(app.newDevices, isEmpty);
+
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await logOf(app).refresh();
+ await settle();
+ expect(app.newDevices.map((d) => d.label), ['Phone']);
+
+ // A restart: same storage, fresh app. The log kept it as pending, so the banner is back on the
+ // next change the log reads — no announcement needed.
+ final again = start();
+ addTearDown(again.dispose);
+ expect(again.newDevices, isEmpty);
+ await backend.add(intruder, 'viewer', '', 'Chrome on macOS');
+ await logOf(again).refresh();
+ await settle();
+ expect(again.newDevices.map((d) => d.label), [
+ 'Phone',
+ 'Chrome on macOS',
+ ]);
+ },
+ );
+
+ test('"It’s mine" and opening the list are written to the log, so they hold across a restart', () async {
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await backend.add(intruder, 'viewer', '', 'Chrome');
+ await logOf(app).refresh();
+ await settle();
+ expect(app.newDevices.length, 2);
+
+ app.dismissNewDevice(b64e(phone.pub));
+ await settle();
+ expect((await logOf(app).list()).pending, [b64e(intruder.pub)]);
+ expect(app.newDevices.map((d) => d.label), ['Chrome']);
+
+ app.seenNewDevices();
+ await settle();
+ expect((await logOf(app).list()).pending, isEmpty);
+
+ final again = start();
+ addTearDown(again.dispose);
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ await logOf(again).refresh();
+ await settle();
+ // Only what joined since: the two seen ones stay seen.
+ expect(again.newDevices.map((d) => d.label), ['box2']);
+ });
+
+ test('opening the list writes back what it read as pending even with no banner up', () async {
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await logOf(app).refresh();
+ await settle();
+ // The banner was closed here, but the write did not land (say, the tab closed first).
+ app.newDevices.clear();
+ final devices = (await app.loadDevices())!;
+ expect(devices.pending, [b64e(phone.pub)]);
+ app.seenNewDevices(pending: devices.pending);
+ await settle();
+ expect((await logOf(app).list()).pending, isEmpty);
+ });
+
+ test(
+ 'the baseline panel is shown until Got it, which the log keeps',
+ () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ final before = (await app.loadDevices())!;
+ expect(before.baselineSeen, isFalse);
+ expect(before.baseline.map((d) => d.label), ['box2']);
+ expect(before.historyAvailable, isTrue);
+
+ await app.seeDeviceBaseline();
+ final again = start();
+ addTearDown(again.dispose);
+ expect((await again.loadDevices())!.baselineSeen, isTrue);
+ },
+ );
+
+ test('a removal read from the log is a band: plain, signed out, or red when a new device did it', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ await backend.add(phone, 'viewer', '', 'Phone');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+
+ // A device that was here before this app joined takes another out: the owner tidying up.
+ await backend.removeBy(b64e(phone.pub), box2);
+ await logOf(app).refresh();
+ await settle();
+ expect(app.deviceRemovals.single.red, isFalse);
+ expect(app.deviceRemovals.single.title, 'Device removed');
+ expect(
+ app.deviceRemovals.single.sentence,
+ 'Phone was removed from your account by box2.',
+ );
+
+ // A device nobody has looked at yet removes a computer: red, naming it with its short code.
+ await backend.add(intruder, 'viewer', '', 'Chrome on macOS');
+ await backend.removeBy(b64e(box2.pub), intruder);
+ await logOf(app).refresh();
+ await settle();
+ final red = app.deviceRemovals.last;
+ expect(red.pub, b64e(box2.pub));
+ expect(red.red, isTrue);
+ expect(red.title, 'Removed by a new device');
+ expect(
+ red.sentence,
+ startsWith(
+ 'box2 was removed from your account by a new device you haven’t looked at (Chrome on macOS · ',
+ ),
+ );
+ expect(red.sentence, endsWith('…).'));
+
+ // It signs itself out: its own act, never red even though it is still new.
+ await backend.removeBy(b64e(intruder.pub), intruder);
+ await logOf(app).refresh();
+ await settle();
+ final out = app.deviceRemovals.last;
+ expect(
+ (out.selfRemoved, out.red, out.title),
+ (true, false, 'Device signed out'),
+ );
+ expect(out.sentence, 'Chrome on macOS signed out of your account.');
+
+ app.dismissDeviceRemoval(out.pub);
+ expect(app.deviceRemovals.map((n) => n.pub), [
+ b64e(phone.pub),
+ b64e(box2.pub),
+ ]);
+ });
+
+ test('the History dialog reads this app’s own log', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ final history = (await app.loadDeviceHistory())!;
+ expect(history.complete, isTrue);
+ // Newest first: this app's own add, then the computer that was already there.
+ expect(history.rows.map((r) => (r.op, r.thisDevice)), [
+ ('added', true),
+ ('added', false),
+ ]);
+ });
+
+ test(
+ 'signing out forgets what was said about the old account’s devices',
+ () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ await backend.add(phone, 'viewer', '', 'Phone');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await backend.removeBy(b64e(phone.pub), box2);
+ await logOf(app).refresh();
+ await settle();
+ await app.seeDeviceBaseline();
+ expect(app.deviceRemovals, isNotEmpty);
+ expect(app.baselineSeenLocally, isTrue);
+ await app.logout();
+ expect(app.deviceRemovals, isEmpty);
+ expect(app.baselineSeenLocally, isFalse);
+ },
+ );
+
+ test('a new device announced while the last-seen request waits is not marked seen with the list', () async {
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await logOf(app).refresh();
+ await settle();
+ expect(app.newDevices.map((d) => d.label), ['Phone']);
+
+ final api = app.api as _Api;
+ api.seenGate = Completer<void>();
+ List<String>? shown;
+ final read = app.loadDevices(onListed: (b) => shown = b);
+ await settle();
+ // The intruder joins while the backend sits on the request.
+ await backend.add(intruder, 'viewer', '', 'Chrome');
+ await logOf(app).refresh();
+ await settle();
+ api.seenGate!.complete();
+ final devices = (await read)!;
+ expect(shown, [b64e(phone.pub)]);
+ app.seenNewDevices(pending: devices.pending, shown: shown);
+ await settle();
+ expect(app.newDevices.map((d) => d.label), ['Chrome']);
+ expect((await logOf(app).list()).pending, [b64e(intruder.pub)]);
+ });
+
+ test(
+ 'a head that moved while reviewing is "changed"; an unreadable log is null',
+ () async {
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ final preview = (await app.rebaselineDevices(confirm: false))!;
+ expect(preview.logChanged, isFalse);
+
+ await backend.add(intruder, 'viewer', '', 'Chrome');
+ final moved = (await app.rebaselineDevices(
+ confirm: true,
+ head: preview.head,
+ ))!;
+ expect(moved.logChanged, isTrue);
+
+ (app.api as _Api).offline = true;
+ expect(
+ await app.rebaselineDevices(confirm: true, head: preview.head),
+ isNull,
+ );
+ },
+ );
+
+ test(
+ 'a key a fork suspended is marked so on the banner (the app\'s own log)',
+ () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await logOf(app).refresh();
+ await settle();
+ expect(app.newDevices.single.suspended, isFalse);
+
+ // A fork left the key suspended in this app's copy of the log (kept as pending).
+ final file = Map<String, dynamic>.from((await keys.deviceLog())! as Map);
+ file['suspended'] = [b64e(phone.pub)];
+ await keys.writeDeviceLog(file);
+ await backend.add(intruder, 'viewer', '', 'Chrome');
+ await logOf(app).refresh();
+ await settle();
+ expect(app.newDevices.map((d) => (d.label, d.suspended)), [
+ ('Phone', true),
+ ('Chrome', false),
+ ]);
+ },
+ );
+
+ test('a removal read while the app starts up is said once it is signed in, not lost', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ await backend.add(phone, 'viewer', '', 'Phone');
+ final posts = _Posts();
+ final app = start(notices: posts);
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.removeBy(b64e(phone.pub), box2);
+ app.status = AppStatus.checkingEnvironment;
+ await logOf(app).refresh();
+ await settle();
+ expect(
+ app.deviceRemovals,
+ isEmpty,
+ reason: 'not before the app is signed in',
+ );
+ expect(posts.ids, isEmpty);
+ app.status = AppStatus.authenticated;
+ expect(app.deviceRemovals.single.pub, b64e(phone.pub));
+ expect(posts.ids, ['harness-device-removed:${b64e(phone.pub)}']);
+ });
+
+ test('a new device read while the app starts up reaches the operating system once it is signed in', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final posts = _Posts();
+ final app = start(notices: posts);
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ // The log has already recorded it as announced: this is the only chance the notification gets.
+ await backend.add(phone, 'viewer', '', 'Phone');
+ app.status = AppStatus.bootstrapping;
+ await logOf(app).refresh();
+ await settle();
+ expect(posts.ids, isEmpty);
+ app.status = AppStatus.authenticated;
+ expect(posts.ids, ['harness-device:${b64e(phone.pub)}']);
+ expect(app.newDevices.map((d) => d.label), ['Phone']);
+ // Said once: a later change of status does not say it again.
+ app.status = AppStatus.authenticated;
+ expect(posts.ids, hasLength(1));
+ });
+
+ test(
+ 'a notice that waited for the app and was then dismissed is not said',
+ () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final posts = _Posts();
+ final app = start(notices: posts);
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ app.status = AppStatus.bootstrapping;
+ await logOf(app).refresh();
+ await settle();
+ app.dismissNewDevice(b64e(phone.pub));
+ app.status = AppStatus.authenticated;
+ expect(posts.ids, isEmpty);
+ },
+ );
+
+ test('a notice that waited for the app is dropped when the person signs out instead', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ await backend.add(phone, 'viewer', '', 'Phone');
+ final posts = _Posts();
+ final app = start(notices: posts);
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.removeBy(b64e(phone.pub), box2);
+ await backend.add(intruder, 'viewer', '', 'Chrome');
+ app.status = AppStatus.preparingEnvironment;
+ await logOf(app).refresh();
+ await settle();
+ app.status = AppStatus.unauthenticated;
+ app.status = AppStatus.authenticated;
+ expect(posts.ids, isEmpty);
+ expect(app.deviceRemovals, isEmpty);
+ });
+
+ test('what waited for the app is not said after the account it was about is left', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final posts = _Posts();
+ final app = start(notices: posts);
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ app.status = AppStatus.bootstrapping;
+ await logOf(app).refresh();
+ await settle();
+ app.clearDeviceNoticeStateForTest();
+ app.status = AppStatus.authenticated;
+ expect(posts.ids, isEmpty);
+ });
+
+ test('a key that joined and left before anyone looked stays flagged from this app\'s own log until Got it', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await backend.removeBy(b64e(phone.pub), box2);
+ await logOf(app).refresh();
+ await settle();
+ final gone = app.departedDevices.single;
+ expect(
+ (gone.pub, gone.label, gone.removedByLabel, gone.selfRemoved),
+ (b64e(phone.pub), 'Phone', 'box2', false),
+ );
+ expect(app.departedIsRed(gone), isFalse);
+ expect(app.newDevices, isEmpty);
+
+ // Opening the list (or a restart) does not clear it.
+ app.seenNewDevices();
+ await settle();
+ final again = await openAs(backend, 'user-a');
+ expect(again.departedDevices.map((d) => d.pub), [b64e(phone.pub)]);
+
+ // Got it clears it, and that holds across a restart too.
+ again.dismissDeparted(b64e(phone.pub));
+ await settle();
+ expect(again.departedDevices, isEmpty);
+ final last = await openAs(backend, 'user-a');
+ expect(last.departedDevices, isEmpty);
+ });
+
+ test('a notice replayed after the key already left does not put it back in the banner', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ // Announced while the app starts up (so the notice waits), and taken out again before it is said.
+ await backend.add(phone, 'viewer', '', 'Phone');
+ app.status = AppStatus.bootstrapping;
+ await logOf(app).refresh();
+ await backend.removeBy(b64e(phone.pub), box2);
+ await logOf(app).refresh();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ app.status = AppStatus.authenticated;
+ await settle();
+ expect(
+ app.newDevices,
+ isEmpty,
+ reason: 'the log says it is not pending: the replay must not keep it',
+ );
+ expect(app.departedDevices.map((d) => d.pub), [b64e(phone.pub)]);
+ });
+
+ test('opening the list never marks a key that joined and left unseen as seen — only its own Got it does', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await backend.removeBy(b64e(phone.pub), box2);
+ await logOf(app).refresh();
+ await settle();
+ final gone = b64e(phone.pub);
+ expect(app.departedDevices.map((d) => d.pub), [gone]);
+
+ // A banner set that still names the key (a replay that raced the sync), and a list that read it as new.
+ app.seenNewDevices(shown: [gone], pending: [gone]);
+ await settle();
+ expect(app.departedDevices.map((d) => d.pub), [gone]);
+ final again = await openAs(backend, 'user-a');
+ expect(again.departedDevices.map((d) => d.pub), [
+ gone,
+ ], reason: 'nothing was written for it');
+
+ again.dismissDeparted(gone);
+ await settle();
+ expect(again.departedDevices, isEmpty);
+ });
+
+ test('opening the list: the departed keys that same read listed are not marked seen even before the app read them', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await backend.removeBy(b64e(phone.pub), box2);
+ await logOf(app).refresh();
+ await settle();
+ final gone = b64e(phone.pub);
+ expect(app.departedDevices.map((d) => d.pub), [gone]);
+
+ // The app has not read the key as departed yet (startup), but the list's own read did.
+ app.departedDevices.clear();
+ final listing = (await app.loadDevices())!;
+ expect(listing.departed, [gone]);
+ app.seenNewDevices(
+ shown: [gone],
+ pending: [gone],
+ departed: listing.departed,
+ );
+ // The next change of the log re-reads the marks: the key is still flagged, because nothing was written for it.
+ await backend.add(intruder, 'viewer', '', 'Chrome');
+ await logOf(app).refresh();
+ await settle();
+ expect(app.departedDevices.map((d) => d.pub), [
+ gone,
+ ], reason: 'not marked seen: only its own Got it clears it');
+ });
+
+ test('opening the list with only a departed key up does not cancel the replay\'s read of the log', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.add(phone, 'viewer', '', 'Phone'); // new, still pending
+ await logOf(app).refresh();
+ await settle();
+ // Announced while the app starts up (the notice waits), and taken out again before it is said.
+ app.status = AppStatus.bootstrapping;
+ await backend.add(intruder, 'viewer', '', 'Chrome');
+ await logOf(app).refresh();
+ await backend.removeBy(b64e(intruder.pub), box2);
+ await logOf(app).refresh();
+ await settle();
+ final gone = b64e(intruder.pub);
+ expect(app.departedDevices.map((d) => d.pub), [gone]);
+ app.newDevices.clear(); // the banner not rebuilt yet: only the replay's read brings Phone back
+ // The list opens the moment the replay put the departed key up, its read of the log under way.
+ var opened = false;
+ void open() {
+ if (opened || !app.newDevices.any((d) => d.pub == gone)) return;
+ opened = true;
+ scheduleMicrotask(() => app.seenNewDevices(shown: [gone]));
+ }
+
+ app.addListener(open);
+ app.status = AppStatus.authenticated;
+ await settle();
+ app.removeListener(open);
+ expect(opened, isTrue);
+ expect(app.newDevices.map((d) => d.pub), [
+ b64e(phone.pub),
+ ], reason: 'nothing was marked: the read lands');
+ expect(app.departedDevices.map((d) => d.pub), [gone]);
+ });
+
+ test('"It\'s mine" on a stale banner for a departed key takes it down and marks nothing', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await backend.removeBy(b64e(phone.pub), box2);
+ await logOf(app).refresh();
+ await settle();
+ final gone = b64e(phone.pub);
+ app.newDevices.add(
+ NewDeviceNotice(pub: gone, label: 'Phone', kind: 'viewer'),
+ );
+ app.dismissNewDevice(gone);
+ await settle();
+ expect(app.newDevices, isEmpty);
+ expect(app.departedDevices.map((d) => d.pub), [gone]);
+ expect((await logOf(app).list()).departed.map((d) => d.pub), [
+ gone,
+ ], reason: 'its own Got it is what clears it');
+ final again = await openAs(backend, 'user-a');
+ expect(again.departedDevices.map((d) => d.pub), [gone]);
+ });
+
+ test('a new device that took the key out is what makes it red; its own sign-out is not', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await settle();
+ await backend.add(intruder, 'viewer', '', 'Chrome on macOS');
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await backend.removeBy(b64e(phone.pub), intruder);
+ await logOf(app).refresh();
+ await settle();
+ final byIntruder = app.departedDevices.single;
+ expect(app.departedIsRed(byIntruder), isTrue);
+ expect(
+ byIntruder.sentence(red: true),
+ contains('a new device you haven’t looked at'),
+ );
+ await backend.removeBy(b64e(intruder.pub), intruder);
+ await logOf(app).refresh();
+ await settle();
+ final own = app.departedDevices.firstWhere(
+ (d) => d.pub == b64e(intruder.pub),
+ );
+ expect(own.selfRemoved, isTrue);
+ expect(app.departedIsRed(own), isFalse);
+ });
+
+ test('the sign-in is known to the log before the boot reads anything else (a pane restore reads it first)', () async {
+ // Account A: this browser joined its log by hand.
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ await openAs(backend, 'user-a', byHand: true);
+ final me = b64e((await keys.identity()).pub);
+ // A's sign-in is long past: only a sign-in made just now may start another account's list.
+ const old = 'a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0@1000';
+ await keys.writeSignInEpoch(old);
+ await keys.writeDeviceLog({
+ ...Map<String, dynamic>.from((await keys.deviceLog())! as Map),
+ 'owner': old,
+ });
+
+ // Signing in as B by hand: whatever reads the log first — here the boot's own pane restore — must
+ // already be under the new sign-in, or A's list would be frozen as a lie before B's is joined.
+ final other = _Backend('acct-2');
+ await other.add(phone, 'viewer', '', 'Phone');
+ final store = _HookedStore();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(storage: MemoryStore()),
+ configStore: null,
+ cliLogin: _SignedIn(),
+ paneLayoutStore: PaneLayoutStore(storage: store),
+ viewer: ViewerServices(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ keys: keys,
+ ),
+ );
+ app.api = _Api(other)..user = 'user-b';
+ addTearDown(app.dispose);
+ store.onRead = () => logOf(app).refresh();
+ await app.viewer!.auth.signIn(const IssuedTokens(token: 'token'));
+ await app.bootstrap();
+ await settle();
+ final listing = await logOf(app).list();
+ expect(listing.frozen, isNull);
+ expect(
+ other.state.active[me]?.kind,
+ 'viewer',
+ reason: 'this browser joined B\'s log',
+ );
+ // A's list was put aside as it was — not frozen as a lie, which coming back to A would have to be
+ // trusted again from.
+ final kept = (await keys.deviceLogArchive())[_acct]! as Map;
+ expect(kept['frozen'], isNull);
+ });
+
+ test('an announcement that lands after signing out is dropped', () async {
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ final app = start();
+ addTearDown(app.dispose);
+ await logOf(app).register();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ app.status = AppStatus.unauthenticated;
+ await logOf(app).refresh();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ expect(app.deviceRemovals, isEmpty);
+ });
+}
diff --git a/desktop/test/machine_list_push_test.dart b/desktop/test/machine_list_push_test.dart
index 8d0d2b53d..6b12703cd 100644
--- a/desktop/test/machine_list_push_test.dart
+++ b/desktop/test/machine_list_push_test.dart
@@ -36,6 +36,10 @@ class _Api extends ApiClient {
@override
Future<Map<String, dynamic>?> desk() async => null;
+ // A retry also re-reads the daemon's pending devices: a daemon that predates them.
+ @override
+ Future<Map<String, dynamic>?> daemonDevices() async => null;
+
@override
Future<List<Machine>> machines() async {
reads++;
diff --git a/desktop/test/new_device_notice_test.dart b/desktop/test/new_device_notice_test.dart
index afd06e67b..bf466b57f 100644
--- a/desktop/test/new_device_notice_test.dart
+++ b/desktop/test/new_device_notice_test.dart
@@ -1,9 +1,14 @@
// The band a new device raises across the window: one device goes straight to its key code, several
// go to Settings ▸ Your devices, where each is a row.
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart' show RenderParagraph;
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/settings/sections/account_devices_section.dart';
import 'package:harness/state/account_devices.dart' hide NewDeviceNotice;
+import 'package:harness/viewer/device_history.dart'
+ show DevLogHistoryRow, DeviceLogHistory;
+import 'package:harness/viewer/device_log_sync.dart'
+ show DeviceLogDeparted, DeviceRemovalNotice;
import 'package:harness/state/account_devices.dart'
as model
show NewDeviceNotice;
@@ -17,8 +22,8 @@ void main() {
setUp(() => app = FakeDevicesApp());
tearDown(() => app.dispose());
- Future<void> mount(WidgetTester tester) async {
- tester.view.physicalSize = const Size(1200, 900);
+ Future<void> mount(WidgetTester tester, {double width = 1200}) async {
+ tester.view.physicalSize = Size(width, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
@@ -30,6 +35,9 @@ void main() {
builder: (context, _) => Column(
children: [
NewDeviceNotice(notifier: app),
+ DeviceRemovalNoticeBand(notifier: app),
+ DeviceDepartedNoticeBand(notifier: app),
+ DeviceConflictNoticeBand(notifier: app),
const Expanded(child: SizedBox()),
],
),
@@ -39,6 +47,54 @@ void main() {
);
}
+ testWidgets(
+ 'It’s mine on the banner dismisses the notice but keeps a fork suspension',
+ (tester) async {
+ app.newDevices.add(
+ const model.NewDeviceNotice(
+ pub: 'p1',
+ label: 'Test iPad',
+ kind: 'viewer',
+ ),
+ );
+ await mount(tester);
+ await tester.tap(find.byKey(const Key('new-device-dismiss')));
+ await tester.pump();
+ expect(app.newDevices, isEmpty);
+ // The banner never says a key is suspended, so it must not lift that: only the detail page does.
+ expect(app.dismissCalls, [('p1', false)]);
+ },
+ );
+
+ testWidgets(
+ 'It’s mine on a suspended entry opens the device instead of dismissing it',
+ (tester) async {
+ // A fork's suspension keeps the key pending, so a dismissal would be back on the next read: the
+ // device's own page shows the suspension, and lifts it there.
+ app.newDevices.add(
+ const model.NewDeviceNotice(
+ pub: 'sus',
+ label: 'Odd Mac',
+ kind: 'viewer',
+ suspended: true,
+ ),
+ );
+ app.devices = AccountDevices(
+ devices: [fakeDevice('sus', label: 'Odd Mac', suspended: true)],
+ );
+ await mount(tester);
+ await tester.tap(find.byKey(const Key('new-device-dismiss')));
+ await tester.pump();
+ await tester.pump();
+ expect(app.dismissCalls, isEmpty);
+ expect(app.newDevices, hasLength(1));
+ expect(find.byKey(const Key('device-detail-suspended')), findsOneWidget);
+ await tester.tap(find.byKey(const Key('device-detail-mine')));
+ await tester.pump();
+ expect(app.dismissCalls, [('sus', true)]);
+ },
+ );
+
testWidgets('one new device: Review opens that device, offering It’s mine', (
tester,
) async {
@@ -140,4 +196,406 @@ void main() {
expect(app.newDevices, isEmpty);
},
);
+
+ DeviceRemovalNotice removal({
+ String label = 'Old iPad',
+ bool selfRemoved = false,
+ bool signerPending = false,
+ String signer = 'signer',
+ }) => DeviceRemovalNotice(
+ pub: 'gone-$label',
+ label: label,
+ kind: 'viewer',
+ fingerprint: 'AAAA·BBBB',
+ signer: signer,
+ signerLabel: 'MacBook',
+ signerFingerprint: 'E2FB·0DF5·5FD8·E6C7',
+ signerPending: signerPending,
+ selfRemoved: selfRemoved,
+ at: 1,
+ );
+
+ group('a device taken out of the account', () {
+ testWidgets(
+ 'removed by a device the owner knows: a plain notice, Got it takes it down',
+ (tester) async {
+ app.deviceRemovals.add(removal());
+ await mount(tester);
+ expect(
+ find.text(
+ 'Device removed. Old iPad was removed from your account by MacBook.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.byKey(const Key('device-removal-review')), findsNothing);
+ await tester.tap(find.byKey(const Key('device-removal-dismiss')));
+ await tester.pump();
+ expect(app.deviceRemovals, isEmpty);
+ expect(find.byKey(const Key('device-removal-notice')), findsNothing);
+ },
+ );
+
+ testWidgets('a device that signed out says so', (tester) async {
+ app.deviceRemovals.add(removal(selfRemoved: true));
+ await mount(tester);
+ expect(
+ find.text('Device signed out. Old iPad signed out of your account.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets(
+ 'removed by a new device nobody looked at: red, and Review opens that device',
+ (tester) async {
+ app.deviceRemovals.add(removal(signerPending: true, signer: 'signer'));
+ app.devices = AccountDevices(
+ devices: [
+ fakeDevice(
+ 'signer',
+ label: 'MacBook',
+ fingerprint: 'E2FB·0DF5·5FD8·E6C7',
+ ),
+ ],
+ );
+ await mount(tester);
+ expect(
+ find.text(
+ 'Removed by a new device. Old iPad was removed from your account by a new device you haven’t looked at (MacBook · E2FB·0DF5…).',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('device-removal-review')));
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('E2FB·0DF5·5FD8·E6C7'), findsOneWidget);
+ },
+ );
+
+ testWidgets('more than one: the first, and how many are behind it', (
+ tester,
+ ) async {
+ app.deviceRemovals
+ ..add(removal())
+ ..add(removal(label: 'Other'));
+ await mount(tester);
+ expect(find.textContaining('(+1 more)'), findsOneWidget);
+ });
+
+ testWidgets(
+ 'a red one behind an older neutral one is the one shown, with its Review',
+ (tester) async {
+ app.deviceRemovals
+ ..add(removal(label: 'Calm'))
+ ..add(removal(label: 'Alarm', signerPending: true, signer: 'signer'));
+ app.devices = AccountDevices(
+ devices: [
+ fakeDevice(
+ 'signer',
+ label: 'MacBook',
+ fingerprint: 'E2FB·0DF5·5FD8·E6C7',
+ ),
+ ],
+ );
+ await mount(tester);
+ final text = tester
+ .widget<Text>(find.byKey(const Key('device-removal-notice')))
+ .data!;
+ expect(text, startsWith('Removed by a new device. Alarm was removed'));
+ expect(text, endsWith('(+1 more)'));
+ expect(find.byKey(const Key('device-removal-review')), findsOneWidget);
+ // Got it takes down the one shown; the neutral one is then what is left.
+ await tester.tap(find.byKey(const Key('device-removal-dismiss')));
+ await tester.pump();
+ expect(app.deviceRemovals.map((n) => n.label), ['Calm']);
+ expect(find.textContaining('Calm was removed'), findsOneWidget);
+ expect(find.byKey(const Key('device-removal-review')), findsNothing);
+ },
+ );
+
+ testWidgets('only neutral ones: the first, in order', (tester) async {
+ app.deviceRemovals
+ ..add(removal(label: 'First'))
+ ..add(removal(label: 'Second'));
+ await mount(tester);
+ expect(find.textContaining('First was removed'), findsOneWidget);
+ });
+ });
+
+ DeviceLogDeparted departed({
+ String pub = 'gone',
+ String label = 'Old iPad',
+ String by = 'signer',
+ String byLabel = 'MacBook',
+ bool self = false,
+ }) => DeviceLogDeparted(
+ pub: pub,
+ label: label,
+ kind: 'viewer',
+ machineId: '',
+ fingerprint: 'AAAA·BBBB',
+ addedAt: 1,
+ removedAt: 2,
+ removedBy: self ? pub : by,
+ removedByLabel: byLabel,
+ selfRemoved: self,
+ );
+
+ group('a device that joined and left before anyone looked', () {
+ testWidgets(
+ 'removed by another key: says who, and Got it clears the flag',
+ (tester) async {
+ app.departedDevices.add(departed());
+ await mount(tester);
+ expect(
+ find.text(
+ 'Old iPad joined your account and left before you looked. Removed by MacBook.',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('device-departed-dismiss')));
+ await tester.pump();
+ expect(app.dismissedDeparted, ['gone']);
+ expect(find.byKey(const Key('device-departed-notice')), findsNothing);
+ },
+ );
+
+ testWidgets('its own sign-out names no one', (tester) async {
+ app.departedDevices.add(departed(self: true));
+ await mount(tester);
+ expect(
+ find.text('Old iPad joined your account and left before you looked.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('more than one: the first, and how many are behind it', (
+ tester,
+ ) async {
+ app.departedDevices
+ ..add(departed())
+ ..add(departed(pub: 'gone2'));
+ await mount(tester);
+ expect(find.textContaining('(+1 more)'), findsOneWidget);
+ });
+
+ testWidgets(
+ 'more than one: Got it clears them all, the ones behind it too',
+ (tester) async {
+ app.departedDevices
+ ..add(departed())
+ ..add(departed(pub: 'gone2'));
+ await mount(tester);
+ await tester.tap(find.byKey(const Key('device-departed-dismiss')));
+ await tester.pump();
+ expect(app.dismissedDeparted, unorderedEquals(['gone', 'gone2']));
+ expect(find.byKey(const Key('device-departed-notice')), findsNothing);
+ },
+ );
+
+ testWidgets('more than one: a red one is the one shown', (tester) async {
+ app.newDevices.add(
+ const model.NewDeviceNotice(
+ pub: 'intruder',
+ label: 'Chrome',
+ kind: 'viewer',
+ ),
+ );
+ app.departedDevices
+ ..add(departed())
+ ..add(
+ departed(
+ pub: 'gone2',
+ label: 'Phone',
+ by: 'intruder',
+ byLabel: 'Chrome',
+ ),
+ );
+ await mount(tester);
+ expect(
+ find.text(
+ 'Phone joined your account and left before you looked. Removed by Chrome, a new device you haven’t looked at. (+1 more)',
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('Review opens the History, where the key is flagged', (
+ tester,
+ ) async {
+ app.departedDevices.add(departed());
+ app.history = DeviceLogHistory(
+ complete: true,
+ rows: [
+ DevLogHistoryRow(
+ seq: 3,
+ op: 'removed',
+ pub: 'gone',
+ kind: 'viewer',
+ machineId: '',
+ label: 'Old iPad',
+ fingerprint: 'AAAA·BBBB',
+ at: 2,
+ thisDevice: false,
+ afterJoin: true,
+ pending: true,
+ active: false,
+ whileFrozen: false,
+ ),
+ ],
+ );
+ await mount(tester);
+ await tester.tap(find.byKey(const Key('device-departed-review')));
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('Device history'), findsOneWidget);
+ expect(find.text('Left before you looked'), findsOneWidget);
+ // Opening it does not clear the flag: only "Got it" does.
+ expect(app.dismissedDeparted, isEmpty);
+ });
+
+ testWidgets(
+ 'removed by a new device that is still on the account: red, and Review opens that device',
+ (tester) async {
+ app.newDevices.add(
+ const model.NewDeviceNotice(
+ pub: 'signer',
+ label: 'MacBook',
+ kind: 'viewer',
+ ),
+ );
+ app.departedDevices.add(departed());
+ app.devices = AccountDevices(
+ devices: [
+ fakeDevice(
+ 'signer',
+ label: 'MacBook',
+ fingerprint: 'E2FB·0DF5·5FD8·E6C7',
+ ),
+ ],
+ );
+ await mount(tester);
+ expect(
+ find.text(
+ 'Old iPad joined your account and left before you looked. Removed by MacBook, a new device you haven’t looked at.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Review'), findsWidgets);
+ await tester.tap(find.byKey(const Key('device-departed-review')));
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('E2FB·0DF5·5FD8·E6C7'), findsOneWidget);
+ },
+ );
+ });
+
+ group('another key holds this computer’s id', () {
+ DeviceConflict conflict({required bool afterJoin}) => DeviceConflict(
+ pub: 'holder',
+ label: 'Old install',
+ fingerprint: 'AAAA·BBBB',
+ addedAt: DateTime.now().subtract(const Duration(days: 3)),
+ afterJoin: afterJoin,
+ );
+
+ testWidgets(
+ 'before this computer joined: neutral, saying it joins on its own once the holder is gone',
+ (tester) async {
+ app.deviceConflict = conflict(afterJoin: false);
+ await mount(tester);
+ final text = tester
+ .widget<Text>(find.byKey(const Key('device-conflict-notice')))
+ .data!;
+ expect(
+ text,
+ startsWith(
+ 'This computer is held by another key on your account: Old install · AAAA·BBBB. If that was an earlier',
+ ),
+ );
+ expect(text, isNot(contains('added')));
+ expect(
+ text,
+ contains(
+ 'remove it from another device (Your devices) — this computer joins on its own once it is gone.',
+ ),
+ );
+ },
+ );
+
+ for (final afterJoin in [false, true]) {
+ testWidgets(
+ '${afterJoin ? 'red' : 'neutral'} copy wraps at a narrow window: nothing is cut off, both buttons stay',
+ (tester) async {
+ app.deviceConflict = conflict(afterJoin: afterJoin);
+ await mount(tester, width: 640);
+ final paragraph = tester.renderObject<RenderParagraph>(
+ find.byKey(const Key('device-conflict-notice')),
+ );
+ expect(
+ paragraph.didExceedMaxLines,
+ isFalse,
+ reason:
+ 'the advice at the end of the copy is not cut with an ellipsis',
+ );
+ // It took more than two lines to say, which is what the old cap cut.
+ expect(
+ paragraph.size.height,
+ greaterThan(paragraph.text.style!.fontSize! * 2 * 1.2),
+ );
+ expect(
+ find.byKey(const Key('device-conflict-dismiss')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const Key('device-conflict-review')),
+ findsOneWidget,
+ );
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
+ testWidgets(
+ 'after it joined: someone took its place, remove that key now',
+ (tester) async {
+ app.deviceConflict = conflict(afterJoin: true);
+ await mount(tester);
+ final text = tester
+ .widget<Text>(find.byKey(const Key('device-conflict-notice')))
+ .data!;
+ expect(
+ text,
+ startsWith(
+ 'Another key took this computer’s place on your account after it joined: Old install · AAAA·BBBB',
+ ),
+ );
+ expect(
+ text,
+ contains(
+ 'If you did not set up Harness here again, remove that key from another device now',
+ ),
+ );
+ },
+ );
+
+ testWidgets('Your devices opens the list', (tester) async {
+ app.deviceConflict = conflict(afterJoin: false);
+ app.devices = AccountDevices(devices: [fakeDevice('holder')]);
+ await mount(tester);
+ await tester.tap(find.byKey(const Key('device-conflict-review')));
+ for (var i = 0; i < 5; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ expect(find.byType(AccountDevicesSection), findsOneWidget);
+ });
+
+ testWidgets('dismissed, it stays down', (tester) async {
+ app.deviceConflict = conflict(afterJoin: false);
+ await mount(tester);
+ await tester.tap(find.byKey(const Key('device-conflict-dismiss')));
+ await tester.pump();
+ expect(app.deviceConflict, isNull);
+ expect(find.byKey(const Key('device-conflict-notice')), findsNothing);
+ });
+ });
}
diff --git a/desktop/test/pane_machine_unknown_test.dart b/desktop/test/pane_machine_unknown_test.dart
index 95463c0d1..f7c734fe5 100644
--- a/desktop/test/pane_machine_unknown_test.dart
+++ b/desktop/test/pane_machine_unknown_test.dart
@@ -42,6 +42,10 @@ class _Api extends ApiClient {
@override
Future<Map<String, dynamic>?> me() async => null;
+ // A retry also re-reads the daemon's pending devices: a daemon that predates them.
+ @override
+ Future<Map<String, dynamic>?> daemonDevices() async => null;
+
@override
Future<List<Machine>> machines() {
final result = Completer<List<Machine>>();
diff --git a/desktop/test/support/devices_app.dart b/desktop/test/support/devices_app.dart
index b4425f098..6304c2374 100644
--- a/desktop/test/support/devices_app.dart
+++ b/desktop/test/support/devices_app.dart
@@ -4,6 +4,8 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/state/account_devices.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/viewer/device_history.dart';
+import 'package:harness/viewer/device_log.dart' show DevLogHead;
const fakeFingerprint = 'E2FB·0DF5·5FD8·E6C7';
@@ -23,10 +25,93 @@ class FakeDevicesApp extends AppNotifier {
String? removeError;
final removed = <String>[];
int loads = 0;
+ final dismissCalls = <(String, bool)>[];
+
+ /// What the History dialog reads; [historyMissing] is a daemon that predates it (null).
+ DeviceLogHistory? history;
+ bool historyMissing = false;
+ int baselineSeenCalls = 0;
+
+ @override
+ Future<DeviceLogHistory?> loadDeviceHistory() async {
+ if (historyMissing) return null;
+ return history ?? (throw StateError('no history'));
+ }
+
+ /// What the list asked to be written back as seen, each time it was opened.
+ final seenPending = <List<String>>[];
+
+ /// The listing's departed keys each open handed over.
+ final seenDeparted = <List<String>>[];
+
+ /// The banner set each open handed over (null: none given).
+ final seenShown = <List<String>?>[];
+
+ /// Called by [loadDevices] with the banner's pubs as [bannerAtRead] has them (the real app reads
+ /// them when the listing returns).
+ List<String> Function()? bannerAtRead;
+
+ // The real ones also write to the daemon, which a screen test has none of.
+ @override
+ void seenNewDevices({
+ Iterable<String> pending = const [],
+ Iterable<String>? shown,
+ Iterable<String> departed = const [],
+ }) {
+ seenPending.add(pending.toList());
+ seenShown.add(shown?.toList());
+ seenDeparted.add(departed.toList());
+ if (newDevices.isEmpty) return;
+ final gone = shown?.toSet();
+ newDevices.removeWhere((d) => gone == null || gone.contains(d.pub));
+ notifyListeners();
+ }
+
+ /// The departed keys "Got it" was pressed for.
+ final dismissedDeparted = <String>[];
+
+ @override
+ void dismissDepartedAll(Iterable<String> pubs) {
+ final cleared = pubs.toSet();
+ dismissedDeparted.addAll(cleared);
+ departedDevices.removeWhere((d) => cleared.contains(d.pub));
+ notifyListeners();
+ }
+
+ @override
+ void dismissNewDevice(String pub, {bool liftSuspension = false}) {
+ dismissCalls.add((pub, liftSuspension));
+ newDevices.removeWhere((d) => d.pub == pub);
+ notifyListeners();
+ }
+
+ /// What Trust again reads: each preview answer in turn, and what a confirm answers (the heads it
+ /// was handed are recorded).
+ final previews = <DevicesRebaseline>[];
+ DevicesRebaseline? confirmAnswer;
+ final confirmedHeads = <DevLogHead?>[];
+
+ @override
+ Future<DevicesRebaseline?> rebaselineDevices({
+ required bool confirm,
+ DevLogHead? head,
+ }) async {
+ if (!confirm) return previews.isEmpty ? null : previews.removeAt(0);
+ confirmedHeads.add(head);
+ return confirmAnswer;
+ }
+
+ @override
+ Future<void> seeDeviceBaseline() async {
+ baselineSeenCalls++;
+ }
@override
- Future<AccountDevices?> loadDevices() async {
+ Future<AccountDevices?> loadDevices({
+ void Function(List<String> banner)? onListed,
+ }) async {
loads++;
+ onListed?.call(bannerAtRead?.call() ?? [for (final d in newDevices) d.pub]);
await loadGate?.future;
if (loadError case final error?) throw error;
return devices;
@@ -58,6 +143,8 @@ AccountDevice fakeDevice(
DateTime? added,
DateTime? seen,
String fingerprint = fakeFingerprint,
+ bool suspended = false,
+ bool pending = false,
}) => AccountDevice(
pub: pub,
label: label,
@@ -67,4 +154,6 @@ AccountDevice fakeDevice(
fingerprint: fingerprint,
self: self,
lastSeen: seen,
+ suspended: suspended,
+ pending: pending,
);
diff --git a/desktop/test/system_notifications_test.dart b/desktop/test/system_notifications_test.dart
index fd852aa4c..081e341aa 100644
--- a/desktop/test/system_notifications_test.dart
+++ b/desktop/test/system_notifications_test.dart
@@ -8,6 +8,7 @@ import 'dart:ui' show SemanticsAction, Tristate;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/local_key_value_store.dart';
@@ -17,6 +18,7 @@ import 'package:harness/notify/alert_sounds.dart';
import 'package:harness/notify/system_notifications.dart';
import 'package:harness/settings/sections/alerts_card.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/viewer/device_log_sync.dart' show DeviceRemovalCopy;
class _Memory implements LocalKeyValueStore {
final values = <String, String?>{};
@@ -103,6 +105,17 @@ AgentAlert _alert(
at: DateTime(2026, 9, 25, 12),
);
+class _ConflictApi extends ApiClient {
+ _ConflictApi() : super(config: AppConfig.dev, session: AuthSession());
+
+ @override
+ Future<Map<String, dynamic>?> daemonDevices() async => {
+ 'members': <Object?>[],
+ 'pending': <String>[],
+ 'conflict': {'pub': 'holder', 'label': 'Old install', 'fingerprint': 'AAAA·BBBB', 'addedAt': 5, 'afterJoin': true},
+ };
+}
+
const _machine = Machine(
machineId: 'm1',
authMode: MachineAuthMode.remote,
@@ -424,6 +437,7 @@ void main() {
addTearDown(app.dispose);
app.machines = [_machine];
app.machineStates['m1'] = MachineState(_machine);
+ app.ownDaemonMachineIdForTest('m1');
await app.handleEventForTest('m1', {
'type': 'device_key_added',
'payload': {'pub': 'pub-1', 'label': 'Test iPad', 'kind': 'viewer', 'fingerprint': 'AAAA·BBBB·CCCC·DDDD'},
@@ -437,6 +451,120 @@ void main() {
expect(shown.body, contains('Test iPad'));
expect((shown.machineId, shown.agentId), ('@device', 'pub-1'));
});
+
+ Map<String, Object?> removedFrame({bool signerPending = false, bool selfRemoved = false, String pub = 'gone'}) => {
+ 'type': 'device_key_removed',
+ 'payload': {
+ 'pub': pub, 'label': 'Old iPad', 'kind': 'viewer', 'fingerprint': 'AAAA·BBBB',
+ 'signer': 'signer', 'signerLabel': 'MacBook', 'signerFingerprint': 'E2FB·0DF5·5FD8·E6C7',
+ 'signerPending': signerPending, 'selfRemoved': selfRemoved, 'at': 1,
+ },
+ };
+
+ test('a removal the daemon reports reaches the system and the band; a red one opens the signer', () async {
+ final os = _Recorder();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ systemNotifications: SystemNotifications(store: store(), notifier: os),
+ );
+ addTearDown(app.dispose);
+ app.machines = [_machine];
+ app.machineStates['m1'] = MachineState(_machine);
+ app.ownDaemonMachineIdForTest('m1');
+ await app.handleEventForTest('m1', removedFrame());
+ await app.handleEventForTest('m1', removedFrame(signerPending: true));
+ await Future<void>.delayed(Duration.zero);
+ // The same device twice is one notice, the later word.
+ expect(app.deviceRemovals.single.signerPending, isTrue);
+ expect(os.shown.map((n) => n.title), ['Device removed', 'Removed by a new device']);
+ expect(os.shown.first.body, 'Old iPad was removed from your account by MacBook.');
+ expect((os.shown.first.machineId, os.shown.first.agentId), ('', ''));
+ expect((os.shown.last.machineId, os.shown.last.agentId), ('@device', 'signer'));
+ // A new device that signs itself out is its own act: not red, and nothing to open.
+ await app.handleEventForTest('m1', removedFrame(signerPending: true, selfRemoved: true, pub: 'other'));
+ expect(os.shown.last.title, 'Device signed out');
+ expect((os.shown.last.machineId, os.shown.last.agentId), ('', ''));
+ app.dismissDeviceRemoval('gone');
+ app.dismissDeviceRemoval('other');
+ expect(app.deviceRemovals, isEmpty);
+ // A frame that is not whole raises nothing.
+ await app.handleEventForTest('m1', {'type': 'device_key_removed', 'payload': {'pub': 'x'}});
+ expect(app.deviceRemovals, isEmpty);
+ });
+
+ test('a red removal is never softened by a later plain one for the same device', () async {
+ final os = _Recorder();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ systemNotifications: SystemNotifications(store: store(), notifier: os),
+ );
+ addTearDown(app.dispose);
+ app.machines = [_machine];
+ app.machineStates['m1'] = MachineState(_machine);
+ app.ownDaemonMachineIdForTest('m1');
+ await app.handleEventForTest('m1', removedFrame(signerPending: true));
+ await app.handleEventForTest('m1', removedFrame());
+ expect(app.deviceRemovals.single.red, isTrue);
+ expect(os.shown.map((n) => n.title), ['Removed by a new device']);
+ });
+
+ test('device frames from any machine but this computer’s own daemon raise nothing', () async {
+ final os = _Recorder();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ systemNotifications: SystemNotifications(store: store(), notifier: os),
+ );
+ addTearDown(app.dispose);
+ const relayed = Machine(machineId: 'relayed', authMode: MachineAuthMode.remote, name: 'Remote');
+ app.machines = [_machine, relayed];
+ app.machineStates['m1'] = MachineState(_machine);
+ // The relayed machine carries a backend-supplied computer id that says it is "local": still not the daemon.
+ app.machineStates['relayed'] = MachineState(relayed)..localOnly = true;
+ app.ownDaemonMachineIdForTest('m1');
+ await app.handleEventForTest('relayed', {
+ 'type': 'device_key_added',
+ 'payload': {'pub': 'fake', 'label': 'X', 'kind': 'viewer'},
+ });
+ await app.handleEventForTest('relayed', removedFrame(signerPending: true));
+ await app.handleEventForTest('relayed', {'type': 'device_conflict', 'payload': {'pub': 'holder', 'label': 'H', 'fingerprint': 'AAAA', 'addedAt': 5, 'afterJoin': true}});
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ expect(app.deviceRemovals, isEmpty);
+ expect(app.deviceConflict, isNull);
+ expect(os.shown, isEmpty);
+ // The same frames from the own daemon are the daemon's word.
+ await app.handleEventForTest('m1', removedFrame(signerPending: true));
+ expect(app.deviceRemovals.single.red, isTrue);
+ });
+
+ test('a conflict frame is only a hint: the conflict is re-read from the daemon, and stays dismissed', () async {
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null);
+ addTearDown(app.dispose);
+ final api = _ConflictApi();
+ app.api = api;
+ app.machines = [_machine];
+ app.machineStates['m1'] = MachineState(_machine);
+ app.ownDaemonMachineIdForTest('m1');
+ // A frame carrying a fake holder changes nothing by itself: what the daemon lists is what shows.
+ final frame = {
+ 'type': 'device_conflict',
+ 'payload': {'pub': 'fake', 'label': 'Fake', 'fingerprint': 'FFFF', 'addedAt': 5, 'afterJoin': true},
+ };
+ await app.handleEventForTest('m1', frame);
+ await Future<void>.delayed(Duration.zero);
+ expect(app.deviceConflict?.pub, 'holder');
+ expect(app.deviceConflict?.afterJoin, isTrue);
+ app.dismissDeviceConflict();
+ await app.handleEventForTest('m1', frame);
+ await Future<void>.delayed(Duration.zero);
+ expect(app.deviceConflict, isNull);
+ });
});
group('Linux', () {
diff --git a/desktop/test/viewer/deviceHistory.vectors.json b/desktop/test/viewer/deviceHistory.vectors.json
new file mode 100644
index 000000000..679ffc2d5
--- /dev/null
+++ b/desktop/test/viewer/deviceHistory.vectors.json
@@ -0,0 +1,543 @@
+{
+ "acct": "acct-history-1",
+ "pubs": {
+ "a": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "b": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "c": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "d": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw="
+ },
+ "entries": [
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 10,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "mac",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "TGq35MQKMb9h+RVuiWBdKkeGL0CpoDzz28ZWmTsgRCr9+Q5EUYP0cBOEvL2l1En0W7pghYv8nrUnQa6pvPrUAQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 2,
+ "prev": "CovFBIdOBn7wiD9rCG4NzW31/eiYY2aQcLLFK7P08bc=",
+ "at": 20,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "phone",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "G3NPtWdtHRzO0qVbbd1jABC7EPAFCf0L7NXcaNC1tPfjkrSo4IqpFF1kMOMQkodYenWVTqr/lbxciclDAROfBA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 3,
+ "prev": "B5nsulFGuwg49bsCmFEg0lJUYigEX/VA/bCccUr94bM=",
+ "at": 30,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "pixel",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "CW+lpHmqR4qSoFxTIbY+fzKZr4G0dSZMfs0ULd6s3kdNpE4zVbkOpaKpL+bzA5bEghk6CiGki5NkV/0ZjYjnAQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 4,
+ "prev": "rQt1wtdStS0QRgoTyNQxnPHCCo+OcAdJoTIEBoXes7c=",
+ "at": 40,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "ipad",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "LAdnsHZy255R8J9jeMq5AMC4QuJxz2Bq+QYnF/YQQarH3QOkTf3jzKk6XweiBouhXSLnposVThku9mI6cl8DBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 5,
+ "prev": "bC4N5mAJgT276SBzBqiEOQSptTRcIQYM+mnpRygEYHM=",
+ "at": 50,
+ "op": "remove",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "LIE",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "xMGVbx5ArRy/NpTcLzBJGYD+oZT+GlJPaX3DbOJ8T9mKy+7wv8zhxzgYRQq4L0FHrX5LXlcEv1Fd6+1w6msuBQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 6,
+ "prev": "yis5+Ci1yxF/tUx+lO0DIExsqBMxDm8bv516DD+0XdA=",
+ "at": 60,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "pixel",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "sL2JKbDDzTcoZSQYcOlp5soXgp8II7n/Mrq5lI1zrmtZE3u0zsB/i3hayhBA1bdxC40Pl9B7vLJQtVxG7yrKCA=="
+ }
+ ],
+ "fork": [
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 10,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "mac",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "TGq35MQKMb9h+RVuiWBdKkeGL0CpoDzz28ZWmTsgRCr9+Q5EUYP0cBOEvL2l1En0W7pghYv8nrUnQa6pvPrUAQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 2,
+ "prev": "CovFBIdOBn7wiD9rCG4NzW31/eiYY2aQcLLFK7P08bc=",
+ "at": 20,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "phone",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "G3NPtWdtHRzO0qVbbd1jABC7EPAFCf0L7NXcaNC1tPfjkrSo4IqpFF1kMOMQkodYenWVTqr/lbxciclDAROfBA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 3,
+ "prev": "B5nsulFGuwg49bsCmFEg0lJUYigEX/VA/bCccUr94bM=",
+ "at": 31,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "evil",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "I5yBaoADRLpyN3I+0t0qhZR7wehgWo6oZqWsj9CY3tb5dotNiCkmf+7YnqW5ir0dwFa4XCz9k/yBxod63p0vBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 4,
+ "prev": "sEpMlwosMHwGtmqVx5x1Dx3Nc8qf3rTnmjXVrUI+YRY=",
+ "at": 41,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "ipad",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "0pp4FidRF84ismPAL5P55sJ/1ZEXdToIxQ6i6glOLHO025TdJF51L4nhoRSAxW3Cuk2YS6yrSK+RsLYpwZ22Dg=="
+ }
+ ],
+ "history": [
+ {
+ "name": "the whole log, newest first",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [
+ "b"
+ ],
+ "seqs": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "pixel",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 3,
+ "op": "renamed",
+ "label": "pixel",
+ "kind": "viewer",
+ "previousLabel": "phone",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 2,
+ "op": "added",
+ "label": "phone",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 1,
+ "op": "added",
+ "label": "mac",
+ "kind": "machine",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "only the recent tail is known (offline)",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [],
+ "seqs": [
+ 4,
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "a removal whose add is outside the known window",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [],
+ "seqs": [
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "a removal applied while frozen",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [],
+ "seqs": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 6
+ ],
+ "loose": [
+ 5
+ ],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "pixel",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": true
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 3,
+ "op": "renamed",
+ "label": "pixel",
+ "kind": "viewer",
+ "previousLabel": "phone",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 2,
+ "op": "added",
+ "label": "phone",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 1,
+ "op": "added",
+ "label": "mac",
+ "kind": "machine",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "no joined point known",
+ "self": "b",
+ "pending": [],
+ "seqs": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "pixel",
+ "kind": "viewer",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 3,
+ "op": "renamed",
+ "label": "pixel",
+ "kind": "viewer",
+ "previousLabel": "phone",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 2,
+ "op": "added",
+ "label": "phone",
+ "kind": "viewer",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 1,
+ "op": "added",
+ "label": "mac",
+ "kind": "machine",
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false
+ }
+ ]
+ }
+ ],
+ "divergence": [
+ {
+ "name": "the first differing position, the one before it matching",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "expect": 3
+ },
+ {
+ "name": "a window that starts at the split cannot prove it",
+ "log": "fork",
+ "from": 3,
+ "to": 4,
+ "expect": null
+ },
+ {
+ "name": "the same log has no split",
+ "log": "main",
+ "from": 1,
+ "to": 4,
+ "expect": null
+ },
+ {
+ "name": "a window with a gap is not usable",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "tamper": "gap",
+ "expect": null
+ },
+ {
+ "name": "a window that does not end at the peer head is not usable",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "tamper": "head",
+ "expect": null
+ },
+ {
+ "name": "not a window at all",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "tamper": "junk",
+ "expect": null
+ }
+ ]
+}
diff --git a/desktop/test/viewer/device_history_test.dart b/desktop/test/viewer/device_history_test.dart
new file mode 100644
index 000000000..c067d3f78
--- /dev/null
+++ b/desktop/test/viewer/device_history_test.dart
@@ -0,0 +1,387 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/viewer/device_history.dart';
+import 'package:harness/viewer/device_log.dart';
+import 'package:harness/viewer/device_log_sync.dart';
+
+/// The Dart port of cli/src/lib/e2ee/deviceHistory.ts, on the same log as deviceHistory.spec.ts.
+void main() {
+ late E2eeIdentity a, b, c;
+ late List<DevLogEntry> entries;
+ late DevLogState state;
+
+ Future<void> push(
+ String op,
+ E2eeIdentity key,
+ E2eeIdentity signer,
+ String label,
+ int at, {
+ String kind = 'viewer',
+ }) async {
+ final e = await signDevLogEntry(
+ nextDevLogEntry(
+ state,
+ op: op,
+ pub: b64e(key.pub),
+ kind: kind,
+ machineId: kind == 'machine' ? 'a' * 32 : '',
+ label: label,
+ signer: b64e(signer.pub),
+ at: at,
+ ),
+ signer,
+ );
+ state = (await applyDevLogEntries(state, [e.toJson()])).state;
+ entries.add(e);
+ }
+
+ setUp(() async {
+ a = await E2eeIdentity.fromSeed(List.filled(32, 1));
+ b = await E2eeIdentity.fromSeed(List.filled(32, 2));
+ c = await E2eeIdentity.fromSeed(List.filled(32, 3));
+ state = DevLogState.empty('acct');
+ entries = [];
+ await push('add', a, a, 'mac', 10, kind: 'machine');
+ await push('add', b, b, 'phone', 20);
+ await push('add', b, b, 'pixel', 30);
+ await push('add', c, c, 'ipad', 40);
+ await push('remove', c, a, 'ipad', 50);
+ await push('remove', b, b, 'pixel', 60);
+ });
+
+ List<DevLogHistoryRow> rows({
+ List<DevLogEntry>? only,
+ List<DevLogEntry> loose = const [],
+ }) => devLogHistory(
+ only ?? entries,
+ selfPub: b64e(a.pub),
+ joinedSeq: 1,
+ pending: [b64e(b.pub)],
+ active: state.active,
+ loose: loose,
+ );
+
+ test('is newest first and tells each operation apart', () {
+ expect(
+ [for (final r in rows()) '${r.seq}:${r.op}'],
+ [
+ '6:signedOut',
+ '5:removed',
+ '4:added',
+ '3:renamed',
+ '2:added',
+ '1:added',
+ ],
+ );
+ });
+
+ test(
+ 'names who removed a key that is gone, and the old label of a rename',
+ () {
+ final r = rows();
+ expect(r[1].by?.label, 'mac');
+ expect(r[1].active, isFalse);
+ expect(r[3].previousLabel, 'phone');
+ expect(r[3].label, 'pixel');
+ },
+ );
+
+ test('flags this device, entries after joining and pending', () {
+ final r = rows();
+ expect(r[5].thisDevice, isTrue);
+ expect(r[5].afterJoin, isFalse);
+ expect(r[4].afterJoin, isTrue);
+ expect(r[4].pending, isTrue);
+ });
+
+ test(
+ 'marks loose removals as applied while frozen and does not duplicate',
+ () {
+ final out = rows(
+ only: entries.sublist(0, 4),
+ loose: [entries[4], entries[4]],
+ );
+ expect(out.first.whileFrozen, isTrue);
+ expect(out, hasLength(5));
+ },
+ );
+
+ test('reads the rows the daemon sends', () {
+ final h = DeviceLogHistory.fromJson({
+ 'complete': false,
+ 'frozen': null,
+ 'rows': [
+ {
+ 'seq': 3,
+ 'op': 'removed',
+ 'pub': 'p',
+ 'kind': 'machine',
+ 'machineId': 'm',
+ 'label': 'box',
+ 'fingerprint': 'AAAA',
+ 'by': {'pub': 'q', 'label': 'mac', 'fingerprint': 'BBBB'},
+ 'at': 5,
+ 'thisDevice': false,
+ 'afterJoin': true,
+ 'pending': false,
+ 'active': false,
+ 'whileFrozen': true,
+ },
+ 'junk',
+ ],
+ })!;
+ expect(h.complete, isFalse);
+ expect(h.rows.single.by?.label, 'mac');
+ expect(h.rows.single.whileFrozen, isTrue);
+ expect(DeviceLogHistory.fromJson('x'), isNull);
+ });
+
+ group('copy', () {
+ DeviceRemovalNotice notice({
+ String signerLabel = 'Mac',
+ bool pending = false,
+ bool self = false,
+ String label = 'iPad',
+ }) => DeviceRemovalNotice(
+ pub: 'p',
+ label: label,
+ kind: 'viewer',
+ fingerprint: 'AAAA',
+ signer: 'q',
+ signerLabel: signerLabel,
+ signerFingerprint: 'E2FB·0DF5·5FD8·E6C7',
+ signerPending: pending,
+ selfRemoved: self,
+ at: 0,
+ );
+
+ test('removal notices', () {
+ expect(notice().title, 'Device removed');
+ expect(notice().sentence, 'iPad was removed from your account by Mac.');
+ expect(
+ notice(signerLabel: '').sentence,
+ 'iPad was removed from your account by another device.',
+ );
+ expect(notice(self: true).title, 'Device signed out');
+ expect(notice(self: true).sentence, 'iPad signed out of your account.');
+ expect(notice(self: true, pending: true).red, isFalse);
+ });
+
+ test('a red notice shows two fingerprint groups', () {
+ final n = notice(pending: true);
+ expect(n.red, isTrue);
+ expect(n.title, 'Removed by a new device');
+ expect(
+ n.sentence,
+ 'iPad was removed from your account by a new device you haven’t looked at (Mac · E2FB·0DF5…).',
+ );
+ expect(
+ notice(pending: true, signerLabel: '').sentence,
+ contains('(another device · E2FB·0DF5…)'),
+ );
+ });
+
+ DeviceLogDeparted departed({
+ String removedBy = 'q',
+ String removedByLabel = 'Mac',
+ bool self = false,
+ }) => DeviceLogDeparted(
+ pub: 'p',
+ label: 'iPad',
+ kind: 'viewer',
+ machineId: '',
+ fingerprint: 'AAAA',
+ addedAt: 0,
+ removedAt: 0,
+ removedBy: removedBy,
+ removedByLabel: removedByLabel,
+ selfRemoved: self,
+ );
+
+ test('a departed key names its remover only when something removed it', () {
+ const head = 'iPad joined your account and left before you looked.';
+ expect(departed().sentence(red: false), '$head Removed by Mac.');
+ expect(
+ departed().sentence(red: true),
+ '$head Removed by Mac, a new device you haven’t looked at.',
+ );
+ expect(
+ departed(removedByLabel: '').sentence(red: false),
+ '$head Removed by another device.',
+ );
+ expect(departed(self: true).sentence(red: false), head);
+ expect(departed(removedBy: 'p').sentence(red: true), head);
+ // Taken off the list by a review of it (no signer): nothing "removed" it.
+ expect(
+ departed(removedBy: '', removedByLabel: '').sentence(red: false),
+ head,
+ );
+ expect(
+ departed(removedBy: '', removedByLabel: '').sentence(red: true),
+ head,
+ );
+ });
+
+ DevLogHistoryRow histRow(
+ String op, {
+ String label = 'Mac',
+ String? previous,
+ String? by,
+ bool frozen = false,
+ }) => DevLogHistoryRow(
+ seq: 1,
+ op: op,
+ pub: 'p',
+ kind: 'viewer',
+ machineId: '',
+ label: label,
+ previousLabel: previous,
+ fingerprint: 'AAAA',
+ by: by == null
+ ? null
+ : DevLogHistoryBy(pub: 'q', label: by, fingerprint: 'BBBB'),
+ at: 0,
+ thisDevice: false,
+ afterJoin: false,
+ pending: false,
+ active: false,
+ whileFrozen: frozen,
+ );
+
+ test('history sentences', () {
+ expect(historySentence(histRow('added')), 'Mac added');
+ expect(
+ historySentence(histRow('renamed', previous: 'Old Mac')),
+ 'Old Mac renamed to Mac',
+ );
+ expect(historySentence(histRow('renamed')), 'Mac renamed');
+ expect(
+ historySentence(histRow('removed', by: 'iPad')),
+ 'Mac removed by iPad',
+ );
+ expect(
+ historySentence(histRow('removed', by: '')),
+ 'Mac removed by another device',
+ );
+ expect(historySentence(histRow('removed')), 'Mac removed');
+ expect(historySentence(histRow('signedOut')), 'Mac signed out');
+ expect(
+ historySentence(histRow('added', frozen: true)),
+ 'Mac added · applied while the list was frozen',
+ );
+ });
+ });
+
+ group('shared vectors (cli/src/lib/e2ee/deviceHistory.vectors.json)', () {
+ final vectors = jsonDecode(
+ File('test/viewer/deviceHistory.vectors.json').readAsStringSync(),
+ ) as Map<String, dynamic>;
+ final pubs = (vectors['pubs'] as Map).cast<String, String>();
+ final all = [
+ for (final e in vectors['entries'] as List) DevLogEntry.parse(e)!,
+ ];
+
+ for (final c in (vectors['history'] as List).cast<Map<String, dynamic>>()) {
+ test('history: ${c['name']}', () async {
+ final state = (await applyDevLogEntries(
+ DevLogState.empty(vectors['acct'] as String),
+ [for (final e in all) e.toJson()],
+ )).state;
+ List<DevLogEntry> pick(List<dynamic> seqs) => [
+ for (final n in seqs) all[(n as int) - 1],
+ ];
+ final rows = devLogHistory(
+ pick(c['seqs'] as List),
+ selfPub: pubs[c['self']]!,
+ joinedSeq: c['joinedSeq'] as int?,
+ pending: [for (final k in c['pending'] as List) pubs[k]!],
+ active: state.active,
+ loose: pick(c['loose'] as List),
+ );
+ final want = (c['rows'] as List).cast<Map<String, dynamic>>();
+ expect(rows, hasLength(want.length));
+ for (var i = 0; i < want.length; i++) {
+ final r = rows[i], w = want[i];
+ expect(
+ {
+ 'seq': r.seq,
+ 'op': r.op,
+ 'label': r.label,
+ 'kind': r.kind,
+ 'previousLabel': r.previousLabel,
+ 'by': r.by?.label,
+ 'thisDevice': r.thisDevice,
+ 'afterJoin': r.afterJoin,
+ 'pending': r.pending,
+ 'active': r.active,
+ 'whileFrozen': r.whileFrozen,
+ },
+ {
+ 'seq': w['seq'],
+ 'op': w['op'],
+ 'label': w['label'],
+ 'kind': w['kind'],
+ 'previousLabel': w['previousLabel'],
+ 'by': w['by'],
+ 'thisDevice': w['thisDevice'],
+ 'afterJoin': w['afterJoin'],
+ 'pending': w['pending'],
+ 'active': w['active'],
+ 'whileFrozen': w['whileFrozen'],
+ },
+ );
+ }
+ });
+ }
+
+ for (final c
+ in (vectors['divergence'] as List).cast<Map<String, dynamic>>()) {
+ test('divergence: ${c['name']}', () async {
+ final acct = vectors['acct'] as String;
+ final mine = (await applyDevLogEntries(DevLogState.empty(acct), [
+ for (final e in vectors['entries'] as List) e,
+ ])).state;
+ final other = (await applyDevLogEntries(DevLogState.empty(acct), [
+ for (final e
+ in (c['log'] == 'fork' ? vectors['fork'] : vectors['entries'])
+ as List)
+ e,
+ ])).state;
+ final from = c['from'] as int, to = c['to'] as int;
+ final hashes = [
+ for (var seq = from; seq <= to; seq++)
+ {'seq': seq, 'hash': other.hashes[seq - 1]},
+ ];
+ Object? theirs = {
+ 'head': {'seq': to, 'hash': other.hashes[to - 1]},
+ 'hashes': hashes,
+ };
+ switch (c['tamper']) {
+ case 'gap':
+ theirs = {
+ 'head': {'seq': to, 'hash': other.hashes[to - 1]},
+ 'hashes': [
+ for (final h in hashes)
+ if (h['seq'] != 2) h,
+ ],
+ };
+ case 'head':
+ theirs = {
+ 'head': {'seq': to, 'hash': 'nope'},
+ 'hashes': hashes,
+ };
+ case 'junk':
+ theirs = {
+ 'head': {'seq': to, 'hash': other.hashes[to - 1]},
+ 'hashes': 'junk',
+ };
+ }
+ expect(devLogDivergence(mine, theirs), c['expect']);
+ });
+ }
+ });
+}
diff --git a/desktop/test/viewer/device_log_sync_test.dart b/desktop/test/viewer/device_log_sync_test.dart
index 947180ff9..476fd2ff1 100644
--- a/desktop/test/viewer/device_log_sync_test.dart
+++ b/desktop/test/viewer/device_log_sync_test.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/local_key_value_store.dart';
import 'package:harness/e2ee/bytes.dart';
@@ -20,13 +22,106 @@ class _Memory implements LocalKeyValueStore {
Future<void> delete(String key) async => values.remove(key);
}
+/// A store whose next write of the device log can be held mid-way, to interleave two changes of it.
+class _GatedMemory extends _Memory {
+ Completer<void>? _hold;
+ Completer<void>? _holding;
+
+ /// Hold the next device-log write; the returned future completes once a write is being held.
+ Future<void> holdNextLogWrite(Completer<void> release) {
+ _hold = release;
+ return (_holding = Completer<void>()).future;
+ }
+
+ @override
+ Future<void> write(String key, String value) async {
+ final hold = _hold;
+ if (key == 'viewer_e2ee_devlog' && hold != null) {
+ _hold = null;
+ _holding!.complete();
+ await hold.future;
+ }
+ await super.write(key, value);
+ }
+}
+
+/// A store whose writes of one key wait while [hold] is set.
+class _HeldWrites extends _Memory {
+ _HeldWrites(this.key);
+
+ final String key;
+ Completer<void>? hold;
+
+ @override
+ Future<void> write(String key, String value) async {
+ if (key == this.key) await hold?.future;
+ await super.write(key, value);
+ }
+}
+
+/// A store whose sign-in id cannot be read once [broken] is set.
+class _NoSignIn extends _Memory {
+ bool broken = false;
+
+ @override
+ Future<String?> read(String key) async {
+ if (broken && key == 'viewer_e2ee_sign_in') throw StateError('unreadable');
+ return super.read(key);
+ }
+}
+
+/// A store whose writes of the kept logs of other accounts fail after [allowed] more, once set.
+class _FailingArchive extends _Memory {
+ int? allowed;
+
+ @override
+ Future<void> write(String key, String value) async {
+ final left = allowed;
+ if (key == 'viewer_e2ee_devlog_archive' && left != null) {
+ if (left <= 0) throw StateError('disk full');
+ allowed = left - 1;
+ }
+ await super.write(key, value);
+ }
+}
+
+/// A store whose next write of the sign-in id waits for [hold], then fails.
+class _LostSignIn extends _Memory {
+ Completer<void>? hold;
+
+ @override
+ Future<void> write(String key, String value) async {
+ final h = hold;
+ if (key == 'viewer_e2ee_sign_in' && h != null) {
+ hold = null;
+ await h.future;
+ throw StateError('disk full');
+ }
+ await super.write(key, value);
+ }
+}
+
+/// Lets whatever is runnable run (crypto included), for at most [ms].
+Future<void> _settle(Future<void> f, [int ms = 300]) =>
+ Future.any([f, Future<void>.delayed(Duration(milliseconds: ms))]);
+
const _acct = 'acct-1';
final _mid2 = 'b' * 32, _mid3 = 'c' * 32;
class _Backend {
+ _Backend([this.acct = _acct]) : state = DevLogState.empty(acct);
+
+ /// The account this backend serves.
+ final String acct;
final entries = <DevLogEntry>[];
- DevLogState state = DevLogState.empty(_acct);
+ DevLogState state;
List<DevLogEntry>? lie;
+ final fetched = <int>[];
+ bool offline = false;
+
+ /// Hold the next fetch until this completes; [fetchHeld] completes once it is being held.
+ Completer<void>? holdFetch;
+ Completer<void>? fetchHeld;
Future<void> add(E2eeIdentity who, String kind, String machineId, String label) async {
final pub = b64e(who.pub);
@@ -52,11 +147,19 @@ class _Backend {
}
Future<DeviceLogFetched?> fetch(int since) async {
+ fetched.add(since);
+ final hold = holdFetch;
+ if (hold != null) {
+ holdFetch = null;
+ fetchHeld?.complete();
+ await hold.future;
+ }
+ if (offline) return null;
final log = lie ?? entries;
final head = log.isEmpty
- ? DevLogState.empty(_acct).head
- : (await applyDevLogEntries(DevLogState.empty(_acct), [for (final e in log) e.toJson()])).state.head;
- return (acct: _acct, head: head, entries: [for (final e in log) if (e.seq > since) e.toJson()]);
+ ? DevLogState.empty(acct).head
+ : (await applyDevLogEntries(DevLogState.empty(acct), [for (final e in log) e.toJson()])).state.head;
+ return (acct: acct, head: head, entries: [for (final e in log) if (e.seq > since) e.toJson()]);
}
Future<DeviceLogAppendAnswer?> append(DevLogEntry entry) async {
@@ -76,6 +179,7 @@ void main() {
late _Backend backend;
late ViewerKeyStore keys;
late List<DevLogMember> announced;
+ late List<DeviceRemovalNotice> removed;
late int signedOut;
late E2eeIdentity box2, box3;
@@ -85,6 +189,7 @@ void main() {
append: backend.append,
label: () => 'my-phone',
onAnnounce: announced.add,
+ onRemoved: removed.add,
onSignedOut: () async => signedOut++,
now: () => 5000,
sleep: (_) async {},
@@ -94,6 +199,7 @@ void main() {
backend = _Backend();
keys = ViewerKeyStore(storage: _Memory());
announced = [];
+ removed = [];
signedOut = 0;
box2 = await E2eeIdentity.fromSeed(List.filled(32, 2));
box3 = await E2eeIdentity.fromSeed(List.filled(32, 3));
@@ -237,6 +343,1716 @@ void main() {
await log.refresh().timeout(const Duration(seconds: 5));
});
+ group('what is new, and what stays visible', () {
+ test('a key the pins and roster held before the log read that adds it is still announced and pending', () async {
+ final log = makeLog();
+ await log.register();
+ await keys.pin(_mid3, box3.pub, label: 'box3'); // the trust group got there first
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['box3']);
+ final listing = await log.list();
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.members.firstWhere((r) => r.member.pub == b64e(box3.pub)).pending, isTrue);
+ });
+
+ test('a first read announces nothing and reports the baseline; an empty log announces the first later device', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final log = makeLog();
+ await log.refresh();
+ expect(announced, isEmpty);
+ final listing = await log.list();
+ expect(listing.baselineSeen, isFalse);
+ expect(listing.joinedSeq, 2);
+ expect(listing.pending, isEmpty);
+
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final empty = makeLog();
+ await empty.refresh();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await empty.refresh();
+ expect(announced.map((m) => m.label), ['box2']);
+ });
+
+ test('pending survives a new instance on the same store; dismiss and seeBaseline persist', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final other = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ await backend.add(other, 'viewer', '', 'tablet');
+ await log.refresh();
+ final again = makeLog();
+ expect((await again.list()).pending, [b64e(box3.pub), b64e(other.pub)]);
+ await again.dismiss(pub: b64e(box3.pub));
+ expect((await makeLog().list()).pending, [b64e(other.pub)]);
+ expect((await again.list()).baselineSeen, isFalse);
+ await again.seeBaseline();
+ expect((await makeLog().list()).baselineSeen, isTrue);
+ await again.dismiss();
+ expect((await makeLog().list()).pending, isEmpty);
+ });
+
+ test('a file from before the joined point migrates: nothing up to notifiedUpTo is announced again', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final log = makeLog();
+ await log.register();
+ final stripped = Map<String, Object?>.from((await keys.deviceLog())! as Map)
+ ..remove('joinedSeq')
+ ..remove('preLog')
+ ..remove('pending')
+ ..remove('announced')
+ ..remove('baselineSeen');
+ await keys.writeDeviceLog(stripped);
+ await backend.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'late');
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['late']);
+ final listing = await log.list();
+ expect(listing.joinedSeq, 3);
+ expect(listing.baselineSeen, isTrue);
+ });
+
+ test('a write path keeps the marks (accept, freeze, dismiss)', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await log.dismiss(pub: 'nobody');
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh();
+ final file = (await keys.deviceLog())! as Map;
+ expect(file['joinedSeq'], 1);
+ expect(file['pending'], [b64e(box3.pub)]);
+ expect(file['baselineSeen'], isFalse);
+ expect(file['frozen'], isNotNull);
+ });
+ });
+
+ group('removal notices', () {
+ late E2eeIdentity tablet;
+ setUp(() async {
+ tablet = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ await backend.add(box3, 'machine', _mid3, 'box3'); // on the account before this app joined
+ });
+
+ Future<ViewerDeviceLog> joined() async {
+ final log = makeLog();
+ await log.register();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.refresh();
+ return log;
+ }
+
+ test('none for a removal this app signed', () async {
+ final log = await joined();
+ expect(await log.remove(b64e(box2.pub)), isNull);
+ expect(removed, isEmpty);
+ });
+
+ test('a device that removed itself signed out', () async {
+ final log = await joined();
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ await backend.removeBy(b64e(tablet.pub), tablet);
+ await log.refresh();
+ expect(removed.single.selfRemoved, isTrue);
+ expect(removed.single.label, 'tablet');
+ });
+
+ test('a removal by a trusted key is normal, naming the signer', () async {
+ final log = await joined();
+ await log.dismiss();
+ await backend.removeBy(b64e(box3.pub), box2);
+ await log.refresh();
+ expect(removed.single.signerLabel, 'box2');
+ expect(removed.single.signerPending, isFalse);
+ expect(removed.single.selfRemoved, isFalse);
+ });
+
+ test('a removal by a signer nobody looked at is red', () async {
+ final log = await joined();
+ await backend.removeBy(b64e(box3.pub), box2);
+ await log.refresh();
+ expect(removed.single.signerPending, isTrue);
+ });
+
+ test('a removal applied while frozen still says so, and is kept for the history', () async {
+ final log = await joined();
+ backend.lie = backend.entries.sublist(0, 2);
+ await log.refresh();
+ backend.lie = null;
+ await backend.removeBy(b64e(box3.pub), box2);
+ await log.refresh();
+ expect(removed.single.signerPending, isTrue);
+ expect(((await keys.deviceLog())! as Map)['looseRemoved'], hasLength(1));
+ expect((await log.history()).rows.firstWhere((r) => r.op == 'removed').whileFrozen, isTrue);
+ });
+ });
+
+ group('a fork', () {
+ test('suspends the new keys at or after the split, unpins them and keeps the rest', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ final other = _Backend();
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await other.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'evil');
+ await other.add(box3, 'machine', _mid3, 'box3');
+ Map<String, Object?> hashes(DevLogState s) => {
+ 'head': s.head.toJson(),
+ 'hashes': [for (var i = 0; i < s.hashes.length; i++) {'seq': i + 1, 'hash': s.hashes[i]}],
+ };
+ await log.heard(b64e(box2.pub), hashes(other.state));
+ expect((await log.list()).frozen?.reason, 'fork');
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ expect(await keys.peer(_mid3), isNull);
+ expect(await keys.peer(_mid2), isNotNull);
+ expect((await log.list()).members.firstWhere((r) => r.member.pub == b64e(box3.pub)).suspended, isTrue);
+ await log.rebaseline(confirm: true);
+ expect(await log.suspendedPubs(), isEmpty);
+ expect(await keys.peer(_mid3), isNotNull);
+ });
+
+ Map<String, Object?> gossipOf(DevLogState s) => {
+ 'head': s.head.toJson(),
+ 'hashes': [for (var i = 0; i < s.hashes.length; i++) {'seq': i + 1, 'hash': s.hashes[i]}],
+ };
+
+ Future<(ViewerDeviceLog, _Backend)> forkedSetup() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register(); // box2 (1), this app (2)
+ await backend.add(box3, 'machine', _mid3, 'box3'); // 3: new since joining
+ await log.refresh();
+ final other = _Backend();
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await other.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'evil');
+ await other.add(box3, 'machine', _mid3, 'box3');
+ return (log, other);
+ }
+
+ test('a log already frozen on a fork still learns the split from a machine that is ahead', () async {
+ final (log, other) = await forkedSetup();
+ backend.lie = other.entries; // same length, a different entry at 2
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'fork');
+ expect(await log.suspendedPubs(), isEmpty);
+ await other.add(await E2eeIdentity.fromSeed(List.filled(32, 7)), 'viewer', '', 'later');
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ expect(await keys.peer(_mid3), isNull);
+ });
+
+ test('a removal signed by a suspended key does not count while frozen', () async {
+ final (log, other) = await forkedSetup();
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ await backend.removeBy(b64e(box2.pub), box3); // the suspended key tries to take out a trusted machine
+ await log.refresh();
+ expect(removed, isEmpty);
+ expect((await log.list()).members.map((r) => r.member.pub), contains(b64e(box2.pub)));
+ expect(await keys.peer(_mid2), isNotNull);
+ expect(((await keys.deviceLog())! as Map)['looseRemoved'], isNull);
+ });
+
+ test('without hashes nothing is suspended', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ final other = _Backend();
+ await other.add(box3, 'machine', _mid3, 'box3');
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await other.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'x');
+ await log.heard(b64e(box2.pub), {'head': other.state.head.toJson()});
+ expect(await log.suspendedPubs(), isEmpty);
+ });
+
+ test('devLogDivergence finds the first differing position the one before confirms', () async {
+ final log = _Backend();
+ await log.add(box2, 'machine', _mid2, 'box2');
+ await log.add(box3, 'machine', _mid3, 'box3');
+ final mine = log.state;
+ Map<String, Object?> theirs(List<String> h) => {
+ 'head': {'seq': h.length, 'hash': h.last},
+ 'hashes': [for (var i = 0; i < h.length; i++) {'seq': i + 1, 'hash': h[i]}],
+ };
+ expect(devLogDivergence(mine, theirs([mine.hashes[0], 'x'])), 2);
+ expect(devLogDivergence(mine, theirs(['x', 'y'])), 1);
+ expect(devLogDivergence(mine, theirs(mine.hashes)), isNull);
+ expect(devLogDivergence(mine, null), isNull);
+ expect(devLogDivergence(mine, {'head': mine.head.toJson()}), isNull);
+ });
+
+ test('gossip carries the newest hashes', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final g = (await log.gossip())!;
+ expect((g['hashes']! as List).length, 2);
+ expect((g['hashes']! as List).last, {'seq': 2, 'hash': backend.state.head.hash});
+ });
+ });
+
+ group('history', () {
+ test('lists every entry newest first, caches, fetches only what is missing, and falls back offline', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.removeBy(b64e(box3.pub), box2);
+ final h = await log.history();
+ expect(h.complete, isTrue);
+ expect([for (final r in h.rows) '${r.seq}:${r.op}'], ['4:removed', '3:added', '2:added', '1:added']);
+ expect(h.rows.first.by?.label, 'box2');
+ expect(h.rows.first.active, isFalse);
+ expect(h.rows[2].thisDevice, isTrue);
+ backend.fetched.clear();
+ await backend.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'late');
+ await log.history();
+ expect(backend.fetched, [4, 4]);
+ backend.offline = true;
+ final fresh = makeLog();
+ final off = await fresh.history();
+ expect(off.complete, isFalse);
+ expect([for (final r in off.rows) r.seq], [5, 4, 3, 2, 1]);
+ });
+
+ test('freezes when the backend serves a different entry at a verified position', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final forged = _Backend();
+ await forged.add(box2, 'machine', _mid2, 'box2');
+ await forged.add(box3, 'machine', _mid3, 'not-me');
+ final fresh = ViewerDeviceLog(
+ keys: keys,
+ fetch: (since) async {
+ // The head is the real one; the entry served at position 2 is not what this app verified.
+ final real = (await backend.fetch(since))!;
+ return (acct: real.acct, head: real.head, entries: since < 2 ? [backend.entries[0].toJson(), forged.entries[1].toJson()] : real.entries);
+ },
+ append: backend.append,
+ label: () => 'my-phone',
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+ final h = await fresh.history();
+ expect(h.complete, isFalse);
+ expect((await fresh.list()).frozen?.reason, 'fork');
+ });
+ });
+
+ group('changes to the file never cross', () {
+ late _GatedMemory store;
+ late E2eeIdentity tablet;
+ setUp(() async {
+ store = _GatedMemory();
+ keys = ViewerKeyStore(storage: store);
+ tablet = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['box3']);
+ });
+
+ Future<void> expectSettled(ViewerDeviceLog log) async {
+ final listing = await log.list();
+ expect(listing.pending, [b64e(tablet.pub)], reason: 'box3 dismissed, tablet still new');
+ expect(((await keys.deviceLog())! as Map)['state']['head']['seq'], 4);
+ // Nothing was rolled back, so nothing is read — or announced — a second time.
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['box3', 'tablet']);
+ expect((await log.list()).frozen, isNull);
+ }
+
+ test('a dismissal that read the file before an accept wrote it does not roll the head back', () async {
+ final log = makeLog();
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ final release = Completer<void>();
+ final held = store.holdNextLogWrite(release);
+ final dismissed = log.dismiss(pub: b64e(box3.pub));
+ await held; // the dismissal has read the file and is writing it
+ final refreshed = log.refresh();
+ await _settle(refreshed);
+ release.complete();
+ await Future.wait([dismissed, refreshed]);
+ await expectSettled(log);
+ });
+
+ test('an accept that read the file before a dismissal wrote it does not undo the dismissal', () async {
+ final log = makeLog();
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ final release = Completer<void>();
+ final held = store.holdNextLogWrite(release);
+ final refreshed = log.refresh();
+ await held; // the accept of tablet is writing the file
+ final dismissed = log.dismiss(pub: b64e(box3.pub));
+ await _settle(dismissed);
+ release.complete();
+ await Future.wait([dismissed, refreshed]);
+ await expectSettled(log);
+ });
+
+ test('seeing the baseline while a peer hands over its tail keeps both', () async {
+ final log = makeLog();
+ final before = backend.state.head;
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ final release = Completer<void>();
+ final held = store.holdNextLogWrite(release);
+ final seen = log.seeBaseline();
+ await held;
+ final heard = log.heard(b64e(box2.pub), {
+ 'head': backend.state.head.toJson(),
+ 'frozen': false,
+ 'tail': [for (final e in backend.entries) if (e.seq > before.seq) e.toJson()],
+ });
+ await _settle(heard);
+ release.complete();
+ await Future.wait([seen, heard]);
+ final file = (await keys.deviceLog())! as Map;
+ expect(file['baselineSeen'], isTrue);
+ expect(file['state']['head']['seq'], 4);
+ expect(announced.map((m) => m.label), ['box3', 'tablet']);
+ });
+
+ test('a page that arrives after a peer moved the log is read again, not taken for a fork', () async {
+ final log = makeLog();
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ final viaPeer = backend.entries[3]; // tablet, seq 4
+ final other = await E2eeIdentity.fromSeed(List.filled(32, 7));
+ await backend.add(other, 'viewer', '', 'laptop'); // seq 5
+ backend
+ ..holdFetch = Completer<void>()
+ ..fetchHeld = Completer<void>();
+ final release = backend.holdFetch!;
+ final refreshed = log.refresh(); // asks for everything after seq 3
+ await backend.fetchHeld!.future;
+ final head4 = (await applyDevLogEntries(DevLogState.empty(_acct), [for (final e in backend.entries.take(4)) e.toJson()])).state.head;
+ await log.heard(b64e(box2.pub), {'head': head4.toJson(), 'frozen': false, 'tail': [viaPeer.toJson()]});
+ release.complete();
+ await refreshed;
+ final listing = await log.list();
+ expect(listing.frozen, isNull);
+ expect(((await keys.deviceLog())! as Map)['state']['head']['seq'], 5);
+ expect(announced.map((m) => m.label), ['box3', 'tablet', 'laptop']);
+ });
+ });
+
+ group('the joined point, reviews, history and dismissals', () {
+ late E2eeIdentity evil;
+ setUp(() async => evil = await E2eeIdentity.fromSeed(List.filled(32, 9)));
+
+ ViewerDeviceLog logWith(DeviceLogFetch f) => ViewerDeviceLog(
+ keys: keys,
+ fetch: f,
+ append: backend.append,
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Map<String, Object?> gossipOf(DevLogState s) => {
+ 'head': s.head.toJson(),
+ 'hashes': [for (var i = 0; i < s.hashes.length; i++) {'seq': i + 1, 'hash': s.hashes[i]}],
+ };
+
+ test('the joined point is the VERIFIED head, never the one the backend claims', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ var first = true;
+ final log = logWith((since) async {
+ final got = await backend.fetch(since);
+ if (got == null || !first) return got;
+ first = false;
+ return (acct: got.acct, head: DevLogHead(1000, 'x' * 64), entries: got.entries);
+ });
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.frozen, isNull);
+ expect(listing.joinedSeq, 2);
+ // A key forged below the claimed 1000 is still new.
+ await backend.add(evil, 'viewer', '', 'evil');
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['evil']);
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ });
+
+ test('a head that is not a position is not read at all', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = logWith((since) async {
+ final got = await backend.fetch(since);
+ return got == null ? null : (acct: got.acct, head: DevLogHead(-1, 'h'), entries: got.entries);
+ });
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.members, isEmpty);
+ // Not read at all — judged against it, a fresh file would read as rolled back and freeze.
+ expect(listing.frozen, isNull);
+ });
+
+ group('rebaseline(confirm)', () {
+ late ViewerDeviceLog log;
+ setUp(() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ log = makeLog();
+ await log.register();
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh(); // frozen (rolled back)
+ backend.lie = null;
+ });
+
+ test('a key the preview did not show is pending and announced', () async {
+ final preview = await log.rebaseline(confirm: false);
+ expect(preview, isNotNull);
+ await backend.add(evil, 'viewer', '', 'evil'); // between preview and confirm
+ expect(await log.rebaseline(confirm: true), isNotNull);
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ expect(announced.map((m) => m.label), ['evil']);
+ });
+
+ test('refuses when the backend head is no longer the one previewed', () async {
+ final preview = (await log.rebaseline(confirm: false))!;
+ await backend.add(evil, 'viewer', '', 'evil');
+ expect((await log.rebaseline(confirm: true, expectedHead: preview.head))!.logChanged, isTrue);
+ expect((await log.list()).frozen, isNotNull);
+ expect(announced, isEmpty);
+ final again = (await log.rebaseline(confirm: false))!;
+ expect((await log.rebaseline(confirm: true, expectedHead: again.head))!.logChanged, isFalse);
+ expect((await log.list()).frozen, isNull);
+ });
+ });
+
+ group('a fork does not cost the user the devices they reviewed', () {
+ late ViewerDeviceLog log;
+ late _Backend other;
+ setUp(() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ log = makeLog();
+ await log.register(); // box2 (1), this app (2)
+ await backend.add(box3, 'machine', _mid3, 'box3'); // 3: new since joining
+ await log.refresh();
+ other = _Backend();
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await other.add(evil, 'viewer', '', 'evil');
+ await other.add(box3, 'machine', _mid3, 'box3');
+ });
+
+ test('O2: a key already marked as seen is not suspended', () async {
+ await log.dismiss(pubs: [b64e(box3.pub)]);
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect((await log.list()).frozen?.reason, 'fork');
+ expect(await log.suspendedPubs(), isEmpty);
+ });
+
+ test('O2: a key let in by a review is not suspended', () async {
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh();
+ backend.lie = null;
+ await log.rebaseline(confirm: true);
+ expect((await log.list()).pending, contains(b64e(box3.pub)));
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect(await log.suspendedPubs(), isEmpty);
+ });
+
+ test('O2: a key that is new here is still suspended', () async {
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ });
+
+ test('"It\'s mine" on a suspended key lifts its suspension; a list that was merely viewed does not', () async {
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ await log.dismiss(pubs: [b64e(box3.pub)]);
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ expect((await log.list()).pending, [b64e(box3.pub)]); // still flagged
+ expect(await keys.peer(_mid3), isNull);
+ await log.dismiss(pub: b64e(box3.pub));
+ expect(await log.suspendedPubs(), isEmpty);
+ expect((await log.list()).pending, isEmpty);
+ expect(await keys.peer(_mid3), isNotNull);
+ });
+ });
+
+ test('two history() calls at once share one walk and freeze nothing', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(evil, 'viewer', '', 'evil');
+ await log.refresh();
+ // Each page takes a moment, so the two walks really are in flight together.
+ final fresh = logWith((since) async {
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ return backend.fetch(since);
+ });
+ final both = await Future.wait([fresh.history(), fresh.history()]);
+ expect((await fresh.list()).frozen, isNull);
+ expect(both[0].complete, isTrue);
+ expect([for (final r in both[1].rows) r.seq], [4, 3, 2, 1]);
+ });
+
+ test('dismiss with a list clears only what it names', () async {
+ final log = makeLog();
+ await log.register();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.refresh();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await log.dismiss(pubs: [b64e(box2.pub)]);
+ expect((await log.list()).pending, [b64e(box3.pub)]);
+ });
+
+ test('keys trusted at joining whose entry came after the joined point are in the baseline', () async {
+ await keys.pin(_mid2, box2.pub, label: 'box2'); // trusted before the log
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final log = makeLog();
+ await log.refresh();
+ await backend.add(box2, 'machine', _mid2, 'box2'); // seq 2 > joinedSeq 1
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.baseline.toSet(), {b64e(box2.pub), b64e(box3.pub)});
+ expect(listing.pending, isEmpty);
+ });
+
+ test('a removal is described by the label and kind the key had, not the remove entry\'s own', () async {
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.refresh();
+ await log.dismiss();
+ final lie = await signDevLogEntry(
+ nextDevLogEntry(backend.state, op: 'remove', pub: b64e(box2.pub), kind: 'viewer', machineId: '', label: 'Totally Fine', signer: b64e(box3.pub), at: 2000),
+ box3,
+ );
+ await backend._push(lie);
+ await log.refresh();
+ expect(removed.single.label, 'box2');
+ expect(removed.single.kind, 'machine');
+ final h = await log.history();
+ expect(h.rows.first.label, 'box2');
+ expect(h.rows.first.kind, 'machine');
+ });
+ });
+
+ group('a backend that moves the list under a running read', () {
+ late E2eeIdentity evil;
+ setUp(() async => evil = await E2eeIdentity.fromSeed(List.filled(32, 9)));
+
+ ViewerDeviceLog logWith(DeviceLogFetch f) => ViewerDeviceLog(
+ keys: keys,
+ fetch: f,
+ append: backend.append,
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Future<void> editFile(void Function(Map<String, Object?> file) edit) async {
+ final file = Map<String, Object?>.from(await keys.deviceLog() as Map);
+ edit(file);
+ await keys.writeDeviceLog(file);
+ }
+
+ test('a backend that flips the account id and back keeps a fork\'s marks', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ var wrong = false;
+ final log = logWith((since) async {
+ if (wrong) return (acct: 'x', head: DevLogState.empty('x').head, entries: <Object?>[]);
+ return backend.fetch(since);
+ });
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await editFile((f) => f['suspended'] = [b64e(box3.pub)]);
+ expect((await log.list()).pending, [b64e(box3.pub)]);
+ wrong = true;
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'invalid');
+ wrong = false;
+ await log.refresh(); // the real log again
+ final listing = await log.list();
+ expect(listing.frozen?.reason, 'invalid');
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.members.firstWhere((r) => r.member.pub == b64e(box3.pub)).suspended, isTrue);
+ });
+
+ test('rebaseline: unreadable is null, a moved list is logChanged', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ backend.offline = true;
+ expect(await log.rebaseline(confirm: false), isNull);
+ backend.offline = false;
+ final preview = (await log.rebaseline(confirm: false))!;
+ expect(preview.logChanged, isFalse);
+ await backend.add(evil, 'viewer', '', 'evil');
+ final moved = await log.rebaseline(confirm: true, expectedHead: preview.head);
+ expect(moved!.logChanged, isTrue);
+ expect(moved.added, isEmpty);
+ });
+
+ test('a rebaseline during the history walk does not freeze the fresh log', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ var armed = false;
+ final alt = _Backend();
+ await alt.add(evil, 'viewer', '', 'evil');
+ await alt.add(box2, 'machine', _mid2, 'box2');
+ final log = logWith((since) async {
+ if (armed && since == 0) {
+ // The person confirms a review while this page is on its way: the file, and what the backend
+ // serves, are another list now.
+ armed = false;
+ await editFile((f) => f['state'] = alt.state.toJson());
+ backend.lie = alt.entries;
+ }
+ return backend.fetch(since);
+ });
+ await log.register();
+ armed = true;
+ final h = await log.history();
+ expect((await log.list()).frozen, isNull);
+ expect(h.complete, isFalse);
+ });
+
+ test('a peer tail that arrives while the first read is still open announces nothing', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(evil, 'viewer', '', 'evil');
+ late ViewerDeviceLog log;
+ var calls = 0;
+ log = logWith((since) async {
+ calls++;
+ final got = await backend.fetch(since);
+ // The first read comes in one entry at a time; between its pages a peer hands over the rest.
+ if (calls == 1) return (acct: got!.acct, head: got.head, entries: got.entries.sublist(0, 1));
+ if (calls == 2) {
+ await log.heard(b64e(box2.pub), {
+ 'head': backend.state.head.toJson(),
+ 'frozen': false,
+ 'tail': [for (final e in backend.entries.skip(1)) e.toJson()],
+ });
+ }
+ return got;
+ });
+ await log.refresh();
+ expect(announced, isEmpty);
+ expect((await log.list()).joinedSeq, 3);
+ expect((await keys.deviceLog() as Map).containsKey('joining'), isFalse);
+ await backend.add(await E2eeIdentity.fromSeed(List.filled(32, 7)), 'viewer', '', 'later');
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['later']);
+ });
+ });
+
+ group('signing in again, and to other accounts', () {
+ late E2eeIdentity evil, phone;
+ setUp(() async {
+ evil = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ phone = await E2eeIdentity.fromSeed(List.filled(32, 7));
+ });
+
+ /// A log whose backend is whichever [at] says now — another account's, after a sign-in.
+ ViewerDeviceLog at(_Backend Function() at, {DeviceLogFetch? fetch}) => ViewerDeviceLog(
+ keys: keys,
+ fetch: fetch ?? (since) => at().fetch(since),
+ append: (e) => at().append(e),
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Future<Map<Object?, Object?>> file() async => await keys.deviceLog() as Map;
+
+ /// A fork suspended box3, still pending, and the list is frozen on it.
+ Future<void> forked(ViewerDeviceLog log) async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ final f = Map<String, Object?>.from(await file());
+ f['suspended'] = [b64e(box3.pub)];
+ f['frozen'] = {'reason': 'fork', 'at': 1, 'lastGoodHead': backend.state.head.toJson()};
+ await keys.writeDeviceLog(f);
+ await keys.unlink(_mid3); // as the suspension does
+ }
+
+ Future<Set<String>> rosterPubs() async => {for (final m in GroupRoster.parse(await keys.groupRoster()).members) m.pub};
+
+ test('signing in again by hand to the same account keeps the list and every mark on it', () async {
+ var current = backend;
+ final log = at(() => current);
+ await forked(log);
+ final owner = (await file())['owner'];
+ await log.register(freshSignIn: true);
+ final listing = await log.list();
+ expect((await file())['owner'], isNot(owner));
+ expect(listing.frozen?.reason, 'fork');
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.joinedSeq, 1);
+ // That sign-in is the file's now: the backend saying another account freezes, never starts over.
+ final f = Map<String, Object?>.from(await file())..['frozen'] = null;
+ await keys.writeDeviceLog(f);
+ current = _Backend('x');
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'invalid');
+ expect((await log.list()).suspended, [b64e(box3.pub)]);
+ });
+
+ test('a sign-in the backend forced, onto a made-up account and back, gives the first account its marks back', () async {
+ var current = backend;
+ final log = at(() => current);
+ await forked(log);
+ final fake = _Backend('x');
+ await fake.add(box3, 'machine', _mid3, 'box3');
+ await fake.add(evil, 'viewer', '', 'evil');
+ current = fake;
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], 'x');
+ expect(await rosterPubs(), contains(b64e(evil.pub)));
+ expect(await keys.peer(_mid3), isNull);
+ expect(await log.suspendedPubs(), contains(b64e(box3.pub)));
+ current = backend;
+ await log.register(freshSignIn: true);
+ final listing = await log.list();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(listing.frozen?.reason, 'fork');
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.joinedSeq, 1);
+ });
+
+ test('a sign-in by hand to another account starts it fresh, and switching back restores the first', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ expect((await log.list()).pending, [b64e(box3.pub)]);
+ final other = _Backend('acct-2');
+ await other.add(phone, 'viewer', '', 'theirs');
+ current = other;
+ await log.register(freshSignIn: true);
+ var listing = await log.list();
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect(listing.pending, isEmpty);
+ expect(listing.baselineSeen, isFalse);
+ current = backend;
+ await log.register(freshSignIn: true);
+ listing = await log.list();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(announced.map((m) => m.label), ['box3']);
+ });
+
+ test('only the newest few other accounts are kept', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ for (var i = 0; i < 5; i++) {
+ current = _Backend('acct-b$i');
+ await log.register(freshSignIn: true);
+ }
+ expect((await keys.deviceLogArchive()).keys, ['acct-b0', 'acct-b1', 'acct-b2', 'acct-b3']);
+ });
+
+ test('a session from before sign-in ids takes the list over but never starts it over', () async {
+ var current = backend;
+ final log = at(() => current);
+ await forked(log);
+ await keys.writeSignInEpoch('');
+ final restarted = at(() => current);
+ current = _Backend('x');
+ await restarted.refresh();
+ final listing = await restarted.list();
+ expect(listing.frozen?.reason, 'fork');
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(await keys.signInEpoch(), startsWith('adopted:'));
+ current = backend;
+ await restarted.refresh();
+ expect((await file())['owner'], await keys.signInEpoch());
+ });
+
+ test('a file from before it recorded its sign-in starts over for a sign-in by hand to another account', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register();
+ final f = Map<String, Object?>.from(await file())
+ ..remove('owner')
+ ..['pending'] = ['x'];
+ await keys.writeDeviceLog(f);
+ current = _Backend('acct-2');
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await log.list()).pending, isEmpty);
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ });
+
+ test('no sign-in id at hand (the store cannot be read) never starts the list over', () async {
+ final store = _NoSignIn();
+ keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await forked(log);
+ store.broken = true;
+ final restarted = at(() => current);
+ current = _Backend('x');
+ await restarted.refresh();
+ final listing = await restarted.list();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.joinedSeq, 1);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ });
+
+ test('a kept list is restored only for the account it is the list of', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ // A kept file filed under another account's id (a damaged archive) whose fork suspended evil.
+ final kept = Map<String, Object?>.from(await file())
+ ..['suspended'] = [b64e(evil.pub)]
+ ..['pending'] = <String>[];
+ await keys.writeDeviceLogArchive({'acct-2': kept});
+ expect(await log.suspendedPubs(), contains(b64e(evil.pub)));
+ current = _Backend('acct-2');
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await log.list()).frozen, isNull);
+ });
+
+ test('a read on its way when the person signs in judges by that sign-in', () async {
+ final store = _HeldWrites('viewer_e2ee_sign_in');
+ keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ final other = _Backend('acct-2');
+ current = other;
+ other.holdFetch = Completer<void>();
+ other.fetchHeld = Completer<void>();
+ final release = other.holdFetch!;
+ final reading = log.refresh();
+ await other.fetchHeld!.future;
+ // The new sign-in is not on disk yet when that read lands.
+ final saved = store.hold = Completer<void>();
+ final signingIn = log.register(freshSignIn: true);
+ release.complete();
+ await reading;
+ saved.complete();
+ await signingIn;
+ expect((await log.list()).frozen, isNull);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ // The account left is kept as it was — not frozen by a read judged by the old sign-in.
+ expect(((await keys.deviceLogArchive())[_acct] as Map)['frozen'], isNull);
+ });
+
+ test('removed by a new key, signed in again to the same account: the key is still new', () async {
+ final log = at(() => backend);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(evil, 'viewer', '', 'evil');
+ await log.refresh();
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ final me = await keys.identity();
+ await backend.removeBy(b64e(me.pub), evil);
+ await log.refresh();
+ expect(signedOut, 1);
+ await keys.forgetIdentity(); // what the app does on being signed out
+ await log.register(freshSignIn: true);
+ final listing = await log.list();
+ expect(listing.pending, [b64e(evil.pub)]);
+ expect(listing.joinedSeq, 1);
+ expect(backend.state.active[b64e((await keys.identity()).pub)], isNotNull);
+ });
+
+ test('a first read the backend cuts short ends the joining: what it held back is news', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(evil, 'viewer', '', 'evil');
+ var calls = 0;
+ final log = at(() => backend, fetch: (since) async {
+ calls++;
+ final got = await backend.fetch(since);
+ if (calls == 1) return (acct: got!.acct, head: got.head, entries: got.entries.sublist(0, 1));
+ if (calls == 2) return null; // the link drops
+ return got;
+ });
+ await log.refresh();
+ expect((await file()).containsKey('joining'), isFalse);
+ await log.heard(b64e(box2.pub), {
+ 'head': backend.state.head.toJson(),
+ 'frozen': false,
+ 'tail': [for (final e in backend.entries.skip(1)) e.toJson()],
+ });
+ expect(announced.map((m) => m.label), ['box3', 'evil']);
+ final listing = await log.list();
+ expect(listing.joinedSeq, 1);
+ expect(listing.pending, [b64e(box3.pub), b64e(evil.pub)]);
+ });
+
+ test('"Got it" on the already-on-your-account list ends the joining', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(evil, 'viewer', '', 'evil');
+ late ViewerDeviceLog log;
+ var calls = 0;
+ log = at(() => backend, fetch: (since) async {
+ calls++;
+ final got = await backend.fetch(since);
+ if (calls == 1) return (acct: got!.acct, head: got.head, entries: got.entries.sublist(0, 1));
+ if (calls == 2) await log.seeBaseline();
+ return got;
+ });
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['evil']);
+ final listing = await log.list();
+ expect(listing.pending, [b64e(evil.pub)]);
+ expect(listing.baselineSeen, isTrue);
+ });
+
+ test('a key taken into an acknowledged already-on-your-account list shows that list again', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(evil, 'viewer', '', 'evil');
+ var calls = 0;
+ final log = at(() => backend, fetch: (since) async {
+ calls++;
+ final got = await backend.fetch(since);
+ if (calls == 1) return (acct: got!.acct, head: got.head, entries: got.entries.sublist(0, 1));
+ if (calls == 2) {
+ // Acknowledged by a client that did not end the joining.
+ await keys.writeDeviceLog(Map<String, Object?>.from(await file())..['baselineSeen'] = true);
+ }
+ return got;
+ });
+ await log.refresh();
+ expect(announced, isEmpty);
+ final listing = await log.list();
+ expect(listing.baselineSeen, isFalse);
+ expect(listing.baseline, contains(b64e(evil.pub)));
+ });
+ });
+
+ group('departed keys, and lists kept across sign-ins', () {
+ late E2eeIdentity evil, phone;
+ setUp(() async {
+ evil = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ phone = await E2eeIdentity.fromSeed(List.filled(32, 7));
+ });
+
+ /// A log whose backend is whichever [at] says now — another account's, after a sign-in.
+ ViewerDeviceLog at(_Backend Function() at, {int now = 5000}) => ViewerDeviceLog(
+ keys: keys,
+ fetch: (since) => at().fetch(since),
+ append: (e) => at().append(e),
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => now,
+ sleep: (_) async {},
+ );
+
+ Future<Map<Object?, Object?>> file() async => await keys.deviceLog() as Map;
+
+ group('a new key that leaves before anyone looked stays flagged', () {
+ late ViewerDeviceLog log;
+ setUp(() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ log = makeLog();
+ await log.register(); // box2 (1), this app (2)
+ await backend.add(evil, 'viewer', '', 'evil'); // 3: new, pending
+ await log.refresh();
+ });
+ Future<List<String>> departed(ViewerDeviceLog l) async => [for (final d in (await l.list()).departed) d.pub];
+
+ test('removed by itself: survives a new instance, keeps its history rows new, goes on dismiss', () async {
+ await backend.removeBy(b64e(evil.pub), evil);
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.pending, isEmpty);
+ final d = listing.departed.single;
+ expect([d.pub, d.label, d.kind, d.addedAt, d.removedAt, d.removedBy, d.selfRemoved],
+ [b64e(evil.pub), 'evil', 'viewer', 1000, 2000, b64e(evil.pub), true]);
+ expect(d.fingerprint, fingerprint(evil.pub));
+ final again = makeLog();
+ expect(await departed(again), [b64e(evil.pub)]);
+ final rows = (await again.history()).rows.where((r) => r.pub == b64e(evil.pub));
+ expect([for (final r in rows) (r.op, r.pending)], [('signedOut', true), ('added', true)]);
+ await again.dismiss(pub: b64e(evil.pub));
+ expect(await departed(again), isEmpty);
+ expect((await again.history()).rows.any((r) => r.pending), isFalse);
+ });
+
+ test('removed by another key: says by whom', () async {
+ await backend.removeBy(b64e(evil.pub), box2);
+ await log.refresh();
+ final d = (await log.list()).departed.single;
+ expect([d.removedBy, d.removedByLabel, d.selfRemoved], [b64e(box2.pub), 'box2', false]);
+ });
+
+ test('added and removed within one page: announced, and departed', () async {
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.removeBy(b64e(phone.pub), phone);
+ await log.refresh();
+ expect(announced.map((m) => m.label), contains('phone'));
+ expect(await departed(log), [b64e(phone.pub)]);
+ });
+
+ test('removed while the list is frozen: departed too', () async {
+ final f = Map<String, Object?>.from(await file());
+ f['frozen'] = {'reason': 'fork', 'at': 1, 'lastGoodHead': backend.state.head.toJson()};
+ await keys.writeDeviceLog(f);
+ await backend.removeBy(b64e(evil.pub), box2);
+ await log.refresh();
+ expect((await file())['looseRemoved'], hasLength(1));
+ expect(await departed(log), [b64e(evil.pub)]);
+ });
+
+ test('a key already marked as seen is not departed', () async {
+ await log.dismiss(pub: b64e(evil.pub));
+ await backend.removeBy(b64e(evil.pub), evil);
+ await log.refresh();
+ expect(await departed(log), isEmpty);
+ });
+
+ test('clears for its own pub, a list naming it, or every one — never for another key', () async {
+ await backend.removeBy(b64e(evil.pub), evil);
+ await log.refresh();
+ await log.seeBaseline();
+ await log.dismiss(pubs: [b64e(box2.pub)]);
+ await log.dismiss(pub: b64e(box2.pub));
+ expect(await departed(log), [b64e(evil.pub)]);
+ await log.dismiss(pubs: [b64e(evil.pub)]);
+ expect(await departed(log), isEmpty);
+ final f = Map<String, Object?>.from(await file())..['departed'] = [
+ {'pub': 'k', 'label': 'x', 'kind': 'viewer', 'machineId': '', 'fingerprint': 'F', 'addedAt': 1,
+ 'removedAt': 2, 'removedBy': 'k', 'removedByLabel': '', 'selfRemoved': true},
+ {'pub': 'junk', 'kind': 'evil'},
+ {'pub': 'odd', 'label': 'x', 'kind': 'evil', 'machineId': '', 'fingerprint': 'F', 'addedAt': 1,
+ 'removedAt': 2, 'removedBy': 'odd', 'removedByLabel': '', 'selfRemoved': true},
+ ];
+ await keys.writeDeviceLog(f);
+ expect(await departed(log), ['k']);
+ await log.dismiss();
+ expect(await departed(log), isEmpty);
+ });
+
+ test('kept up to the cap, the oldest going first', () async {
+ for (var i = 40; i < 40 + 33; i++) {
+ final k = await E2eeIdentity.fromSeed(List.filled(32, i));
+ await backend.add(k, 'viewer', '', 'k$i');
+ await backend.removeBy(b64e(k.pub), k);
+ }
+ await log.refresh();
+ final d = (await log.list()).departed;
+ expect(d, hasLength(32));
+ expect(d.first.label, 'k41');
+ expect(d.last.label, 'k72');
+ });
+ });
+
+ group('a sign-in by hand starts the list over only shortly after it was made', () {
+ const now = 30 * 60 * 1000;
+
+ /// Signed in on [backend] (box3 new there), then the sign-in [epoch] (not yet the list's), whose
+ /// first read — at [now] — is of another account.
+ Future<void> later(String epoch) async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ expect(await keys.signInEpoch(), matches(RegExp(r'^[0-9a-f]{32}@5000$')));
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await keys.writeSignInEpoch(epoch);
+ final restarted = at(() => current, now: now);
+ current = _Backend('acct-2');
+ await restarted.refresh();
+ }
+
+ test('one made over 10 minutes ago, with no read of its account yet, only freezes', () async {
+ await later('${'f' * 32}@${now - 11 * 60 * 1000}');
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ expect((await file())['pending'], [b64e(box3.pub)]);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ });
+
+ test('one with no time recorded only freezes', () async {
+ await later('f' * 32);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ });
+
+ test('one made just now starts it over', () async {
+ await later('${'f' * 32}@${now - 9 * 60 * 1000}');
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ });
+ });
+
+ test('a restore that fails half way has the kept list live first: its marks are never lost', () async {
+ final store = _FailingArchive();
+ keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ current = _Backend('acct-2');
+ await log.register(freshSignIn: true);
+ store.allowed = 1; // the list left is kept; taking the restored one out of the archive fails
+ current = backend;
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['pending'], [b64e(box3.pub)]);
+ expect((await keys.deviceLogArchive()).keys, contains(_acct));
+ });
+
+ test('gossip waits for the new sign-in\'s first read', () async {
+ final log = at(() => backend);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ final other = _Backend();
+ await other.add(evil, 'viewer', '', 'evil');
+ await other.add(phone, 'viewer', '', 'phone'); // another entry at the same position: a fork
+ final hashes = [for (var i = 0; i < other.state.hashes.length; i++) {'seq': i + 1, 'hash': other.state.hashes[i]}];
+ log.beginSignIn(fresh: true);
+ expect(await log.gossip(), isNull);
+ await log.heard(b64e(box2.pub), {'head': other.state.head.toJson(), 'frozen': false, 'hashes': hashes});
+ expect((await file())['frozen'], isNull);
+ await log.register(); // same account: the list is this sign-in's now
+ expect(await log.gossip(), isNotNull);
+ await log.heard(b64e(box2.pub), {'head': other.state.head.toJson(), 'frozen': false, 'hashes': hashes});
+ expect((await file())['frozen'], containsPair('reason', 'fork'));
+ });
+
+ group('beginSignIn', () {
+ test('a read before register already judges by the new sign-in, and register mints nothing more', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ final before = await keys.signInEpoch();
+ current = _Backend('acct-2');
+ log.beginSignIn(fresh: true);
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['frozen'], isNull);
+ final minted = await keys.signInEpoch();
+ expect(minted, isNot(before));
+ await log.register();
+ expect(await keys.signInEpoch(), minted);
+ expect((await file())['owner'], minted);
+ });
+
+ test('a sign-in id that could not be kept is not judged by: no read starts the list over on it', () async {
+ final store = _LostSignIn();
+ keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ current = _Backend('acct-2');
+ final saving = store.hold = Completer<void>();
+ final registering = log.register(freshSignIn: true);
+ await _settle(Future<void>.delayed(const Duration(milliseconds: 50)));
+ saving.complete();
+ await registering;
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ });
+
+ test('a stored session mints nothing', () async {
+ final log = makeLog();
+ await log.register();
+ final before = await keys.signInEpoch();
+ log.beginSignIn(fresh: false);
+ await log.register();
+ expect(await keys.signInEpoch(), before);
+ });
+
+ test('this app\'s old key removed, read before register: no sign-out', () async {
+ final log = at(() => backend);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ final me = await keys.identity();
+ await backend.removeBy(b64e(me.pub), box2);
+ log.beginSignIn(fresh: true);
+ await log.refresh();
+ expect(signedOut, 0);
+ await log.register();
+ expect(signedOut, 0);
+ expect(backend.state.active[b64e((await keys.identity()).pub)], isNotNull);
+ });
+ });
+
+ group('a suspension kept in another account\'s list shows, and lifts, in this one', () {
+ /// On [backend] a fork suspended the machine evil; then signed in by hand to acct-2, whose log
+ /// has evil.
+ Future<ViewerDeviceLog> moved() async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(evil, 'machine', _mid3, 'evil');
+ await log.refresh();
+ final f = Map<String, Object?>.from(await file())..['suspended'] = [b64e(evil.pub)];
+ await keys.writeDeviceLog(f);
+ await keys.unlink(_mid3); // as the suspension does
+ final b = _Backend('acct-2');
+ await b.add(phone, 'viewer', '', 'phone');
+ await b.add(evil, 'machine', _mid3, 'evil');
+ current = b;
+ await log.register(freshSignIn: true);
+ return log;
+ }
+
+ test('is suspended and new in the list, never trusted', () async {
+ final log = await moved();
+ final row = (await log.list()).members.firstWhere((r) => r.member.pub == b64e(evil.pub));
+ expect([row.suspended, row.pending], [true, true]);
+ expect(await keys.peer(_mid3), isNull);
+ });
+
+ test('"It\'s mine" lifts it here and in the kept list', () async {
+ final log = await moved();
+ await log.dismiss(pub: b64e(evil.pub));
+ expect(await log.suspendedPubs(), isNot(contains(b64e(evil.pub))));
+ expect(b64e((await keys.peer(_mid3))!.pub), b64e(evil.pub));
+ });
+
+ test('a review does not lift it (it never showed it as suspended): only "It\'s mine" does', () async {
+ final log = await moved();
+ final r = await log.rebaseline(confirm: true);
+ expect(r, isNotNull);
+ expect(await log.suspendedPubs(), contains(b64e(evil.pub)));
+ expect(((await keys.deviceLogArchive())[_acct] as Map)['suspended'], [b64e(evil.pub)]);
+ final row = (await log.list()).members.firstWhere((r) => r.member.pub == b64e(evil.pub));
+ expect([row.suspended, row.pending], [true, true]);
+ expect(await keys.peer(_mid3), isNull);
+ });
+ });
+
+ test('a kept list restored is suspended where another kept list says so', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(phone, 'viewer', '', 'phone');
+ await log.refresh();
+ await log.dismiss(pub: b64e(phone.pub));
+ final b = _Backend('acct-2');
+ await b.add(phone, 'viewer', '', 'phone');
+ current = b;
+ await log.register(freshSignIn: true);
+ // A fork in acct-2 suspended phone; then back to the first account, where phone is on the list.
+ final f = Map<String, Object?>.from(await file())..['suspended'] = [b64e(phone.pub)];
+ await keys.writeDeviceLog(f);
+ current = backend;
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ final row = (await log.list()).members.firstWhere((r) => r.member.pub == b64e(phone.pub));
+ expect([row.suspended, row.pending], [true, true]);
+ });
+
+ test('a review of another account\'s list after a sign-in keeps the one it leaves', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await makeLog().register();
+ final f = Map<String, Object?>.from(await file());
+ f['state'] = {...(f['state'] as Map).cast<String, Object?>(), 'acct': 'old'};
+ f['suspended'] = ['k'];
+ await keys.writeDeviceLog(f);
+ await keys.writeSignInEpoch('f' * 32); // signed in again, long ago: the list is not its yet
+ final log = makeLog();
+ final r = await log.rebaseline(confirm: true);
+ expect(r!.otherAccount, isFalse);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['owner'], 'f' * 32);
+ expect((await keys.deviceLogArchive()).keys, ['old']);
+ });
+
+ group('another account\'s list under the sign-in the live list belongs to', () {
+ /// Signed in to the first account, a new key K pending; the backend then serves an empty
+ /// "acct-2" under the same sign-in.
+ Future<ViewerDeviceLog> switched([_Memory? store]) async {
+ if (store != null) keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(evil, 'viewer', '', 'K');
+ await log.refresh();
+ expect((await file())['pending'], [b64e(evil.pub)]);
+ current = _Backend('acct-2');
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ announced.clear();
+ return log;
+ }
+
+ test('refuses the preview and the confirm (otherAccount), writing nothing', () async {
+ final store = _Memory();
+ final log = await switched(store);
+ final before = Map.of(store.values);
+ final preview = await log.rebaseline(confirm: false);
+ expect([preview!.otherAccount, preview.logChanged, preview.added, preview.removed], [true, false, isEmpty, isEmpty]);
+ expect((await log.rebaseline(confirm: true))!.otherAccount, isTrue);
+ expect((await log.rebaseline(confirm: true, expectedHead: _Backend('acct-2').state.head))!.otherAccount, isTrue);
+ // Said before logChanged: a confirm on another head is still about another account.
+ final stale = (await log.rebaseline(confirm: true, expectedHead: const DevLogHead(99, 'x')))!;
+ expect([stale.otherAccount, stale.logChanged], [true, false]);
+ expect(store.values, before); // nothing written: the list, its marks, trust
+ expect(await keys.deviceLogArchive(), isEmpty);
+ expect(announced, isEmpty);
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ });
+
+ test('a sign-in by hand made since goes ahead', () async {
+ await switched();
+ await keys.writeSignInEpoch('f' * 32);
+ final log = at(() => _Backend('acct-2'));
+ final r = await log.rebaseline(confirm: true);
+ expect(r!.otherAccount, isFalse);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ });
+
+ test('a list stamped by a sign-in, then this app taken over by an adopted one: neither goes ahead', () async {
+ final store = _Memory();
+ await switched(store);
+ expect((await file())['owner'], isNotNull);
+ await keys.writeSignInEpoch('adopted:x'); // a session taken over (an older version refreshed the token)
+ final log = at(() => _Backend('acct-2'));
+ final before = Map.of(store.values);
+ expect((await log.rebaseline(confirm: false))!.otherAccount, isTrue);
+ expect((await log.rebaseline(confirm: true))!.otherAccount, isTrue);
+ expect(store.values, before);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ });
+
+ /// A list no sign-in stamped yet (written before sign-in ids existed, or by an older version after
+ /// a downgrade) on the first account with K pending, under [epoch] (made long ago); the backend
+ /// then serves an empty "acct-2".
+ Future<ViewerDeviceLog> unstamped(_Memory store, String epoch) async {
+ keys = ViewerKeyStore(storage: store);
+ await keys.writeSignInEpoch(epoch);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register();
+ await backend.add(evil, 'viewer', '', 'K');
+ await log.refresh();
+ await keys.writeDeviceLog(Map<String, Object?>.from(await file())..remove('owner'));
+ current = _Backend('acct-2');
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ expect((await file())['pending'], [b64e(evil.pub)]);
+ expect((await file()).containsKey('owner'), isFalse);
+ announced.clear();
+ return log;
+ }
+
+ test('an unstamped list under an adopted sign-in (the session it was written under) refuses too', () async {
+ final store = _Memory();
+ final log = await unstamped(store, 'adopted:a');
+ final before = Map.of(store.values);
+ expect((await log.rebaseline(confirm: false))!.otherAccount, isTrue);
+ expect((await log.rebaseline(confirm: true))!.otherAccount, isTrue);
+ expect(store.values, before);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ });
+
+ test('an unstamped list under a sign-in by hand is that sign-in moving accounts: the review goes ahead', () async {
+ final log = await unstamped(_Memory(), 'f' * 32);
+ final r = await log.rebaseline(confirm: true);
+ expect(r!.otherAccount, isFalse);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['owner'], 'f' * 32);
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ });
+ });
+ });
+
+ group('a review (rebaseline)', () {
+ late E2eeIdentity evil, phone, k5, k6, k7;
+ setUp(() async {
+ evil = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ phone = await E2eeIdentity.fromSeed(List.filled(32, 7));
+ k5 = await E2eeIdentity.fromSeed(List.filled(32, 15));
+ k6 = await E2eeIdentity.fromSeed(List.filled(32, 16));
+ k7 = await E2eeIdentity.fromSeed(List.filled(32, 17));
+ });
+
+ ViewerDeviceLog at(_Backend Function() at) => ViewerDeviceLog(
+ keys: keys,
+ fetch: (since) => at().fetch(since),
+ append: (e) => at().append(e),
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Future<Map<Object?, Object?>> file() async => await keys.deviceLog() as Map;
+ List<String> pubs(Object? list) => [for (final d in (list as List? ?? const [])) (d as Map)['pub'] as String];
+
+ test('after the list froze on another account, a key added below the old joined point is news', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.add(k5, 'viewer', '', 'k5');
+ await log.refresh();
+ expect((await file())['joinedSeq'], 4);
+ final b = _Backend('acct-2');
+ await b.add(k7, 'viewer', '', 'k7');
+ // Signed in again by hand long ago: the backend held the new account's list back past the window.
+ await keys.writeSignInEpoch('f' * 32);
+ final signedIn = at(() => current);
+ current = b;
+ await signedIn.refresh();
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ await signedIn.rebaseline(confirm: true); // "Trust again"
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['joinedSeq'], 0);
+ announced.clear();
+ await b.add(evil, 'viewer', '', 'evil'); // seq 2: below the old account's joined point
+ await signedIn.refresh();
+ expect(announced.map((m) => m.label), ['evil']);
+ final listing = await signedIn.list();
+ expect(listing.pending, contains(b64e(evil.pub)));
+ expect(listing.baseline, isNot(contains(b64e(evil.pub))));
+ });
+
+ test('after a rollback 4 → 1 it was reviewed on, a key added at 2 is news', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.add(k5, 'viewer', '', 'k5');
+ await log.refresh();
+ expect((await file())['joinedSeq'], 4);
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh();
+ expect((await file())['frozen'], containsPair('reason', 'rollback'));
+ final preview = await log.rebaseline(confirm: false);
+ expect(preview!.added, isEmpty);
+ await log.rebaseline(confirm: true, expectedHead: preview.head);
+ expect((await file())['frozen'], isNull);
+ expect((await file())['joinedSeq'], 1);
+ final rolled = _Backend();
+ await rolled.add(box2, 'machine', _mid2, 'box2'); // the same entry 1
+ await rolled.add(evil, 'viewer', '', 'evil');
+ current = rolled;
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['evil']);
+ expect((await file())['pending'], [b64e(evil.pub)]);
+ });
+
+ group('back to an account this app kept the list of', () {
+ /// The first account: phone new and pending, evil suspended by a fork, k7 joined and left before
+ /// anyone looked; then signed in by hand to acct-2; then the backend serves the first account
+ /// again with no sign-in (frozen: a review does not switch accounts — see [back]).
+ Future<ViewerDeviceLog> away() async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.add(evil, 'machine', _mid3, 'evil');
+ await backend.add(k7, 'viewer', '', 'k7');
+ await backend.removeBy(b64e(k7.pub), box2);
+ await log.refresh();
+ final f = Map<String, Object?>.from(await file())..['suspended'] = [b64e(evil.pub)];
+ await keys.writeDeviceLog(f);
+ await keys.unlink(_mid3); // as the suspension does
+ final b = _Backend('acct-2');
+ await b.add(k5, 'viewer', '', 'k5');
+ current = b;
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ current = backend; // no sign-in: the backend says the first account
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ announced.clear();
+ return log;
+ }
+
+ /// …then signed in again by hand (long ago: the list froze rather than started over) — the only
+ /// way back to the first account.
+ Future<ViewerDeviceLog> back() async {
+ await away();
+ await keys.writeSignInEpoch('e' * 32);
+ final log = at(() => backend);
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ return log;
+ }
+
+ test('without a sign-in, neither the preview nor "Trust again" goes back to it', () async {
+ final log = await away();
+ final before = '${await keys.deviceLog()}';
+ expect((await log.rebaseline(confirm: false))!.otherAccount, isTrue);
+ expect((await log.rebaseline(confirm: true))!.otherAccount, isTrue);
+ expect('${await keys.deviceLog()}', before);
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ expect(announced, isEmpty);
+ expect(await keys.peer(_mid3), isNull);
+ });
+
+ Future<void> wentOn(ViewerDeviceLog log) async {
+ final f = await file();
+ expect((f['state'] as Map)['acct'], _acct);
+ expect(f['frozen'], isNull);
+ expect(f['pending'], containsAll([b64e(phone.pub), b64e(evil.pub)]));
+ expect(f['suspended'], [b64e(evil.pub)]);
+ expect(pubs(f['departed']), [b64e(k7.pub)]);
+ expect(announced, isEmpty);
+ expect(await keys.peer(_mid3), isNull);
+ final row = (await log.list()).members.firstWhere((r) => r.member.pub == b64e(evil.pub));
+ expect([row.suspended, row.pending], [true, true]);
+ expect((await keys.deviceLogArchive()).keys, isNot(contains(_acct)));
+ }
+
+ test('the preview compares against the kept list, not the account being left', () async {
+ final log = await back();
+ final preview = await log.rebaseline(confirm: false);
+ expect(preview!.added, isEmpty);
+ expect(preview.removed, isEmpty);
+ });
+
+ test('"Trust again" goes on from its marks: pending, departed, suspended, nothing re-announced', () async {
+ final log = await back();
+ await log.rebaseline(confirm: true);
+ await wentOn(log);
+ expect((await file())['owner'], 'e' * 32);
+ expect((await keys.deviceLogArchive()).keys, ['acct-2']);
+ });
+
+ test('…even when keeping the account left pushes it out of the archive', () async {
+ final log = await back();
+ final live = Map<String, Object?>.from(await file());
+ final all = await keys.deviceLogArchive();
+ for (final acct in ['x1', 'x2', 'x3']) {
+ all[acct] = {...live, 'state': {...(live['state'] as Map).cast<String, Object?>(), 'acct': acct}};
+ }
+ await keys.writeDeviceLogArchive(all);
+ await log.rebaseline(confirm: true);
+ await wentOn(log);
+ });
+ });
+
+ group('what the reviewed list took out', () {
+ late ViewerDeviceLog log;
+ setUp(() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(k5, 'viewer', '', 'k5');
+ log = makeLog();
+ await log.register(); // this app: 3
+ await backend.add(phone, 'viewer', '', 'phone'); // 4: new, pending
+ await log.refresh();
+ expect((await file())['pending'], [b64e(phone.pub)]);
+ });
+
+ Future<void> freeze(int keep) async {
+ backend.lie = backend.entries.sublist(0, keep);
+ await log.refresh();
+ expect((await file())['frozen'], containsPair('reason', 'rollback'));
+ backend.lie = null;
+ }
+
+ test('a pending key the reviewed list does not have stays flagged as departed', () async {
+ backend.lie = backend.entries.sublist(0, 3);
+ await log.refresh();
+ await log.rebaseline(confirm: true);
+ expect((await file())['pending'], isEmpty);
+ final d = (await log.list()).departed.single;
+ expect([d.pub, d.label, d.removedBy, d.selfRemoved], [b64e(phone.pub), 'phone', '', false]);
+ });
+
+ test('a pending key removed while frozen is departed, with who removed it', () async {
+ await freeze(3);
+ await backend.removeBy(b64e(phone.pub), box2);
+ await log.rebaseline(confirm: true);
+ final d = (await log.list()).departed.single;
+ expect([d.pub, d.removedBy, d.removedByLabel], [b64e(phone.pub), b64e(box2.pub), 'box2']);
+ });
+
+ test('a key added and removed while frozen is departed; a reviewed-out key nobody flagged is not', () async {
+ await freeze(3);
+ await backend.add(evil, 'viewer', '', 'evil');
+ await backend.removeBy(b64e(evil.pub), box2);
+ await backend.removeBy(b64e(k5.pub), box2); // known since joining: not new
+ await log.rebaseline(confirm: true);
+ final d = (await log.list()).departed;
+ expect([for (final x in d) x.pub], [b64e(evil.pub)]);
+ expect([d.single.label, d.single.removedBy], ['evil', b64e(box2.pub)]);
+ });
+
+ test('a key that joined and left before the freeze, and was looked at, is not flagged again', () async {
+ await backend.add(k6, 'viewer', '', 'k6');
+ await backend.removeBy(b64e(k6.pub), box2);
+ await log.refresh();
+ expect([for (final d in (await log.list()).departed) d.pub], [b64e(k6.pub)]);
+ await log.dismiss(pub: b64e(k6.pub));
+ await freeze(5);
+ await log.rebaseline(confirm: true);
+ expect((await log.list()).departed, isEmpty);
+ });
+ });
+
+ test('a sign-in by hand that never registers expects this app\'s removal for one read only', () async {
+ final log = at(() => backend);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ log.beginSignIn(fresh: true);
+ await log.refresh(); // the read it was waiting for: nothing removed
+ final me = await keys.identity();
+ await backend.removeBy(b64e(me.pub), box2);
+ await log.refresh();
+ expect(signedOut, 1);
+ });
+ });
+
test('forgetting the identity mints a new one', () async {
final before = b64e((await keys.identity()).pub);
await keys.forgetIdentity();
diff --git a/desktop/test/viewer/group_sync_test.dart b/desktop/test/viewer/group_sync_test.dart
index db0a81c51..30d1394ea 100644
--- a/desktop/test/viewer/group_sync_test.dart
+++ b/desktop/test/viewer/group_sync_test.dart
@@ -174,6 +174,88 @@ void main() {
},
);
+ test(
+ 'a suspended key is neither pinned nor seeded into the roster',
+ () async {
+ final keys = ViewerKeyStore(storage: _Memory());
+ final machine = await E2eeIdentity.generate();
+ final cPub = b64e((await E2eeIdentity.generate()).pub);
+ final dId = 'd' * 32;
+ final dPub = b64e((await E2eeIdentity.generate()).pub);
+ await keys.pin(_machineId, machine.pub);
+ await keys.pin(dId, b64d(dPub)); // a pin the roster does not name yet
+ Map<String, dynamic>? seen;
+ final socket = await _machine(machine, (request) {
+ seen = request;
+ return {
+ 'members': [
+ {
+ 'pub': cPub,
+ 'kind': 'machine',
+ 'machineId': _c,
+ 'label': 'c',
+ 'at': 50,
+ },
+ ],
+ 'removed': [],
+ };
+ });
+ final outcome = await syncTrustGroup(
+ machineId: _machineId,
+ keys: keys,
+ accessToken: 't',
+ wsBaseUrl: 'wss://relay.test',
+ autonomousEnv: 'prod',
+ label: 'Studio PC',
+ socket: socket.factory,
+ suspended: () async => {cPub, dPub},
+ );
+ expect(outcome.pinned, isEmpty);
+ expect(await keys.peer(_c), isNull);
+ expect([
+ for (final m in seen!['members'] as List) (m as Map)['pub'],
+ ], isNot(contains(dPub)));
+ },
+ );
+
+ test('a key suspended by the devlog this very exchange carries is not pinned either', () async {
+ final keys = ViewerKeyStore(storage: _Memory());
+ final machine = await E2eeIdentity.generate();
+ final cPub = b64e((await E2eeIdentity.generate()).pub);
+ await keys.pin(_machineId, machine.pub);
+ final socket = await _machine(machine, (request) {
+ return {
+ 'members': [
+ {
+ 'pub': cPub,
+ 'kind': 'machine',
+ 'machineId': _c,
+ 'label': 'c',
+ 'at': 50,
+ },
+ ],
+ 'removed': [],
+ 'devlog': {
+ 'head': {'seq': 1, 'hash': 'x'},
+ },
+ };
+ });
+ final suspendedNow = <String>{};
+ final outcome = await syncTrustGroup(
+ machineId: _machineId,
+ keys: keys,
+ accessToken: 't',
+ wsBaseUrl: 'wss://relay.test',
+ autonomousEnv: 'prod',
+ label: 'Studio PC',
+ socket: socket.factory,
+ onDevlog: (_, _) async => suspendedNow.add(cPub),
+ suspended: () async => {...suspendedNow},
+ );
+ expect(outcome.pinned, isEmpty);
+ expect(await keys.peer(_c), isNull);
+ });
+
test('the merge matches the CLI: tombstones beat older entries, newer links beat tombstones', () async {
final self = b64e((await E2eeIdentity.generate()).pub);
final pub = b64e((await E2eeIdentity.generate()).pub);
diff --git a/docs/cli.md b/docs/cli.md
index cb6d34af7..6c6ed5ac1 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -23,6 +23,7 @@ works the same on a headless Linux server; the app is not required on a machine,
| `harness remote-password set\|status\|clear` | This machine's persistent password for machine-to-machine links. |
| `harness link connect <id> [--name=<label>]` · `harness link list` · `harness link unlink <id>` | Let this machine reach another of yours, terminating E2EE here; list; unlink. |
| `harness remote` | From a Harness terminal tile: choose another of your machines (linking it on the spot if needed), open a terminal there and move this tile to it. |
+| `harness devices [list] [--json]` · `show <#\|fp>` · `remove <fp>` · `history [--json]` · `dismiss [<#\|fp>]` · `rebaseline [--yes]` | The account's devices as this machine verified them (below): list · one in full · take one out on every device · every add and removal, newest first · mark new ones seen · review and trust a frozen list again. |
| `harness grid login [--force] [--json]` · `harness grid logout` | Sign the `grid` CLI in with this computer's account, no second browser. |
| `harness flash [flags]` | Re-flash a plugged-in Harness device over USB. Flags pass straight to the flasher. |
| `harness autonomous-device discover\|status\|list\|pair\|revoke` | Pair Autonomous OS devices found on the LAN, directly, with no relay. |
@@ -73,6 +74,43 @@ it), a path looks like a path, the first other word is the agent and a second na
`--mode auto|ask|plan|full`, `--name`, `--new [name]` and `--json` are the rest. There is still no
`harness split`: panes are arranged in the app.
+## Your devices
+
+Signing in is what makes a device trusted: every computer and app signed in to the account adds its
+key to the account's device key log, and the others trust it with no password. Nothing asks you to
+confirm a device; instead every device shows you each one it did not know before.
+`harness devices` is this machine's view, the same one Settings ▸ Your devices shows in the app.
+
+- **New.** A device added after this machine joined the account is flagged `new` (an OS notification
+ in the apps) and stays flagged across restarts until you look: `harness devices dismiss` marks every
+ one seen, `dismiss <#|fp>` just one; opening Your devices does the same in the apps.
+- **Already on your account.** The first time a device reads the log it announces nothing; the apps
+ show the devices that were already there once, until you press Got it.
+- **Joined and left before you looked.** A new device that was removed before you saw it stays listed,
+ with who removed it, until you dismiss that one: `harness devices dismiss <fp>`, or its own Got it
+ in the apps.
+- **Removed.** When another device is removed, the others say who removed it, or that it signed out.
+ It is marked in red when a device you have not looked at yet did the removing.
+- **Held by another key.** If another key already holds this computer's place (`harness status`
+ says `not registered — another key holds this computer`), an earlier install is the usual reason:
+ remove it from another device and this computer joins on its own. Marked in red when that key
+ appeared after this computer joined.
+- **Frozen.** When the backend serves a log that does not match what this machine verified, the list
+ freezes and adds nothing until you review it: `harness devices rebaseline` shows what would change,
+ `--yes` trusts it (Trust again in the apps). If devices disagree about the log, keys added after the
+ point where they split are also **suspended** — not trusted here until that review, or until you
+ `dismiss` one that is yours.
+- **Another account.** The list belongs to the account this device last signed in to here. If the
+ backend starts serving another account's list, the list freezes and Trust again refuses to switch:
+ sign in again (`harness login`) to change accounts. Each account's marks are kept for when you
+ return to it.
+- **History.** `harness devices history` lists every add, rename, removal and sign-out, newest first,
+ with who did it. Each entry is checked against what this machine already verified, so the backend
+ cannot rewrite it; offline, it shows only the recent part.
+
+A `history` or `dismiss` that answers *This needs a newer Harness running here* means the daemon
+still running is an older version: `harness stop && harness start`.
+
## The daemon's control interface
`harness pair <verb>` is how the paired daemon ([daemons/BRAIN.md](../daemons/BRAIN.md)) reads and
diff --git a/mobile/lib/phone/device_detail_page.dart b/mobile/lib/phone/device_detail_page.dart
index 265fba675..7e45a77fc 100644
--- a/mobile/lib/phone/device_detail_page.dart
+++ b/mobile/lib/phone/device_detail_page.dart
@@ -70,12 +70,17 @@ class _DeviceDetailPageState extends State<DeviceDetailPage> {
}
setState(() {
_removing = false;
- _error = "Couldn't remove $name. Try again.";
+ _error = 'Couldn’t remove $name. Try again.';
});
}
void _mine() {
- widget.notifier.dismissNewDevice(_row.member.pub);
+ // The suspension is lifted only when this page says there is one: "It's mine" is the person
+ // vouching for what is on screen.
+ widget.notifier.dismissNewDevice(
+ _row.member.pub,
+ liftSuspension: _row.suspended,
+ );
widget.onMine?.call();
Navigator.of(context).pop();
}
@@ -147,9 +152,17 @@ class _DeviceDetailPageState extends State<DeviceDetailPage> {
style: tty.style(color: tty.dim),
),
],
+ if (_row.suspended) ...[
+ const SizedBox(height: 12),
+ Text(
+ 'Not trusted here: added after this device’s list and another’s split. '
+ 'Review the list to trust it again.',
+ style: tty.style(color: tty.red),
+ ),
+ ],
if (_error case final error?) ...[
const SizedBox(height: 12),
- TtyText(error, color: tty.red),
+ Text(error, style: tty.style(color: tty.red)),
],
if (widget.isNew || !_row.self) ...[
const SizedBox(height: 16),
diff --git a/mobile/lib/phone/device_history_page.dart b/mobile/lib/phone/device_history_page.dart
new file mode 100644
index 000000000..a8ebd83b7
--- /dev/null
+++ b/mobile/lib/phone/device_history_page.dart
@@ -0,0 +1,211 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/core/relative_time.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/viewer/device_history.dart';
+
+import 'devices_page.dart' show openDeviceFromLog;
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// Settings ▸ Your devices ▸ History — every device added to or removed from the account, newest
+/// first, as this phone verified it. An active device opens its page.
+class DeviceHistoryPage extends StatefulWidget {
+ const DeviceHistoryPage({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ State<DeviceHistoryPage> createState() => _DeviceHistoryPageState();
+}
+
+class _DeviceHistoryPageState extends State<DeviceHistoryPage> {
+ DeviceLogHistory? _history;
+ bool _failed = false;
+
+ /// [AppNotifier.devicesRevision] as of the last read, and the read in flight: the page re-reads when
+ /// the log changes under it (a "Got it" on a banner clears a flag, a device joins), and only the
+ /// newest read is shown.
+ int _revision = 0;
+ int _loads = 0;
+
+ AppNotifier get _app => widget.notifier;
+
+ @override
+ void initState() {
+ super.initState();
+ _app.addListener(_changed);
+ unawaited(_load());
+ }
+
+ @override
+ void dispose() {
+ _app.removeListener(_changed);
+ super.dispose();
+ }
+
+ void _changed() {
+ if (_app.devicesRevision != _revision) unawaited(_load(quiet: true));
+ }
+
+ /// [quiet]: a refresh keeps what is on screen until the new read lands (and keeps it if that fails).
+ Future<void> _load({bool quiet = false}) async {
+ _revision = _app.devicesRevision;
+ final load = ++_loads;
+ if (!quiet) setState(() => _failed = false);
+ try {
+ final history = await _app.deviceHistory();
+ if (!mounted || load != _loads) return;
+ setState(() {
+ _history = history;
+ _failed = false;
+ });
+ } catch (_) {
+ // A refresh that fails keeps what is on screen; with nothing on screen yet, it says so.
+ if (mounted && load == _loads && (!quiet || _history == null)) {
+ setState(() => _failed = true);
+ }
+ }
+ }
+
+ void _open(DevLogHistoryRow r) =>
+ unawaited(openDeviceFromLog(Navigator.of(context), _app, r.pub));
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ final history = _history;
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ bottom: false,
+ child: ListView(
+ padding: EdgeInsets.fromLTRB(
+ Tty.origin,
+ 12,
+ Tty.origin,
+ MediaQuery.paddingOf(context).bottom + 24,
+ ),
+ children: [
+ const TtyText(
+ 'Device history',
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'Every device added to or removed from your account, newest first, as this device verified it.',
+ style: tty.style(color: tty.dim),
+ ),
+ const SizedBox(height: 12),
+ if (_failed)
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Couldn’t load the history. Try again.',
+ key: const Key('device-history-failed'),
+ style: tty.style(color: tty.red),
+ ),
+ ),
+ TextButton(
+ onPressed: () => unawaited(_load()),
+ child: const Text('Try again'),
+ ),
+ ],
+ )
+ else if (history != null) ...[
+ for (final r in history.rows)
+ _HistoryRow(
+ key: ValueKey('device-history-${r.seq}'),
+ sentence: historySentence(r),
+ when: fullDateTime(DateTime.fromMillisecondsSinceEpoch(r.at)),
+ fingerprint: r.fingerprint,
+ // Still new: a flag. A key that left before anyone looked stays flagged (on both its
+ // rows) until "Got it" on the banner.
+ flag: r.pending
+ ? (r.active ? 'New' : 'Left before you looked')
+ : null,
+ thisDevice: r.thisDevice,
+ onTap: r.active && !r.thisDevice ? () => _open(r) : null,
+ ),
+ if (history.rows.isEmpty && history.complete)
+ Text(
+ 'No history yet.',
+ key: const Key('device-history-empty'),
+ style: tty.style(),
+ ),
+ if (!history.complete) ...[
+ const SizedBox(height: 8),
+ Text(
+ 'Older history needs a connection.',
+ key: const Key('device-history-incomplete'),
+ style: tty.style(color: tty.dim),
+ ),
+ ],
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _HistoryRow extends StatelessWidget {
+ const _HistoryRow({
+ super.key,
+ required this.sentence,
+ required this.when,
+ required this.fingerprint,
+ required this.flag,
+ required this.thisDevice,
+ this.onTap,
+ });
+
+ final String sentence;
+ final String when;
+ final String fingerprint;
+ final String? flag;
+ final bool thisDevice;
+ final VoidCallback? onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ return InkWell(
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ // The flag sits under the date, not beside the sentence: a long one ("Left before you looked")
+ // would squeeze the sentence into a column.
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ thisDevice ? '$sentence (this device)' : sentence,
+ style: tty.style(),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ fingerprint.isEmpty ? when : '$when · $fingerprint',
+ style: tty.style(color: tty.dim),
+ ),
+ if (flag != null) ...[
+ const SizedBox(height: 2),
+ Text(
+ flag!,
+ key: const Key('device-history-flag'),
+ style: tty.style(color: tty.yellow),
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/device_rows.dart b/mobile/lib/phone/device_rows.dart
index 2b05005be..0e9eb5773 100644
--- a/mobile/lib/phone/device_rows.dart
+++ b/mobile/lib/phone/device_rows.dart
@@ -1,7 +1,4 @@
import 'package:harness_mobile/core/relative_time.dart';
-import 'package:harness_mobile/e2ee/bytes.dart';
-import 'package:harness_mobile/e2ee/keys.dart' as keys;
-import 'package:harness_mobile/viewer/device_log.dart';
import 'package:harness_mobile/viewer/device_log_sync.dart';
/// This phone's own row, which the Devices page shows on its own card rather than in the list.
@@ -70,13 +67,3 @@ String deviceDetailLine(
: '';
return '$what · $when$tail';
}
-
-/// A row for a device only known from its log entry (a new-device notice), with its key code worked
-/// out from the key. Never this phone: a notice is about a device this phone had not trusted.
-DeviceLogRow rowFromMember(DevLogMember m) {
- var fp = '';
- try {
- fp = keys.fingerprint(b64d(m.pub));
- } catch (_) {}
- return DeviceLogRow(m, fingerprint: fp, self: false);
-}
diff --git a/mobile/lib/phone/devices_page.dart b/mobile/lib/phone/devices_page.dart
index afa25d069..d90152750 100644
--- a/mobile/lib/phone/devices_page.dart
+++ b/mobile/lib/phone/devices_page.dart
@@ -8,6 +8,7 @@ import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/viewer/device_log_sync.dart';
import 'device_detail_page.dart';
+import 'device_history_page.dart';
import 'device_rows.dart';
import 'fingerprint_text.dart';
import 'phone_navigation.dart' show phoneRoute;
@@ -16,6 +17,53 @@ import 'settings_row.dart';
import 'tty.dart';
import 'tty_controls.dart';
+/// [pub]'s page, from what the log itself lists: the row carries the log's own `suspended` and
+/// `pending` flags, so the page says what the log says (a row made up from a notice would not — and
+/// its "It's mine" would vouch for a key the page never showed as suspended). A device the log no
+/// longer lists opens the list, which says so by not showing it; so does one that is not news when
+/// [onlyWhileNew] (a removal's signer is only worth a page while nobody has looked at it).
+///
+/// Never throws: a listing that cannot be read opens the list, and a navigator that went away while
+/// the log was being read (the app was signed out, the screen closed) is left alone.
+Future<void> openDeviceFromLog(
+ NavigatorState navigator,
+ AppNotifier notifier,
+ String pub, {
+ bool onlyWhileNew = false,
+}) async {
+ try {
+ DeviceLogListing listing;
+ try {
+ listing = await notifier.deviceListing();
+ } catch (_) {
+ listing = DeviceLogListing.empty;
+ }
+ if (!navigator.mounted) return;
+ DeviceLogRow? found;
+ for (final row in listing.members) {
+ if (row.member.pub == pub) found = row;
+ }
+ final isNew =
+ found != null &&
+ (found.pending || notifier.newDevices.any((d) => d.pub == pub));
+ final row = found != null && (isNew || !onlyWhileNew) ? found : null;
+ await navigator.push(
+ phoneRoute(
+ (_) => row == null
+ ? DevicesPage(notifier: notifier)
+ : DeviceDetailPage(notifier: notifier, row: row, isNew: isNew),
+ ),
+ );
+ } catch (error) {
+ debugPrint('devices: could not open the device: $error');
+ }
+}
+
+/// What "Trust again" says when the list it would trust is another account's than the one signed in to.
+const otherAccountMessage =
+ 'The device list now belongs to a different account than the one you signed in with. '
+ 'Sign in again to switch accounts.';
+
/// Settings ▸ Your devices — every computer and app signed in to this account. Signing in on one is
/// what makes the others trust it (the device key log, `viewer/device_log_sync.dart`), so this is also
/// where a device that is not yours is seen, and taken out.
@@ -35,10 +83,19 @@ class _DevicesPageState extends State<DevicesPage> {
int _revision = -1;
String? _error;
+ /// [_error] is advice rather than a failure (amber, not red).
+ bool _errorWarns = false;
+
/// The devices that were new when this page opened: they keep their `New` badge for the visit,
/// though opening the page clears the banner that announced them.
late final Set<String> _newPubs;
+ /// The visit's devices were marked seen (once, after the first read of the list).
+ bool _seenMarked = false;
+
+ /// "Already on your account" was dismissed on this visit, saved or not.
+ bool _baselineHidden = false;
+
AppNotifier get _app => widget.notifier;
@override
@@ -47,10 +104,6 @@ class _DevicesPageState extends State<DevicesPage> {
_app.addListener(_changed);
_newPubs = {for (final m in _app.newDevices) m.pub};
unawaited(_load());
- // Looking at the list IS reviewing the new devices: the banner that pointed here is done.
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) _app.seenNewDevices();
- });
}
@override
@@ -66,14 +119,48 @@ class _DevicesPageState extends State<DevicesPage> {
Future<void> _load() async {
_revision = _app.devicesRevision;
final listing = await _app.deviceListing();
+ // The banner as it is while the list is read: what the visit reviews. A device announced during the
+ // awaits below was never shown, and must stay.
+ final banner = [for (final d in _app.newDevices) d.pub];
final seen = await _app.devicesLastSeen();
if (!mounted) return;
setState(() {
_listing = listing;
_seen = seen;
+ // What was pending when the list loaded keeps its badge for the visit, though the visit clears it.
+ _newPubs.addAll(listing.pending);
});
+ // Looking at the list IS reviewing the new devices: the banner that pointed here is done. Only
+ // once the list has been read, so the badges above were taken first.
+ if (!_seenMarked) {
+ _seenMarked = true;
+ // A key that joined and left before anyone looked is cleared by its own "Got it" only. At startup
+ // the app may not have read it as departed yet (a replayed notice put it on the banner); this
+ // list did.
+ final gone = {for (final d in listing.departed) d.pub};
+ _app.seenNewDevices(
+ pending: listing.pending,
+ shown: [
+ for (final p in banner)
+ if (!gone.contains(p)) p,
+ ],
+ );
+ }
+ }
+
+ Future<void> _gotIt() async {
+ // Hidden here whether or not it could be saved: it was read.
+ if (mounted) setState(() => _baselineHidden = true);
+ await _app.seeDeviceBaseline();
+ if (!mounted) return;
+ unawaited(_load());
}
+ void _openHistory() => unawaited(
+ Navigator.of(context)
+ .push(phoneRoute((_) => DeviceHistoryPage(notifier: _app))),
+ );
+
void _open(DeviceLogRow row) => unawaited(
Navigator.of(context).push(
phoneRoute(
@@ -117,6 +204,7 @@ class _DevicesPageState extends State<DevicesPage> {
setState(() {
_removingUnused = true;
_error = null;
+ _errorWarns = false;
});
var failed = 0;
for (final row in rows) {
@@ -125,21 +213,45 @@ class _DevicesPageState extends State<DevicesPage> {
if (!mounted) return;
setState(() {
_removingUnused = false;
+ _errorWarns = false;
_error = failed == 0
? null
- : "Couldn't remove $failed of them. Try again.";
+ : 'Couldn’t remove $failed of them. Try again.';
});
}
+ /// What was on the account before this device joined, apart from this device.
+ List<DeviceLogRow> _baseline(DeviceLogListing listing) {
+ // The log names the set (it also holds keys that were on the account before a re-trusted list);
+ // without it, the keys at or before the seq this device joined at.
+ final named = listing.baseline.toSet();
+ return [
+ for (final row in listing.members)
+ if (!row.self &&
+ (named.isNotEmpty
+ ? named.contains(row.member.pub)
+ : row.member.seq <= listing.joinedSeq))
+ row,
+ ];
+ }
+
Future<void> _trustAgain() async {
final log = _app.deviceLog;
if (log == null) return;
final preview = await log.rebaseline(confirm: false);
if (!mounted) return;
if (preview == null) {
- setState(
- () => _error = "Couldn't read a valid device list. Try again later.",
- );
+ setState(() {
+ _error = 'Couldn’t read a valid device list. Try again later.';
+ _errorWarns = false;
+ });
+ return;
+ }
+ if (preview.otherAccount) {
+ setState(() {
+ _error = otherAccountMessage;
+ _errorWarns = true;
+ });
return;
}
final lines = [
@@ -153,12 +265,43 @@ class _DevicesPageState extends State<DevicesPage> {
title: 'Trust this device list again?',
message: lines.isEmpty
? 'It changes no device. Continue only if you expected this.'
- : 'Only if every device added is yours:\n${lines.join('\n')}',
+ : 'Only if every device added below is yours:\n\n${lines.join('\n')}',
confirmLabel: 'Trust again',
icon: LucideIcons.shieldAlert300,
);
if (!confirmed || !mounted) return;
- await log.rebaseline(confirm: true);
+ // Confirm the list that was shown, not whatever the backend serves now.
+ final result = await log.rebaseline(
+ confirm: true,
+ expectedHead: preview.head,
+ );
+ if (!mounted) return;
+ if (result == null) {
+ setState(() {
+ _error = 'Couldn’t trust the device list again. Try again later.';
+ _errorWarns = false;
+ });
+ return;
+ }
+ if (result.otherAccount) {
+ setState(() {
+ _error = otherAccountMessage;
+ _errorWarns = true;
+ });
+ } else if (result.logChanged) {
+ // The list moved between the preview and the confirm: show it again.
+ setState(() {
+ _error = 'The device list changed while you were reviewing it. Review it again.';
+ _errorWarns = true;
+ });
+ unawaited(_trustAgain());
+ } else if (_error != null) {
+ // Trusted: an error from an earlier try no longer applies.
+ setState(() {
+ _error = null;
+ _errorWarns = false;
+ });
+ }
}
@override
@@ -187,10 +330,10 @@ class _DevicesPageState extends State<DevicesPage> {
weight: FontWeight.w600,
),
const SizedBox(height: 8),
- TtyText(
+ Text(
'Every computer and app signed in to your account. Each reaches your machines '
'end to end encrypted. Remove one you do not recognise.',
- color: tty.dim,
+ style: tty.style(color: tty.dim),
),
if (frozen) ...[
const SizedBox(height: 12),
@@ -203,6 +346,7 @@ class _DevicesPageState extends State<DevicesPage> {
'No device is added until you review it.'
: 'Frozen on ${listing.frozenPeers.join(', ')}. Review it on that computer.',
destructive: true,
+ detailLines: null,
onTap: listing.frozen != null
? () => unawaited(_trustAgain())
: null,
@@ -211,9 +355,28 @@ class _DevicesPageState extends State<DevicesPage> {
],
),
],
+ if (listing != null &&
+ !listing.baselineSeen &&
+ !_baselineHidden) ...[
+ if (_baseline(listing) case final baseline
+ when baseline.isNotEmpty) ...[
+ const SizedBox(height: 12),
+ _BaselinePanel(
+ key: const Key('account-devices-baseline'),
+ rows: baseline,
+ onGotIt: () => unawaited(_gotIt()),
+ ),
+ ],
+ ],
if (_error case final error?) ...[
const SizedBox(height: 12),
- TtyText(error, color: tty.red),
+ Text(
+ error,
+ key: const Key('account-devices-error'),
+ // Amber when the person has something to act on (another account, a list that moved):
+ // the same severity as the desktop. A failure is red.
+ style: tty.style(color: _errorWarns ? tty.yellow : tty.red),
+ ),
],
if (listing != null && _unused(listing).isNotEmpty) ...[
const SizedBox(height: 12),
@@ -267,11 +430,25 @@ class _DevicesPageState extends State<DevicesPage> {
sameName: sharedNames(listing.members)
.contains(row.member.label.trim()),
),
- value: _newPubs.contains(row.member.pub) ? 'New' : null,
+ value: row.suspended
+ ? 'Suspended'
+ : _newPubs.contains(row.member.pub)
+ ? 'New'
+ : null,
onTap: () => _open(row),
),
],
),
+ const SizedBox(height: 12),
+ SettingsGroup(
+ children: [
+ SettingsRow(
+ key: const Key('account-devices-history'),
+ title: 'History',
+ onTap: _openHistory,
+ ),
+ ],
+ ),
],
],
),
@@ -326,3 +503,56 @@ class _ThisDeviceCard extends StatelessWidget {
);
}
}
+
+/// "Already on your account": the devices this one found when it joined, shown once so a stranger
+/// among them is seen. Nothing to confirm — "Got it" only stops showing it.
+class _BaselinePanel extends StatelessWidget {
+ const _BaselinePanel({super.key, required this.rows, required this.onGotIt});
+
+ final List<DeviceLogRow> rows;
+ final VoidCallback onGotIt;
+
+ static String _line(DeviceLogRow row) {
+ final label = row.member.label.trim();
+ final kind = row.member.kind == 'machine' ? 'Computer' : 'App';
+ return '${label.isEmpty ? 'A device' : label} · $kind · ${row.fingerprint}';
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ return SettingsGroup(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(13, 12, 13, 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const TtyText('Already on your account', weight: FontWeight.w600),
+ const SizedBox(height: 4),
+ Text(
+ 'These were on your account before this device joined. If one isn’t yours, remove it.',
+ style: tty.style(color: tty.dim),
+ ),
+ const SizedBox(height: 8),
+ for (final row in rows)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 4),
+ child: Text(_line(row), style: tty.style()),
+ ),
+ Align(
+ alignment: Alignment.centerRight,
+ child: TextButton(
+ key: const Key('account-devices-baseline-got-it'),
+ onPressed: onGotIt,
+ child: const Text('Got it'),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/mobile/lib/phone/new_device_banner.dart b/mobile/lib/phone/new_device_banner.dart
index 35e3dbdce..c026281de 100644
--- a/mobile/lib/phone/new_device_banner.dart
+++ b/mobile/lib/phone/new_device_banner.dart
@@ -4,9 +4,9 @@ import 'package:flutter/material.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/viewer/device_log_sync.dart';
-import 'device_detail_page.dart';
-import 'device_rows.dart';
+import 'device_history_page.dart';
import 'devices_page.dart';
import 'phone_navigation.dart' show phoneRoute;
import 'tty.dart';
@@ -14,6 +14,10 @@ import 'tty.dart';
/// "New device: X" across the top of the phone: a device this phone had never trusted joined the
/// account. Signing in is what makes a device trusted, so this is how one signed in by someone else
/// is seen. It stays until it is looked at or dismissed.
+///
+/// Above it, stacked under one status-bar inset with a hairline between them: a device removed or
+/// signed out by someone else, and a device that joined and left before anyone looked. Each band shows
+/// one item and counts the rest as "(+N more)".
class NewDeviceBanner extends StatelessWidget {
const NewDeviceBanner({
super.key,
@@ -24,51 +28,260 @@ class NewDeviceBanner extends StatelessWidget {
final AppNotifier notifier;
final GlobalKey<NavigatorState> navigator;
+ /// Whether any band is on screen. The bands take the status-bar inset, so what is under them must
+ /// not take it again.
+ static bool showing(AppNotifier notifier) =>
+ notifier.deviceRemovals.isNotEmpty ||
+ notifier.departedDevices.isNotEmpty ||
+ notifier.newDevices.isNotEmpty;
+
+ /// The removal notices that get a band. A device that signed itself out and is ALSO held as having
+ /// "joined and left before you looked" is one ghost, not two: only the departed band says so (its
+ /// "Got it" is the one dismissal), so a "signed out" band for the same key is left out — suppressed,
+ /// not dismissed, as dismissing it would not touch the departed mark.
+ static List<DeviceRemovalNotice> removalsShown(AppNotifier notifier) {
+ final gone = {for (final d in notifier.departedDevices) d.pub};
+ return [
+ for (final r in notifier.deviceRemovals)
+ if (!(r.selfRemoved && gone.contains(r.pub))) r,
+ ];
+ }
+
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
- if (notifier.newDevices.isEmpty) return const SizedBox.shrink();
+ final removed = removalsShown(notifier);
+ // The departed mark and a removal notice for another device are separate things, each cleared by
+ // its own "Got it" — dismissing the notice never erases the mark.
+ final departed = notifier.departedDevices;
+ if (!showing(notifier)) return const SizedBox.shrink();
+ // The alarming one first, in each band: a removal by a new device nobody looked at, a departed key
+ // removed by one. Behind a neutral one it would be dismissed (or just overlooked) unseen.
+ final removal = removed.isEmpty
+ ? null
+ : removed.firstWhere((r) => r.red, orElse: () => removed.first);
+ final departedShown = departed.isEmpty
+ ? null
+ : departed.firstWhere(
+ notifier.departedRed,
+ orElse: () => departed.first,
+ );
+ // What this build counts: "Got it" clears exactly these. A key that arrives after this build was
+ // never drawn, so it is not cleared.
+ final shown = [for (final d in departed) d.pub];
+ final bands = <Widget>[
+ // Same order as the desktop: a removal, then a device that left unseen, then a new device.
+ if (removal != null)
+ _RemovalBand(
+ notice: removal,
+ more: removed.length - 1,
+ onGotIt: () => notifier.dismissDeviceRemoval(removal.pub),
+ onReview: removal.red ? () => _reviewSigner(removal) : null,
+ ),
+ if (departedShown != null)
+ _DepartedBand(
+ departed: departedShown,
+ more: departed.length - 1,
+ red: notifier.departedRed(departedShown),
+ // The band counts every one of them ("(+N more)"), so "Got it" is for all it counts — each
+ // dismissal saved on its own, as one "Got it" per device would.
+ onGotIt: () {
+ for (final pub in shown) {
+ notifier.dismissDeparted(pub);
+ }
+ },
+ onReview: () => unawaited(
+ navigator.currentState?.push(
+ phoneRoute((_) => DeviceHistoryPage(notifier: notifier)),
+ ) ??
+ Future<void>.value(),
+ ),
+ ),
+ if (notifier.newDevices.isNotEmpty) _newDevice(context),
+ ];
+ final tty = Tty.of(context);
+ // One SafeArea around every band: the status-bar inset is taken once, at the top. A SafeArea per
+ // band would also push the lower band down by the notch. A hairline between stacked bands keeps
+ // two of the same tint apart.
+ return SafeArea(
+ bottom: false,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ for (var i = 0; i < bands.length; i++) ...[
+ if (i > 0)
+ Container(height: 1, color: tty.dim.withValues(alpha: 0.25)),
+ bands[i],
+ ],
+ ],
+ ),
+ );
+ }
+
+ /// "Review" on a removal by a new device: that signer's page when it is still new, else the list.
+ void _reviewSigner(DeviceRemovalNotice n) {
+ notifier.dismissDeviceRemoval(n.pub);
+ unawaited(_open(n.signer, onlyWhileNew: true));
+ }
+
+ /// [openDeviceFromLog] on the app's navigator, when it has one.
+ Future<void> _open(String pub, {bool onlyWhileNew = false}) async {
+ final nav = navigator.currentState;
+ if (nav == null) return;
+ await openDeviceFromLog(nav, notifier, pub, onlyWhileNew: onlyWhileNew);
+ }
+
+ Widget _newDevice(BuildContext context) {
final tty = Tty.of(context);
final m = notifier.newDevices.first;
final name = m.label.isEmpty ? 'A device' : m.label;
final more = notifier.newDevices.length - 1;
- return SafeArea(
- bottom: false,
- child: Material(
- color: Color.alphaBlend(tty.red.withValues(alpha: 0.12), tty.ground),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(Tty.origin, 8, 8, 8),
- child: Row(
- children: [
- Expanded(
- child: TtyText(
- 'New device: $name${more > 0 ? ' +$more' : ''}',
- key: const Key('new-device-banner'),
- ),
+ return Material(
+ color: Color.alphaBlend(tty.red.withValues(alpha: 0.12), tty.ground),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 8, 8, 8),
+ child: Row(
+ children: [
+ Expanded(
+ // Wraps: "(+N more)" is the part that must not be clipped.
+ child: Text(
+ 'New device: $name${more > 0 ? ' (+$more more)' : ''}',
+ key: const Key('new-device-banner'),
+ style: tty.style(),
),
- TextButton(
- onPressed: () => notifier.dismissNewDevice(m.pub),
- child: const Text('Mine'),
+ ),
+ TextButton(
+ // A key a fork suspended stays suspended however often the banner is dismissed (the next
+ // read of the log would bring it back), so "Mine" opens its page, which says why and
+ // is where the person can vouch for it.
+ onPressed: () => notifier.newDeviceSuspended(m.pub)
+ ? unawaited(_open(m.pub))
+ : notifier.dismissNewDevice(m.pub),
+ child: const Text('Mine'),
+ ),
+ TextButton(
+ // One new device goes straight to its key code; several go to the list, where each is a row.
+ onPressed: () => unawaited(
+ more == 0
+ ? _open(m.pub)
+ : navigator.currentState?.push(
+ phoneRoute((_) => DevicesPage(notifier: notifier)),
+ ),
),
- TextButton(
- // One new device goes straight to its key code; several go to the list, where each is a row.
- onPressed: () => unawaited(
- navigator.currentState?.push(
- phoneRoute(
- (_) => more == 0
- ? DeviceDetailPage(
- notifier: notifier,
- row: rowFromMember(m),
- isNew: true,
- )
- : DevicesPage(notifier: notifier),
- ),
+ child: const Text('Review'),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// "Device removed" / "Device signed out" / "Removed by a new device": a device left the account
+/// without this phone doing it. Red when the removal came from a new device nobody has looked at.
+class _RemovalBand extends StatelessWidget {
+ const _RemovalBand({
+ required this.notice,
+ required this.more,
+ required this.onGotIt,
+ this.onReview,
+ });
+
+ final DeviceRemovalNotice notice;
+ final int more;
+ final VoidCallback onGotIt;
+ final VoidCallback? onReview;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ final red = notice.red;
+ final title = notice.title;
+ final body = notice.sentence;
+ return Material(
+ color: Color.alphaBlend(
+ (red ? tty.red : tty.dim).withValues(alpha: 0.12),
+ tty.ground,
+ ),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 8, 8, 8),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ key: const Key('device-removed-banner'),
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ more > 0 ? '$title (+$more more)' : title,
+ style: tty.style(weight: FontWeight.w600),
),
- ),
- child: const Text('Review'),
+ Text(body, style: tty.style()),
+ ],
),
- ],
- ),
+ ),
+ TextButton(onPressed: onGotIt, child: const Text('Got it')),
+ if (onReview != null)
+ TextButton(onPressed: onReview, child: const Text('Review')),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// A device that came and went while nobody here was looking ([DeviceDepartedCopy] words it), kept
+/// until "Got it". "History" opens the History, where it is flagged. Red when the key that removed it
+/// is itself a device nobody looked at.
+class _DepartedBand extends StatelessWidget {
+ const _DepartedBand({
+ required this.departed,
+ required this.more,
+ required this.red,
+ required this.onGotIt,
+ required this.onReview,
+ });
+
+ final DeviceLogDeparted departed;
+ final int more;
+ final bool red;
+ final VoidCallback onGotIt;
+ final VoidCallback onReview;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ return Material(
+ color: Color.alphaBlend(
+ (red ? tty.red : tty.dim).withValues(alpha: 0.12),
+ tty.ground,
+ ),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 8, 8, 8),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ more > 0
+ ? '${departed.sentence(red: red)} (+$more more)'
+ : departed.sentence(red: red),
+ key: const Key('device-departed-banner'),
+ style: tty.style(),
+ ),
+ ),
+ TextButton(
+ key: const Key('device-departed-got-it'),
+ onPressed: onGotIt,
+ child: const Text('Got it'),
+ ),
+ TextButton(
+ key: const Key('device-departed-review'),
+ onPressed: onReview,
+ child: const Text('History'),
+ ),
+ ],
),
),
);
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 9ae126966..e9ade5b6e 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -5,14 +5,10 @@ import 'new_device_banner.dart';
import 'package:flutter/material.dart';
import 'package:harness_mobile/state/app_state.dart';
-import 'package:harness_mobile/viewer/device_log_sync.dart';
import '../p2p/phone_terminal_p2p.dart';
import 'agent_home.dart';
-import 'device_detail_page.dart';
-import 'device_rows.dart';
import 'devices_page.dart';
-import 'phone_navigation.dart' show phoneRoute;
import 'phone_shell_scope.dart';
/// The signed-in phone app: one page stack, rooted in [AgentHome] — the terminal the phone opens
@@ -143,8 +139,8 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
}
/// A tapped "new device" notice: that device's page. One this phone has just been told of opens as
- /// new; one it no longer lists as new but the account still holds opens plain; one that is gone
- /// opens the list, which says so by not showing it.
+ /// new (so does one the log still holds as pending); one already seen but still on the account opens
+ /// plain; one that is gone opens the list, which says so by not showing it.
void _openNoticedDevice() {
final opened = widget.notifier.agentNotices.system.openedDevice;
final pub = opened.value;
@@ -153,36 +149,20 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
unawaited(_showDevice(pub));
}
- Future<void> _showDevice(String pub) async {
+ Future<void> _showDevice(String key) async {
final navigator = _navigator.currentState;
if (navigator == null) return;
- for (final m in widget.notifier.newDevices) {
- if (m.pub != pub) continue;
- await navigator.push(
- phoneRoute(
- (_) => DeviceDetailPage(
- notifier: widget.notifier,
- row: rowFromMember(m),
- isNew: true,
- ),
- ),
- );
- return;
+ // A removal by a new device is keyed `removedBy:<signer>:<removed pub>`: it opens the signer.
+ var pub = key;
+ if (key.startsWith('removedBy:')) {
+ final rest = key.substring('removedBy:'.length);
+ final cut = rest.indexOf(':');
+ pub = cut < 0 ? rest : rest.substring(0, cut);
}
- final DeviceLogListing listing = await widget.notifier.deviceListing();
- if (!mounted) return;
- for (final row in listing.members) {
- if (row.member.pub != pub) continue;
- await navigator.push(
- phoneRoute(
- (_) => DeviceDetailPage(notifier: widget.notifier, row: row),
- ),
- );
- return;
- }
- await navigator.push(
- phoneRoute((_) => DevicesPage(notifier: widget.notifier)),
- );
+ // From the log's own listing, never a row made up from the notice: it carries the real
+ // `suspended` and `pending` flags (a tap that launched the app comes before the banner list is
+ // rebuilt from the log, and is still news while the log holds it pending).
+ await openDeviceFromLog(navigator, widget.notifier, pub);
}
/// Back in the foreground: a p2p retry waiting out its delay fires now, and so does every machine
@@ -271,20 +251,26 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
navigator: _navigator,
),
Expanded(
- child: HeroControllerScope(
- controller: _heroController,
- child: Navigator(
- key: _navigator,
- // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.
- // `NavigatorState._updateEffectiveObservers` appends the scope's controller to
- // `widget.observers` itself, so listing it here registers it twice and trips
- // "A HeroController can not be shared by multiple Navigators" — which reads
- // like a sharing bug and is really a double-subscription by one navigator.
- onGenerateRoute: (_) => MaterialPageRoute<void>(
- builder: (_) => AgentHome(
- notifier: widget.notifier,
- openMachineId: _linkedMachineId,
- openAgent: _openAgentRequest,
+ // While a band shows it has taken the status-bar inset, so the pages under it must
+ // not take it again (a blank gap the height of the notch otherwise).
+ child: MediaQuery.removePadding(
+ context: context,
+ removeTop: NewDeviceBanner.showing(widget.notifier),
+ child: HeroControllerScope(
+ controller: _heroController,
+ child: Navigator(
+ key: _navigator,
+ // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.
+ // `NavigatorState._updateEffectiveObservers` appends the scope's controller to
+ // `widget.observers` itself, so listing it here registers it twice and trips
+ // "A HeroController can not be shared by multiple Navigators" — which reads
+ // like a sharing bug and is really a double-subscription by one navigator.
+ onGenerateRoute: (_) => MaterialPageRoute<void>(
+ builder: (_) => AgentHome(
+ notifier: widget.notifier,
+ openMachineId: _linkedMachineId,
+ openAgent: _openAgentRequest,
+ ),
),
),
),
diff --git a/mobile/lib/phone/settings_row.dart b/mobile/lib/phone/settings_row.dart
index 88eb3ecdb..264bafff1 100644
--- a/mobile/lib/phone/settings_row.dart
+++ b/mobile/lib/phone/settings_row.dart
@@ -130,6 +130,7 @@ class SettingsRow extends StatelessWidget {
this.onTap,
this.destructive = false,
this.nested = false,
+ this.detailLines = 2,
});
final String title;
@@ -147,6 +148,10 @@ class SettingsRow extends StatelessWidget {
final VoidCallback? onTap;
final bool destructive;
+ /// How many lines [detail] may take before it is cut short with an ellipsis; null lets it wrap in full
+ /// (a warning is read to the end).
+ final int? detailLines;
+
/// Draws this row as a CHILD of the one above it — the Codex profiles under Codex, the folders
/// under Recent.
///
@@ -198,8 +203,13 @@ class SettingsRow extends StatelessWidget {
const SizedBox(height: 3),
Text(
detail!,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
+ maxLines: detailLines,
+ // ⚠️ Not `ellipsis` when the detail may take every line: an ellipsis with no
+ // `maxLines` still cuts the text to ONE line (measured on iOS and in a widget
+ // test), which is exactly the clipping `detailLines: null` is meant to prevent.
+ overflow: detailLines == null
+ ? TextOverflow.clip
+ : TextOverflow.ellipsis,
style: TextStyle(
color: AppPalette.textSecondary,
fontSize: 12.5,
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 65534a6c5..e45826ef7 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -60,6 +60,7 @@ import '../usage/remote_usage.dart';
import '../usage/usage_accounts.dart';
import '../phone/phone_name_store.dart';
import '../viewer/device_log.dart';
+import '../viewer/device_history.dart';
import '../viewer/device_log_sync.dart';
enum AppStatus { bootstrapping, unauthenticated, authenticated }
@@ -1246,6 +1247,10 @@ class AppNotifier extends ChangeNotifier {
Future<void> _finishBootstrapSignedIn() async {
final revision = _authRevision;
if (!_authWorkCurrent(revision)) return;
+ // Before ANYTHING below can start a connection, a machine refresh or a pane restore — each can
+ // end in a read of the device log, which must be judged by THIS sign-in (a hand sign-in mints its
+ // id here), not the previous account's. Synchronous: no await may come first.
+ _beginDeviceLogSignIn(revision);
// Stays on the pre-navigation `bootstrapping` screen (main.dart) until the local state is
// restored. A phone has no local service to start — the desktop's "Starting local service…"
// was a sentence about somebody else's computer shown while this one read its own disk.
@@ -1309,6 +1314,12 @@ class AppNotifier extends ChangeNotifier {
_bootStatusMessage = null;
status = AppStatus.authenticated;
notifyListeners();
+ // What the device log announced while the app was still starting up (see [_whenSignedIn]).
+ _flushDeviceNotices(revision);
+ // The device log is joined NOW, not after the machine list or the profile: a read of it that
+ // landed first (a push, a reconnect) would judge a just-signed-in phone by the old sign-in's
+ // file, and the log has to know the sign-in is fresh before anything waits.
+ _registerDeviceLog(revision);
// Signed in. Display-name/avatar metadata is independent of machine
// discovery and must not delay work.
unawaited(_loadProfile());
@@ -1378,6 +1389,7 @@ class AppNotifier extends ChangeNotifier {
signingIn = false;
// The code was scanned into the session that just ended — see [logout].
pendingPairing = null;
+ _clearDeviceNotices();
_desk.reset();
zoo.reset();
unawaited(_pool?.closeAll());
@@ -1525,12 +1537,26 @@ class AppNotifier extends ChangeNotifier {
unawaited(_machineCache?.clear());
sessionPreviews.clear();
agentNotices.reset();
+ // The account's device notices go with it: the next sign-in may be another account's, and what
+ // is still pending comes back from its own log once it registers.
+ _clearDeviceNotices();
expandedMachines.clear();
selectedMachineId = null;
status = AppStatus.unauthenticated;
notifyListeners();
}
+ /// Forget every device notice of the account that just left (banner, removals), and make a read of
+ /// its `pending` that is still in flight drop its result: the next sign-in may be another account's.
+ void _clearDeviceNotices() {
+ _pendingSyncGen++;
+ _startupDeviceNotices.clear();
+ newDevices.clear();
+ departedDevices.clear();
+ deviceRemovals.clear();
+ _failedDismissals.clear();
+ }
+
void _onLocalFailure(String machineId, int code, String reason) {
final machine = machineStates[machineId];
if (machine == null || code != 4404) return;
@@ -1668,12 +1694,6 @@ class AppNotifier extends ChangeNotifier {
}
try {
await _refreshMachines(revision);
- // The account's device key log: this phone's key joins it (an existing sign-in too, from
- // before the log existed), and every machine it names is reached with no password.
- if (_authWorkCurrent(revision) && status == AppStatus.authenticated && _deviceLogRegistered != revision) {
- _deviceLogRegistered = revision;
- unawaited(_deviceLog?.register(freshSignIn: viewer.auth.consumeFreshSignIn()));
- }
} finally {
// Said out loud: the list's own notify fires before this, so a flag
// dropped silently here would leave the rail on its placeholders.
@@ -1684,6 +1704,37 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Tell the device log who is signed in, once per sign-in, synchronously (see
+ /// [ViewerDeviceLog.beginSignIn]); [_registerDeviceLog] then finds it done.
+ void _beginDeviceLogSignIn(int revision) {
+ if (_deviceLogBegun == revision) return;
+ _deviceLogBegun = revision;
+ _deviceLog?.beginSignIn(fresh: viewer.auth.consumeFreshSignIn());
+ }
+
+ /// The account's device key log: this phone's key joins it (an existing sign-in too, from
+ /// before the log existed), and every machine it names is reached with no password. Once per
+ /// sign-in, the moment the app is authenticated ([_finishBootstrapSignedIn]) — before the machine
+ /// list and the profile, and not waiting for either. Which account the log belongs to is a local
+ /// fact the log keeps itself ([_beginDeviceLogSignIn]), never something the backend says, so
+ /// there is nothing to read first.
+ void _registerDeviceLog(int revision) {
+ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated || _deviceLogRegistered == revision) {
+ return;
+ }
+ _deviceLogRegistered = revision;
+ final log = _deviceLog;
+ if (log == null) return;
+ // Normally already begun at the top of [_finishBootstrapSignedIn]; a no-op then.
+ _beginDeviceLogSignIn(revision);
+ unawaited(
+ log
+ .register()
+ // Then what is still pending from before (a restart) comes back as the banner.
+ .whenComplete(_syncPendingDevices),
+ );
+ }
+
Future<void> _refreshMachines(int revision) async {
// No machine is "this computer" to a viewer, which has no local CLI: every one — even the one
// it runs on — is reached through the relay.
@@ -1982,22 +2033,108 @@ class AppNotifier extends ChangeNotifier {
ViewerDeviceLog? _deviceLog;
int? _deviceLogRegistered;
+ int? _deviceLogBegun;
+
+ /// What the device log announced (a new device, a removal) while the app was still starting up:
+ /// the OS notice and the banner wait for [_flushDeviceNotices], so a read that lands before the
+ /// app is `authenticated` is not lost. Each carries the sign-in it belongs to; only a signed-out
+ /// app drops them.
+ final List<({int revision, void Function() run})> _startupDeviceNotices = [];
+
+ /// Run [notice] now when the app is signed in; park it while it is still starting up; drop it
+ /// when signed out (an in-flight read of the account that just left must not raise anything).
+ void _whenSignedIn(void Function() notice) {
+ if (_disposed || status == AppStatus.unauthenticated) return;
+ if (status == AppStatus.bootstrapping) {
+ _startupDeviceNotices.add((revision: _authRevision, run: notice));
+ return;
+ }
+ notice();
+ }
+
+ void _flushDeviceNotices(int revision) {
+ final parked = [..._startupDeviceNotices];
+ _startupDeviceNotices.clear();
+ for (final p in parked) {
+ // Another sign-in began meanwhile: these are the previous account's.
+ if (p.revision != revision || !_authWorkCurrent(revision)) continue;
+ p.run();
+ }
+ // The replay put keys on the banner as they were when they were read; the log may have moved
+ // on since (dismissed, removed): the banner is what the log holds now.
+ if (parked.isNotEmpty) unawaited(_syncPendingDevices());
+ }
- /// Devices that joined the account and this phone had never trusted, not yet dismissed.
+ /// Devices that joined the account and this phone had never trusted, not yet dismissed. Rebuilt
+ /// from the log's persisted `pending` ([_syncPendingDevices]), so a restart does not lose them.
final List<DevLogMember> newDevices = [];
+ /// Which of [newDevices] a fork suspended (not trusted here until the list is reviewed), as of the
+ /// last read of the log. "Mine" on the banner cannot lift that, so for these it opens the device's
+ /// page, which says why.
+ final Set<String> _suspendedNew = {};
+
+ bool newDeviceSuspended(String pub) => _suspendedNew.contains(pub);
+
+ /// Devices taken out of the account by another device, until dismissed. Not persisted: the device
+ /// history is the durable record.
+ final List<DeviceRemovalNotice> deviceRemovals = [];
+
+ /// Devices that joined and left the account before anyone here looked, until "Got it" (read from
+ /// the log's persisted `departed`, so a restart does not lose them), oldest first.
+ final List<DeviceLogDeparted> departedDevices = [];
+
+ /// The key that removed [d] is itself a device nobody looked at (still new, or itself gone before
+ /// anyone looked) — the alarming case. A device that signed itself out is never red.
+ bool departedRed(DeviceLogDeparted d) =>
+ !d.selfRemoved &&
+ d.removedBy.isNotEmpty &&
+ (newDevices.any((n) => n.pub == d.removedBy) ||
+ departedDevices.any((o) => o.pub == d.removedBy));
+
+ /// "Got it" on a device that left before it was looked at: saved, so the banner does not come back.
+ void dismissDeparted(String pub) {
+ _pendingSyncGen++;
+ departedDevices.removeWhere((d) => d.pub == pub);
+ // A "signed out" notice for the same key is the same ghost: the banner leaves it out while the
+ // departed mark is up, so this "Got it" is its dismissal too (it must not surface afterwards).
+ deviceRemovals.removeWhere((r) => r.pub == pub && r.selfRemoved);
+ unawaited(_dismissInLog(pubs: [pub]));
+ devicesRevision++;
+ notifyListeners();
+ }
+
/// Bumped whenever the account's devices may have changed; the Devices page re-reads on it.
int devicesRevision = 0;
ViewerDeviceLog? get deviceLog => _deviceLog;
+ /// Devices this phone dismissed whose write to the log failed: the banner must not bring them back
+ /// on the next read of `pending`. Gone with the sign-in, or when the key is announced afresh.
+ final Set<String> _failedDismissals = {};
+
+ Future<void> _dismissInLog({String? pub, List<String>? pubs}) async {
+ final log = _deviceLog;
+ if (log == null) return;
+ try {
+ await log.dismiss(pub: pub, pubs: pubs);
+ } catch (error) {
+ debugPrint('devices: could not save the dismissal: $error');
+ _failedDismissals.addAll([...?pubs, ?pub]);
+ }
+ }
+
void _initDeviceLog() {
final log = _deviceLog = ViewerDeviceLog(
keys: viewer.keys,
fetch: (since) => api.deviceKeys(since),
append: (entry) => api.appendDeviceKey(entry),
label: () => phoneClientDescriptor().name,
- onAnnounce: (m) {
+ // The log saves "announced" before it calls back, so a call that found the app still starting
+ // up and was dropped would never be made again: [_whenSignedIn] parks it instead. Only a
+ // signed-out app (an in-flight read of the account that just left) drops one.
+ onAnnounce: (m) => _whenSignedIn(() {
+ _failedDismissals.remove(m.pub);
if (newDevices.any((d) => d.pub == m.pub)) return;
newDevices.add(m);
devicesRevision++;
@@ -2009,7 +2146,8 @@ class AppNotifier extends ChangeNotifier {
'your machines. Not yours? Remove it in Settings ▸ Your devices.',
));
if (!_disposed) notifyListeners();
- },
+ }),
+ onRemoved: (n) => _whenSignedIn(() => announceDeviceRemoval(n)),
onSignedOut: () async {
// Sign out first: it takes this phone's key out of the log, which needs the key it is about.
await logout();
@@ -2017,6 +2155,7 @@ class AppNotifier extends ChangeNotifier {
},
onChanged: () {
devicesRevision++;
+ unawaited(_syncPendingDevices());
unawaited(_redialNewlyTrusted());
if (!_disposed) notifyListeners();
},
@@ -2025,6 +2164,76 @@ class AppNotifier extends ChangeNotifier {
if (links is DirectLink) links.deviceLog = log;
}
+ /// A device was taken out of the account (not by this phone): say so, once. A removal by a new
+ /// device nobody looked at is the alarming one; its notice opens that signer, the rest open the list.
+ void announceDeviceRemoval(DeviceRemovalNotice n) {
+ if (deviceRemovals.any((r) => r.pub == n.pub)) return;
+ deviceRemovals.add(n);
+ devicesRevision++;
+ unawaited(agentNotices.system.showAccountNotice(
+ key: n.red ? 'removedBy:${n.signer}:${n.pub}' : 'removed:${n.pub}',
+ title: n.title,
+ body: n.sentence,
+ ));
+ if (!_disposed) notifyListeners();
+ }
+
+ void dismissDeviceRemoval(String pub) {
+ // Only the notice. The same event may also be kept by the log as "left before you looked" (the
+ // departed band, which has its own "Got it" and is a durable mark): a notice dismissed here —
+ // however benign it reads, e.g. a self sign-out — never clears it.
+ deviceRemovals.removeWhere((r) => r.pub == pub);
+ notifyListeners();
+ }
+
+ /// Bumped by every read of `pending` and every local dismissal: a read that started before either
+ /// is stale and must not put dismissed devices back on the banner.
+ int _pendingSyncGen = 0;
+
+ /// Rebuild [newDevices] from the log's persisted `pending`, oldest first: what survived a restart,
+ /// and what another path (a `group_sync`, a dismiss) changed.
+ Future<void> _syncPendingDevices() async {
+ final log = _deviceLog;
+ if (log == null) return;
+ final gen = ++_pendingSyncGen;
+ final DeviceLogListing listing;
+ try {
+ listing = await log.list();
+ } catch (_) {
+ return;
+ }
+ if (_disposed || gen != _pendingSyncGen || status != AppStatus.authenticated) return;
+ final pending = listing.pending.toSet();
+ _suspendedNew
+ ..clear()
+ ..addAll([
+ for (final r in listing.members)
+ if (r.suspended) r.member.pub,
+ ]);
+ final next = [
+ for (final r in listing.members)
+ if (pending.contains(r.member.pub) &&
+ !r.self &&
+ !_failedDismissals.contains(r.member.pub))
+ r.member,
+ ]..sort((a, b) => a.seq.compareTo(b.seq));
+ final nextDeparted = [
+ for (final d in listing.departed)
+ if (!_failedDismissals.contains(d.pub)) d,
+ ];
+ final same = listEquals([for (final m in next) m.pub], [for (final m in newDevices) m.pub]);
+ final sameDeparted =
+ listEquals([for (final d in nextDeparted) d.pub], [for (final d in departedDevices) d.pub]);
+ if (same && sameDeparted) return;
+ newDevices
+ ..clear()
+ ..addAll(next);
+ departedDevices
+ ..clear()
+ ..addAll(nextDeparted);
+ notifyListeners();
+ }
+
/// A machine waiting for its password that the device key log now vouches for: dial it again.
Future<void> _redialNewlyTrusted() async {
for (final state in [...machineStates.values]) {
@@ -2058,18 +2267,63 @@ class AppNotifier extends ChangeNotifier {
unawaited(log.refresh());
}
- /// The devices list was opened: every device announced so far has been seen.
- void seenNewDevices() {
- if (newDevices.isEmpty) return;
- newDevices.clear();
+ /// The devices list was opened: every device announced so far has been seen — the banner's, and
+ /// [pending], what the list itself read from the log (after a restart, before the banner is rebuilt
+ /// from it). Persisted, so the banner does not come back.
+ ///
+ /// [shown] is the banner's set as it was when the list was read: pass it when the page awaited
+ /// anything in between, or a device announced meanwhile — never shown — would be dismissed unseen.
+ /// Without it, the banner as it is now.
+ void seenNewDevices({Iterable<String> pending = const [], Iterable<String>? shown}) {
+ final bannerPubs = (shown ?? newDevices.map((d) => d.pub)).toList();
+ if (bannerPubs.isEmpty && pending.isEmpty) return;
+ // Exactly what was shown, never "all": a device added since (and not yet shown) stays pending.
+ // And a device that left before anyone looked is cleared by its own "Got it" only: opening the
+ // list is not that.
+ final departed = {for (final d in departedDevices) d.pub};
+ final marked = {...pending, ...bannerPubs}.where((p) => !departed.contains(p)).toList();
+ // Nothing marked: a read of `pending` under way (the one a startup replay starts, which takes a
+ // departed key's stale "New device" down) is not stale — let it land.
+ if (marked.isEmpty) return;
+ // A read of `pending` already under way predates this: it must not put them back.
+ _pendingSyncGen++;
+ unawaited(_dismissInLog(pubs: marked));
+ final before = newDevices.length;
+ newDevices.removeWhere((d) => marked.contains(d.pub));
+ if (newDevices.length != before) notifyListeners();
+ }
+
+ /// "It's mine" on [pub]. Only the device's own page, which shows why a key is Suspended, passes
+ /// [liftSuspension]: that is the person vouching for it. Anywhere else the key stays suspended —
+ /// the banner never said so.
+ void dismissNewDevice(String pub, {bool liftSuspension = false}) {
+ newDevices.removeWhere((d) => d.pub == pub);
+ // A key that joined and left before anyone looked: a "New device" for it is a stale replay, and its
+ // flag is cleared by its own "Got it" only ([dismissDeparted]) — "It's mine" here takes the banner
+ // down and marks nothing.
+ if (departedDevices.any((d) => d.pub == pub)) {
+ notifyListeners();
+ return;
+ }
+ _pendingSyncGen++;
+ unawaited(liftSuspension ? _dismissInLog(pub: pub) : _dismissInLog(pubs: [pub]));
notifyListeners();
}
- void dismissNewDevice(String pub) {
- newDevices.removeWhere((d) => d.pub == pub);
- notifyListeners();
+ /// "Got it" on the Devices page's "Already on your account" list: persisted, shown once.
+ Future<void> seeDeviceBaseline() async {
+ try {
+ await deviceLog?.seeBaseline();
+ } catch (error) {
+ debugPrint('devices: could not save the baseline as seen: $error');
+ }
}
+ /// Every add and remove on the account as this phone verified it. A seam of its own so a test can
+ /// answer without a real device log.
+ Future<DeviceLogHistory> deviceHistory() async =>
+ await _deviceLog?.history() ?? const DeviceLogHistory(rows: [], complete: false);
+
/// Take [pub] out of the account on every device. Null when done, else why not.
Future<String?> removeDevice(String pub) async {
final log = _deviceLog;
diff --git a/mobile/lib/viewer/device_history.dart b/mobile/lib/viewer/device_history.dart
new file mode 100644
index 000000000..540a23a4b
--- /dev/null
+++ b/mobile/lib/viewer/device_history.dart
@@ -0,0 +1,459 @@
+import '../e2ee/bytes.dart';
+import '../e2ee/keys.dart';
+import 'device_log.dart';
+
+/// The device key log read as a history — the Dart port of cli/src/lib/e2ee/deviceHistory.ts. The rows
+/// are the wire format of the daemon's `GET /api/devices/history`, so [DevLogHistoryRow.fromJson]
+/// reads exactly what the CLI's `devLogHistory` writes. Change both together.
+
+/// A key that was new here and was removed before anyone marked it as seen: it stays flagged — "joined
+/// your account and left before you looked" — until it is dismissed. The same JSON as an item of the
+/// daemon's `GET /api/devices` `departed` (cli deviceLogStore.ts `DevLogDeparted`).
+class DeviceLogDeparted {
+ const DeviceLogDeparted({
+ required this.pub,
+ required this.label,
+ required this.kind,
+ required this.machineId,
+ required this.fingerprint,
+ required this.addedAt,
+ required this.removedAt,
+ required this.removedBy,
+ required this.removedByLabel,
+ required this.selfRemoved,
+ });
+
+ final String pub;
+ final String label;
+
+ /// `machine` | `viewer`.
+ final String kind;
+ final String machineId;
+ final String fingerprint;
+
+ /// The `at` of the entry that added it (picked by that device).
+ final int addedAt;
+
+ /// The `at` of the entry that removed it (picked by its signer).
+ final int removedAt;
+
+ /// The key that signed the removal, and what it was called then ('' when not known).
+ final String removedBy;
+ final String removedByLabel;
+
+ /// It removed itself (signed out).
+ final bool selfRemoved;
+
+ Map<String, Object?> toJson() => {
+ 'pub': pub,
+ 'label': label,
+ 'kind': kind,
+ 'machineId': machineId,
+ 'fingerprint': fingerprint,
+ 'addedAt': addedAt,
+ 'removedAt': removedAt,
+ 'removedBy': removedBy,
+ 'removedByLabel': removedByLabel,
+ 'selfRemoved': selfRemoved,
+ };
+
+ static DeviceLogDeparted? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'],
+ label = raw['label'],
+ kind = raw['kind'],
+ machineId = raw['machineId'];
+ final fp = raw['fingerprint'],
+ addedAt = raw['addedAt'],
+ removedAt = raw['removedAt'];
+ final by = raw['removedBy'],
+ byLabel = raw['removedByLabel'],
+ self = raw['selfRemoved'];
+ if (pub is! String ||
+ pub.isEmpty ||
+ label is! String ||
+ (kind != 'machine' && kind != 'viewer')) {
+ return null;
+ }
+ if (machineId is! String ||
+ fp is! String ||
+ addedAt is! int ||
+ removedAt is! int) {
+ return null;
+ }
+ if (by is! String || byLabel is! String || self is! bool) return null;
+ return DeviceLogDeparted(
+ pub: pub,
+ label: label,
+ kind: kind as String,
+ machineId: machineId,
+ fingerprint: fp,
+ addedAt: addedAt,
+ removedAt: removedAt,
+ removedBy: by,
+ removedByLabel: byLabel,
+ selfRemoved: self,
+ );
+ }
+
+ /// A `departed` list as the daemon (or a stored file) has it: what cannot be read is left out.
+ static List<DeviceLogDeparted> listFromJson(Object? raw) => [
+ if (raw is List)
+ for (final d in raw) ?DeviceLogDeparted.fromJson(d),
+ ];
+}
+
+/// A device taken out of the account after this app joined it — the same JSON as the daemon's
+/// `device_key_removed` frame (cli deviceLogSyncer.ts `DeviceRemovalNotice`).
+class DeviceRemovalNotice {
+ const DeviceRemovalNotice({
+ required this.pub,
+ required this.label,
+ required this.kind,
+ required this.fingerprint,
+ required this.signer,
+ required this.signerLabel,
+ required this.signerFingerprint,
+ required this.signerPending,
+ required this.selfRemoved,
+ required this.at,
+ });
+
+ final String pub;
+ final String label;
+ final String kind;
+ final String fingerprint;
+ final String signer;
+ final String signerLabel;
+ final String signerFingerprint;
+
+ /// The signer is itself a new device nobody has looked at.
+ final bool signerPending;
+
+ /// The device removed itself (signed out).
+ final bool selfRemoved;
+ final int at;
+
+ Map<String, Object?> toJson() => {
+ 'pub': pub,
+ 'label': label,
+ 'kind': kind,
+ 'fingerprint': fingerprint,
+ 'signer': signer,
+ 'signerLabel': signerLabel,
+ 'signerFingerprint': signerFingerprint,
+ 'signerPending': signerPending,
+ 'selfRemoved': selfRemoved,
+ 'at': at,
+ };
+
+ static DeviceRemovalNotice? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'],
+ label = raw['label'],
+ kind = raw['kind'],
+ fp = raw['fingerprint'];
+ final signer = raw['signer'],
+ signerLabel = raw['signerLabel'],
+ signerFp = raw['signerFingerprint'];
+ if (pub is! String ||
+ label is! String ||
+ kind is! String ||
+ fp is! String) {
+ return null;
+ }
+ if (signer is! String || signerLabel is! String || signerFp is! String) {
+ return null;
+ }
+ return DeviceRemovalNotice(
+ pub: pub,
+ label: label,
+ kind: kind,
+ fingerprint: fp,
+ signer: signer,
+ signerLabel: signerLabel,
+ signerFingerprint: signerFp,
+ signerPending: raw['signerPending'] == true,
+ selfRemoved: raw['selfRemoved'] == true,
+ at: raw['at'] is int ? raw['at'] as int : 0,
+ );
+ }
+}
+
+class DevLogHistoryBy {
+ const DevLogHistoryBy({
+ required this.pub,
+ required this.label,
+ required this.fingerprint,
+ });
+
+ final String pub;
+ final String label;
+ final String fingerprint;
+
+ static DevLogHistoryBy? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'], label = raw['label'], fp = raw['fingerprint'];
+ if (pub is! String || label is! String || fp is! String) return null;
+ return DevLogHistoryBy(pub: pub, label: label, fingerprint: fp);
+ }
+}
+
+class DevLogHistoryRow {
+ const DevLogHistoryRow({
+ required this.seq,
+ required this.op,
+ required this.pub,
+ required this.kind,
+ required this.machineId,
+ required this.label,
+ this.previousLabel,
+ required this.fingerprint,
+ this.by,
+ required this.at,
+ required this.thisDevice,
+ required this.afterJoin,
+ required this.pending,
+ required this.active,
+ required this.whileFrozen,
+ });
+
+ final int seq;
+
+ /// `added` | `renamed` | `removed` | `signedOut`.
+ final String op;
+ final String pub;
+ final String kind;
+ final String machineId;
+ final String label;
+
+ /// For `renamed`: the name it had before, when known.
+ final String? previousLabel;
+ final String fingerprint;
+
+ /// For `removed`: the key that signed the removal.
+ final DevLogHistoryBy? by;
+ final int at;
+ final bool thisDevice;
+
+ /// Added after this device joined.
+ final bool afterJoin;
+
+ /// Still new: nobody marked it as seen here.
+ final bool pending;
+
+ /// The key is active in the log now.
+ final bool active;
+
+ /// A removal applied while the list was frozen (unchained, so unverified).
+ final bool whileFrozen;
+
+ static DevLogHistoryRow? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final seq = raw['seq'],
+ op = raw['op'],
+ pub = raw['pub'],
+ kind = raw['kind'];
+ final machineId = raw['machineId'], label = raw['label'];
+ final fp = raw['fingerprint'], at = raw['at'];
+ if (seq is! int || op is! String || pub is! String || kind is! String) {
+ return null;
+ }
+ if (machineId is! String || label is! String || fp is! String) return null;
+ if (at is! int) return null;
+ final previous = raw['previousLabel'];
+ return DevLogHistoryRow(
+ seq: seq,
+ op: op,
+ pub: pub,
+ kind: kind,
+ machineId: machineId,
+ label: label,
+ previousLabel: previous is String ? previous : null,
+ fingerprint: fp,
+ by: DevLogHistoryBy.fromJson(raw['by']),
+ at: at,
+ thisDevice: raw['thisDevice'] == true,
+ afterJoin: raw['afterJoin'] == true,
+ pending: raw['pending'] == true,
+ active: raw['active'] == true,
+ whileFrozen: raw['whileFrozen'] == true,
+ );
+ }
+}
+
+class DeviceLogHistory {
+ const DeviceLogHistory({required this.rows, required this.complete});
+
+ final List<DevLogHistoryRow> rows;
+
+ /// false when only part of the log could be read (offline).
+ final bool complete;
+
+ static DeviceLogHistory? fromJson(Object? raw) {
+ if (raw is! Map || raw['rows'] is! List) return null;
+ return DeviceLogHistory(
+ rows: [
+ for (final r in raw['rows'] as List) ?DevLogHistoryRow.fromJson(r),
+ ],
+ complete: raw['complete'] == true,
+ );
+ }
+}
+
+String _fp(String pub) {
+ try {
+ return fingerprint(b64d(pub));
+ } catch (_) {
+ return '';
+ }
+}
+
+/// Newest first. [entries] may have gaps at the front (offline: only the recent tail is known).
+/// [loose] are removals applied while frozen: they are not part of the chain, and are shown as such.
+List<DevLogHistoryRow> devLogHistory(
+ List<DevLogEntry> entries, {
+ required String selfPub,
+ int? joinedSeq,
+ required List<String> pending,
+ required Map<String, DevLogMember> active,
+ List<DevLogEntry> loose = const [],
+}) {
+ final seen = <String>{};
+ final ordered = <(DevLogEntry, bool)>[];
+ final sorted = [...entries]..sort((a, b) => a.seq.compareTo(b.seq));
+ for (final e in sorted) {
+ if (seen.add('${e.seq}:${e.sig}')) ordered.add((e, false));
+ }
+ for (final e in loose) {
+ if (seen.add('${e.seq}:${e.sig}')) ordered.add((e, true));
+ }
+ // The name each key last went by, to say "renamed from" and to name a signer that is gone.
+ final labels = {for (final m in active.values) m.pub: m.label};
+ final known = <String, ({String label, String kind, String machineId})>{};
+ final rows = <DevLogHistoryRow>[];
+ for (final (e, isLoose) in ordered) {
+ // A removal names the key as the log had it BEFORE: the remove entry's own label, kind and machine
+ // id are chosen by whoever signed it, and say nothing checked. When the add is outside what is
+ // known (offline, the newest entries only) the key is named by its fingerprint alone: an empty
+ // label, shown as "A device", and no kind or machine id of the signer's.
+ final prior = e.op == 'remove' ? known[e.pub] : null;
+ DevLogHistoryRow row(
+ String op, {
+ String? previousLabel,
+ DevLogHistoryBy? by,
+ }) => DevLogHistoryRow(
+ seq: e.seq,
+ op: op,
+ pub: e.pub,
+ kind: e.op == 'remove' ? prior?.kind ?? 'viewer' : e.kind,
+ machineId: e.op == 'remove' ? prior?.machineId ?? '' : e.machineId,
+ label: e.op == 'remove' ? prior?.label ?? '' : e.label,
+ previousLabel: previousLabel,
+ fingerprint: _fp(e.pub),
+ by: by,
+ at: e.at,
+ thisDevice: e.pub == selfPub,
+ afterJoin: joinedSeq != null && e.seq > joinedSeq,
+ pending: pending.contains(e.pub),
+ active: active.containsKey(e.pub),
+ whileFrozen: isLoose,
+ );
+ if (e.op == 'add') {
+ final before = known[e.pub];
+ final member = active[e.pub];
+ if (before != null || (member != null && member.seq < e.seq)) {
+ rows.add(row('renamed', previousLabel: before?.label));
+ } else {
+ rows.add(row('added'));
+ }
+ known[e.pub] = (label: e.label, kind: e.kind, machineId: e.machineId);
+ labels[e.pub] = e.label;
+ } else if (e.signer == e.pub) {
+ rows.add(row('signedOut'));
+ known.remove(e.pub);
+ } else {
+ final label = known[e.signer]?.label ?? labels[e.signer] ?? '';
+ rows.add(
+ row(
+ 'removed',
+ by: DevLogHistoryBy(
+ pub: e.signer,
+ label: label,
+ fingerprint: _fp(e.signer),
+ ),
+ ),
+ );
+ known.remove(e.pub);
+ }
+ }
+ rows.sort((a, b) => b.seq.compareTo(a.seq));
+ return rows;
+}
+
+String _name(String label) => label.trim().isEmpty ? 'A device' : label.trim();
+
+/// How the apps word a [DeviceRemovalNotice], so the band and the notification say the same thing.
+extension DeviceRemovalCopy on DeviceRemovalNotice {
+ /// Removed by a new device nobody has looked at (a signed-out device is never red: it is its own act).
+ bool get red => signerPending && !selfRemoved;
+
+ String get title => selfRemoved
+ ? 'Device signed out'
+ : red
+ ? 'Removed by a new device'
+ : 'Device removed';
+
+ String get sentence {
+ final name = _name(label);
+ if (selfRemoved) return '$name signed out of your account.';
+ final signerName = signerLabel.trim().isEmpty
+ ? 'another device'
+ : signerLabel.trim();
+ if (!red) return '$name was removed from your account by $signerName.';
+ final groups = signerFingerprint
+ .split('·')
+ .take(2)
+ .where((g) => g.isNotEmpty)
+ .join('·');
+ final short = groups.isEmpty ? '' : ' · $groups…';
+ return '$name was removed from your account by a new device you haven’t looked at ($signerName$short).';
+ }
+}
+
+/// How the apps word a [DeviceLogDeparted]: "`label` joined your account and left before you looked."
+/// and, unless it signed itself out or nothing took it out (a review of the list), who took it out: " Removed by `signer`." With [red] — the signer is
+/// itself a device nobody has looked at — the sentence says so too, not the colour alone.
+extension DeviceDepartedCopy on DeviceLogDeparted {
+ String sentence({required bool red}) {
+ final head =
+ '${_name(label)} joined your account and left before you looked.';
+ if (selfRemoved || removedBy.isEmpty || removedBy == pub) return head;
+ final signer = removedByLabel.trim().isEmpty
+ ? 'another device'
+ : removedByLabel.trim();
+ return red
+ ? '$head Removed by $signer, a new device you haven’t looked at.'
+ : '$head Removed by $signer.';
+ }
+}
+
+/// What the row says happened, in words: `iPad added`, `Old Mac renamed to Mac`, `iPad removed by Mac`.
+/// A signer with no known name is "another device".
+String historySentence(DevLogHistoryRow row) {
+ final name = _name(row.label);
+ final signer = row.by?.label.trim() ?? '';
+ final text = switch (row.op) {
+ 'renamed' =>
+ row.previousLabel == null || row.previousLabel!.trim().isEmpty
+ ? '$name renamed'
+ : '${row.previousLabel!.trim()} renamed to $name',
+ 'removed' =>
+ row.by == null
+ ? '$name removed'
+ : '$name removed by ${signer.isEmpty ? 'another device' : signer}',
+ 'signedOut' => '$name signed out',
+ _ => '$name added',
+ };
+ return row.whileFrozen ? '$text · applied while the list was frozen' : text;
+}
diff --git a/mobile/lib/viewer/device_log_sync.dart b/mobile/lib/viewer/device_log_sync.dart
index 8057241ca..9248b9c1a 100644
--- a/mobile/lib/viewer/device_log_sync.dart
+++ b/mobile/lib/viewer/device_log_sync.dart
@@ -3,17 +3,22 @@ import 'dart:math';
import '../e2ee/bytes.dart';
import '../e2ee/keys.dart';
+import 'device_history.dart';
import 'device_log.dart';
import 'group_sync.dart';
import 'viewer_key_store.dart';
+export 'device_history.dart'
+ show DeviceDepartedCopy, DeviceLogDeparted, DeviceRemovalCopy, DeviceRemovalNotice, historySentence;
+
/// The account's device key log, on a device with no harness CLI — the viewer's half of
/// cli/src/lib/e2ee/deviceLogSyncer.ts.
///
/// Signing in is what puts this app's key into the log ([register]); every machine the log names is
/// then pinned here with no password, and every machine trusts this app. A backend that rewrites the
/// log or rolls it back FREEZES it here: nothing more is pinned from it until someone reviews what
-/// changed ([rebaseline]). A machine this app had never trusted is announced ("New device: X").
+/// changed ([rebaseline]). A key added after this app joined the log is announced ("New device: X") and
+/// stays pending until it is marked seen; what the log says is never read against what the roster holds.
/// What `GET /api/device-keys?since=` answered; null from the fetcher when there is no log to read.
typedef DeviceLogFetched = ({String acct, DevLogHead head, List<Object?> entries});
@@ -43,47 +48,165 @@ class DeviceLogFreeze {
}
class _File {
- _File(this.state, this.recent, this.frozen, this.notifiedUpTo);
+ _File(
+ this.state,
+ this.recent,
+ this.frozen,
+ this.notifiedUpTo, {
+ this.joinedSeq,
+ this.preLog = const [],
+ this.pending = const [],
+ this.announced = const [],
+ this.suspended = const [],
+ this.baselineSeen = true,
+ this.looseRemoved = const [],
+ this.reviewedSeq,
+ this.owner,
+ this.joining = false,
+ this.departed = const [],
+ });
DevLogState? state;
List<DevLogEntry> recent;
DeviceLogFreeze? frozen;
int notifiedUpTo;
+ /// The head seq this app's first read ended at: only an `add` past it is news. Null in a file from
+ /// before this existed (migrated on first use).
+ int? joinedSeq;
+
+ /// Keys this app trusted when it joined (or migrated): never news.
+ List<String> preLog;
+
+ /// New keys nobody has marked as seen yet.
+ List<String> pending;
+
+ /// Keys already announced — never twice.
+ List<String> announced;
+
+ /// Keys not trusted here after a fork, until [ViewerDeviceLog.rebaseline].
+ List<String> suspended;
+
+ /// false until the "Already on your account" panel was dismissed.
+ bool baselineSeen;
+
+ /// Removals applied while frozen: never in [recent], which is handed to peers as a chained tail.
+ List<DevLogEntry> looseRemoved;
+
+ /// The head seq of the list a person last reviewed ([ViewerDeviceLog.rebaseline]): a key at or
+ /// before it was looked at, so a later fork never suspends it.
+ int? reviewedSeq;
+
+ /// Which sign-in by hand this file belongs to (see [ViewerDeviceLog.register]). Null in a file from
+ /// before this existed.
+ String? owner;
+
+ /// true from the fresh write of a log until the first read of it reaches the head (or stops on a
+ /// freeze): while set, whatever is verified is what was there at joining — none of it is news.
+ bool joining;
+
+ /// New keys removed before anyone looked (oldest first, at most [_departedKept]).
+ List<DeviceLogDeparted> departed;
+
Map<String, Object?> toJson() => {
'state': state?.toJson(),
'recent': [for (final e in recent.skip(max(0, recent.length - _recentKept))) e.toJson()],
'frozen': frozen?.toJson(),
'notifiedUpTo': notifiedUpTo,
+ if (joinedSeq != null) ...{
+ 'joinedSeq': joinedSeq,
+ 'preLog': preLog,
+ 'pending': pending,
+ 'announced': announced,
+ 'baselineSeen': baselineSeen,
+ },
+ if (suspended.isNotEmpty) 'suspended': suspended,
+ if (reviewedSeq != null) 'reviewedSeq': reviewedSeq,
+ if (owner != null) 'owner': owner,
+ if (joining) 'joining': true,
+ if (looseRemoved.isNotEmpty)
+ 'looseRemoved': [for (final e in looseRemoved.skip(max(0, looseRemoved.length - _recentKept))) e.toJson()],
+ if (departed.isNotEmpty)
+ 'departed': [for (final d in departed.skip(max(0, departed.length - _departedKept))) d.toJson()],
};
+ static List<String> _strings(Object? raw) => raw is List ? [for (final v in raw) if (v is String) v] : <String>[];
+
static _File parse(Object? raw) {
if (raw is! Map) return _File(null, [], null, 0);
final recent = raw['recent'];
+ final loose = raw['looseRemoved'];
return _File(
DevLogState.fromJson(raw['state']),
recent is List ? recent.map(DevLogEntry.parse).whereType<DevLogEntry>().toList() : [],
DeviceLogFreeze.fromJson(raw['frozen']),
raw['notifiedUpTo'] is int ? raw['notifiedUpTo'] as int : 0,
+ joinedSeq: raw['joinedSeq'] is int && (raw['joinedSeq'] as int) >= 0 ? raw['joinedSeq'] as int : null,
+ preLog: _strings(raw['preLog']),
+ pending: _strings(raw['pending']),
+ announced: _strings(raw['announced']),
+ suspended: _strings(raw['suspended']),
+ baselineSeen: raw['baselineSeen'] is bool ? raw['baselineSeen'] as bool : true,
+ looseRemoved: loose is List ? loose.map(DevLogEntry.parse).whereType<DevLogEntry>().toList() : [],
+ reviewedSeq: raw['reviewedSeq'] is int && (raw['reviewedSeq'] as int) >= 0 ? raw['reviewedSeq'] as int : null,
+ owner: raw['owner'] is String && (raw['owner'] as String).isNotEmpty ? raw['owner'] as String : null,
+ joining: raw['joining'] == true,
+ departed: DeviceLogDeparted.listFromJson(raw['departed']),
);
}
}
const _recentKept = 64;
+
+/// How many departed keys are kept ([_File.departed]); the oldest goes first.
+const _departedKept = 32;
+
+/// How long after a sign-in by hand a read of another account may start the log over: past it, with no
+/// read of that account yet, the backend has had the time to pick when it says so.
+const _resetWindowMs = 10 * 60 * 1000;
const _appendAttempts = 5;
const _pages = 20;
+/// How many other accounts' logs are kept ([ViewerKeyStore.deviceLogArchive]); the oldest goes first.
+const _archivedKept = 4;
+
+/// How a sign-in id given to a session from before sign-in ids existed starts: nobody saw that
+/// sign-in being made here, so it may take a file over but never starts one over.
+const _adoptedSignIn = 'adopted:';
+
/// One device on the account, for the Devices list.
class DeviceLogRow {
- const DeviceLogRow(this.member, {required this.fingerprint, required this.self});
+ const DeviceLogRow(
+ this.member, {
+ required this.fingerprint,
+ required this.self,
+ this.pending = false,
+ this.suspended = false,
+ });
final DevLogMember member;
final String fingerprint;
final bool self;
+
+ /// Joined after this app did and nobody marked it as seen.
+ final bool pending;
+
+ /// Not trusted here after a fork, until the list is reviewed.
+ final bool suspended;
}
class DeviceLogListing {
- const DeviceLogListing({required this.members, required this.frozen, required this.frozenPeers});
+ const DeviceLogListing({
+ required this.members,
+ required this.frozen,
+ required this.frozenPeers,
+ this.pending = const [],
+ this.suspended = const [],
+ this.joinedSeq = 0,
+ this.baseline = const [],
+ this.baselineSeen = true,
+ this.departed = const [],
+ });
static const empty = DeviceLogListing(members: [], frozen: null, frozenPeers: []);
@@ -92,14 +215,98 @@ class DeviceLogListing {
/// Machines whose own copy of the log is frozen, as their last `group_sync` said.
final List<String> frozenPeers;
+
+ /// Keys that joined after this app did and nobody marked as seen.
+ final List<String> pending;
+
+ /// Keys not trusted here after a fork, until the list is reviewed.
+ final List<String> suspended;
+ final int joinedSeq;
+
+ /// The keys that were on the account before this app joined (the "Already on your account" list):
+ /// active, not this app, at or before [joinedSeq] — plus any key this app already trusted at joining
+ /// whose entry came after it (a log cut short at the first read must not hide it).
+ final List<String> baseline;
+
+ /// false until the "already on your account" list was acknowledged.
+ final bool baselineSeen;
+
+ /// New keys removed before anyone marked them as seen (oldest first): flagged until [ViewerDeviceLog.dismiss]
+ /// names them (`pub`, or `pubs`) or clears every one.
+ final List<DeviceLogDeparted> departed;
+}
+
+/// The newest hashes a `group_sync` carries, so a fork can be located.
+const _gossipHashes = 64;
+
+/// Where a peer's log first differs from [state]: the first seq, in the window of hashes the peer sent
+/// (`theirs['hashes']`, the last of which is `theirs['head']`), whose hash is not ours — only when the
+/// entry before it matches (or it is the first), so the split is proven rather than guessed. Null when
+/// the peer sent no usable hashes, nothing in the shared window differs, or the split lies before it.
+int? devLogDivergence(DevLogState state, Object? theirs) {
+ if (theirs is! Map) return null;
+ final hashes = theirs['hashes'];
+ if (hashes is! List || hashes.isEmpty || hashes.length > 4 * _gossipHashes) return null;
+ final window = <int, String>{};
+ var prev = 0;
+ for (final h in hashes) {
+ if (h is! Map) return null;
+ final seq = h['seq'], hash = h['hash'];
+ if (seq is! int || seq < 1 || hash is! String || hash.length > 128) return null;
+ if (prev != 0 && seq != prev + 1) return null;
+ prev = seq;
+ window[seq] = hash;
+ }
+ // The window must end where the peer's head is, or it describes some other log.
+ final head = DevLogHead.fromJson(theirs['head']);
+ if (head == null || head.seq != prev || head.hash != window[prev]) return null;
+ final first = window.keys.reduce(min);
+ for (final e in window.entries) {
+ if (e.key > state.head.seq || state.hashes[e.key - 1] == e.value) continue;
+ if (e.key == 1) return 1;
+ if (e.key == first) return null;
+ return state.hashes[e.key - 2] == window[e.key - 1] ? e.key : null;
+ }
+ return null;
+}
+
+
+/// What a step under the file lock found to tell the app — said once the lock is let go, since a
+/// listener may well read the log again (and signing out waits on the app).
+class _Effects {
+ final announce = <DevLogMember>[];
+ final removed = <DeviceRemovalNotice>[];
+ bool signOut = false;
+ bool changed = false;
}
class DeviceLogRebaseline {
- const DeviceLogRebaseline(this.head, this.added, this.removed);
+ const DeviceLogRebaseline(this.head, this.added, this.removed) : logChanged = false, otherAccount = false;
+
+ /// The backend's list is no longer the one that was previewed: nothing was done. Branch on
+ /// [logChanged]; [head], [added] and [removed] are empty placeholders then.
+ const DeviceLogRebaseline.changed()
+ : head = const DevLogHead(0, ''),
+ added = const [],
+ removed = const [],
+ logChanged = true,
+ otherAccount = false;
+
+ /// The backend's list is another account's while the live log is the one of the sign-in this app is
+ /// under: nothing was done — only a sign-in switches accounts. Branch on [otherAccount]; [head],
+ /// [added] and [removed] are empty placeholders then.
+ const DeviceLogRebaseline.otherAccount()
+ : head = const DevLogHead(0, ''),
+ added = const [],
+ removed = const [],
+ logChanged = false,
+ otherAccount = true;
final DevLogHead head;
final List<DevLogMember> added;
final List<DevLogMember> removed;
+ final bool logChanged;
+ final bool otherAccount;
}
class ViewerDeviceLog {
@@ -109,6 +316,7 @@ class ViewerDeviceLog {
required this.append,
required this.label,
this.onAnnounce,
+ this.onRemoved,
this.onSignedOut,
this.onChanged,
int Function()? now,
@@ -123,9 +331,12 @@ class ViewerDeviceLog {
/// How this app calls itself in the account's list of devices.
final String Function() label;
- /// A machine this app had never trusted joined the account: "New device: X".
+ /// A key joined the account after this app did: "New device: X".
final void Function(DevLogMember member)? onAnnounce;
+ /// A device was taken out of the account after this app joined it (not by this app).
+ final void Function(DeviceRemovalNotice notice)? onRemoved;
+
/// This app's own key was removed from the account: it is signed out.
final Future<void> Function()? onSignedOut;
@@ -139,11 +350,34 @@ class ViewerDeviceLog {
final _random = Random();
final Set<String> _removing = {};
+ /// Every entry fetched for the history so far (seq 1..n), this run only: never written to disk.
+ List<DevLogEntry> _histCache = [];
+ String? _histAcct;
+
/// Set while a sign-in by hand registers: this app's old key being removed is then expected, and is
/// replaced rather than signed out over.
bool _signingInAgain = false;
bool _signedOut = false;
+ /// Set while [register] runs.
+ bool _registering = false;
+
+ /// Moves on with each [beginSignIn]: a read that began after one, outside [register], ends what it
+ /// set — a sign-in by hand that never registers must not keep this app's own removal from signing
+ /// it out for good.
+ int _signInRound = 0;
+
+ /// Which sign-in by hand this app is under ([ViewerKeyStore.signInEpoch]), once known: minted by
+ /// [beginSignIn] (or [register] with `freshSignIn`), never anything the backend sends (not the
+ /// profile's id either).
+ String? _epoch;
+
+ /// Set by [beginSignIn] until [register] takes it: a sign-in by hand waiting to be registered.
+ bool _freshPending = false;
+
+ /// The write of the sign-in id [beginSignIn] minted; [register] waits for it.
+ Future<void>? _epochSaving;
+
/// This app's key is gone from the log: sign out, once.
Future<void> _signOut() async {
if (_signedOut) return;
@@ -161,10 +395,19 @@ class ViewerDeviceLog {
/// a reason to sign out — this app may have been signed out by the removal before it could read it
/// (a revoked session answers 401 first), and signing in again must not end in a second sign-out.
/// A stored session (the app opening) under a removed key signs out, as it always did.
+ ///
+ /// A sign-in by hand is also what lets this app's copy of the log move to another account (keeping
+ /// the one it leaves, to restore if it comes back) — for a short while after it ([_resetWindowMs]).
+ /// Its id is minted by [beginSignIn], which [register] calls itself when it was not called before.
Future<void> register({bool freshSignIn = false}) async {
- _signingInAgain = freshSignIn;
+ if (freshSignIn && !_freshPending) beginSignIn(fresh: true);
+ final fresh = _freshPending;
+ _freshPending = false;
+ _signingInAgain = fresh;
_signedOut = false;
+ _registering = true;
try {
+ await _epochSaving;
await refresh();
var identity = await keys.identity();
var pub = b64e(identity.pub);
@@ -174,7 +417,7 @@ class ViewerDeviceLog {
final state = file.state;
if (state == null || file.frozen != null) return;
if (state.removed.contains(pub)) {
- if (!freshSignIn) {
+ if (!fresh) {
await _signOut();
return;
}
@@ -204,80 +447,531 @@ class ViewerDeviceLog {
// The next sign-in, resume or push tries again.
} finally {
_signingInAgain = false;
+ _registering = false;
}
}
+ /// The app knows who is signed in — call it synchronously, before anything that reads the log (a
+ /// restored pane, a machine list, a connection) can start, then [register]. [fresh]: the person
+ /// signed in by hand just now (`DirectAuth.consumeFreshSignIn()`); its id is minted here, so a read
+ /// already on its way judges by this sign-in, not the one before. A stored session (the app opening)
+ /// is not fresh: nothing is minted.
+ void beginSignIn({required bool fresh}) {
+ _signedOut = false;
+ _freshPending = fresh;
+ // A removal of this app's old key read before [register] runs is then expected, not a sign-out —
+ // for the read that comes first ([_doRefresh] ends it), or until [register] takes over.
+ _signingInAgain = fresh;
+ _signInRound++;
+ if (!fresh) return;
+ final previous = _epoch;
+ final minted = _mintEpoch();
+ _epoch = minted;
+ _epochSaving = keys.writeSignInEpoch(minted).then(
+ (_) {},
+ onError: (Object _) {
+ // Not kept, not used: after a restart the file would be another sign-in's than the store's.
+ if (_epoch == minted) _epoch = previous;
+ },
+ );
+ }
+
/// Read and verify whatever the log gained. Concurrent calls share one read. Never throws.
Future<void> refresh() => _refreshing ??= _doRefresh().catchError((Object _) {}).whenComplete(() => _refreshing = null);
+ /// The tail of the queue every read-modify-write of the file waits in. A refresh, a peer's tail, a
+ /// dismissal and a review each read the file, change it and write it back; two of them interleaved
+ /// would write the older read over the newer one — a head rolled back, an announcement forgotten
+ /// and made twice, a dismissal undone.
+ Future<void> _fileQueue = Future.value();
+
+ /// Run [body] alone against the file — within this instance: two instances over one store (two web
+ /// tabs) do not see each other's lock and can still interleave. [body] must not wait on anything
+ /// that takes the lock itself (and nothing the app is told runs inside it: see [_Effects]).
+ Future<T> _locked<T>(Future<T> Function() body) {
+ final before = _fileQueue;
+ final done = Completer<void>();
+ _fileQueue = done.future;
+ return before.then((_) => body()).whenComplete(() => done.complete());
+ }
+
+ /// Tell the app what a step under the lock decided, once the lock is let go.
+ Future<void> _fire(_Effects e) async {
+ for (final m in e.announce) {
+ onAnnounce?.call(m);
+ }
+ for (final n in e.removed) {
+ onRemoved?.call(n);
+ }
+ if (e.signOut) await _signOut();
+ if (e.changed) onChanged?.call();
+ }
+
+ /// A sign-in id: random, then `@` and when it was made (ms) — see [_mayStartOver].
+ String _mintEpoch() =>
+ '${[for (var i = 0; i < 16; i++) _secure.nextInt(256).toRadixString(16).padLeft(2, '0')].join()}@${_now()}';
+ static final _secure = Random.secure();
+
+ /// Whether [local] — a sign-in by hand the file is not yet the log of — may start it over for another
+ /// account: never an adopted one, and only shortly after it was made. A backend that holds the log
+ /// back after a sign-in must not keep that door open, to name another account days later.
+ bool _mayStartOver(String local) {
+ if (local.startsWith(_adoptedSignIn)) return false;
+ final made = RegExp(r'@(\d{1,15})$').firstMatch(local);
+ if (made == null) return false;
+ return (_now() - int.parse(made.group(1)!)).abs() <= _resetWindowMs;
+ }
+
+ /// Whether [file] is the log of the sign-in this app is under (or that cannot be told). Until a read
+ /// of it under a new sign-in it may be the account just left: what a machine gossips is not judged
+ /// against it — a machine of the new account would read as a fork of the old one.
+ Future<bool> _ownsFile(_File file) async {
+ final local = await _localOwner();
+ return local == null || file.owner == local;
+ }
+
+ /// The sign-in by hand this app is under; a session from before sign-in ids existed is given one,
+ /// adopted ([_adoptedSignIn]). Null when the store cannot be read.
+ Future<String?> _localOwner() async {
+ if (_epoch case final epoch?) return epoch;
+ try {
+ final stored = await keys.signInEpoch();
+ if (stored != null && stored.isNotEmpty) return _epoch ??= stored;
+ final adopted = '$_adoptedSignIn${_mintEpoch()}';
+ await keys.writeSignInEpoch(adopted);
+ return _epoch ??= adopted;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// The first read of the log is over, however it ended: what is verified from here on is news.
+ Future<void> _endJoin() => _locked(() async {
+ final file = await _read();
+ if (!file.joining) return;
+ file.joining = false;
+ await _write(file);
+ });
+
+ /// The logs of accounts this app was signed in to before, by account id.
+ Future<Map<String, Object?>> _archived() async {
+ try {
+ return await keys.deviceLogArchive();
+ } catch (_) {
+ return {};
+ }
+ }
+
+ /// Keep [file] — the log of an account this app is leaving — to restore if it comes back. Under the lock.
+ Future<void> _archiveIn(_File file) async {
+ final acct = file.state?.acct;
+ if (acct == null) return;
+ final all = await _archived()
+ ..remove(acct);
+ all[acct] = file.toJson();
+ while (all.length > _archivedKept) {
+ all.remove(all.keys.first);
+ }
+ await keys.writeDeviceLogArchive(all);
+ }
+
+ /// The kept log of [acct], made the live file (this sign-in's: [owner]) and only then taken out of
+ /// the archive — a crash in between leaves it in both, never in neither. Null when there is none.
+ /// Under the lock.
+ Future<_File?> _restoreIn(String acct, String? owner) async {
+ final kept = _File.parse((await _archived())[acct]);
+ if (kept.state?.acct != acct) return null;
+ kept.owner = owner ?? kept.owner;
+ await _carrySuspensionsIn(kept);
+ await _write(kept);
+ final all = await _archived()
+ ..remove(acct);
+ await keys.writeDeviceLogArchive(all);
+ return kept;
+ }
+
+ /// [file], with every key a fork suspended in another account's kept log, and active in this one,
+ /// suspended (and new) here as well: it is not trusted either way, so the list says so — and "It's
+ /// mine" lifts it, everywhere (a review of this list does not: it never showed that suspension).
+ /// Under the lock.
+ Future<void> _carrySuspensionsIn(_File file) async {
+ final state = file.state;
+ if (state == null) return;
+ final selfPub = await _selfPub();
+ final carried = [
+ for (final k in await _archivedSuspended())
+ if (state.active.containsKey(k) && k != selfPub && !file.suspended.contains(k)) k,
+ ];
+ if (carried.isEmpty) return;
+ file
+ ..suspended = [...file.suspended, ...carried]
+ ..pending = {...file.pending, ...carried}.toList();
+ }
+
+ /// A suspension lifted here holds for every kept account too: none of them keeps [pubs] out. Under
+ /// the lock.
+ Future<void> _unsuspendArchivedIn(Iterable<String> pubs) async {
+ final lift = pubs.toSet();
+ final all = await _archived();
+ var changed = false;
+ for (final e in all.entries.toList()) {
+ final f = _File.parse(e.value);
+ if (!f.suspended.any(lift.contains)) continue;
+ f.suspended = [for (final k in f.suspended) if (!lift.contains(k)) k];
+ all[e.key] = f.toJson();
+ changed = true;
+ }
+ if (changed) await keys.writeDeviceLogArchive(all);
+ }
+
+ /// [gone], just taken out by [e], kept flagged: it was new here and nobody had looked at it yet.
+ DeviceLogDeparted _departedOf(DevLogMember gone, DevLogEntry e, String signerLabel) => DeviceLogDeparted(
+ pub: gone.pub,
+ label: gone.label,
+ kind: gone.kind,
+ machineId: gone.machineId,
+ fingerprint: fingerprint(b64d(gone.pub)),
+ addedAt: gone.addedAt,
+ removedAt: e.at,
+ removedBy: e.signer,
+ removedByLabel: signerLabel,
+ selfRemoved: e.signer == gone.pub,
+ );
+
+ /// [prev] plus [more] (a key once, at its newest), the oldest dropped past [_departedKept].
+ List<DeviceLogDeparted> _withDeparted(List<DeviceLogDeparted> prev, List<DeviceLogDeparted> more) {
+ if (more.isEmpty) return prev;
+ final pubs = {for (final d in more) d.pub};
+ final all = [for (final d in prev) if (!pubs.contains(d.pub)) d, ...more];
+ return all.skip(max(0, all.length - _departedKept)).toList();
+ }
+
+ /// The kept log of [acct], left in the archive; null when there is none.
+ Future<_File?> _archivedFileIn(String acct) async {
+ final kept = _File.parse((await _archived())[acct]);
+ return kept.state?.acct == acct ? kept : null;
+ }
+
+ /// What a review ([rebaseline]) takes out that was new here and never looked at: a key pending in
+ /// [base] that the reviewed list does not keep — and a key the list added and removed again at
+ /// entries this app never verified (while it was frozen) — stays flagged as departed.
+ List<DeviceLogDeparted> _reviewDeparted(
+ _File base,
+ DevLogState next,
+ List<DevLogEntry> parsed,
+ List<DevLogMember> removed,
+ String selfPub,
+ Set<String> pre,
+ ) {
+ final verified = base.state;
+ if (verified == null) return [];
+ final known = <String, ({String label, String kind})>{};
+ final adds = <String, DevLogEntry>{};
+ final out = <String, DeviceLogDeparted>{};
+ for (final e in [...parsed]..sort((a, b) => a.seq.compareTo(b.seq))) {
+ if (e.op == 'add') {
+ if (!known.containsKey(e.pub)) adds[e.pub] = e; // added (not renamed)
+ known[e.pub] = (label: e.label, kind: e.kind);
+ continue;
+ }
+ final was = removed.where((m) => m.pub == e.pub).firstOrNull;
+ final add = adds[e.pub];
+ final label = known[e.pub]?.label;
+ known.remove(e.pub);
+ if (e.pub == selfPub || next.active[e.pub] != null) continue;
+ // Added at an entry this app never verified, and gone again before it could see it.
+ final unseen = was == null &&
+ add != null &&
+ (add.seq > verified.hashes.length || verified.hashes[add.seq - 1] != devLogHash(add)) &&
+ !pre.contains(e.pub);
+ if ((was != null && base.pending.contains(e.pub)) || unseen) {
+ final member = was ??
+ DevLogMember(pub: e.pub, kind: add!.kind, machineId: add.machineId, label: label ?? add.label, addedAt: add.at, seq: add.seq);
+ out[e.pub] = _departedOf(member, e, known[e.signer]?.label ?? '');
+ }
+ }
+ // Pending here, and not on the reviewed list at all (a branch the backend no longer serves).
+ for (final m in removed) {
+ if (out.containsKey(m.pub) || m.pub == selfPub || !base.pending.contains(m.pub)) continue;
+ out[m.pub] = DeviceLogDeparted(
+ pub: m.pub,
+ label: m.label,
+ kind: m.kind,
+ machineId: m.machineId,
+ fingerprint: fingerprint(b64d(m.pub)),
+ addedAt: m.addedAt,
+ removedAt: _now(),
+ removedBy: '',
+ removedByLabel: '',
+ selfRemoved: false,
+ );
+ }
+ return [...out.values];
+ }
+
+ /// Every key a fork suspended in another account's kept log: no other account's log brings it back.
+ Future<Set<String>> _archivedSuspended() async => {
+ for (final f in (await _archived()).values) ..._File.parse(f).suspended,
+ };
+
+ Future<_File> _marks() => _locked(_marksIn);
+
+ /// [_marks], for a caller already holding the lock: the file, with the joined point filled in for one
+ /// written before it existed (or by a client that dropped it) — everything up to what was already
+ /// announced is then known, as it was.
+ Future<_File> _marksIn() async {
+ final file = await _read();
+ if (file.state == null || file.joinedSeq != null) return file;
+ file.joinedSeq = file.notifiedUpTo;
+ file.preLog = (await _knownPubs()).toList();
+ file.pending = [];
+ file.announced = [];
+ file.baselineSeen = true;
+ await _write(file);
+ return file;
+ }
+
Future<void> _doRefresh() async {
+ // A sign-in by hand waiting for [register]: this read is the one its old key's removal is expected
+ // in. After it, with no [register] under way, a removal of this app's key signs out again.
+ final round = _signInRound;
+ final expecting = _signingInAgain;
+ try {
+ await _readPages();
+ } finally {
+ // However the read ended — at the head, on a freeze, or cut short (no answer, the page cap) — the
+ // first read of a log is over: what is verified from here on is news. Held open, a backend that
+ // stalls the second page would have every key it adds later taken for one there at joining.
+ await _endJoin();
+ if (expecting && !_registering && round == _signInRound) _signingInAgain = false;
+ }
+ }
+
+ Future<void> _readPages() async {
+ await _marks();
var bootstrap = ((await _read()).state?.head.seq ?? 0) == 0;
for (var page = 0; page < _pages; page++) {
- final file = await _read();
- final since = file.state?.head.seq ?? 0;
+ final seen = (await _read()).state;
+ final since = seen?.head.seq ?? 0;
final got = await fetch(since);
if (got == null) return;
- if (file.state == null || file.state!.acct != got.acct) {
- // First read, or signed in to another account: that account's log starts from nothing here.
- await _write(_File(DevLogState.empty(got.acct), [], null, 0));
- bootstrap = true;
- if (got.head.seq == 0) return;
- if (since != 0) continue;
- }
- final current = await _read();
- final state = current.state!;
- if (current.frozen != null) {
- await _looseRemovals(got.entries);
- return;
- }
- if (got.head.seq < state.head.seq) return _freeze('rollback');
- if (got.head.seq == state.head.seq) {
- if (got.head.hash != state.head.hash) await _freeze('fork');
- return;
- }
- if (got.entries.isEmpty) return _freeze('invalid');
- if (!await _accept(got.entries, bootstrap)) return;
- if ((await _read()).state!.head.seq >= got.head.seq) return;
+ // A head that is not a position is the backend lying (or broken): nothing to verify it against.
+ if (!_isPosition(got.head.seq)) return;
+ final effects = _Effects();
+ // Whether to read another page.
+ final more = await _locked(() async {
+ var file = await _marksIn();
+ final local = await _localOwner();
+ var reset = file.state == null;
+ if (!reset) {
+ final signedInAgain = local != null && file.owner != local;
+ if (file.state!.acct != got.acct) {
+ // Another account only after a sign-in by hand here. Otherwise it is the backend saying so
+ // — and starting over would clear every mark a fork put on the list, the real log then
+ // adopted whole.
+ if (local == null || !signedInAgain || !_mayStartOver(local)) {
+ await _freezeIn(file, 'invalid', effects);
+ return false;
+ }
+ reset = true;
+ } else if (signedInAgain) {
+ // Signed in again to the same account: the same list, now this sign-in's.
+ file.owner = local;
+ await _write(file);
+ }
+ }
+ if (reset) {
+ if (file.state != null) await _archiveIn(file);
+ // Back to an account this app was signed in to before: its log as verified then, and every
+ // mark on it (frozen, suspended, pending), go on from where they were.
+ final kept = await _restoreIn(got.acct, local);
+ if (kept != null) {
+ bootstrap = (kept.state?.head.seq ?? 0) == 0;
+ return true;
+ }
+ // First read, or signed in to another account here: that account's log starts from nothing.
+ // `joinedSeq` starts at 0 and follows the head of each page this app VERIFIES ([_acceptIn]):
+ // never the head the backend merely claims, or it could park it far ahead and have every key
+ // it forges below that adopted without a word. `preLog` is what was trusted already.
+ file = _File(
+ DevLogState.empty(got.acct),
+ [],
+ null,
+ 0,
+ joinedSeq: 0,
+ preLog: (await _knownPubs()).toList(),
+ baselineSeen: false,
+ joining: true,
+ owner: local,
+ );
+ await _write(file);
+ bootstrap = true;
+ if (got.head.seq == 0) return false;
+ if (since != 0) return true;
+ } else if (seen == null || seen.acct != file.state!.acct || seen.head != file.state!.head) {
+ // The log moved here while this page was on its way (a peer handed over its tail): the page
+ // answers a question nobody is asking any more — judged against the newer head it would read
+ // as a rollback, or as entries out of order. Ask again from where the log is now.
+ return true;
+ }
+ final state = file.state!;
+ if (file.frozen != null) {
+ await _looseRemovalsIn(file, got.entries, effects);
+ return false;
+ }
+ if (got.head.seq < state.head.seq) {
+ await _freezeIn(file, 'rollback', effects);
+ return false;
+ }
+ if (got.head.seq == state.head.seq) {
+ if (got.head.hash != state.head.hash) await _freezeIn(file, 'fork', effects);
+ return false;
+ }
+ if (got.entries.isEmpty) {
+ await _freezeIn(file, 'invalid', effects);
+ return false;
+ }
+ if (!await _acceptIn(file, got.entries, bootstrap, effects)) return false;
+ return file.state!.head.seq < got.head.seq;
+ });
+ await _fire(effects);
+ if (!more) return;
}
}
- Future<bool> _accept(List<Object?> entries, bool bootstrap) async {
- final file = await _read();
+ /// [keys] cut to the ones still active — the marks never outlive the key.
+ List<String> _prune(List<String> keys, DevLogState state) => [
+ for (final k in keys.toSet())
+ if (state.active.containsKey(k)) k,
+ ];
+
+ /// What each active key in [state] is called now, to be walked forward through entries.
+ Map<String, ({String label, String kind})> _knownOf(DevLogState state) => {
+ for (final m in state.active.values) m.pub: (label: m.label, kind: m.kind),
+ };
+
+ /// The notice for a `remove`, or null when there is nothing to say: this app's own removal, its own
+ /// key, or a removal from before it joined. [known] says what each key was called, and what kind it
+ /// was, BEFORE this removal — the remove entry's own label and kind are the signer's to pick, so they
+ /// are never what the person is told.
+ DeviceRemovalNotice? _removalNotice(
+ DevLogEntry e,
+ int joinedSeq,
+ String selfPub,
+ List<String> pending,
+ Map<String, ({String label, String kind})> known,
+ ) {
+ if (e.op != 'remove' || e.seq <= joinedSeq || e.pub == selfPub || e.signer == selfPub) return null;
+ final was = known[e.pub];
+ return DeviceRemovalNotice(
+ pub: e.pub,
+ label: was?.label ?? e.label,
+ kind: was?.kind ?? e.kind,
+ fingerprint: fingerprint(b64d(e.pub)),
+ signer: e.signer,
+ signerLabel: known[e.signer]?.label ?? '',
+ signerFingerprint: fingerprint(b64d(e.signer)),
+ signerPending: pending.contains(e.signer),
+ selfRemoved: e.signer == e.pub,
+ at: _now(),
+ );
+ }
+
+ /// The entries a peer handed over that this app lacks, applied under the lock — judged against the
+ /// head the file has by then, which a refresh may have moved since the peer was heard.
+ Future<bool> _acceptFromPeer(List<Object?> entries) async {
+ final effects = _Effects();
+ final ok = await _locked(() async {
+ final file = await _marksIn();
+ final state = file.state;
+ if (state == null || file.frozen != null) return false;
+ final missing = [
+ for (final e in entries)
+ if ((DevLogEntry.parse(e)?.seq ?? 0) > state.head.seq) e,
+ ];
+ if (missing.isEmpty) return true;
+ return _acceptIn(file, missing, false, effects);
+ });
+ await _fire(effects);
+ return ok;
+ }
+
+ /// Apply [entries] to [file] and write it; under the lock. What the app is told goes in [effects].
+ Future<bool> _acceptIn(_File file, List<Object?> entries, bool bootstrap, _Effects effects) async {
+ // While the first read of this log is open (a peer's tail can arrive between its pages too):
+ // whatever is verified before it reaches the head is what was there at joining.
+ final joining = file.joining;
final DevLogApplied applied;
try {
applied = await applyDevLogEntries(file.state!, entries);
} on DevLogError catch (err) {
- await _freeze(err.code == 'BROKEN_CHAIN' || err.code == 'OUT_OF_ORDER' ? 'fork' : 'invalid');
+ await _freezeIn(file, err.code == 'BROKEN_CHAIN' || err.code == 'OUT_OF_ORDER' ? 'fork' : 'invalid', effects);
return false;
}
final selfPub = await _selfPub();
- final known = await _knownPubs();
- final news = bootstrap
- ? const <DevLogMember>[]
- : [
- for (final m in applied.added)
- if (m.seq > file.notifiedUpTo && m.pub != selfPub && !known.contains(m.pub)) m,
- ];
- await _write(_File(
- applied.state,
- [...file.recent, ...entries.map(DevLogEntry.parse).whereType<DevLogEntry>()],
- null,
- applied.state.head.seq,
- ));
+ // While joining, everything this page verified is what was there before: the joined point moves up
+ // to the verified head (never past it), and none of it is news.
+ final joinedSeq = joining ? applied.state.head.seq : file.joinedSeq ?? 0;
+ final pre = file.preLog.toSet();
+ final parsed = entries.map(DevLogEntry.parse).whereType<DevLogEntry>().toList();
+ // News is decided from the log alone: an `add` past the point this app joined, for a key it did not
+ // already trust then. What the roster or the pins hold now says nothing — a key can reach them
+ // (over `group_sync`) before this app reads the entry that adds it.
+ final news = [
+ for (final m in applied.added)
+ if (m.seq > joinedSeq && m.pub != selfPub && !pre.contains(m.pub)) m,
+ ];
+ final pendingNow = [...file.pending, for (final m in news) m.pub];
+ // Walk the entries in order: a removal is described by what the key was called when it was removed.
+ final known = _knownOf(file.state!);
+ final notices = <DeviceRemovalNotice>[];
+ final gone = {for (final m in applied.removed) m.pub: m};
+ final departed = <DeviceLogDeparted>[];
+ for (final e in [...parsed]..sort((a, b) => a.seq.compareTo(b.seq))) {
+ if (e.op == 'add') {
+ known[e.pub] = (label: e.label, kind: e.kind);
+ } else {
+ final n = _removalNotice(e, joinedSeq, selfPub, pendingNow, known);
+ if (n != null) notices.add(n);
+ // A new key nobody looked at, gone again (even within this page): it stays flagged.
+ final member = gone[e.pub];
+ if (member != null && pendingNow.contains(e.pub) && e.pub != selfPub) {
+ departed.add(_departedOf(member, e, known[e.signer]?.label ?? ''));
+ }
+ known.remove(e.pub);
+ }
+ }
+ final toAnnounce = [
+ for (final m in news)
+ if (!file.announced.contains(m.pub)) m,
+ ];
+ // A key taken into the "already on your account" list after that list was acknowledged: show it.
+ if (joining && applied.added.any((m) => m.pub != selfPub)) file.baselineSeen = false;
+ file
+ ..state = applied.state
+ ..joinedSeq = joinedSeq
+ ..recent = [...file.recent, ...parsed]
+ ..frozen = null
+ ..notifiedUpTo = applied.state.head.seq
+ ..pending = _prune(pendingNow, applied.state)
+ ..announced = _prune([...file.announced, for (final m in toAnnounce) m.pub], applied.state)
+ ..suspended = _prune(file.suspended, applied.state)
+ ..departed = _withDeparted(file.departed, departed);
+ await _carrySuspensionsIn(file);
+ await _write(file);
await _trust(bootstrap ? applied.state.active.values.toList() : [...applied.added, ...applied.relabeled]);
for (final m in applied.removed) {
await _drop(m);
}
- for (final m in news) {
- onAnnounce?.call(m);
- }
- if (applied.state.removed.contains(selfPub) && !_signingInAgain) await _signOut();
- onChanged?.call();
+ effects.announce.addAll(toAnnounce);
+ effects.removed.addAll(notices);
+ if (applied.state.removed.contains(selfPub) && !_signingInAgain) effects.signOut = true;
+ effects.changed = true;
return true;
}
- /// What this app already trusted — its pins and its trust group — so a key the log adds that is
- /// among them is not news.
+ /// What this app trusts right now — its pins and its trust group — snapshotted once, when it joins
+ /// the log (or migrates), so what it already knew then is never news.
Future<Set<String>> _knownPubs() async {
final roster = GroupRoster.parse(await keys.groupRoster());
return {
@@ -293,10 +987,11 @@ class ViewerDeviceLog {
final stored = GroupRoster.parse(await keys.groupRoster());
final inRoster = {for (final m in stored.members) m.pub};
final tombstoned = {for (final t in stored.removed) if (!inRoster.contains(t.pub)) t.pub};
+ final suspended = await suspendedPubs();
final now = _now();
final adopt = [
for (final m in members)
- if (m.pub != selfPub && !tombstoned.contains(m.pub)) m,
+ if (m.pub != selfPub && !tombstoned.contains(m.pub) && !suspended.contains(m.pub)) m,
];
final incoming = [
for (final m in adopt)
@@ -340,35 +1035,58 @@ class ViewerDeviceLog {
}
}
- /// While frozen, a removal still counts — if a key this app trusts signed it.
- Future<void> _looseRemovals(List<Object?> entries) async {
- final file = await _read();
+ /// While frozen, a removal still counts — if a key this app trusts signed it. A key a fork suspended
+ /// is not trusted here, so what it signs does not count either.
+ /// Under the lock.
+ Future<void> _looseRemovalsIn(_File file, List<Object?> entries, _Effects effects) async {
final state = file.state;
if (state == null) return;
- var changed = false;
+ final selfPub = await _selfPub();
+ final joinedSeq = file.joinedSeq ?? 0;
+ final suspended = file.suspended.toSet();
+ final known = _knownOf(state);
+ final loose = <DevLogEntry>[];
+ final notices = <DeviceRemovalNotice>[];
+ final departed = <DeviceLogDeparted>[];
for (final raw in entries) {
final e = DevLogEntry.parse(raw);
- if (e == null || e.op != 'remove' || state.active[e.signer] == null) continue;
+ if (e == null || e.op != 'remove' || state.active[e.signer] == null || suspended.contains(e.signer)) continue;
final target = state.active[e.pub];
if (target == null) continue;
if (!await verifySignature(b64d(e.signer), devLogMessage(e), b64d(e.sig))) continue;
+ final notice = _removalNotice(e, joinedSeq, selfPub, file.pending, known);
+ if (file.pending.contains(e.pub) && e.pub != selfPub) departed.add(_departedOf(target, e, known[e.signer]?.label ?? ''));
state.active.remove(e.pub);
state.removed.add(e.pub);
await _drop(target);
- changed = true;
- }
- if (changed) {
- await _write(file);
- onChanged?.call();
+ loose.add(e);
+ if (notice != null) notices.add(notice);
}
+ if (loose.isEmpty) return;
+ file
+ ..looseRemoved = [...file.looseRemoved, ...loose]
+ ..pending = _prune(file.pending, state)
+ ..announced = _prune(file.announced, state)
+ ..suspended = _prune(file.suspended, state)
+ ..departed = _withDeparted(file.departed, departed);
+ await _write(file);
+ effects.removed.addAll(notices);
+ effects.changed = true;
}
Future<void> _freeze(String reason) async {
- final file = await _read();
+ final effects = _Effects();
+ await _locked(() async => _freezeIn(await _read(), reason, effects));
+ await _fire(effects);
+ }
+
+ /// [_freeze], for a caller already holding the lock.
+ Future<void> _freezeIn(_File file, String reason, _Effects effects) async {
if (file.frozen != null || file.state == null) return;
file.frozen = DeviceLogFreeze(reason, _now(), file.state!.head);
+ file.joining = false;
await _write(file);
- onChanged?.call();
+ effects.changed = true;
}
/// Remove a device from the account, signed by this app. It stops being trusted here at once.
@@ -418,14 +1136,19 @@ class ViewerDeviceLog {
} catch (_) {}
}
- /// What trusting the backend's log again would change; with [confirm], do it.
- Future<DeviceLogRebaseline?> rebaseline({required bool confirm}) async {
+ /// What trusting the backend's log again would change; with [confirm], do it. [expectedHead] is the
+ /// head the person was shown in the preview: if the backend's log is not that one any more, nothing is
+ /// done and the result has [DeviceLogRebaseline.logChanged] set — what gets trusted is what was
+ /// reviewed. Another account's list under the sign-in the live log belongs to is refused, preview and
+ /// confirm alike ([DeviceLogRebaseline.otherAccount]). Null: the backend's list could not be read or
+ /// did not verify.
+ Future<DeviceLogRebaseline?> rebaseline({required bool confirm, DevLogHead? expectedHead}) async {
final entries = <Object?>[];
var acct = '';
DevLogHead? head;
for (var page = 0; page < _pages; page++) {
final got = await fetch(entries.length);
- if (got == null) return null;
+ if (got == null || !_isPosition(got.head.seq)) return null;
acct = got.acct;
head = got.head;
entries.addAll(got.entries);
@@ -438,69 +1161,347 @@ class ViewerDeviceLog {
return null;
}
if (head == null || next.head != head) return null;
- final file = await _read();
- final before = file.state?.active ?? const <String, DevLogMember>{};
- final added = [for (final m in next.active.values) if (before[m.pub] == null) m];
- final removed = [for (final m in before.values) if (next.active[m.pub] == null) m];
- if (confirm) {
- await _write(_File(next, entries.map(DevLogEntry.parse).whereType<DevLogEntry>().toList(), null, next.head.seq));
- await _trust(next.active.values.toList());
- for (final m in removed) {
- await _drop(m);
+ final effects = _Effects();
+ final result = await _locked(() async {
+ final file = await _marksIn();
+ final same = file.state != null && file.state!.acct == next.acct;
+ // Another account's list while the live log is the one of the sign-in this app is under: the
+ // backend switched accounts on its own. A review must not move this app there (the account it is
+ // signed in to, and every mark on it, would go out of sight): only a sign-in switches accounts.
+ // Only a sign-in by hand the list is not stamped with is that switch: none recorded, an adopted one
+ // (a session this app took over — whatever stamp the list has, or lacks, from an older version), or
+ // the sign-in the list is stamped with is not.
+ if (file.state != null && !same) {
+ final local = await _localOwner();
+ if (local == null || local.startsWith(_adoptedSignIn) || file.owner == local) {
+ return const DeviceLogRebaseline.otherAccount();
+ }
}
- onChanged?.call();
- }
- return DeviceLogRebaseline(next.head, added, removed);
+ if (confirm && expectedHead != null && next.head != expectedHead) return const DeviceLogRebaseline.changed();
+ // The list under review is judged against this account's own log as this app verified it: the
+ // live file, or — for another account — the one kept when this app left it (its marks go on), or
+ // else nothing (every key on it is new here). Never against the account being left.
+ final kept = same ? null : await _archivedFileIn(next.acct);
+ final base = same ? file : kept ?? _File(null, [], null, 0, joinedSeq: 0, preLog: [...file.preLog]);
+ final before = base.state?.active ?? const <String, DevLogMember>{};
+ final added = [for (final m in next.active.values) if (before[m.pub] == null) m];
+ final removed = [for (final m in before.values) if (next.active[m.pub] == null) m];
+ if (confirm) {
+ final selfPub = await _selfPub();
+ final pre = base.preLog.toSet();
+ // Every key the review let in is new here — however the preview and this read differ — unless
+ // this app knew it already.
+ final news = [
+ for (final m in added)
+ if (m.pub != selfPub && !pre.contains(m.pub)) m,
+ ];
+ final toAnnounce = [
+ for (final m in news)
+ if (!base.announced.contains(m.pub)) m,
+ ];
+ final parsed = entries.map(DevLogEntry.parse).whereType<DevLogEntry>().toList();
+ final departed = _reviewDeparted(base, next, parsed, removed, selfPub, pre);
+ // The reviewed list is another account's: the one this app leaves is kept, as on a sign-in (and
+ // what a fork suspended in it stays suspended here) — and a kept one of the reviewed account
+ // goes on from where it was.
+ if (file.state != null && !same) await _archiveIn(file);
+ base
+ ..state = next
+ ..recent = parsed
+ ..frozen = null
+ ..notifiedUpTo = next.head.seq
+ // The joined point never moves up past the reviewed head: a shorter list (rolled back, or
+ // another account's) must leave every key added to it from here on news.
+ ..joinedSeq = min(base.joinedSeq ?? base.notifiedUpTo, next.head.seq)
+ ..pending = _prune([...base.pending, for (final m in news) m.pub], next)
+ ..announced = _prune([...base.announced, for (final m in toAnnounce) m.pub], next)
+ // A review lifts what a fork suspended in this list; a kept list's suspensions were never in
+ // the preview, so they stay.
+ ..suspended = same ? [] : _prune(base.suspended, next)
+ ..looseRemoved = []
+ ..joining = false
+ ..reviewedSeq = next.head.seq
+ ..departed = _withDeparted(base.departed, departed)
+ ..owner = await _localOwner() ?? base.owner;
+ await _carrySuspensionsIn(base);
+ // Live first, then out of the archive: a crash in between leaves it in both, never in neither.
+ await _write(base);
+ if (kept != null) {
+ final all = await _archived();
+ if (all.remove(next.acct) != null) await keys.writeDeviceLogArchive(all);
+ }
+ await _trust(next.active.values.toList());
+ for (final m in removed) {
+ await _drop(m);
+ }
+ effects.announce.addAll(toAnnounce);
+ effects.changed = true;
+ }
+ return DeviceLogRebaseline(next.head, added, removed);
+ });
+ await _fire(effects);
+ return result;
}
/// What rides this app's side of a `group_sync`.
Future<Map<String, Object?>?> gossip() async {
final file = await _read();
final state = file.state;
- if (state == null) return null;
- return {'head': state.head.toJson(), 'frozen': file.frozen != null};
+ // Not this sign-in's log yet (it may be the account this app just left): nothing to say.
+ if (state == null || !await _ownsFile(file)) return null;
+ // The newest hashes let a peer that finds the logs forked say where they split.
+ final from = max(0, state.hashes.length - _gossipHashes);
+ return {
+ 'head': state.head.toJson(),
+ 'frozen': file.frozen != null,
+ 'hashes': [
+ for (var i = from; i < state.hashes.length; i++) {'seq': i + 1, 'hash': state.hashes[i]},
+ ],
+ };
}
/// A machine's answer to this app's `group_sync`: its head, whether it is frozen, and the entries
/// this app lacks if it is behind.
Future<void> heard(String machinePub, Object? raw) async {
- final file = await _read();
+ final file = await _marks();
final state = file.state;
if (state == null || raw is! Map) return;
+ // A sign-in waiting for its first read: the file may be the account left behind, and a machine of
+ // the new one would freeze it as a fork. Nothing is judged until the log is this sign-in's.
+ if (!await _ownsFile(file)) return;
_frozenPeers[machinePub] = raw['frozen'] == true;
final theirs = DevLogHead.fromJson(raw['head']);
if (theirs == null) return;
final relation = compareDevLogHead(state, theirs);
- if (relation == 'fork') return _freeze('fork');
+ if (relation == 'fork') {
+ await _freeze('fork');
+ return _suspendAfterFork(raw);
+ }
if (relation == 'behind') {
final tail = raw['tail'];
final missing = tail is List
? [for (final e in tail) if ((DevLogEntry.parse(e)?.seq ?? 0) > state.head.seq) e]
: const <Object?>[];
- if (missing.isNotEmpty && file.frozen == null) await _accept(missing, false);
+ // A tail that does not continue this log is a fork; and a log already frozen on one can still
+ // learn from this machine's hashes where it split.
+ if (file.frozen != null || (missing.isNotEmpty && !await _acceptFromPeer(missing))) {
+ await _suspendAfterFork(raw);
+ }
unawaited(refresh());
}
}
+ /// A fork a peer proved with its hashes: the keys added at or after the split — and new here — are
+ /// not trusted until the list is reviewed ([rebaseline]). Only locally: nothing is tombstoned or
+ /// written to the log. Without usable hashes the freeze alone stands.
+ Future<void> _suspendAfterFork(Object? theirs) async {
+ final changed = await _locked(() async {
+ final file = await _read();
+ final state = file.state;
+ if (state == null || file.frozen?.reason != 'fork') return false;
+ final split = devLogDivergence(state, theirs);
+ if (split == null) return false;
+ final selfPub = await _selfPub();
+ // Only keys nobody here has marked as seen — and not one a review (`rebaseline`) already let in:
+ // another device's old branch must not cost this one the devices its user just looked at.
+ final reviewed = file.reviewedSeq ?? -1;
+ final fresh = [
+ for (final m in state.active.values)
+ if (m.seq >= split &&
+ m.pub != selfPub &&
+ file.pending.contains(m.pub) &&
+ m.seq > reviewed &&
+ !file.suspended.contains(m.pub))
+ m,
+ ];
+ if (fresh.isEmpty) return false;
+ file.suspended = [...file.suspended, for (final m in fresh) m.pub];
+ await _write(file);
+ for (final m in fresh) {
+ if (m.kind != 'machine') continue;
+ final current = await keys.peer(m.machineId);
+ if (current != null && b64e(current.pub) == m.pub) await keys.unlink(m.machineId);
+ }
+ return true;
+ });
+ if (changed) onChanged?.call();
+ }
+
+ /// Keys not trusted here after a fork, until [rebaseline] — and every key a fork suspended in another
+ /// account's kept log, which no other account's log can bring back in.
+ Future<Set<String>> suspendedPubs() async => {...(await _read()).suspended, ...await _archivedSuspended()};
+
+ /// Mark new devices as seen: the ones in [pubs] (what a window displayed), one ([pub]), or every one
+ /// (neither). The "already on your account" list is [seeBaseline]. Persisted, so it holds across
+ /// restarts. A key a fork suspended stays flagged when it is only part of a list that was looked at;
+ /// [pub] — "It's mine" on that very device — is the person vouching for it, and lifts its suspension
+ /// (here and in every kept account's log). A key that joined and left before anyone looked
+ /// ([DeviceLogListing.departed]) is cleared the same way: named, or every one.
+ Future<void> dismiss({String? pub, List<String>? pubs}) async {
+ final lifted = <DevLogMember>[];
+ final changed = await _locked(() async {
+ final file = await _marksIn();
+ if (file.state == null) return false;
+ final named = pub != null || pubs != null;
+ final gone = {...?pubs, ?pub};
+ file.pending = [
+ for (final k in file.pending)
+ if ((named ? !gone.contains(k) : false) || (file.suspended.contains(k) && k != pub)) k,
+ ];
+ file.departed = [
+ for (final d in file.departed)
+ if (named && !gone.contains(d.pub)) d,
+ ];
+ final lifting = pub != null && file.suspended.contains(pub) ? pub : null;
+ if (lifting != null) {
+ file.suspended = [for (final k in file.suspended) if (k != lifting) k];
+ final m = file.state!.active[lifting];
+ if (m != null) lifted.add(m);
+ }
+ await _write(file);
+ if (lifting != null) await _unsuspendArchivedIn([lifting]);
+ if (lifted.isNotEmpty) await _trust(lifted);
+ return true;
+ });
+ if (changed) onChanged?.call();
+ }
+
+ /// The "Already on your account" list was acknowledged: the first read is over, whatever comes after
+ /// is news — or a backend that stalls that read could add a key to a list nobody looks at again.
+ Future<void> seeBaseline() => _change((file) {
+ file
+ ..baselineSeen = true
+ ..joining = false;
+ });
+
+ /// Read the file, [edit] it and write it back, under the lock; nothing when there is no log yet.
+ Future<void> _change(void Function(_File file) edit) async {
+ final changed = await _locked(() async {
+ final file = await _marksIn();
+ if (file.state == null) return false;
+ edit(file);
+ await _write(file);
+ return true;
+ });
+ if (changed) onChanged?.call();
+ }
+
+ /// Every add and remove in the log, newest first, as this app verified it: the entries come from the
+ /// backend but each must hash to what this app already verified, or the log freezes. Offline, what
+ /// is kept locally (`complete: false`).
+ Future<DeviceLogHistory> history() => _historying ??= _historyOnce().whenComplete(() => _historying = null);
+
+ /// One walk at a time: two interleaved on the same cache would each read the other's entries as a
+ /// gap in the log and freeze it.
+ Future<DeviceLogHistory>? _historying;
+
+ Future<DeviceLogHistory> _historyOnce() async {
+ await refresh();
+ final file = await _marks();
+ final state = file.state;
+ if (state == null) return const DeviceLogHistory(rows: [], complete: false);
+ if (_histAcct != state.acct) {
+ _histAcct = state.acct;
+ _histCache = [];
+ }
+ final last = _histCache.isEmpty ? null : _histCache.last;
+ if (last != null && (last.seq > state.head.seq || devLogHash(last) != state.hashes[last.seq - 1])) {
+ _histCache = [];
+ }
+ for (var page = 0; page < _pages && _histCache.length < state.head.seq; page++) {
+ final since = _histCache.length;
+ final got = await fetch(since);
+ if (got == null || got.acct != state.acct) break;
+ var progressed = false;
+ for (final raw in got.entries) {
+ final e = DevLogEntry.parse(raw);
+ final rawSeq = raw is Map ? raw['seq'] : null;
+ final seq = e?.seq ?? (rawSeq is int ? rawSeq : 0);
+ if (seq <= _histCache.length || seq > state.head.seq) continue;
+ // At a position this app verified, anything unreadable or off-hash means the backend is lying
+ // about the past: freeze, and show only what was already checked.
+ if (e == null || e.seq != _histCache.length + 1 || devLogHash(e) != state.hashes[e.seq - 1]) {
+ // Only against the log this walk started from: if the file was rebaselined (or moved to
+ // another account) while the pages were on their way, the mismatch is with a log that is
+ // gone, and says nothing about the backend.
+ final now = (await _read()).state;
+ if (now == null || now.acct != state.acct || now.head != state.head) {
+ _histCache = [];
+ _histAcct = null;
+ return _historyOf(const [], false);
+ }
+ await _freeze('fork');
+ return _historyOf(_histCache, false);
+ }
+ _histCache.add(e);
+ progressed = true;
+ }
+ if (!progressed) break;
+ }
+ return _historyOf(_histCache, _histCache.length >= state.head.seq);
+ }
+
+ Future<DeviceLogHistory> _historyOf(List<DevLogEntry> fetched, bool complete) async {
+ final file = await _read();
+ final state = file.state;
+ if (state == null) return const DeviceLogHistory(rows: [], complete: false);
+ // Offline, the newest entries kept locally fill in what could not be fetched.
+ final from = fetched.isEmpty ? 0 : fetched.last.seq;
+ final entries = complete ? fetched : [...fetched, for (final e in file.recent) if (e.seq > from) e];
+ return DeviceLogHistory(
+ rows: devLogHistory(
+ entries,
+ selfPub: await _selfPub(),
+ joinedSeq: file.joinedSeq,
+ // A key that joined and left before anyone looked is still new, in its rows too.
+ pending: [...file.pending, for (final d in file.departed) d.pub],
+ active: state.active,
+ loose: file.looseRemoved,
+ ),
+ complete: complete,
+ );
+ }
+
/// The account's devices as this app's log has them.
Future<DeviceLogListing> list() async {
- final file = await _read();
+ final file = await _marks();
final selfPub = await _selfPub();
final members = (file.state?.active.values.toList() ?? [])..sort((a, b) => a.seq.compareTo(b.seq));
final labels = {for (final m in members) m.pub: m.label};
+ final joinedSeq = file.joinedSeq ?? 0;
+ final pre = file.preLog.toSet();
return DeviceLogListing(
members: [
- for (final m in members) DeviceLogRow(m, fingerprint: fingerprint(b64d(m.pub)), self: m.pub == selfPub),
+ for (final m in members)
+ DeviceLogRow(
+ m,
+ fingerprint: fingerprint(b64d(m.pub)),
+ self: m.pub == selfPub,
+ pending: file.pending.contains(m.pub),
+ suspended: file.suspended.contains(m.pub),
+ ),
],
frozen: file.frozen,
frozenPeers: [
for (final e in _frozenPeers.entries)
if (e.value) labels[e.key] ?? fingerprint(b64d(e.key)),
],
+ pending: file.pending,
+ suspended: file.suspended,
+ joinedSeq: joinedSeq,
+ baseline: [
+ for (final m in members)
+ if (m.pub != selfPub && (m.seq <= joinedSeq || pre.contains(m.pub))) m.pub,
+ ],
+ baselineSeen: file.baselineSeen,
+ departed: file.departed,
);
}
}
+/// Whether [seq] can be a log position: a whole number, not negative, not past what a double holds.
+bool _isPosition(int seq) => seq >= 0 && seq <= 9007199254740991;
+
String _clip(String label) {
final clean = label.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim();
return clean.length > devLogLabelMax ? clean.substring(0, devLogLabelMax) : clean;
diff --git a/mobile/lib/viewer/direct_link.dart b/mobile/lib/viewer/direct_link.dart
index 615446664..755d827dd 100644
--- a/mobile/lib/viewer/direct_link.dart
+++ b/mobile/lib/viewer/direct_link.dart
@@ -180,6 +180,7 @@ class DirectLink implements PeerLinkClient {
label: label,
socket: socket,
devlog: await log?.gossip(),
+ suspended: log?.suspendedPubs,
onDevlog: log?.heard,
);
}
diff --git a/mobile/lib/viewer/group_sync.dart b/mobile/lib/viewer/group_sync.dart
index bbab7a8f0..fb33b4127 100644
--- a/mobile/lib/viewer/group_sync.dart
+++ b/mobile/lib/viewer/group_sync.dart
@@ -217,6 +217,10 @@ Future<GroupSyncOutcome> syncTrustGroup({
Duration timeout = const Duration(seconds: 20),
Map<String, Object?>? devlog,
Future<void> Function(String machinePub, Object? devlog)? onDevlog,
+
+ /// Keys a fork put out of trust here until reviewed (device_log_sync.dart): never pinned or seeded.
+ /// Asked again after [onDevlog], which can suspend a key in this very exchange.
+ Future<Set<String>> Function()? suspended,
}) async {
WebSocketChannel? channel;
try {
@@ -224,7 +228,7 @@ Future<GroupSyncOutcome> syncTrustGroup({
if (pin == null) return GroupSyncOutcome.none;
final identity = await keys.identity();
final selfPub = b64e(identity.pub);
- final local = await _seeded(keys, selfPub);
+ final local = await _seeded(keys, selfPub, await suspended?.call() ?? const {});
final self = GroupMember(
pub: selfPub,
kind: 'viewer',
@@ -268,7 +272,7 @@ Future<GroupSyncOutcome> syncTrustGroup({
selfPub,
);
await keys.writeGroupRoster(merged.roster.toJson());
- return await _apply(keys, merged);
+ return await _apply(keys, merged, await suspended?.call() ?? const {});
} catch (_) {
return GroupSyncOutcome.none;
} finally {
@@ -278,7 +282,11 @@ Future<GroupSyncOutcome> syncTrustGroup({
/// This phone's roster, with every machine it has pinned folded in — how a machine this phone linked
/// by password reaches the rest of the group, and how links made before the group existed join it.
-Future<GroupRoster> _seeded(ViewerKeyStore keys, String selfPub) async {
+Future<GroupRoster> _seeded(
+ ViewerKeyStore keys,
+ String selfPub,
+ Set<String> suspended,
+) async {
final stored = GroupRoster.parse(await keys.groupRoster());
// Only pins the roster does not name yet: a pin's `linkedAt` is when THIS device pinned it (the
// group's own pins included), and folding that in again would restamp the member as new on every
@@ -286,7 +294,7 @@ Future<GroupRoster> _seeded(ViewerKeyStore keys, String selfPub) async {
final known = {for (final m in stored.members) m.pub};
final pins = [
for (final p in await keys.peers())
- if (!known.contains(b64e(p.pub)))
+ if (!known.contains(b64e(p.pub)) && !suspended.contains(b64e(p.pub)))
?GroupMember.tryParse({
'pub': b64e(p.pub),
'machineId': p.machineId,
@@ -298,11 +306,15 @@ Future<GroupRoster> _seeded(ViewerKeyStore keys, String selfPub) async {
return mergeGroupRoster(stored, GroupRoster(pins, const []), selfPub).roster;
}
-Future<GroupSyncOutcome> _apply(ViewerKeyStore keys, GroupMerge merged) async {
+Future<GroupSyncOutcome> _apply(
+ ViewerKeyStore keys,
+ GroupMerge merged,
+ Set<String> suspended,
+) async {
final pinned = <String>[], unpinned = <String>[];
for (final m in merged.upserted) {
final id = m.machineId;
- if (!m.isMachine || id == null) continue;
+ if (!m.isMachine || id == null || suspended.contains(m.pub)) continue;
final current = await keys.peer(id);
if (current != null && b64e(current.pub) == m.pub) continue;
await keys.pin(id, b64d(m.pub), label: m.label);
diff --git a/mobile/lib/viewer/viewer_key_store.dart b/mobile/lib/viewer/viewer_key_store.dart
index 20c54993d..604a1879a 100644
--- a/mobile/lib/viewer/viewer_key_store.dart
+++ b/mobile/lib/viewer/viewer_key_store.dart
@@ -79,6 +79,8 @@ class ViewerKeyStore {
static const _peersKey = 'viewer_e2ee_machine_peers';
static const _groupKey = 'viewer_e2ee_group';
static const _devLogKey = 'viewer_e2ee_devlog';
+ static const _devLogArchiveKey = 'viewer_e2ee_devlog_archive';
+ static const _signInKey = 'viewer_e2ee_sign_in';
/// Minted on first use and kept: every linked machine has pinned it.
Future<E2eeIdentity> identity() => _identity ??= _heldUnlessItFails(
@@ -197,12 +199,35 @@ class ViewerKeyStore {
Future<void> writeDeviceLog(Map<String, Object?> log) =>
_storage.write(_devLogKey, jsonEncode(log));
+ /// The device key logs of accounts this device was signed in to before, by account id, as stored
+ /// JSON; empty when there are none or they cannot be read.
+ Future<Map<String, Object?>> deviceLogArchive() async {
+ final raw = await _storage.read(_devLogArchiveKey);
+ if (raw == null) return {};
+ try {
+ final decoded = jsonDecode(raw);
+ return decoded is Map ? decoded.cast<String, Object?>() : {};
+ } on FormatException {
+ return {};
+ }
+ }
+
+ Future<void> writeDeviceLogArchive(Map<String, Object?> archive) =>
+ _storage.write(_devLogArchiveKey, jsonEncode(archive));
+
+ /// Which sign-in by hand this device is under (`device_log_sync.dart` keeps its marks per sign-in);
+ /// null when none was recorded.
+ Future<String?> signInEpoch() => _storage.read(_signInKey);
+
+ Future<void> writeSignInEpoch(String epoch) =>
+ _storage.write(_signInKey, epoch);
+
/// This device was removed from the account's device key log: its identity is spent. The next one
- /// minted is a new device, which every other device announces as one.
+ /// minted is a new device, which every other device announces as one. The log as this device
+ /// verified it stays, with every mark on it: signing in again to the same account goes on from there.
Future<void> forgetIdentity() async {
_identity = null;
await _storage.delete(_seedKey);
- await _storage.delete(_devLogKey);
}
/// The one path that changes the peer list, so the one place the cache is
diff --git a/mobile/test/phone/device_detail_page_test.dart b/mobile/test/phone/device_detail_page_test.dart
index cbb7ea4c8..5d802a365 100644
--- a/mobile/test/phone/device_detail_page_test.dart
+++ b/mobile/test/phone/device_detail_page_test.dart
@@ -6,6 +6,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/core/relative_time.dart';
import 'package:harness_mobile/phone/device_detail_page.dart';
import 'package:harness_mobile/phone/fingerprint_text.dart';
+import 'package:harness_mobile/phone/tty.dart';
import 'package:harness_mobile/viewer/device_log_sync.dart';
import 'devices_fixture.dart';
@@ -178,11 +179,35 @@ void main() {
await tester.pumpAndSettle();
expect(notifier.newDevices, isEmpty);
+ // Nothing on this page said the key was suspended: "mine" vouches for nothing it did not show.
+ expect(notifier.dismissed, [(pub: r.member.pub, liftSuspension: false)]);
expect(mine, 1);
expect(find.byType(DeviceDetailPage), findsNothing);
expect(notifier.removed, isEmpty);
});
+ testWidgets('It’s mine lifts a fork suspension only when the page shows it', (
+ tester,
+ ) async {
+ final notifier = DevicesApp();
+ addTearDown(notifier.dispose);
+ final r = DeviceLogRow(
+ app().member,
+ fingerprint: app().fingerprint,
+ self: false,
+ pending: true,
+ suspended: true,
+ );
+ notifier.newDevices.add(r.member);
+ await pump(tester, notifier, r, isNew: true);
+ expect(find.textContaining('Not trusted here'), findsOneWidget);
+
+ await tester.tap(find.byKey(const Key('device-detail-mine')));
+ await tester.pumpAndSettle();
+
+ expect(notifier.dismissed, [(pub: r.member.pub, liftSuspension: true)]);
+ });
+
testWidgets('Remove asks first; backing out removes nothing', (tester) async {
final notifier = DevicesApp();
addTearDown(notifier.dispose);
@@ -249,8 +274,14 @@ void main() {
await tester.pumpAndSettle();
expect(find.byType(DeviceDetailPage), findsOneWidget);
- expect(find.text("Couldn't remove iPad. Try again."), findsOneWidget);
+ expect(find.text('Couldn’t remove iPad. Try again.'), findsOneWidget);
expect(find.text('Remove this device'), findsOneWidget);
+ // A failure is red (only advice — another account, a list that moved — is amber).
+ final message = find.text('Couldn’t remove iPad. Try again.');
+ expect(
+ tester.widget<Text>(message).style!.color,
+ Tty.of(tester.element(message)).red,
+ );
});
testWidgets('this phone itself has no Remove and no It’s mine', (
diff --git a/mobile/test/phone/device_history_page_test.dart b/mobile/test/phone/device_history_page_test.dart
new file mode 100644
index 000000000..45f3a6a72
--- /dev/null
+++ b/mobile/test/phone/device_history_page_test.dart
@@ -0,0 +1,313 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/device_detail_page.dart';
+import 'package:harness_mobile/phone/device_history_page.dart';
+import 'package:harness_mobile/phone/devices_page.dart';
+import 'package:harness_mobile/phone/tty.dart';
+import 'package:harness_mobile/viewer/device_history.dart';
+
+import 'devices_fixture.dart';
+
+/// Settings ▸ Your devices ▸ History: every add and remove, newest first, in the app's own words.
+void main() {
+ late DevicesApp app;
+ late String selfPub, ipadPub, gonePub;
+ final at = DateTime(2026, 10, 1, 14, 5).millisecondsSinceEpoch;
+
+ setUp(() {
+ selfPub = pubOf(0);
+ ipadPub = pubOf(1);
+ gonePub = pubOf(2);
+ app = DevicesApp(
+ rows: [
+ row(member(selfPub, label: 'My iPhone', addedAt: at), self: true),
+ row(member(ipadPub, label: 'iPad', addedAt: at), pending: true),
+ ],
+ );
+ });
+ tearDown(() => app.dispose());
+
+ Future<void> pump(WidgetTester tester) async {
+ await tester.pumpWidget(
+ MaterialApp(home: DeviceHistoryPage(notifier: app)),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('rows read as sentences, newest first, with New and (this '
+ 'device)', (tester) async {
+ app.history = DeviceLogHistory(
+ rows: [
+ historyRow(5, 'added', ipadPub, label: 'iPad', pending: true, at: at),
+ historyRow(
+ 4,
+ 'removed',
+ gonePub,
+ label: 'Pixel',
+ active: false,
+ at: at,
+ by: DevLogHistoryBy(
+ pub: selfPub,
+ label: 'My iPhone',
+ fingerprint: '',
+ ),
+ ),
+ historyRow(3, 'signedOut', gonePub, label: 'Old Mac', active: false),
+ historyRow(
+ 2,
+ 'renamed',
+ ipadPub,
+ label: 'iPad Pro',
+ previousLabel: 'iPad',
+ ),
+ historyRow(1, 'added', selfPub, label: 'My iPhone', thisDevice: true),
+ ],
+ complete: true,
+ );
+ await pump(tester);
+ expect(find.text('Device history'), findsOneWidget);
+ expect(
+ find.text(
+ 'Every device added to or removed from your account, newest first, as this device verified it.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('iPad added'), findsOneWidget);
+ expect(find.text('Pixel removed by My iPhone'), findsOneWidget);
+ expect(find.text('Old Mac signed out'), findsOneWidget);
+ expect(find.text('iPad renamed to iPad Pro'), findsOneWidget);
+ expect(find.text('My iPhone added (this device)'), findsOneWidget);
+ expect(find.text('New'), findsOneWidget);
+ expect(find.byKey(const Key('device-history-incomplete')), findsNothing);
+ final top = tester.getTopLeft(
+ find.byKey(const ValueKey('device-history-5')),
+ );
+ final bottom = tester.getTopLeft(
+ find.byKey(const ValueKey('device-history-1')),
+ );
+ expect(top.dy, lessThan(bottom.dy));
+ });
+
+ testWidgets('a frozen-time removal says so; incomplete says older history '
+ 'needs a connection', (tester) async {
+ app.history = DeviceLogHistory(
+ rows: [
+ historyRow(
+ 4,
+ 'removed',
+ gonePub,
+ label: 'Pixel',
+ active: false,
+ whileFrozen: true,
+ by: DevLogHistoryBy(pub: selfPub, label: '', fingerprint: ''),
+ ),
+ ],
+ complete: false,
+ );
+ await pump(tester);
+ expect(
+ find.text(
+ 'Pixel removed by another device · applied while the list was frozen',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Older history needs a connection.'), findsOneWidget);
+ });
+
+ testWidgets('no rows: No history yet.', (tester) async {
+ await pump(tester);
+ expect(find.text('No history yet.'), findsOneWidget);
+ });
+
+ testWidgets('a failed load says so and Try again reloads', (tester) async {
+ app.historyError = true;
+ await pump(tester);
+ expect(find.text('Couldn’t load the history. Try again.'), findsOneWidget);
+ // A failure is red.
+ final failed = find.byKey(const Key('device-history-failed'));
+ expect(
+ tester.widget<Text>(failed).style!.color,
+ Tty.of(tester.element(failed)).red,
+ );
+ app
+ ..historyError = false
+ ..history = DeviceLogHistory(
+ rows: [historyRow(2, 'added', ipadPub, label: 'iPad')],
+ complete: true,
+ );
+ await tester.tap(find.text('Try again'));
+ await tester.pumpAndSettle();
+ expect(find.text('iPad added'), findsOneWidget);
+ expect(find.byKey(const Key('device-history-failed')), findsNothing);
+ });
+
+ testWidgets('an active device opens its page, as new while pending', (
+ tester,
+ ) async {
+ app.history = DeviceLogHistory(
+ rows: [historyRow(2, 'added', ipadPub, label: 'iPad', pending: true)],
+ complete: true,
+ );
+ await pump(tester);
+ await tester.tap(find.text('iPad added'));
+ await tester.pumpAndSettle();
+ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));
+ expect(page.row.member.pub, ipadPub);
+ expect(page.isNew, isTrue);
+ });
+
+ testWidgets('offline and empty: only "Older history needs a connection", '
+ 'not "No history yet." with it', (tester) async {
+ app.history = const DeviceLogHistory(rows: [], complete: false);
+ await pump(tester);
+ expect(find.text('Older history needs a connection.'), findsOneWidget);
+ expect(find.text('No history yet.'), findsNothing);
+ });
+
+ testWidgets('a key that left before anyone looked stays flagged on both its '
+ 'rows; an ordinary removal is not', (tester) async {
+ app.history = DeviceLogHistory(
+ rows: [
+ historyRow(
+ 4,
+ 'signedOut',
+ gonePub,
+ label: 'Pixel',
+ active: false,
+ pending: true,
+ ),
+ historyRow(
+ 3,
+ 'added',
+ gonePub,
+ label: 'Pixel',
+ active: false,
+ pending: true,
+ ),
+ historyRow(2, 'signedOut', pubOf(3), label: 'Old Mac', active: false),
+ ],
+ complete: true,
+ );
+ await pump(tester);
+ expect(find.text('Left before you looked'), findsNWidgets(2));
+ expect(find.text('New'), findsNothing);
+ });
+
+ testWidgets('a device that cannot be listed opens no error: the list is '
+ 'what is left', (tester) async {
+ app.history = DeviceLogHistory(
+ rows: [historyRow(2, 'added', ipadPub, label: 'iPad', pending: true)],
+ complete: true,
+ );
+ app.listingFailures = 1;
+ await pump(tester);
+ await tester.tap(find.text('iPad added'));
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ expect(find.byType(DeviceDetailPage), findsNothing);
+ expect(find.byType(DevicesPage), findsOneWidget);
+ });
+
+ testWidgets('the flag sits under the date, so a long sentence keeps the '
+ 'row\'s width', (tester) async {
+ tester.view.physicalSize = const Size(360, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ app.history = DeviceLogHistory(
+ rows: [
+ historyRow(
+ 4,
+ 'signedOut',
+ gonePub,
+ label: 'Ghost Tablet',
+ active: false,
+ pending: true,
+ at: at,
+ ),
+ ],
+ complete: true,
+ );
+ await pump(tester);
+ final sentence = tester.getRect(find.text('Ghost Tablet signed out'));
+ final flag = tester.getRect(find.byKey(const Key('device-history-flag')));
+ // One line for the sentence, with the flag below the whole row's text.
+ expect(sentence.height, lessThan(30));
+ expect(flag.top, greaterThanOrEqualTo(sentence.bottom));
+ expect(
+ tester.widget<Text>(find.byKey(const Key('device-history-flag'))).data,
+ 'Left before you looked',
+ );
+ });
+
+ testWidgets('it refreshes while open: a Got it elsewhere clears the flag, a '
+ 'new add shows', (tester) async {
+ app.history = DeviceLogHistory(
+ rows: [
+ historyRow(
+ 3,
+ 'added',
+ gonePub,
+ label: 'Ghost',
+ active: false,
+ pending: true,
+ at: at,
+ ),
+ ],
+ complete: true,
+ );
+ await pump(tester);
+ expect(find.text('Left before you looked'), findsOneWidget);
+
+ app.history = DeviceLogHistory(
+ rows: [
+ historyRow(4, 'added', ipadPub, label: 'iPad', at: at),
+ historyRow(3, 'added', gonePub, label: 'Ghost', active: false, at: at),
+ ],
+ complete: true,
+ );
+ app.devicesRevision++;
+ app.poke();
+ await tester.pumpAndSettle();
+ expect(find.text('Left before you looked'), findsNothing);
+ expect(find.text('iPad added'), findsOneWidget);
+
+ // A change that does not touch the devices does not re-read.
+ app.history = const DeviceLogHistory(rows: [], complete: true);
+ app.poke();
+ await tester.pumpAndSettle();
+ expect(find.text('iPad added'), findsOneWidget);
+ });
+
+ testWidgets('a failed refresh keeps what is on screen', (tester) async {
+ app.history = DeviceLogHistory(
+ rows: [historyRow(2, 'added', ipadPub, label: 'iPad', at: at)],
+ complete: true,
+ );
+ await pump(tester);
+ app.historyError = true;
+ app.devicesRevision++;
+ app.poke();
+ await tester.pumpAndSettle();
+ expect(find.text('iPad added'), findsOneWidget);
+ expect(find.byKey(const Key('device-history-failed')), findsNothing);
+ });
+
+ testWidgets('a refresh that fails while the first read is still in flight '
+ 'says so, not a blank page', (tester) async {
+ final gate = Completer<void>();
+ app.historyGate = gate;
+ await tester.pumpWidget(
+ MaterialApp(home: DeviceHistoryPage(notifier: app)),
+ );
+ // The log changes before the first read lands: a quiet re-read supersedes it.
+ app.devicesRevision++;
+ app.poke();
+ await tester.pump();
+ app.historyError = true;
+ gate.complete();
+ await tester.pumpAndSettle();
+ expect(find.byKey(const Key('device-history-failed')), findsOneWidget);
+ });
+}
diff --git a/mobile/test/phone/device_rows_test.dart b/mobile/test/phone/device_rows_test.dart
index 3daf2fc36..2ab13cae2 100644
--- a/mobile/test/phone/device_rows_test.dart
+++ b/mobile/test/phone/device_rows_test.dart
@@ -152,22 +152,4 @@ void main() {
},
);
});
-
- test('rowFromMember: the key code from the key, never this phone, and '
- 'the member with its added time kept', () {
- final m = member(
- pubOf(5),
- label: 'iPad',
- addedAt: ago(const Duration(hours: 3)),
- );
- final r = rowFromMember(m);
- expect(r.fingerprint, fpOf(pubOf(5)));
- expect(r.fingerprint, matches(RegExp(r'^[0-9A-F]{4}(·[0-9A-F]{4}){3}$')));
- expect(r.self, isFalse);
- expect(r.member.addedAt, m.addedAt);
- expect(
- rowFromMember(member('not base64!', addedAt: 0)).fingerprint,
- isEmpty,
- );
- });
}
diff --git a/mobile/test/phone/devices_fixture.dart b/mobile/test/phone/devices_fixture.dart
index 58c1a3f2a..e13ac1c52 100644
--- a/mobile/test/phone/devices_fixture.dart
+++ b/mobile/test/phone/devices_fixture.dart
@@ -3,11 +3,14 @@ import 'dart:typed_data';
import 'package:harness_mobile/auth/auth_session.dart';
import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/local_key_value_store.dart';
import 'package:harness_mobile/e2ee/bytes.dart';
import 'package:harness_mobile/e2ee/keys.dart' as keys;
import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/viewer/device_history.dart';
import 'package:harness_mobile/viewer/device_log.dart';
import 'package:harness_mobile/viewer/device_log_sync.dart';
+import 'package:harness_mobile/viewer/viewer_key_store.dart';
/// A 32-byte key, distinct per [n], base64 — what a device log carries as `pub`.
String pubOf(int n) =>
@@ -32,8 +35,48 @@ DevLogMember member(
seq: seq,
);
-DeviceLogRow row(DevLogMember m, {bool self = false}) =>
- DeviceLogRow(m, fingerprint: fpOf(m.pub), self: self);
+DeviceLogRow row(
+ DevLogMember m, {
+ bool self = false,
+ bool pending = false,
+ bool suspended = false,
+}) => DeviceLogRow(
+ m,
+ fingerprint: fpOf(m.pub),
+ self: self,
+ pending: pending,
+ suspended: suspended,
+);
+
+DevLogHistoryRow historyRow(
+ int seq,
+ String op,
+ String pub, {
+ String label = 'Device',
+ String? previousLabel,
+ DevLogHistoryBy? by,
+ bool thisDevice = false,
+ bool pending = false,
+ bool active = true,
+ bool whileFrozen = false,
+ int at = 0,
+}) => DevLogHistoryRow(
+ seq: seq,
+ op: op,
+ pub: pub,
+ kind: 'viewer',
+ machineId: '',
+ label: label,
+ previousLabel: previousLabel,
+ fingerprint: fpOf(pub),
+ by: by,
+ at: at,
+ thisDevice: thisDevice,
+ afterJoin: true,
+ pending: pending,
+ active: active,
+ whileFrozen: whileFrozen,
+);
/// An app whose device list, last-seen times and removal are canned, so a page test is about what the
/// page does with them.
@@ -48,6 +91,29 @@ class DevicesApp extends AppNotifier {
List<DeviceLogRow> rows;
Map<String, int> seen;
+ /// What the listing says about this phone's join: the devices already there ([joinedSeq]) and
+ /// whether "Already on your account" was acknowledged.
+ int joinedSeq = 0;
+ bool baselineSeen = true;
+
+ /// What the listing names as the "already on your account" set; empty = not named.
+ List<String> baseline = const [];
+
+ /// What the listing names as departed: new keys removed before anyone looked.
+ List<DeviceLogDeparted> departed = const [];
+
+ /// A frozen list (offers Review / Trust again) and the log that answers it.
+ DeviceLogFreeze? frozen;
+ ViewerDeviceLog? log;
+
+ @override
+ ViewerDeviceLog? get deviceLog => log;
+
+ /// What [deviceHistory] answers; [historyError] makes it throw.
+ DeviceLogHistory history = const DeviceLogHistory(rows: [], complete: true);
+ bool historyError = false;
+ int baselineSeenCalls = 0;
+
/// What [removeDevice] answers: null is done, else why not.
String? removeError;
final removed = <String>[];
@@ -55,12 +121,100 @@ class DevicesApp extends AppNotifier {
/// When set, a removal waits on it — to see the page while the removal is in flight.
Completer<void>? removeGate;
+ /// The next this many [deviceListing] calls throw.
+ int listingFailures = 0;
+
+ @override
+ Future<DeviceLogListing> deviceListing() async {
+ if (listingFailures > 0) {
+ listingFailures--;
+ throw StateError('listing');
+ }
+ return _listing();
+ }
+
+ DeviceLogListing _listing() => DeviceLogListing(
+ members: rows,
+ frozen: frozen,
+ frozenPeers: const [],
+ pending: [
+ for (final r in rows)
+ if (r.pending) r.member.pub,
+ ],
+ joinedSeq: joinedSeq,
+ baseline: baseline,
+ baselineSeen: baselineSeen,
+ departed: departed,
+ );
+
+ /// When set, [deviceHistory] waits for it before answering (a read still in flight).
+ Completer<void>? historyGate;
+
@override
- Future<DeviceLogListing> deviceListing() async =>
- DeviceLogListing(members: rows, frozen: null, frozenPeers: const []);
+ Future<DeviceLogHistory> deviceHistory() async {
+ if (historyGate case final gate?) await gate.future;
+ if (historyError) throw StateError('history');
+ return history;
+ }
+
+ /// What each [seenNewDevices] was handed as the list's own `pending`, and as the banner's set.
+ final seenPending = <List<String>>[];
+ final seenShown = <List<String>?>[];
@override
- Future<Map<String, int>> devicesLastSeen() async => seen;
+ void seenNewDevices({
+ Iterable<String> pending = const [],
+ Iterable<String>? shown,
+ }) {
+ seenPending.add(pending.toList());
+ seenShown.add(shown?.toList());
+ super.seenNewDevices(pending: pending, shown: shown);
+ }
+
+ /// The pubs each [dismissNewDevice] was given, and whether it lifted a suspension.
+ final dismissed = <({String pub, bool liftSuspension})>[];
+
+ @override
+ void dismissNewDevice(String pub, {bool liftSuspension = false}) {
+ dismissed.add((pub: pub, liftSuspension: liftSuspension));
+ super.dismissNewDevice(pub, liftSuspension: liftSuspension);
+ }
+
+ /// Tell the page the app changed (a test edited it directly).
+ void poke() => notifyListeners();
+
+ /// The pubs each [dismissDeparted] was given.
+ final dismissedDeparted = <String>[];
+
+ @override
+ void dismissDeparted(String pub) {
+ dismissedDeparted.add(pub);
+ super.dismissDeparted(pub);
+ }
+
+ /// The banner entries the (canned) log holds as suspended.
+ final suspendedNew = <String>{};
+
+ @override
+ bool newDeviceSuspended(String pub) => suspendedNew.contains(pub);
+
+ /// Held: the page's last-seen read waits on it.
+ Completer<void>? seenGate;
+
+ @override
+ Future<void> seeDeviceBaseline() async {
+ baselineSeenCalls++;
+ if (log is ScriptedDeviceLog) return super.seeDeviceBaseline();
+ baselineSeen = true;
+ devicesRevision++;
+ notifyListeners();
+ }
+
+ @override
+ Future<Map<String, int>> devicesLastSeen() async {
+ await seenGate?.future;
+ return seen;
+ }
@override
Future<String?> removeDevice(String pub) async {
@@ -78,3 +232,62 @@ class DevicesApp extends AppNotifier {
return removeError;
}
}
+
+class _MemoryStore implements LocalKeyValueStore {
+ final _values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => _values[key];
+ @override
+ Future<void> write(String key, String value) async => _values[key] = value;
+ @override
+ Future<void> delete(String key) async => _values.remove(key);
+}
+
+/// A device log whose review (`rebaseline`) answers from a script, and which records what it was asked.
+class ScriptedDeviceLog extends ViewerDeviceLog {
+ ScriptedDeviceLog()
+ : super(
+ keys: ViewerKeyStore(storage: _MemoryStore()),
+ fetch: (_) async => null,
+ append: (_) async => null,
+ label: () => 'phone',
+ );
+
+ /// Answers to successive `rebaseline` calls (null: unreadable on a preview, "list changed" on a confirm).
+ final answers = <DeviceLogRebaseline?>[];
+ final calls = <({bool confirm, DevLogHead? expectedHead})>[];
+ bool seeBaselineThrows = false;
+
+ @override
+ Future<DeviceLogRebaseline?> rebaseline({
+ required bool confirm,
+ DevLogHead? expectedHead,
+ }) async {
+ calls.add((confirm: confirm, expectedHead: expectedHead));
+ return answers.isEmpty ? null : answers.removeAt(0);
+ }
+
+ @override
+ Future<void> seeBaseline() async {
+ if (seeBaselineThrows) throw StateError('disk');
+ }
+}
+
+DeviceLogDeparted departedKey(
+ String pub, {
+ String label = 'iPad',
+ String removedBy = '',
+ String removedByLabel = '',
+ bool selfRemoved = false,
+}) => DeviceLogDeparted(
+ pub: pub,
+ label: label,
+ kind: 'viewer',
+ machineId: '',
+ fingerprint: fpOf(pub),
+ addedAt: 1000,
+ removedAt: 2000,
+ removedBy: removedBy,
+ removedByLabel: removedByLabel,
+ selfRemoved: selfRemoved,
+);
diff --git a/mobile/test/phone/devices_page_test.dart b/mobile/test/phone/devices_page_test.dart
index 1e480ec77..8a44e758d 100644
--- a/mobile/test/phone/devices_page_test.dart
+++ b/mobile/test/phone/devices_page_test.dart
@@ -1,8 +1,17 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/phone/device_detail_page.dart';
+import 'package:harness_mobile/phone/device_history_page.dart';
import 'package:harness_mobile/phone/devices_page.dart';
import 'package:harness_mobile/phone/settings_row.dart';
+import 'package:harness_mobile/phone/tty.dart';
+
+import 'package:harness_mobile/viewer/device_history.dart';
+import 'package:harness_mobile/viewer/device_log.dart';
+import 'package:harness_mobile/viewer/device_log_sync.dart';
import 'devices_fixture.dart';
@@ -203,4 +212,515 @@ void main() {
expect(find.byKey(const Key('account-device-this')), findsNothing);
expect(rowOrder(tester), hasLength(3));
});
+
+ testWidgets('a pending device from the log shows New though the banner list '
+ 'is empty, and opening the list marks it seen', (tester) async {
+ app.newDevices.clear();
+ app.rows = [
+ for (final r in app.rows)
+ row(r.member, self: r.self, pending: r.member.pub == newPub),
+ ];
+ await pump(tester);
+ expect(rowFor(tester, newPub).value, 'New');
+ expect(rowOrder(tester).first, newPub);
+ expect(app.seenPending, [
+ [newPub],
+ ]);
+ });
+
+ testWidgets('a suspended device says Suspended, which wins over New', (
+ tester,
+ ) async {
+ app.rows = [
+ for (final r in app.rows)
+ row(r.member, self: r.self, suspended: r.member.pub == newPub),
+ ];
+ await pump(tester);
+ expect(rowFor(tester, newPub).value, 'Suspended');
+ await tester.tap(find.byKey(ValueKey('account-device-$newPub')));
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining('Not trusted here: added after this device’s list'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('"Already on your account" lists what was there before this '
+ 'device joined, and Got it is persisted once', (tester) async {
+ app
+ ..baselineSeen = false
+ ..joinedSeq = 2;
+ app.rows = [
+ row(member(selfPub, label: 'My iPhone', addedAt: 1, seq: 3), self: true),
+ row(
+ member(
+ oldPub,
+ label: 'mbp',
+ kind: 'machine',
+ machineId: 'abcdef1234',
+ addedAt: 1,
+ seq: 1,
+ ),
+ ),
+ row(member(newPub, label: 'iPad', addedAt: 2, seq: 4)),
+ ];
+ await pump(tester);
+ final panel = find.byKey(const Key('account-devices-baseline'));
+ expect(panel, findsOneWidget);
+ expect(
+ find.descendant(
+ of: panel,
+ matching: find.text('Already on your account'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: panel,
+ matching: find.text(
+ 'These were on your account before this device joined. If one isn’t yours, remove it.',
+ ),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: panel,
+ matching: find.text('mbp · Computer · ${fpOf(oldPub)}'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: panel, matching: find.text('iPad')),
+ findsNothing,
+ );
+
+ await tester.tap(find.text('Got it'));
+ await tester.pumpAndSettle();
+ expect(app.baselineSeenCalls, 1);
+ expect(panel, findsNothing);
+ });
+
+ testWidgets('no baseline panel once it was seen', (tester) async {
+ await pump(tester);
+ expect(find.byKey(const Key('account-devices-baseline')), findsNothing);
+ });
+
+ testWidgets('History opens the history page', (tester) async {
+ app.history = DeviceLogHistory(
+ rows: [historyRow(2, 'added', newPub, label: 'iPad')],
+ complete: true,
+ );
+ await pump(tester);
+ await tester.tap(find.byKey(const Key('account-devices-history')));
+ await tester.pumpAndSettle();
+ expect(find.byType(DeviceHistoryPage), findsOneWidget);
+ expect(find.text('iPad added'), findsOneWidget);
+ });
+
+ testWidgets('the baseline panel is the set the listing names, not the seq '
+ 'rule: a key that came after this phone joined but was already trusted '
+ 'is on it', (tester) async {
+ final lateKey = pubOf(9);
+ app
+ ..baselineSeen = false
+ ..joinedSeq = 2
+ ..baseline = [oldPub, lateKey];
+ app.rows = [
+ ...app.rows,
+ row(member(lateKey, label: 'Surface', addedAt: 3, seq: 6)),
+ ];
+ await pump(tester);
+ final panel = find.byKey(const Key('account-devices-baseline'));
+ expect(
+ find.descendant(of: panel, matching: find.textContaining('Surface')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: panel, matching: find.textContaining('mbp')),
+ findsOneWidget,
+ );
+ });
+
+ group('Trust again', () {
+ const head = DevLogHead(7, 'hash-7');
+ final preview = DeviceLogRebaseline(head, const [], const []);
+
+ Future<void> openFrozen(WidgetTester tester) async {
+ app.frozen = const DeviceLogFreeze('fork', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ await tester.tap(find.text('The device list froze'));
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('confirms the list that was previewed (its head)', (
+ tester,
+ ) async {
+ final log = ScriptedDeviceLog()..answers.addAll([preview, preview]);
+ app.log = log;
+ await openFrozen(tester);
+ await tester.tap(find.text('Trust again'));
+ await tester.pumpAndSettle();
+ expect(log.calls, hasLength(2));
+ expect(log.calls[0].confirm, isFalse);
+ expect(log.calls[1].confirm, isTrue);
+ expect(log.calls[1].expectedHead?.seq, 7);
+ expect(log.calls[1].expectedHead?.hash, 'hash-7');
+ });
+
+ testWidgets('a list that changed meanwhile says so and is previewed '
+ 'again', (tester) async {
+ // preview, confirm refused (the list moved), preview again.
+ final log = ScriptedDeviceLog()
+ ..answers.addAll([
+ preview,
+ const DeviceLogRebaseline.changed(),
+ preview,
+ ]);
+ app.log = log;
+ await openFrozen(tester);
+ await tester.tap(find.text('Trust again'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ 'The device list changed while you were reviewing it. Review it again.',
+ ),
+ findsOneWidget,
+ );
+ expect(log.calls.map((c) => c.confirm), [false, true, false]);
+ // The second preview is on screen, waiting for a choice.
+ expect(find.text('Trust this device list again?'), findsOneWidget);
+ });
+ });
+
+ group('Trust again on another account\'s list says to sign in again', () {
+ const message =
+ 'The device list now belongs to a different account than the one '
+ 'you signed in with. Sign in again to switch accounts.';
+
+ Future<ScriptedDeviceLog> trust(
+ WidgetTester tester,
+ List<DeviceLogRebaseline?> answers,
+ ) async {
+ final log = ScriptedDeviceLog()..answers.addAll(answers);
+ app.log = log;
+ app.frozen = const DeviceLogFreeze('invalid', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ await tester.tap(find.text('The device list froze')); // the preview
+ await tester.pumpAndSettle();
+ if (answers.length > 1) {
+ await tester.tap(find.text('Trust again')); // the confirm
+ await tester.pumpAndSettle();
+ }
+ return log;
+ }
+
+ testWidgets('at the preview: nothing to confirm', (tester) async {
+ final log = await trust(tester, [
+ const DeviceLogRebaseline.otherAccount(),
+ ]);
+ expect(find.text(message), findsOneWidget);
+ expect(log.calls.map((c) => c.confirm), [false]);
+ expect(find.text('Trust this device list again?'), findsNothing);
+ });
+
+ testWidgets('at the confirm: said once, not previewed again', (
+ tester,
+ ) async {
+ final log = await trust(tester, [
+ const DeviceLogRebaseline(DevLogHead(7, 'hash-7'), [], []),
+ const DeviceLogRebaseline.otherAccount(),
+ ]);
+ expect(find.text(message), findsOneWidget);
+ expect(find.textContaining('changed while you were'), findsNothing);
+ expect(log.calls.map((c) => c.confirm), [false, true]);
+ expect(find.text('Trust this device list again?'), findsNothing);
+ });
+ });
+
+ group('error text on a narrow phone', () {
+ Future<void> narrow(WidgetTester tester) async {
+ tester.view.physicalSize = const Size(360, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ }
+
+ /// [finder]'s text as it is LAID OUT, not as it is configured: no ellipsis, on more than one line,
+ /// every line inside [width], and the last line is the end of [full] (nothing cut off after it).
+ void expectLaidOutInFull(
+ WidgetTester tester,
+ Finder finder,
+ String full, {
+ required double width,
+ }) {
+ final text = tester.widget<Text>(finder);
+ expect(text.data, full);
+ final box = tester.renderObject<RenderParagraph>(finder);
+ expect(box.didExceedMaxLines, isFalse, reason: 'cut short by maxLines');
+ final boxes = box.getBoxesForSelection(
+ TextSelection(baseOffset: 0, extentOffset: full.length),
+ );
+ final tops = {for (final b in boxes) b.top.round()};
+ expect(tops.length, greaterThan(1), reason: 'long enough to wrap');
+ expect(tester.getRect(finder).right, lessThanOrEqualTo(width));
+ // The paragraph is exactly as tall as the lines it wrapped to — none was dropped.
+ final bottom = boxes.map((b) => b.bottom).reduce((a, b) => a > b ? a : b);
+ expect(box.size.height, inInclusiveRange(bottom - 0.5, bottom + 3));
+ // The point at the end of the last line is the end of the text.
+ final last = boxes.last;
+ final end = box.getPositionForOffset(Offset(last.right, last.top + 1));
+ expect(end.offset, full.length);
+ }
+
+ testWidgets('the other-account message wraps whole, in amber', (
+ tester,
+ ) async {
+ await narrow(tester);
+ final log = ScriptedDeviceLog()
+ ..answers.add(const DeviceLogRebaseline.otherAccount());
+ app.log = log;
+ app.frozen = const DeviceLogFreeze('invalid', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ await tester.tap(find.text('The device list froze'));
+ await tester.pumpAndSettle();
+ final finder = find.byKey(const Key('account-devices-error'));
+ final text = tester.widget<Text>(finder);
+ expect(text.data, otherAccountMessage);
+ expect(text.maxLines, isNull);
+ expect(text.softWrap, isNot(false));
+ final tty = Tty.of(tester.element(finder));
+ expect(text.style!.color, tty.yellow);
+ // Several lines, none wider than the screen.
+ expect(
+ tester.getSize(finder).height,
+ greaterThan(text.style!.fontSize! * 2),
+ );
+ expect(tester.getRect(finder).right, lessThanOrEqualTo(360));
+ });
+
+ for (final width in [360.0, 390.0]) {
+ testWidgets('the other-account message is laid out in full at '
+ '${width.toInt()}pt, ending "Sign in again to switch accounts."', (
+ tester,
+ ) async {
+ tester.view.physicalSize = Size(width, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ app
+ ..log = (ScriptedDeviceLog()
+ ..answers.add(const DeviceLogRebaseline.otherAccount()))
+ ..frozen = const DeviceLogFreeze('invalid', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ await tester.tap(find.text('The device list froze'));
+ await tester.pumpAndSettle();
+ final finder = find.byKey(const Key('account-devices-error'));
+ expect(
+ otherAccountMessage,
+ endsWith('Sign in again to switch accounts.'),
+ );
+ expectLaidOutInFull(tester, finder, otherAccountMessage, width: width);
+ });
+ }
+
+ testWidgets('a failure is red and wraps too', (tester) async {
+ await narrow(tester);
+ final log = ScriptedDeviceLog()..answers.add(null);
+ app.log = log;
+ app.frozen = const DeviceLogFreeze('invalid', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ await tester.tap(find.text('The device list froze'));
+ await tester.pumpAndSettle();
+ final finder = find.byKey(const Key('account-devices-error'));
+ final text = tester.widget<Text>(finder);
+ expect(text.maxLines, isNull);
+ expect(text.style!.color, Tty.of(tester.element(finder)).red);
+ });
+
+ testWidgets('the list-moved message is amber', (tester) async {
+ await narrow(tester);
+ const head = DevLogHead(7, 'hash-7');
+ final preview = DeviceLogRebaseline(head, const [], const []);
+ final log = ScriptedDeviceLog()
+ // preview, confirm refused (moved), then the preview it opens again.
+ ..answers.addAll([
+ preview,
+ const DeviceLogRebaseline.changed(),
+ preview,
+ ]);
+ app.log = log;
+ app.frozen = const DeviceLogFreeze('fork', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ await tester.tap(find.text('The device list froze'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Trust again'));
+ await tester.pumpAndSettle();
+ final finder = find.byKey(const Key('account-devices-error'));
+ expect(
+ tester.widget<Text>(finder).style!.color,
+ Tty.of(tester.element(finder)).yellow,
+ );
+ });
+
+ for (final width in [360.0, 390.0]) {
+ testWidgets('the frozen card body is laid out in full at '
+ '${width.toInt()}pt: wrapped, not clipped to a line', (tester) async {
+ tester.view.physicalSize = Size(width, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ app.frozen = const DeviceLogFreeze('fork', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ expectLaidOutInFull(
+ tester,
+ find.textContaining('Harness served a list'),
+ 'Harness served a list that does not match what this phone verified. '
+ 'No device is added until you review it.',
+ width: width,
+ );
+ // The row grew with its text rather than clipping it.
+ final row = find.ancestor(
+ of: find.text('The device list froze'),
+ matching: find.byType(SettingsRow),
+ );
+ expect(
+ tester.getSize(row).height,
+ greaterThan(kSettingsRowHeight + 20),
+ );
+ });
+ }
+
+ testWidgets('the frozen card says all of what it has to say, and the page '
+ 'subtitle wraps', (tester) async {
+ await narrow(tester);
+ app.frozen = const DeviceLogFreeze('fork', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ final detail = tester.widget<Text>(
+ find.textContaining('Harness served a list'),
+ );
+ expect(detail.maxLines, isNull);
+ final subtitle = tester.widget<Text>(
+ find.textContaining('Every computer and app signed in'),
+ );
+ expect(subtitle.maxLines, isNull);
+ expect(subtitle.softWrap, isNot(false));
+ });
+ });
+
+ testWidgets('a removal of unused apps that fails is red, not amber', (
+ tester,
+ ) async {
+ final stale = pubOf(9);
+ app
+ ..rows = [
+ ...app.rows,
+ row(
+ member(
+ stale,
+ label: 'Old browser',
+ addedAt: ago(const Duration(days: 300)),
+ ),
+ ),
+ ]
+ ..seen = {stale: ago(const Duration(days: 120))}
+ ..removeError = 'UNAVAILABLE';
+ await pump(tester);
+ await tester.tap(find.byKey(const Key('account-devices-unused')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(FilledButton, 'Remove'));
+ await tester.pumpAndSettle();
+ final finder = find.byKey(const Key('account-devices-error'));
+ expect(find.text('Couldn’t remove 1 of them. Try again.'), findsOneWidget);
+ expect(
+ tester.widget<Text>(finder).style!.color,
+ Tty.of(tester.element(finder)).red,
+ );
+ });
+
+ testWidgets('Trust again that succeeds clears an earlier error', (
+ tester,
+ ) async {
+ const head = DevLogHead(7, 'hash-7');
+ final preview = DeviceLogRebaseline(head, const [], const []);
+ // preview, confirm refused (moved), preview again, confirm done.
+ final log = ScriptedDeviceLog()
+ ..answers.addAll([
+ preview,
+ const DeviceLogRebaseline.changed(),
+ preview,
+ preview,
+ ]);
+ app.log = log;
+ app.frozen = const DeviceLogFreeze('fork', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ await tester.tap(find.text('The device list froze'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Trust again'));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('changed while you were'), findsOneWidget);
+ await tester.tap(find.text('Trust again'));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('changed while you were'), findsNothing);
+ expect(log.calls.map((c) => c.confirm), [false, true, false, true]);
+ });
+
+ testWidgets('Trust again that cannot be confirmed (unreadable, not moved) '
+ 'says to try later and does not preview again', (tester) async {
+ const head = DevLogHead(7, 'hash-7');
+ // preview, then a confirm that could not read the list at all.
+ final log = ScriptedDeviceLog()
+ ..answers.addAll([DeviceLogRebaseline(head, const [], const []), null]);
+ app.log = log;
+ app.frozen = const DeviceLogFreeze('fork', 0, DevLogHead(3, 'h3'));
+ await pump(tester);
+ await tester.tap(find.text('The device list froze'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Trust again'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Couldn’t trust the device list again. Try again later.'),
+ findsOneWidget,
+ );
+ expect(find.textContaining('changed while you were'), findsNothing);
+ expect(log.calls.map((c) => c.confirm), [false, true]);
+ });
+
+ testWidgets('opening the list dismisses the banner as it was when the list '
+ 'was read, not a device announced during the last-seen read', (
+ tester,
+ ) async {
+ final shownPub = app.newDevices.single.pub;
+ final lateKey = pubOf(11);
+ app.seenGate = Completer<void>();
+ await pump(tester);
+ app.newDevices.add(member(lateKey, label: 'Late', addedAt: 5, seq: 9));
+ app.seenGate!.complete();
+ await tester.pumpAndSettle();
+ expect(app.seenShown.single, [shownPub]);
+ expect(app.newDevices.map((d) => d.pub), [lateKey]);
+ });
+
+ testWidgets('opening the list does not mark a departed key the banner '
+ 'still names (the app has not read it as departed yet)', (tester) async {
+ final shownPub = app.newDevices.single.pub;
+ final gone = pubOf(12);
+ app.newDevices.add(member(gone, label: 'Gone', addedAt: 5, seq: 9));
+ app.departed = [departedKey(gone)];
+ await pump(tester);
+ await tester.pumpAndSettle();
+ expect(app.seenShown.single, [shownPub]);
+ expect(app.seenPending.single, isNot(contains(gone)));
+ });
+
+ testWidgets('Got it that cannot be saved does not throw', (tester) async {
+ app
+ ..baselineSeen = false
+ ..joinedSeq = 2;
+ app.rows = [...app.rows];
+ app.log = ScriptedDeviceLog()..seeBaselineThrows = true;
+ await pump(tester);
+ await tester.tap(find.text('Got it'));
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ // Hidden anyway: it was read.
+ expect(find.byKey(const Key('account-devices-baseline')), findsNothing);
+ });
}
diff --git a/mobile/test/phone/new_device_banner_test.dart b/mobile/test/phone/new_device_banner_test.dart
index b4ae53964..e55537798 100644
--- a/mobile/test/phone/new_device_banner_test.dart
+++ b/mobile/test/phone/new_device_banner_test.dart
@@ -1,9 +1,12 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/phone/device_detail_page.dart';
+import 'package:harness_mobile/phone/device_history_page.dart';
import 'package:harness_mobile/phone/devices_page.dart';
import 'package:harness_mobile/phone/new_device_banner.dart';
+import 'package:harness_mobile/viewer/device_log_sync.dart';
+
import 'devices_fixture.dart';
/// "New device: X" — Review goes to that device when there is one, to the list when there are more.
@@ -19,7 +22,10 @@ void main() {
MaterialApp(
navigatorKey: nav,
home: Scaffold(
- body: NewDeviceBanner(notifier: app, navigator: nav),
+ body: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => NewDeviceBanner(notifier: app, navigator: nav),
+ ),
),
),
);
@@ -35,7 +41,10 @@ void main() {
.subtract(const Duration(hours: 1))
.millisecondsSinceEpoch,
);
- app.newDevices.add(m);
+ // The page is the log's own row, read when Review is tapped.
+ app
+ ..rows = [row(m, pending: true)]
+ ..newDevices.add(m);
await pump(tester);
expect(find.text('New device: iPad'), findsOneWidget);
expect(find.textContaining('·'), findsNothing);
@@ -70,7 +79,7 @@ void main() {
..rows = [row(older), row(newer)]
..newDevices.addAll([older, newer]);
await pump(tester);
- expect(find.text('New device: iPad +1'), findsOneWidget);
+ expect(find.text('New device: iPad (+1 more)'), findsOneWidget);
await tester.tap(find.text('Review'));
await tester.pumpAndSettle();
@@ -85,4 +94,602 @@ void main() {
);
expect(newerTop.dy, lessThan(olderTop.dy));
});
+
+ DeviceRemovalNotice notice({
+ bool selfRemoved = false,
+ bool signerPending = false,
+ String signerLabel = 'Pixel',
+ }) => DeviceRemovalNotice(
+ pub: pubOf(9),
+ label: 'iPad',
+ kind: 'viewer',
+ fingerprint: 'AAAA·BBBB',
+ signer: pubOf(8),
+ signerLabel: signerLabel,
+ signerFingerprint: 'E2FB·0DF5',
+ signerPending: signerPending,
+ selfRemoved: selfRemoved,
+ at: 0,
+ );
+
+ testWidgets('a removal by a known device: Device removed, Got it dismisses', (
+ tester,
+ ) async {
+ app.deviceRemovals.add(notice());
+ await pump(tester);
+ expect(find.text('Device removed'), findsOneWidget);
+ expect(
+ find.text('iPad was removed from your account by Pixel.'),
+ findsOneWidget,
+ );
+ expect(find.text('Review'), findsNothing);
+ await tester.tap(find.text('Got it'));
+ await tester.pumpAndSettle();
+ expect(app.deviceRemovals, isEmpty);
+ expect(find.text('Device removed'), findsNothing);
+ });
+
+ testWidgets('a device that signed out', (tester) async {
+ app.deviceRemovals.add(notice(selfRemoved: true));
+ await pump(tester);
+ expect(find.text('Device signed out'), findsOneWidget);
+ expect(find.text('iPad signed out of your account.'), findsOneWidget);
+ });
+
+ testWidgets('a removal by a new device: red copy, Review opens that signer', (
+ tester,
+ ) async {
+ final signer = member(pubOf(8), label: 'Pixel', addedAt: 1);
+ app
+ ..rows = [row(signer, pending: true)]
+ ..newDevices.add(signer)
+ ..deviceRemovals.add(notice(signerPending: true));
+ await pump(tester);
+ expect(find.text('Removed by a new device'), findsOneWidget);
+ expect(
+ find.text(
+ 'iPad was removed from your account by a new device you haven’t looked at (Pixel · E2FB·0DF5…).',
+ ),
+ findsOneWidget,
+ );
+ // The removal band is above the new-device band: its Review is the first.
+ await tester.tap(find.text('Review').first);
+ await tester.pumpAndSettle();
+ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));
+ expect(page.row.member.pub, signer.pub);
+ expect(page.isNew, isTrue);
+ expect(app.deviceRemovals, isEmpty);
+ });
+
+ testWidgets('a removal announced while on screen shows up; a device that '
+ 'signed itself out is never red', (tester) async {
+ await pump(tester);
+ expect(find.byKey(const Key('device-removed-banner')), findsNothing);
+ app.announceDeviceRemoval(notice(selfRemoved: true, signerPending: true));
+ await tester.pumpAndSettle();
+ expect(find.text('Device signed out'), findsOneWidget);
+ expect(find.text('Review'), findsNothing);
+ });
+
+ testWidgets('a red removal whose signer is no longer new: Review opens the '
+ 'list', (tester) async {
+ // The signer is still on the account, but nobody has it as news any more.
+ app
+ ..rows = [row(member(pubOf(8), label: 'Pixel', addedAt: 1))]
+ ..deviceRemovals.add(notice(signerPending: true));
+ await pump(tester);
+ await tester.tap(find.text('Review'));
+ await tester.pumpAndSettle();
+ expect(find.byType(DeviceDetailPage), findsNothing);
+ expect(find.byType(DevicesPage), findsOneWidget);
+ expect(app.deviceRemovals, isEmpty);
+ });
+
+ testWidgets('two removals: one at a time, with a count', (tester) async {
+ app.deviceRemovals
+ ..add(notice())
+ ..add(
+ DeviceRemovalNotice(
+ pub: pubOf(10),
+ label: 'Mac',
+ kind: 'machine',
+ fingerprint: '',
+ signer: pubOf(8),
+ signerLabel: 'Pixel',
+ signerFingerprint: '',
+ signerPending: false,
+ selfRemoved: false,
+ at: 0,
+ ),
+ );
+ await pump(tester);
+ expect(find.text('Device removed (+1 more)'), findsOneWidget);
+ await tester.tap(find.text('Got it'));
+ await tester.pumpAndSettle();
+ expect(find.text('Device removed'), findsOneWidget);
+ expect(
+ find.text('Mac was removed from your account by Pixel.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a removal and a new device share ONE SafeArea: the lower band '
+ 'is not pushed down by the notch again', (tester) async {
+ final m = member(pubOf(7), label: 'iPad', addedAt: 1);
+ app
+ ..deviceRemovals.add(notice())
+ ..newDevices.add(m);
+ await tester.pumpWidget(
+ MaterialApp(
+ navigatorKey: nav,
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(padding: const EdgeInsets.only(top: 50)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => NewDeviceBanner(notifier: app, navigator: nav),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ find.descendant(
+ of: find.byType(NewDeviceBanner),
+ matching: find.byType(SafeArea),
+ ),
+ findsOneWidget,
+ );
+ final removalBottom = tester
+ .getBottomLeft(find.byKey(const Key('device-removed-banner')))
+ .dy;
+ final newTop = tester
+ .getTopLeft(find.byKey(const Key('new-device-banner')))
+ .dy;
+ // Only the band's own padding (8 + 8) lies between the two texts, not another 50.
+ expect(newTop - removalBottom, lessThan(40));
+ // And the top band does start below the notch.
+ expect(
+ tester.getTopLeft(find.byKey(const Key('device-removed-banner'))).dy,
+ greaterThanOrEqualTo(50),
+ );
+ });
+
+ testWidgets(
+ 'Review opens the log\'s own row: a key a fork suspended says so, '
+ 'and It\'s mine there lifts it',
+ (tester) async {
+ final m = member(pubOf(7), label: 'iPad', addedAt: 1);
+ app
+ ..rows = [row(m, pending: true, suspended: true)]
+ ..suspendedNew.add(m.pub)
+ ..newDevices.add(m);
+ await pump(tester);
+ await tester.tap(find.text('Review'));
+ await tester.pumpAndSettle();
+
+ expect(find.textContaining('Not trusted here'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('device-detail-mine')));
+ await tester.pumpAndSettle();
+ expect(app.dismissed, [(pub: m.pub, liftSuspension: true)]);
+ },
+ );
+
+ testWidgets('Mine on a suspended entry opens its page instead of dismissing '
+ '(a dismissal could not hold: the next read brings it back)', (
+ tester,
+ ) async {
+ final m = member(pubOf(7), label: 'iPad', addedAt: 1);
+ app
+ ..rows = [row(m, pending: true, suspended: true)]
+ ..suspendedNew.add(m.pub)
+ ..newDevices.add(m);
+ await pump(tester);
+ await tester.tap(find.text('Mine'));
+ await tester.pumpAndSettle();
+
+ expect(app.dismissed, isEmpty);
+ expect(app.newDevices, [m]);
+ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));
+ expect(page.row.suspended, isTrue);
+ expect(find.textContaining('Not trusted here'), findsOneWidget);
+ });
+
+ testWidgets('a red removal\'s Review opens a suspended signer as the log '
+ 'lists it (Suspended shown)', (tester) async {
+ final signer = member(pubOf(8), label: 'Pixel', addedAt: 1);
+ app
+ ..rows = [row(signer, pending: true, suspended: true)]
+ ..newDevices.add(signer)
+ ..deviceRemovals.add(notice(signerPending: true));
+ await pump(tester);
+ await tester.tap(find.text('Review').first);
+ await tester.pumpAndSettle();
+ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));
+ expect(page.row.suspended, isTrue);
+ expect(find.textContaining('Not trusted here'), findsOneWidget);
+ });
+
+ testWidgets('Mine on the banner keeps a fork suspension (pubs only)', (
+ tester,
+ ) async {
+ final m = member(pubOf(7), label: 'iPad', addedAt: 1);
+ app.newDevices.add(m);
+ await pump(tester);
+ await tester.tap(find.text('Mine'));
+ await tester.pumpAndSettle();
+ expect(app.dismissed, [(pub: m.pub, liftSuspension: false)]);
+ expect(app.newDevices, isEmpty);
+ });
+
+ group('a device that joined and left before anyone looked', () {
+ testWidgets('self sign-out: the sentence alone, neutral; Got it saves the '
+ 'dismissal and clears the band', (tester) async {
+ // A sign-out is signed by the key itself: no "Removed by".
+ app.departedDevices.add(
+ departedKey(
+ pubOf(5),
+ selfRemoved: true,
+ removedBy: pubOf(5),
+ removedByLabel: 'iPad',
+ ),
+ );
+ await pump(tester);
+ expect(
+ find.text('iPad joined your account and left before you looked.'),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('device-departed-got-it')));
+ await tester.pumpAndSettle();
+ expect(app.dismissedDeparted, [pubOf(5)]);
+ expect(app.departedDevices, isEmpty);
+ expect(find.byKey(const Key('device-departed-banner')), findsNothing);
+ });
+
+ testWidgets('removed by another key: names the signer', (tester) async {
+ app.departedDevices.add(
+ departedKey(pubOf(5), removedBy: pubOf(8), removedByLabel: 'Pixel'),
+ );
+ await pump(tester);
+ expect(
+ find.text(
+ 'iPad joined your account and left before you looked. Removed by Pixel.',
+ ),
+ findsOneWidget,
+ );
+ // Its signer is a known device: not red.
+ expect(app.departedRed(app.departedDevices.single), isFalse);
+ });
+
+ testWidgets('a signer with no name is "another device"; no label is '
+ '"A device"', (tester) async {
+ app.departedDevices.add(
+ departedKey(pubOf(5), label: '', removedBy: pubOf(8)),
+ );
+ await pump(tester);
+ expect(
+ find.text(
+ 'A device joined your account and left before you looked. '
+ 'Removed by another device.',
+ ),
+ findsOneWidget,
+ );
+ });
+
+ test('red only when the removing key is itself new or departed; a '
+ 'sign-out never is', () {
+ final signer = member(pubOf(8), label: 'Pixel', addedAt: 1);
+ final byNew = departedKey(pubOf(5), removedBy: pubOf(8));
+ final bySelf = departedKey(
+ pubOf(5),
+ selfRemoved: true,
+ removedBy: pubOf(8),
+ );
+ expect(app.departedRed(byNew), isFalse);
+ app.newDevices.add(signer);
+ expect(app.departedRed(byNew), isTrue);
+ expect(app.departedRed(bySelf), isFalse);
+ app.newDevices.clear();
+ app.departedDevices.add(departedKey(pubOf(8), selfRemoved: true));
+ expect(app.departedRed(byNew), isTrue);
+ });
+
+ testWidgets('the band is red when its signer is itself new, neutral '
+ 'otherwise', (tester) async {
+ Color bandColor() => tester
+ .widget<Material>(
+ find
+ .ancestor(
+ of: find.byKey(const Key('device-departed-banner')),
+ matching: find.byType(Material),
+ )
+ .first,
+ )
+ .color!;
+ app.departedDevices.add(
+ departedKey(pubOf(5), removedBy: pubOf(8), removedByLabel: 'Pixel'),
+ );
+ await pump(tester);
+ final neutral = bandColor();
+ app.newDevices.add(member(pubOf(8), label: 'Pixel', addedAt: 1));
+ app.poke();
+ await tester.pumpAndSettle();
+ expect(bandColor(), isNot(neutral));
+ // Said in words as well, as the desktop says it — not by the colour alone.
+ expect(
+ find.text(
+ 'iPad joined your account and left before you looked. '
+ 'Removed by Pixel, a new device you haven’t looked at.',
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('History opens the History and leaves the band', (
+ tester,
+ ) async {
+ app.departedDevices.add(departedKey(pubOf(5), selfRemoved: true));
+ await pump(tester);
+ await tester.tap(find.byKey(const Key('device-departed-review')));
+ await tester.pumpAndSettle();
+ expect(find.byType(DeviceHistoryPage), findsOneWidget);
+ expect(app.dismissedDeparted, isEmpty);
+ expect(app.departedDevices, hasLength(1));
+ });
+
+ testWidgets('a signed-out notice and the departed mark for the same key '
+ 'are one ghost: only the departed band shows', (tester) async {
+ app
+ ..departedDevices.add(departedKey(pubOf(9), selfRemoved: true))
+ ..deviceRemovals.add(notice(selfRemoved: true));
+ await pump(tester);
+ expect(find.byKey(const Key('device-departed-banner')), findsOneWidget);
+ expect(find.byKey(const Key('device-removed-banner')), findsNothing);
+ expect(find.text('Device signed out'), findsNothing);
+ expect(find.text('iPad signed out of your account.'), findsNothing);
+ // One Got it, the departed band's: it is the one dismissal.
+ expect(find.text('Got it'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('device-departed-got-it')));
+ await tester.pumpAndSettle();
+ expect(app.dismissedDeparted, [pubOf(9)]);
+ // Neither band comes back: the notice does not surface once the mark is gone.
+ expect(app.deviceRemovals, isEmpty);
+ expect(find.byKey(const Key('device-departed-banner')), findsNothing);
+ expect(find.byKey(const Key('device-removed-banner')), findsNothing);
+ expect(find.text('Device signed out'), findsNothing);
+ });
+
+ testWidgets('a signed-out notice for ANOTHER key still shows beside the '
+ 'departed band', (tester) async {
+ app
+ ..departedDevices.add(departedKey(pubOf(5), selfRemoved: true))
+ ..deviceRemovals.add(notice(selfRemoved: true));
+ await pump(tester);
+ expect(find.byKey(const Key('device-departed-banner')), findsOneWidget);
+ expect(find.text('Device signed out'), findsOneWidget);
+ });
+
+ testWidgets('a removal BY another key of a departed key keeps both bands '
+ '(it is not one ghost: someone else did it)', (tester) async {
+ app
+ ..departedDevices.add(departedKey(pubOf(9), removedBy: pubOf(8)))
+ ..deviceRemovals.add(notice());
+ await pump(tester);
+ expect(find.byKey(const Key('device-departed-banner')), findsOneWidget);
+ expect(find.text('Device removed'), findsOneWidget);
+ // Each band has its own Got it: the departed one leaves the removal notice up.
+ await tester.tap(find.byKey(const Key('device-departed-got-it')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const Key('device-departed-banner')), findsNothing);
+ expect(app.deviceRemovals, hasLength(1));
+ expect(find.text('Device removed'), findsOneWidget);
+ });
+
+ testWidgets('the suppressed notice still counts the banner as showing '
+ '(the departed band is on screen, so the status-bar inset is taken)', (
+ tester,
+ ) async {
+ app
+ ..deviceRemovals.add(notice(selfRemoved: true))
+ ..departedDevices.add(departedKey(pubOf(9), selfRemoved: true));
+ expect(NewDeviceBanner.removalsShown(app), isEmpty);
+ expect(NewDeviceBanner.showing(app), isTrue);
+ });
+
+ testWidgets('a red removal\'s Review does not clear the departed mark of '
+ 'the same device', (tester) async {
+ final signer = member(pubOf(8), label: 'Pixel', addedAt: 1);
+ app
+ ..rows = [row(signer, pending: true)]
+ ..newDevices.add(signer)
+ ..departedDevices.add(departedKey(pubOf(9), removedBy: pubOf(8)))
+ ..deviceRemovals.add(notice(signerPending: true));
+ await pump(tester);
+ await tester.tap(find.text('Review').first);
+ await tester.pumpAndSettle();
+ expect(app.deviceRemovals, isEmpty);
+ expect(app.dismissedDeparted, isEmpty);
+ expect(app.departedDevices, hasLength(1));
+ });
+
+ testWidgets('two: one at a time, with a count; Got it clears every one it '
+ 'counts, each dismissal saved', (tester) async {
+ app.departedDevices
+ ..add(departedKey(pubOf(5), selfRemoved: true))
+ ..add(departedKey(pubOf(6), label: 'Mac', selfRemoved: true));
+ await pump(tester);
+ expect(
+ find.text(
+ 'iPad joined your account and left before you looked. (+1 more)',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('device-departed-got-it')));
+ await tester.pumpAndSettle();
+ expect(app.dismissedDeparted, [pubOf(5), pubOf(6)]);
+ expect(app.departedDevices, isEmpty);
+ expect(find.byKey(const Key('device-departed-banner')), findsNothing);
+ });
+
+ testWidgets('a departed key with no recorded signer (it left in a review) '
+ 'says no one removed it', (tester) async {
+ app.departedDevices.add(departedKey(pubOf(5)));
+ await pump(tester);
+ expect(
+ find.text('iPad joined your account and left before you looked.'),
+ findsOneWidget,
+ );
+ expect(find.textContaining('Removed by'), findsNothing);
+ });
+
+ testWidgets('its button is labelled History, where it opens', (
+ tester,
+ ) async {
+ app.departedDevices.add(departedKey(pubOf(5), selfRemoved: true));
+ await pump(tester);
+ expect(
+ find.descendant(
+ of: find.byKey(const Key('device-departed-review')),
+ matching: find.text('History'),
+ ),
+ findsOneWidget,
+ );
+ });
+ });
+
+ group('what the bands lead with', () {
+ Color bandColor(WidgetTester tester, Key inner) => tester
+ .widget<Material>(
+ find
+ .ancestor(of: find.byKey(inner), matching: find.byType(Material))
+ .first,
+ )
+ .color!;
+
+ DeviceRemovalNotice removal(
+ int n, {
+ bool signerPending = false,
+ String label = 'iPad',
+ }) => DeviceRemovalNotice(
+ pub: pubOf(n),
+ label: label,
+ kind: 'viewer',
+ fingerprint: '',
+ signer: pubOf(8),
+ signerLabel: 'Pixel',
+ signerFingerprint: '',
+ signerPending: signerPending,
+ selfRemoved: false,
+ at: 0,
+ );
+
+ testWidgets('a removal by a new device is shown first, red, though an '
+ 'older neutral one is queued ahead of it', (tester) async {
+ app.deviceRemovals
+ ..add(removal(9, label: 'Mac'))
+ ..add(removal(10, signerPending: true, label: 'Evil'));
+ await pump(tester);
+ expect(find.text('Removed by a new device (+1 more)'), findsOneWidget);
+ expect(find.text('Device removed (+1 more)'), findsNothing);
+ expect(find.text('Review'), findsOneWidget);
+ // Got it dismisses the one shown, not the one behind it.
+ await tester.tap(find.text('Got it'));
+ await tester.pumpAndSettle();
+ expect(app.deviceRemovals.map((r) => r.pub), [pubOf(9)]);
+ expect(find.text('Device removed'), findsOneWidget);
+ });
+
+ testWidgets('a departed key removed by a new device is shown first and '
+ 'red, ahead of an older neutral one', (tester) async {
+ final signer = member(pubOf(8), label: 'Pixel', addedAt: 1);
+ app.departedDevices.add(
+ departedKey(pubOf(6), label: 'Mac', selfRemoved: true),
+ );
+ await pump(tester);
+ final neutral = bandColor(tester, const Key('device-departed-banner'));
+ app
+ ..newDevices.add(signer)
+ ..departedDevices.add(
+ departedKey(pubOf(5), removedBy: pubOf(8), removedByLabel: 'Pixel'),
+ )
+ ..poke();
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ 'iPad joined your account and left before you looked. '
+ 'Removed by Pixel, a new device you haven’t looked at. (+1 more)',
+ ),
+ findsOneWidget,
+ );
+ expect(
+ bandColor(tester, const Key('device-departed-banner')),
+ isNot(neutral),
+ );
+ });
+
+ testWidgets('Got it clears the keys the band counted when it was built, '
+ 'not one that arrived after', (tester) async {
+ app.departedDevices.add(departedKey(pubOf(5), selfRemoved: true));
+ await pump(tester);
+ // Arrives without a rebuild: never drawn, so never dismissed.
+ app.departedDevices.add(
+ departedKey(pubOf(6), label: 'Mac', selfRemoved: true),
+ );
+ await tester.tap(find.byKey(const Key('device-departed-got-it')));
+ await tester.pumpAndSettle();
+ expect(app.dismissedDeparted, [pubOf(5)]);
+ expect(app.departedDevices.map((d) => d.pub), [pubOf(6)]);
+ expect(
+ find.text('Mac joined your account and left before you looked.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('bands stack in one order: removal, departed, new device', (
+ tester,
+ ) async {
+ app
+ ..deviceRemovals.add(removal(9))
+ ..departedDevices.add(departedKey(pubOf(5), selfRemoved: true))
+ ..newDevices.add(member(pubOf(7), label: 'iPad', addedAt: 1));
+ await pump(tester);
+ double top(Key k) => tester.getTopLeft(find.byKey(k)).dy;
+ expect(
+ top(const Key('device-removed-banner')),
+ lessThan(top(const Key('device-departed-banner'))),
+ );
+ expect(
+ top(const Key('device-departed-banner')),
+ lessThan(top(const Key('new-device-banner'))),
+ );
+ });
+
+ testWidgets('the new-device sentence wraps beside Mine and Review: '
+ '"(+N more)" is not clipped', (tester) async {
+ tester.view.physicalSize = const Size(360, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ app.newDevices.addAll([
+ member(pubOf(7), label: 'Evil Phone', addedAt: 1),
+ member(pubOf(8), label: 'Pixel', addedAt: 2),
+ member(pubOf(9), label: 'Mac', addedAt: 3),
+ ]);
+ await pump(tester);
+ final text = find.byKey(const Key('new-device-banner'));
+ final widget = tester.widget<Text>(text);
+ expect(widget.maxLines, isNull);
+ expect(widget.softWrap, isNot(false));
+ expect(widget.overflow, isNot(TextOverflow.clip));
+ expect(tester.takeException(), isNull);
+ // It has the room left of the buttons, and is taller than one line.
+ expect(
+ tester.getRect(text).right,
+ lessThanOrEqualTo(tester.getRect(find.text('Mine')).left),
+ );
+ expect(find.textContaining('(+2 more)'), findsOneWidget);
+ });
+ });
}
diff --git a/mobile/test/phone/open_device_from_log_test.dart b/mobile/test/phone/open_device_from_log_test.dart
new file mode 100644
index 000000000..5acf026ed
--- /dev/null
+++ b/mobile/test/phone/open_device_from_log_test.dart
@@ -0,0 +1,78 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/device_detail_page.dart';
+import 'package:harness_mobile/phone/devices_page.dart';
+import 'package:harness_mobile/viewer/device_log_sync.dart';
+
+import 'devices_fixture.dart';
+
+/// A [DevicesApp] whose listing waits on [gate], to take the navigator away mid-read.
+class _SlowApp extends DevicesApp {
+ _SlowApp({super.rows});
+
+ final gate = Completer<void>();
+
+ @override
+ Future<DeviceLogListing> deviceListing() async {
+ await gate.future;
+ return super.deviceListing();
+ }
+}
+
+/// A device's page from the log's own listing, on the navigator it is handed — which may be gone by
+/// the time the log has been read.
+void main() {
+ final key = GlobalKey<NavigatorState>();
+
+ Future<void> pumpApp(WidgetTester tester) => tester.pumpWidget(
+ MaterialApp(
+ navigatorKey: key,
+ home: const Scaffold(body: Text('home')),
+ ),
+ );
+
+ testWidgets('opens the device; one the log does not list opens the list', (
+ tester,
+ ) async {
+ final m = member(pubOf(3), label: 'iPad', addedAt: 1);
+ final app = DevicesApp(rows: [row(m, pending: true)]);
+ addTearDown(app.dispose);
+ await pumpApp(tester);
+
+ unawaited(openDeviceFromLog(key.currentState!, app, m.pub));
+ await tester.pumpAndSettle();
+ expect(find.byType(DeviceDetailPage), findsOneWidget);
+
+ key.currentState!.pop();
+ await tester.pumpAndSettle();
+ unawaited(openDeviceFromLog(key.currentState!, app, pubOf(99)));
+ await tester.pumpAndSettle();
+ expect(find.byType(DevicesPage), findsOneWidget);
+ });
+
+ testWidgets('a listing that throws opens the list, no error', (tester) async {
+ final app = DevicesApp()..listingFailures = 1;
+ addTearDown(app.dispose);
+ await pumpApp(tester);
+ unawaited(openDeviceFromLog(key.currentState!, app, pubOf(3)));
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ expect(find.byType(DevicesPage), findsOneWidget);
+ });
+
+ testWidgets('a navigator that went away while the log was read is left '
+ 'alone: no throw', (tester) async {
+ final m = member(pubOf(3), label: 'iPad', addedAt: 1);
+ final app = _SlowApp(rows: [row(m, pending: true)]);
+ addTearDown(app.dispose);
+ await pumpApp(tester);
+ final nav = key.currentState!;
+ final opened = openDeviceFromLog(nav, app, m.pub);
+ await tester.pumpWidget(const SizedBox());
+ app.gate.complete();
+ await opened;
+ expect(tester.takeException(), isNull);
+ });
+}
diff --git a/mobile/test/phone/phone_shell_device_notice_test.dart b/mobile/test/phone/phone_shell_device_notice_test.dart
index 5d645dc69..2c021e0a6 100644
--- a/mobile/test/phone/phone_shell_device_notice_test.dart
+++ b/mobile/test/phone/phone_shell_device_notice_test.dart
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/phone/device_detail_page.dart';
+import 'package:harness_mobile/phone/agent_home.dart';
import 'package:harness_mobile/phone/devices_page.dart';
import 'package:harness_mobile/phone/phone_shell.dart';
@@ -30,7 +31,9 @@ void main() {
tester,
) async {
final m = member(pubOf(3), label: 'iPad', addedAt: at);
- app.newDevices.add(m);
+ app
+ ..rows = [row(m, pending: true)]
+ ..newDevices.add(m);
await pumpShell(tester);
await tapNotice(tester, m.pub);
@@ -47,7 +50,9 @@ void main() {
) async {
// The launch tap is read before the shell exists, so no listener sees it change.
final m = member(pubOf(5), label: 'iPad', addedAt: at);
- app.newDevices.add(m);
+ app
+ ..rows = [row(m, pending: true)]
+ ..newDevices.add(m);
app.agentNotices.system.openedDevice.value = m.pub;
await pumpShell(tester);
await tester.pump(const Duration(seconds: 1));
@@ -57,6 +62,37 @@ void main() {
expect(app.agentNotices.system.openedDevice.value, isNull);
});
+ testWidgets('a launch tap for a device the log still holds as pending opens '
+ 'as new, before the banner list is rebuilt', (tester) async {
+ // After a restart the banner list is empty until the log has been read; the tap can come first.
+ final m = member(pubOf(6), label: 'iPad', addedAt: at);
+ app.rows = [row(m, pending: true)];
+ app.agentNotices.system.openedDevice.value = m.pub;
+ await pumpShell(tester);
+ await tester.pump(const Duration(seconds: 1));
+
+ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));
+ expect(page.row.member.pub, m.pub);
+ expect(page.isNew, isTrue);
+ });
+
+ testWidgets('a suspended pending device opens as the log lists it: Suspended '
+ 'shown, and It\'s mine there lifts the suspension', (tester) async {
+ // The notice is built from the log's entry; the page is not: it carries the log's own flags.
+ final m = member(pubOf(3), label: 'iPad', addedAt: at);
+ app
+ ..rows = [row(m, pending: true, suspended: true)]
+ ..newDevices.add(m);
+ await pumpShell(tester);
+
+ await tapNotice(tester, m.pub);
+
+ expect(find.textContaining('Not trusted here'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('device-detail-mine')));
+ await tester.pumpAndSettle();
+ expect(app.dismissed, [(pub: m.pub, liftSuspension: true)]);
+ });
+
testWidgets('a device only on the list opens plain', (tester) async {
final m = member(pubOf(4), label: 'Pixel', addedAt: at);
app.rows = [row(m)];
@@ -79,4 +115,85 @@ void main() {
expect(find.byType(DeviceDetailPage), findsNothing);
expect(find.byType(DevicesPage), findsOneWidget);
});
+
+ testWidgets('a removal notice (removed:<pub>) opens the list', (
+ tester,
+ ) async {
+ await pumpShell(tester);
+
+ await tapNotice(tester, 'removed:${pubOf(6)}');
+
+ expect(find.byType(DeviceDetailPage), findsNothing);
+ expect(find.byType(DevicesPage), findsOneWidget);
+ });
+
+ testWidgets('a red removal notice (removedBy:<signer>:<pub>) opens the '
+ 'signer, as new', (tester) async {
+ final signer = member(pubOf(7), label: 'Pixel', addedAt: at);
+ app
+ ..rows = [row(signer, pending: true)]
+ ..newDevices.add(signer);
+ await pumpShell(tester);
+
+ await tapNotice(tester, 'removedBy:${signer.pub}:${pubOf(6)}');
+
+ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));
+ expect(page.row.member.pub, signer.pub);
+ expect(page.isNew, isTrue);
+ });
+
+ testWidgets('a red removal notice whose signer is gone opens the list', (
+ tester,
+ ) async {
+ await pumpShell(tester);
+
+ await tapNotice(tester, 'removedBy:${pubOf(7)}:${pubOf(6)}');
+
+ expect(find.byType(DeviceDetailPage), findsNothing);
+ expect(find.byType(DevicesPage), findsOneWidget);
+ });
+
+ group('the status-bar inset', () {
+ Future<void> pumpPadded(WidgetTester tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(padding: const EdgeInsets.only(top: 50)),
+ child: child!,
+ ),
+ home: PhoneShell(notifier: app),
+ ),
+ );
+ await tester.pump();
+ }
+
+ double pageTopInset(WidgetTester tester) =>
+ MediaQuery.paddingOf(tester.element(find.byType(AgentHome))).top;
+
+ testWidgets('a band takes it, so the pages under it do not take it '
+ 'again', (tester) async {
+ app.newDevices.add(member(pubOf(3), label: 'iPad', addedAt: at));
+ await pumpPadded(tester);
+ expect(pageTopInset(tester), 0);
+ });
+
+ testWidgets('with no band the pages keep it, and it comes back when the '
+ 'last band goes', (tester) async {
+ await pumpPadded(tester);
+ expect(pageTopInset(tester), 50);
+
+ app
+ ..newDevices.add(member(pubOf(3), label: 'iPad', addedAt: at))
+ ..poke();
+ await tester.pump();
+ expect(pageTopInset(tester), 0);
+
+ app
+ ..newDevices.clear()
+ ..poke();
+ await tester.pump();
+ expect(pageTopInset(tester), 50);
+ });
+ });
}
diff --git a/mobile/test/state/device_pending_sync_test.dart b/mobile/test/state/device_pending_sync_test.dart
new file mode 100644
index 000000000..45a776439
--- /dev/null
+++ b/mobile/test/state/device_pending_sync_test.dart
@@ -0,0 +1,994 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/local_key_value_store.dart';
+import 'package:harness_mobile/e2ee/bytes.dart';
+import 'package:harness_mobile/e2ee/keys.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/pane_layout_store.dart';
+import 'package:harness_mobile/viewer/device_log.dart';
+import 'package:harness_mobile/viewer/device_log_sync.dart';
+import 'package:harness_mobile/viewer/direct_auth_api.dart';
+import 'package:harness_mobile/viewer/viewer_key_store.dart';
+
+import '../viewer_app_fixture.dart';
+import '../voice_fakes.dart' show MemoryKeyValueStore;
+
+/// The phone's new-device banner is the log's persisted `pending`, not a list in memory: it comes back
+/// after a restart, a dismissal holds across one, and a read that started before a dismissal never
+/// brings the dismissed device back. Against a real [ViewerDeviceLog] and an honest backend.
+
+const _acct = 'acct-1';
+final _mid2 = 'b' * 32, _mid3 = 'c' * 32;
+
+class _Backend {
+ _Backend([this.acct = _acct]) : state = DevLogState.empty(acct);
+
+ final entries = <DevLogEntry>[];
+ DevLogState state;
+
+ /// The account id the backend claims.
+ String acct;
+
+ Future<void> add(
+ E2eeIdentity who,
+ String kind,
+ String machineId,
+ String label,
+ ) async {
+ final pub = b64e(who.pub);
+ await _push(
+ await signDevLogEntry(
+ nextDevLogEntry(
+ state,
+ op: 'add',
+ pub: pub,
+ kind: kind,
+ machineId: machineId,
+ label: label,
+ signer: pub,
+ at: 1000,
+ ),
+ who,
+ ),
+ );
+ }
+
+ Future<void> removeBy(String target, E2eeIdentity by) async {
+ final t = state.active[target]!;
+ await _push(
+ await signDevLogEntry(
+ nextDevLogEntry(
+ state,
+ op: 'remove',
+ pub: t.pub,
+ kind: t.kind,
+ machineId: t.machineId,
+ label: t.label,
+ signer: b64e(by.pub),
+ at: 2000,
+ ),
+ by,
+ ),
+ );
+ }
+
+ Future<void> _push(DevLogEntry e) async {
+ state = (await applyDevLogEntries(state, [e.toJson()])).state;
+ entries.add(e);
+ }
+
+ /// Held: a read of the log waits on it (answering with what the backend held when it was asked).
+ Completer<void>? fetchGate;
+
+ Future<DeviceLogFetched?> fetch(int since) async {
+ final gate = fetchGate;
+ final snapshot = _snapshot(since);
+ if (gate != null) await gate.future;
+ return snapshot;
+ }
+
+ DeviceLogFetched _snapshot(int since) => (
+ acct: acct,
+ head: state.head,
+ entries: [
+ for (final e in entries)
+ if (e.seq > since) e.toJson(),
+ ],
+ );
+
+ Future<DeviceLogAppendAnswer?> append(DevLogEntry entry) async {
+ if (entry.seq != state.head.seq + 1 || entry.prev != state.head.hash) {
+ return (head: state.head, error: 'STALE_HEAD');
+ }
+ await _push(entry);
+ return (head: state.head, error: null);
+ }
+}
+
+class _Api extends FakeApi {
+ _Api(this.backend);
+
+ final _Backend backend;
+
+ @override
+ Future<DeviceLogFetched?> deviceKeys(int since) => backend.fetch(since);
+
+ @override
+ Future<DeviceLogAppendAnswer?> appendDeviceKey(DevLogEntry entry) =>
+ backend.append(entry);
+}
+
+/// The phone's own storage, kept across "restarts". [holdDevLogRead] parks one read of the device log
+/// file (after [skip] others) until the test lets it go — answering with what the file held when it
+/// was asked, as a slow disk would.
+class _Disk implements LocalKeyValueStore {
+ final values = <String, String>{};
+ Completer<void>? _hold;
+ Completer<void>? held;
+ var _skip = 0;
+
+ /// Writes of the device log file fail while set.
+ bool failDevLogWrites = false;
+
+ void holdDevLogRead({int skip = 0}) {
+ _skip = skip;
+ _hold = Completer<void>();
+ held = Completer<void>();
+ }
+
+ void release() => _hold?.complete();
+
+ @override
+ Future<String?> read(String key) async {
+ final value = values[key];
+ if (key == 'viewer_e2ee_devlog' && _hold != null && !held!.isCompleted) {
+ if (_skip > 0) {
+ _skip--;
+ return value;
+ }
+ final hold = _hold!;
+ held!.complete();
+ await hold.future;
+ _hold = null;
+ }
+ return value;
+ }
+
+ @override
+ Future<void> write(String key, String value) async {
+ if (failDevLogWrites && key == 'viewer_e2ee_devlog') {
+ throw StateError('disk full');
+ }
+ values[key] = value;
+ }
+
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+/// A viewer whose key store — the phone's disk — outlives one launch.
+class _Viewer extends FakeViewer {
+ _Viewer(super.session, this._keys);
+
+ final ViewerKeyStore _keys;
+
+ @override
+ ViewerKeyStore get keys => _keys;
+}
+
+/// The pane layout's disk read, parked: the boot waits on it while the app is still `bootstrapping`.
+class _GatedLayout extends PaneLayoutStore {
+ _GatedLayout(this._gate) : super(storage: MemoryKeyValueStore());
+
+ final Completer<void> _gate;
+
+ @override
+ Future<Map<String, dynamic>?> loadSwarms() async {
+ await _gate.future;
+ return null;
+ }
+}
+
+class _Notices extends SilentSystemNotices {
+ final keys = <String>[];
+
+ @override
+ Future<void> showAccountNotice({
+ required String key,
+ required String title,
+ required String body,
+ }) async => keys.add(key);
+}
+
+void main() {
+ late _Backend backend;
+ late _Disk disk;
+ late E2eeIdentity box2, box3;
+ final apps = <AppNotifier>[];
+ late Future<void> lastBoot;
+
+ /// The phone opening, signed in, on [disk]: it registers with the log on its own.
+ ///
+ /// [profileId] is what the backend's `/me` says; [fresh] makes it a sign-in by hand just done (not
+ /// a stored session). With a gate held, the boot is left running: the future is [lastBoot].
+ Future<(AppNotifier, _Notices)> launch({
+ Completer<void>? profileGate,
+ Completer<void>? machinesGate,
+ Completer<void>? layoutGate,
+ String? profileId,
+ bool fresh = false,
+ }) async {
+ final session = AuthSession(storage: MemoryKeyValueStore());
+ final notices = _Notices();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: session,
+ configStore: null,
+ cliLogin: FakeSignIn(),
+ peerLinks: FakeLinks(),
+ viewer: _Viewer(session, ViewerKeyStore(storage: disk)),
+ systemNotices: notices,
+ connectionForTest: (_) => ScriptedConn(),
+ paneLayoutStore: layoutGate == null ? null : _GatedLayout(layoutGate),
+ );
+ final api = _Api(backend);
+ app.api = api;
+ if (profileId != null) {
+ api.profile = {
+ 'user': {'id': profileId, 'email': '[email protected]', 'name': 'Pat'},
+ };
+ }
+ if (profileGate != null) {
+ api.onProfile = () async {
+ await profileGate.future;
+ return api.profile;
+ };
+ }
+ if (machinesGate != null) {
+ api.onMachines = () async {
+ await machinesGate.future;
+ return const [];
+ };
+ }
+ if (fresh) await app.viewer.auth.signIn(const IssuedTokens(token: 'tok'));
+ apps.add(app);
+ lastBoot = app.bootstrap();
+ final held =
+ profileGate != null || machinesGate != null || layoutGate != null;
+ if (!held) await lastBoot;
+ await settle();
+ if (!held) expect(app.status, AppStatus.authenticated);
+ return (app, notices);
+ }
+
+ List<String> pubs(List<DevLogMember> ms) => [for (final m in ms) m.pub];
+
+ setUp(() async {
+ backend = _Backend();
+ disk = _Disk();
+ box2 = await E2eeIdentity.fromSeed(List.filled(32, 2));
+ box3 = await E2eeIdentity.fromSeed(List.filled(32, 3));
+ });
+
+ tearDown(() {
+ for (final app in apps) {
+ app.dispose();
+ }
+ apps.clear();
+ });
+
+ test('a device that joins later is on the banner, and still is after a restart — announced once', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final (first, firstNotices) = await launch();
+ // What was there when this phone joined is not news.
+ expect(first.newDevices, isEmpty);
+
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await first.deviceLog!.refresh();
+ await settle();
+ expect(pubs(first.newDevices), [b64e(box3.pub)]);
+ expect(firstNotices.keys, [b64e(box3.pub)]);
+
+ first.dispose();
+ apps.remove(first);
+ final (second, secondNotices) = await launch();
+ expect(pubs(second.newDevices), [b64e(box3.pub)]);
+ // The OS was told once already.
+ expect(secondNotices.keys, isEmpty);
+ });
+
+ test('"It’s mine" on one device holds across a restart', () async {
+ final (first, _) = await launch();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await first.deviceLog!.refresh();
+ await settle();
+ expect(pubs(first.newDevices), [b64e(box2.pub), b64e(box3.pub)]);
+
+ first.dismissNewDevice(b64e(box2.pub));
+ await settle();
+ expect(pubs(first.newDevices), [b64e(box3.pub)]);
+
+ first.dispose();
+ apps.remove(first);
+ final (second, _) = await launch();
+ expect(pubs(second.newDevices), [b64e(box3.pub)]);
+ });
+
+ test('opening the list (seenNewDevices) holds across a restart', () async {
+ final (first, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await first.deviceLog!.refresh();
+ await settle();
+ first.seenNewDevices();
+ await settle();
+ expect(first.newDevices, isEmpty);
+ expect((await first.deviceLog!.list()).pending, isEmpty);
+
+ first.dispose();
+ apps.remove(first);
+ final (second, _) = await launch();
+ expect(second.newDevices, isEmpty);
+ });
+
+ test('opening the list before the banner is rebuilt still marks what the list read as seen', () async {
+ final (first, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await first.deviceLog!.refresh();
+ await settle();
+ // As after a restart, before the log has been read again: the banner list is empty.
+ first.newDevices.clear();
+ final listing = await first.deviceLog!.list();
+ expect(listing.pending, [b64e(box3.pub)]);
+ first.seenNewDevices(pending: listing.pending);
+ await settle();
+ expect((await first.deviceLog!.list()).pending, isEmpty);
+ expect(first.newDevices, isEmpty);
+ });
+
+ test('a read of the log that started before a dismissal does not bring the device back', () async {
+ final (app, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(pubs(app.newDevices), [b64e(box3.pub)]);
+
+ // Something else changes the log (here: an unrelated dismissal) and the app re-reads `pending`;
+ // that read is slow.
+ disk.holdDevLogRead(skip: 1);
+ unawaited(app.deviceLog!.dismiss(pub: 'nobody'));
+ // The dismissal's own read goes through; the re-read of `pending` it sets off is the one held.
+ await disk.held!.future;
+ // Meanwhile the person opens the list: everything is seen.
+ app.seenNewDevices();
+ await settle();
+ expect(app.newDevices, isEmpty);
+
+ // The slow read lands last, with what `pending` held before.
+ disk.release();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ expect((await app.deviceLog!.list()).pending, isEmpty);
+ });
+
+ test('a removal by a device nobody has looked at is red and keyed by the signer; a sign-out is not', () async {
+ final (app, notices) = await launch();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ notices.keys.clear();
+
+ // box3 is still pending here when it takes box2 out.
+ await backend.removeBy(b64e(box2.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ final red = app.deviceRemovals.single;
+ expect(red.pub, b64e(box2.pub));
+ expect(red.red, isTrue);
+ expect(red.title, 'Removed by a new device');
+ expect(
+ red.sentence,
+ 'box2 was removed from your account by a new device you haven’t looked at '
+ '(box3 · ${fingerprint(box3.pub).split('·').take(2).join('·')}…).',
+ );
+ expect(notices.keys, ['removedBy:${b64e(box3.pub)}:${b64e(box2.pub)}']);
+
+ // box3 then signs itself out: neutral, and its notice is keyed by the removal.
+ await backend.removeBy(b64e(box3.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ final out = app.deviceRemovals.last;
+ expect(out.selfRemoved, isTrue);
+ expect(out.red, isFalse);
+ expect(out.title, 'Device signed out');
+ expect(notices.keys.last, 'removed:${b64e(box3.pub)}');
+ });
+
+ test('signing out drops the account’s device notices with it', () async {
+ final (app, _) = await launch();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ await backend.removeBy(b64e(box2.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(app.newDevices, isNotEmpty);
+ expect(app.deviceRemovals, isNotEmpty);
+
+ await app.logout();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ expect(app.deviceRemovals, isEmpty);
+ });
+
+ test(
+ 'opening the list dismisses what was shown, not a device added since',
+ () async {
+ final (app, _) = await launch();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect((await app.deviceLog!.list()).pending, hasLength(2));
+ // The page showed box2 only (box3 landed in the log after it was read).
+ app.newDevices.removeWhere((d) => d.pub == b64e(box3.pub));
+ app.seenNewDevices(pending: [b64e(box2.pub)]);
+ await settle();
+ expect((await app.deviceLog!.list()).pending, [b64e(box3.pub)]);
+ },
+ );
+
+ test(
+ 'a session lost at runtime drops the notices and a read in flight',
+ () async {
+ final (app, _) = await launch();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(app.newDevices, isNotEmpty);
+
+ disk.holdDevLogRead();
+ unawaited(app.deviceLog!.dismiss(pub: 'nobody'));
+ await disk.held!.future;
+ app.authFailureForTest('gone');
+ expect(app.newDevices, isEmpty);
+ disk.release();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ },
+ );
+
+ test('a dismissal that could not be saved does not throw, and the banner does not bring the device back', () async {
+ final (app, _) = await launch();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(pubs(app.newDevices), [b64e(box2.pub)]);
+
+ disk.failDevLogWrites = true;
+ app.dismissNewDevice(b64e(box2.pub));
+ await settle();
+ disk.failDevLogWrites = false;
+ expect(app.newDevices, isEmpty);
+
+ // The log still lists box2 as pending (the write failed); the next read of it must not raise it again.
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect((await app.deviceLog!.list()).pending, contains(b64e(box2.pub)));
+ expect(pubs(app.newDevices), [b64e(box3.pub)]);
+ });
+
+ group('a fork suspended a new key', () {
+ Future<AppNotifier> forked() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final (app, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ final other = _Backend();
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await other.add(
+ await E2eeIdentity.fromSeed(List.filled(32, 9)),
+ 'viewer',
+ '',
+ 'evil',
+ );
+ await other.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.heard(b64e(box2.pub), {
+ 'head': other.state.head.toJson(),
+ 'hashes': [
+ for (var i = 0; i < other.state.hashes.length; i++)
+ {'seq': i + 1, 'hash': other.state.hashes[i]},
+ ],
+ });
+ await settle();
+ expect(await app.deviceLog!.suspendedPubs(), {b64e(box3.pub)});
+ return app;
+ }
+
+ test('the banner knows which of its devices the fork suspended', () async {
+ final app = await forked();
+ expect(app.newDeviceSuspended(b64e(box3.pub)), isTrue);
+ expect(app.newDeviceSuspended(b64e(box2.pub)), isFalse);
+ });
+
+ test('the banner\'s "Mine" does not lift the suspension', () async {
+ final app = await forked();
+ app.dismissNewDevice(b64e(box3.pub));
+ await settle();
+ expect(await app.deviceLog!.suspendedPubs(), {b64e(box3.pub)});
+ });
+
+ test('the detail page\'s "Mine" does', () async {
+ final app = await forked();
+ app.dismissNewDevice(b64e(box3.pub), liftSuspension: true);
+ await settle();
+ expect(await app.deviceLog!.suspendedPubs(), isEmpty);
+ });
+ });
+
+ test('opening the list dismisses the banner as it was when the list was read, not a device announced meanwhile', () async {
+ final (app, _) = await launch();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await app.deviceLog!.refresh();
+ await settle();
+ final shown = pubs(app.newDevices);
+ expect(shown, [b64e(box2.pub)]);
+ // box3 is announced while the page waits on the backend for the last-seen times.
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(pubs(app.newDevices), [b64e(box2.pub), b64e(box3.pub)]);
+
+ app.seenNewDevices(shown: shown);
+ await settle();
+ expect(pubs(app.newDevices), [b64e(box3.pub)]);
+ expect((await app.deviceLog!.list()).pending, [b64e(box3.pub)]);
+ });
+
+ test(
+ 'a read of the account that signed out raises no banner and no notice',
+ () async {
+ final (app, notices) = await launch();
+ await app.logout();
+ await settle();
+ notices.keys.clear();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ expect(notices.keys, isEmpty);
+ },
+ );
+
+ test(
+ 'a read in flight when the session is lost raises no banner and no notice',
+ () async {
+ final (app, notices) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ backend.fetchGate = Completer<void>();
+ unawaited(app.deviceLog!.refresh());
+ await settle();
+ app.authFailureForTest('gone');
+ backend.fetchGate!.complete();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ expect(notices.keys, isEmpty);
+ },
+ );
+
+ test(
+ 'a removal read in flight when the session is lost raises no notice',
+ () async {
+ final (app, notices) = await launch();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ notices.keys.clear();
+ await backend.removeBy(b64e(box2.pub), box3);
+ backend.fetchGate = Completer<void>();
+ unawaited(app.deviceLog!.refresh());
+ await settle();
+ app.authFailureForTest('gone');
+ backend.fetchGate!.complete();
+ await settle();
+ expect(app.deviceRemovals, isEmpty);
+ expect(notices.keys, isEmpty);
+ },
+ );
+
+ group('while the app is still starting up', () {
+ test('a new device read before `authenticated` is announced once it is — the OS notice is not lost', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final layout = Completer<void>();
+ final (app, notices) = await launch(layoutGate: layout);
+ expect(app.status, AppStatus.bootstrapping);
+ // The first read (a connection coming up) joins the log; the next one finds a new key.
+ await app.deviceLog!.refresh();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ expect(notices.keys, isEmpty);
+
+ layout.complete();
+ await lastBoot;
+ await settle();
+ expect(app.status, AppStatus.authenticated);
+ expect(notices.keys, [b64e(box3.pub)]);
+ expect(pubs(app.newDevices), [b64e(box3.pub)]);
+ });
+
+ test('what was parked is checked against the log once replayed: a key dismissed meanwhile leaves the banner without waiting for the next read', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final layout = Completer<void>();
+ final (app, notices) = await launch(layoutGate: layout);
+ await app.deviceLog!.refresh();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(notices.keys, isEmpty);
+ // Seen elsewhere (the log is shared) before the app is up: still parked here.
+ // (By another instance over the same file, so this app is not told: only the replay can notice.)
+ await ViewerDeviceLog(
+ keys: app.viewer.keys,
+ fetch: (since) => backend.fetch(since),
+ append: (e) => backend.append(e),
+ label: () => 'other tab',
+ ).dismiss(pubs: [b64e(box3.pub)]);
+ // The log's own read after register is stuck behind the backend: only the replay can fix the banner.
+ backend.fetchGate = Completer<void>();
+ layout.complete();
+ await lastBoot;
+ await settle();
+ expect(app.status, AppStatus.authenticated);
+ expect(app.newDevices, isEmpty);
+ backend.fetchGate!.complete();
+ });
+
+ test(
+ 'a removal read before `authenticated` is announced once it is',
+ () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final layout = Completer<void>();
+ final (app, notices) = await launch(layoutGate: layout);
+ await app.deviceLog!.refresh();
+ await backend.removeBy(b64e(box2.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(app.deviceRemovals, isEmpty);
+
+ layout.complete();
+ await lastBoot;
+ await settle();
+ expect(notices.keys, contains('removed:${b64e(box2.pub)}'));
+ expect(app.deviceRemovals.map((r) => r.pub), [b64e(box2.pub)]);
+ },
+ );
+
+ test(
+ 'signed out meanwhile: what was parked is dropped, not posted',
+ () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final layout = Completer<void>();
+ final (app, notices) = await launch(layoutGate: layout);
+ await app.deviceLog!.refresh();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ app.authFailureForTest('gone');
+ layout.complete();
+ await lastBoot;
+ await settle();
+ expect(app.status, AppStatus.unauthenticated);
+ expect(notices.keys, isEmpty);
+ expect(app.newDevices, isEmpty);
+ },
+ );
+
+ test(
+ 'what was parked for a sign-in that ended is not posted by the next one',
+ () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final layout = Completer<void>();
+ final (app, notices) = await launch(layoutGate: layout);
+ await app.deviceLog!.refresh();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ app.authFailureForTest('gone');
+ // The next sign-in (the session is still kept) reaches `authenticated`.
+ layout.complete();
+ await app.bootstrap();
+ await lastBoot;
+ await settle();
+ expect(app.status, AppStatus.authenticated);
+ // box3 was announced once, into a sign-in that is gone: the OS is not told again by this one.
+ expect(notices.keys, isEmpty);
+ },
+ );
+
+ test('a hand sign-in under a key the log removed is spent, not a sign-out (the id is begun once, not overwritten by register)', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final (first, _) = await launch();
+ final phone = b64e((await first.viewer.keys.identity()).pub);
+ expect(
+ (await first.deviceLog!.list()).members.map((r) => r.member.pub),
+ contains(phone),
+ );
+ first.dispose();
+ apps.remove(first);
+ await backend.removeBy(phone, box2);
+
+ final (second, _) = await launch(fresh: true);
+ expect(second.status, AppStatus.authenticated);
+ final now = await second.viewer.keys.identity();
+ expect(b64e(now.pub), isNot(phone));
+ expect(
+ (await second.deviceLog!.list()).members.map((r) => r.member.pub),
+ contains(b64e(now.pub)),
+ );
+ });
+
+ test('a hand sign-in\'s id is minted before the boot can read the log: a read while the pane layout loads is judged by it', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final (first, _) = await launch();
+ expect((await first.deviceLog!.list()).frozen, isNull);
+ first.dispose();
+ apps.remove(first);
+
+ // Another account signs in by hand on this phone. A read that lands before the boot reaches
+ // `register` (a connection, the machine list) must already be that sign-in's.
+ backend = _Backend('acct-2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final layout = Completer<void>();
+ final (second, _) = await launch(layoutGate: layout, fresh: true);
+ expect(second.status, AppStatus.bootstrapping);
+ await second.deviceLog!.refresh();
+ expect((await second.deviceLog!.list()).frozen?.reason, isNull);
+ layout.complete();
+ await lastBoot;
+ await settle();
+ expect((await second.deviceLog!.list()).frozen, isNull);
+ });
+ });
+
+ group('a device that joined and left before anyone looked', () {
+ test('flagged by the app, kept across a restart, until Got it', () async {
+ final (first, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await first.deviceLog!.refresh();
+ await settle();
+ expect(pubs(first.newDevices), [b64e(box3.pub)]);
+ await backend.removeBy(b64e(box3.pub), box3);
+ await first.deviceLog!.refresh();
+ await settle();
+ expect(first.newDevices, isEmpty);
+ expect(first.departedDevices.map((d) => d.pub), [b64e(box3.pub)]);
+ expect(first.departedDevices.single.selfRemoved, isTrue);
+
+ first.dispose();
+ apps.remove(first);
+ final (second, _) = await launch();
+ expect(second.departedDevices.map((d) => d.pub), [b64e(box3.pub)]);
+
+ second.dismissDeparted(b64e(box3.pub));
+ await settle();
+ expect(second.departedDevices, isEmpty);
+ expect((await second.deviceLog!.list()).departed, isEmpty);
+ second.dispose();
+ apps.remove(second);
+ final (third, _) = await launch();
+ expect(third.departedDevices, isEmpty);
+ });
+
+ test('removed by another key: the signer is named; red while that signer is itself new', () async {
+ final (app, _) = await launch();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ // box3 (still new) removes box2 (also new).
+ await backend.removeBy(b64e(box2.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ final d = app.departedDevices.single;
+ expect(d.pub, b64e(box2.pub));
+ expect(d.removedBy, b64e(box3.pub));
+ expect(d.removedByLabel, 'box3');
+ expect(app.departedRed(d), isTrue);
+ // Opening the list marks what is new as seen; box2's departure is still unseen.
+ app.seenNewDevices(pending: [b64e(box3.pub)]);
+ await settle();
+ expect(app.departedDevices.map((x) => x.pub), [b64e(box2.pub)]);
+ });
+
+ test('a self sign-out notice\'s Got it leaves the departed mark and the History row pending', () async {
+ final (app, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await backend.removeBy(b64e(box3.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ final pub = b64e(box3.pub);
+ expect(app.departedDevices.map((d) => d.pub), [pub]);
+ expect(app.deviceRemovals.map((r) => r.pub), [pub]);
+ app.dismissDeviceRemoval(pub);
+ await settle();
+ expect(app.deviceRemovals, isEmpty);
+ expect(app.departedDevices.map((d) => d.pub), [pub]);
+ expect((await app.deviceLog!.list()).departed.map((d) => d.pub), [pub]);
+ final history = await app.deviceHistory();
+ expect(
+ history.rows.where((r) => r.pub == pub).any((r) => r.pending),
+ isTrue,
+ );
+ // Its own Got it is what clears it.
+ app.dismissDeparted(pub);
+ await settle();
+ expect(app.departedDevices, isEmpty);
+ });
+
+ test(
+ 'opening the list (seenNewDevices) never dismisses a departed key',
+ () async {
+ final (app, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await backend.removeBy(b64e(box3.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ final pub = b64e(box3.pub);
+ expect(app.departedDevices.map((d) => d.pub), [pub]);
+ app.seenNewDevices(pending: [pub], shown: [pub]);
+ await settle();
+ expect(app.departedDevices.map((d) => d.pub), [pub]);
+ expect((await app.deviceLog!.list()).departed.map((d) => d.pub), [pub]);
+ },
+ );
+
+ test('opening the list with only it on the banner does not cancel a read of the log under way', () async {
+ final (app, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ final member = app.newDevices.single;
+ await backend.removeBy(b64e(box3.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ final pub = b64e(box3.pub);
+ expect(app.departedDevices.map((d) => d.pub), [pub]);
+ app.newDevices.add(
+ member,
+ ); // a stale banner for it (a notice replayed at startup)
+ // The read of the log that takes it down is under way (and slow)...
+ disk.holdDevLogRead(skip: 1);
+ unawaited(app.deviceLog!.dismiss(pub: 'nobody'));
+ await disk.held!.future;
+ // ...when the person opens the list: nothing on the banner is marked, so that read is not stale.
+ app.seenNewDevices(shown: [pub]);
+ disk.release();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ expect(app.departedDevices.map((d) => d.pub), [pub]);
+ expect((await app.deviceLog!.list()).departed.map((d) => d.pub), [pub]);
+ });
+
+ test('"It\'s mine" on a stale banner for it takes the banner down and marks nothing', () async {
+ final (app, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ final member = app.newDevices.single;
+ await backend.removeBy(b64e(box3.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ final pub = b64e(box3.pub);
+ app.newDevices.add(member);
+ app.dismissNewDevice(pub);
+ await settle();
+ expect(app.newDevices, isEmpty);
+ expect(app.departedDevices.map((d) => d.pub), [pub]);
+ expect((await app.deviceLog!.list()).departed.map((d) => d.pub), [
+ pub,
+ ], reason: 'its own Got it is what clears it');
+ });
+
+ test(
+ 'signing out drops it with the rest of the account\'s notices',
+ () async {
+ final (app, _) = await launch();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await backend.removeBy(b64e(box3.pub), box3);
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(app.departedDevices, isNotEmpty);
+ await app.logout();
+ expect(app.departedDevices, isEmpty);
+ },
+ );
+ });
+
+ group('the local sign-in', () {
+ Map<String, dynamic> file() =>
+ jsonDecode(disk.values['viewer_e2ee_devlog']!) as Map<String, dynamic>;
+
+ test('the log registers the moment the app is authenticated, before the machine list and the profile', () async {
+ final profile = Completer<void>(), machines = Completer<void>();
+ await launch(profileGate: profile, machinesGate: machines);
+ // Neither the machine list nor the profile has answered.
+ expect(disk.values['viewer_e2ee_devlog'], isNotNull);
+ expect(file()['owner'], isNotNull);
+ profile.complete();
+ machines.complete();
+ await lastBoot;
+ });
+
+ test(
+ 'a stored session is adopted by the log (never a reason to start over)',
+ () async {
+ await launch();
+ expect(file()['owner'], startsWith('adopted:'));
+ },
+ );
+
+ test(
+ 'a sign-in by hand mints the log\'s own id, not the profile\'s',
+ () async {
+ await launch(fresh: true, profileId: 'u1');
+ expect(file()['owner'], isNot(startsWith('adopted:')));
+ expect(file()['owner'], isNot('u1'));
+ },
+ );
+
+ test(
+ 'a restored session whose profile id differs does not reset the list',
+ () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final (first, _) = await launch(profileId: 'u1');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await first.deviceLog!.refresh();
+ await settle();
+ expect(pubs(first.newDevices), [b64e(box3.pub)]);
+ final joined = file()['joinedSeq'];
+ first.dispose();
+ apps.remove(first);
+
+ // The backend answers /me with another id for the same stored session: it says nothing about
+ // who signed in here.
+ final (second, _) = await launch(profileId: 'u2');
+ expect(pubs(second.newDevices), [b64e(box3.pub)]);
+ expect(file()['joinedSeq'], joined);
+ final listing = await second.deviceLog!.list();
+ expect(listing.frozen, isNull);
+ expect(listing.pending, [b64e(box3.pub)]);
+ },
+ );
+
+ test('a backend that says the account changed freezes the log; it does not start over', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final (app, _) = await launch();
+ expect((await app.deviceLog!.list()).frozen, isNull);
+ backend.acct = 'acct-2';
+ await app.deviceLog!.refresh();
+ await settle();
+ final listing = await app.deviceLog!.list();
+ expect(listing.frozen?.reason, 'invalid');
+ expect(
+ listing.members.map((r) => r.member.pub),
+ contains(b64e(box2.pub)),
+ );
+ });
+ });
+}
diff --git a/mobile/test/state/device_removal_notice_test.dart b/mobile/test/state/device_removal_notice_test.dart
new file mode 100644
index 000000000..c1c216d58
--- /dev/null
+++ b/mobile/test/state/device_removal_notice_test.dart
@@ -0,0 +1,166 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/viewer/device_log.dart';
+import 'package:harness_mobile/viewer/device_log_sync.dart';
+
+class _Recorder extends SilentSystemNotices {
+ final posted = <({String key, String title, String body})>[];
+
+ @override
+ Future<void> showAccountNotice({
+ required String key,
+ required String title,
+ required String body,
+ }) async => posted.add((key: key, title: title, body: body));
+}
+
+DeviceRemovalNotice _notice({
+ bool selfRemoved = false,
+ bool signerPending = false,
+ String signerLabel = 'Pixel',
+}) => DeviceRemovalNotice(
+ pub: 'gone-pub',
+ label: 'iPad',
+ kind: 'viewer',
+ fingerprint: 'AAAA·BBBB',
+ signer: 'signer-pub',
+ signerLabel: signerLabel,
+ signerFingerprint: 'E2FB·0DF5',
+ signerPending: signerPending,
+ selfRemoved: selfRemoved,
+ at: 0,
+);
+
+/// A device taken out of the account by another device is announced once, and a red one opens the
+/// signer, not the removed device.
+void main() {
+ late _Recorder notices;
+ late AppNotifier app;
+
+ setUp(() {
+ notices = _Recorder();
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ systemNotices: notices,
+ );
+ });
+ tearDown(() => app.dispose());
+
+ test('removed by a known device: its own key, neutral copy', () {
+ app.announceDeviceRemoval(_notice());
+ expect(app.deviceRemovals, hasLength(1));
+ expect(notices.posted.single.key, 'removed:gone-pub');
+ expect(notices.posted.single.title, 'Device removed');
+ expect(
+ notices.posted.single.body,
+ 'iPad was removed from your account by Pixel.',
+ );
+ });
+
+ test('signed out', () {
+ app.announceDeviceRemoval(_notice(selfRemoved: true));
+ expect(notices.posted.single.title, 'Device signed out');
+ expect(notices.posted.single.body, 'iPad signed out of your account.');
+ });
+
+ test(
+ 'removed by a new device: red copy, keyed by signer and removed device',
+ () {
+ app.announceDeviceRemoval(_notice(signerPending: true));
+ expect(notices.posted.single.key, 'removedBy:signer-pub:gone-pub');
+ expect(notices.posted.single.title, 'Removed by a new device');
+ expect(
+ notices.posted.single.body,
+ 'iPad was removed from your account by a new device you haven’t looked at '
+ '(Pixel · E2FB·0DF5…).',
+ );
+ },
+ );
+
+ test('a device that signed itself out is never red, though it was new', () {
+ app.announceDeviceRemoval(_notice(selfRemoved: true, signerPending: true));
+ expect(notices.posted.single.key, 'removed:gone-pub');
+ expect(notices.posted.single.title, 'Device signed out');
+ });
+
+ test('blank names read as "A device" and "another device"', () {
+ app.announceDeviceRemoval(
+ DeviceRemovalNotice(
+ pub: 'gone-pub',
+ label: ' ',
+ kind: 'viewer',
+ fingerprint: '',
+ signer: 'signer-pub',
+ signerLabel: '',
+ signerFingerprint: '',
+ signerPending: false,
+ selfRemoved: false,
+ at: 0,
+ ),
+ );
+ expect(
+ notices.posted.single.body,
+ 'A device was removed from your account by another device.',
+ );
+ });
+
+ test('the same removal is announced once; dismissing clears it', () {
+ app.announceDeviceRemoval(_notice());
+ app.announceDeviceRemoval(_notice());
+ expect(notices.posted, hasLength(1));
+ var notified = 0;
+ app.addListener(() => notified++);
+ app.dismissDeviceRemoval('gone-pub');
+ expect(app.deviceRemovals, isEmpty);
+ expect(notified, 1);
+ });
+
+ test('removals by one signer get distinct keys, none equal to the signer’s '
+ 'new-device key', () {
+ app.announceDeviceRemoval(_notice(signerPending: true));
+ app.announceDeviceRemoval(
+ DeviceRemovalNotice(
+ pub: 'gone-2',
+ label: 'Mac',
+ kind: 'machine',
+ fingerprint: '',
+ signer: 'signer-pub',
+ signerLabel: 'Pixel',
+ signerFingerprint: 'E2FB·0DF5',
+ signerPending: true,
+ selfRemoved: false,
+ at: 0,
+ ),
+ );
+ final keys = [for (final p in notices.posted) p.key];
+ expect(keys, [
+ 'removedBy:signer-pub:gone-pub',
+ 'removedBy:signer-pub:gone-2',
+ ]);
+ expect(keys, isNot(contains('signer-pub')));
+ });
+
+ test('a session lost at runtime drops the account’s device notices', () {
+ app.announceDeviceRemoval(_notice());
+ app.newDevices.add(
+ const DevLogMember(
+ pub: 'p',
+ kind: 'viewer',
+ machineId: '',
+ label: 'x',
+ addedAt: 0,
+ seq: 1,
+ ),
+ );
+ // Only a signed-in app signs out at runtime.
+ app.status = AppStatus.authenticated;
+ app.authFailureForTest('gone');
+ expect(app.deviceRemovals, isEmpty);
+ expect(app.newDevices, isEmpty);
+ });
+}
diff --git a/mobile/test/viewer/deviceHistory.vectors.json b/mobile/test/viewer/deviceHistory.vectors.json
new file mode 100644
index 000000000..679ffc2d5
--- /dev/null
+++ b/mobile/test/viewer/deviceHistory.vectors.json
@@ -0,0 +1,543 @@
+{
+ "acct": "acct-history-1",
+ "pubs": {
+ "a": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "b": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "c": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "d": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw="
+ },
+ "entries": [
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 10,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "mac",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "TGq35MQKMb9h+RVuiWBdKkeGL0CpoDzz28ZWmTsgRCr9+Q5EUYP0cBOEvL2l1En0W7pghYv8nrUnQa6pvPrUAQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 2,
+ "prev": "CovFBIdOBn7wiD9rCG4NzW31/eiYY2aQcLLFK7P08bc=",
+ "at": 20,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "phone",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "G3NPtWdtHRzO0qVbbd1jABC7EPAFCf0L7NXcaNC1tPfjkrSo4IqpFF1kMOMQkodYenWVTqr/lbxciclDAROfBA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 3,
+ "prev": "B5nsulFGuwg49bsCmFEg0lJUYigEX/VA/bCccUr94bM=",
+ "at": 30,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "pixel",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "CW+lpHmqR4qSoFxTIbY+fzKZr4G0dSZMfs0ULd6s3kdNpE4zVbkOpaKpL+bzA5bEghk6CiGki5NkV/0ZjYjnAQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 4,
+ "prev": "rQt1wtdStS0QRgoTyNQxnPHCCo+OcAdJoTIEBoXes7c=",
+ "at": 40,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "ipad",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "LAdnsHZy255R8J9jeMq5AMC4QuJxz2Bq+QYnF/YQQarH3QOkTf3jzKk6XweiBouhXSLnposVThku9mI6cl8DBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 5,
+ "prev": "bC4N5mAJgT276SBzBqiEOQSptTRcIQYM+mnpRygEYHM=",
+ "at": 50,
+ "op": "remove",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "LIE",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "xMGVbx5ArRy/NpTcLzBJGYD+oZT+GlJPaX3DbOJ8T9mKy+7wv8zhxzgYRQq4L0FHrX5LXlcEv1Fd6+1w6msuBQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 6,
+ "prev": "yis5+Ci1yxF/tUx+lO0DIExsqBMxDm8bv516DD+0XdA=",
+ "at": 60,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "pixel",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "sL2JKbDDzTcoZSQYcOlp5soXgp8II7n/Mrq5lI1zrmtZE3u0zsB/i3hayhBA1bdxC40Pl9B7vLJQtVxG7yrKCA=="
+ }
+ ],
+ "fork": [
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 10,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "mac",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "TGq35MQKMb9h+RVuiWBdKkeGL0CpoDzz28ZWmTsgRCr9+Q5EUYP0cBOEvL2l1En0W7pghYv8nrUnQa6pvPrUAQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 2,
+ "prev": "CovFBIdOBn7wiD9rCG4NzW31/eiYY2aQcLLFK7P08bc=",
+ "at": 20,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "phone",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "G3NPtWdtHRzO0qVbbd1jABC7EPAFCf0L7NXcaNC1tPfjkrSo4IqpFF1kMOMQkodYenWVTqr/lbxciclDAROfBA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 3,
+ "prev": "B5nsulFGuwg49bsCmFEg0lJUYigEX/VA/bCccUr94bM=",
+ "at": 31,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "evil",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "I5yBaoADRLpyN3I+0t0qhZR7wehgWo6oZqWsj9CY3tb5dotNiCkmf+7YnqW5ir0dwFa4XCz9k/yBxod63p0vBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-history-1",
+ "seq": 4,
+ "prev": "sEpMlwosMHwGtmqVx5x1Dx3Nc8qf3rTnmjXVrUI+YRY=",
+ "at": 41,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "ipad",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "0pp4FidRF84ismPAL5P55sJ/1ZEXdToIxQ6i6glOLHO025TdJF51L4nhoRSAxW3Cuk2YS6yrSK+RsLYpwZ22Dg=="
+ }
+ ],
+ "history": [
+ {
+ "name": "the whole log, newest first",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [
+ "b"
+ ],
+ "seqs": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "pixel",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 3,
+ "op": "renamed",
+ "label": "pixel",
+ "kind": "viewer",
+ "previousLabel": "phone",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 2,
+ "op": "added",
+ "label": "phone",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": true,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 1,
+ "op": "added",
+ "label": "mac",
+ "kind": "machine",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "only the recent tail is known (offline)",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [],
+ "seqs": [
+ 4,
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "a removal whose add is outside the known window",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [],
+ "seqs": [
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "a removal applied while frozen",
+ "self": "a",
+ "joinedSeq": 1,
+ "pending": [],
+ "seqs": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 6
+ ],
+ "loose": [
+ 5
+ ],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "pixel",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": true
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 3,
+ "op": "renamed",
+ "label": "pixel",
+ "kind": "viewer",
+ "previousLabel": "phone",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 2,
+ "op": "added",
+ "label": "phone",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": true,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 1,
+ "op": "added",
+ "label": "mac",
+ "kind": "machine",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false
+ }
+ ]
+ },
+ {
+ "name": "no joined point known",
+ "self": "b",
+ "pending": [],
+ "seqs": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6
+ ],
+ "loose": [],
+ "rows": [
+ {
+ "seq": 6,
+ "op": "signedOut",
+ "label": "pixel",
+ "kind": "viewer",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 5,
+ "op": "removed",
+ "label": "ipad",
+ "kind": "viewer",
+ "by": "mac",
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 4,
+ "op": "added",
+ "label": "ipad",
+ "kind": "viewer",
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 3,
+ "op": "renamed",
+ "label": "pixel",
+ "kind": "viewer",
+ "previousLabel": "phone",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 2,
+ "op": "added",
+ "label": "phone",
+ "kind": "viewer",
+ "thisDevice": true,
+ "afterJoin": false,
+ "pending": false,
+ "active": false,
+ "whileFrozen": false
+ },
+ {
+ "seq": 1,
+ "op": "added",
+ "label": "mac",
+ "kind": "machine",
+ "thisDevice": false,
+ "afterJoin": false,
+ "pending": false,
+ "active": true,
+ "whileFrozen": false
+ }
+ ]
+ }
+ ],
+ "divergence": [
+ {
+ "name": "the first differing position, the one before it matching",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "expect": 3
+ },
+ {
+ "name": "a window that starts at the split cannot prove it",
+ "log": "fork",
+ "from": 3,
+ "to": 4,
+ "expect": null
+ },
+ {
+ "name": "the same log has no split",
+ "log": "main",
+ "from": 1,
+ "to": 4,
+ "expect": null
+ },
+ {
+ "name": "a window with a gap is not usable",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "tamper": "gap",
+ "expect": null
+ },
+ {
+ "name": "a window that does not end at the peer head is not usable",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "tamper": "head",
+ "expect": null
+ },
+ {
+ "name": "not a window at all",
+ "log": "fork",
+ "from": 1,
+ "to": 4,
+ "tamper": "junk",
+ "expect": null
+ }
+ ]
+}
diff --git a/mobile/test/viewer/device_history_test.dart b/mobile/test/viewer/device_history_test.dart
new file mode 100644
index 000000000..a3a3be4f6
--- /dev/null
+++ b/mobile/test/viewer/device_history_test.dart
@@ -0,0 +1,387 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/e2ee/bytes.dart';
+import 'package:harness_mobile/e2ee/keys.dart';
+import 'package:harness_mobile/viewer/device_history.dart';
+import 'package:harness_mobile/viewer/device_log.dart';
+import 'package:harness_mobile/viewer/device_log_sync.dart';
+
+/// The Dart port of cli/src/lib/e2ee/deviceHistory.ts, on the same log as deviceHistory.spec.ts.
+void main() {
+ late E2eeIdentity a, b, c;
+ late List<DevLogEntry> entries;
+ late DevLogState state;
+
+ Future<void> push(
+ String op,
+ E2eeIdentity key,
+ E2eeIdentity signer,
+ String label,
+ int at, {
+ String kind = 'viewer',
+ }) async {
+ final e = await signDevLogEntry(
+ nextDevLogEntry(
+ state,
+ op: op,
+ pub: b64e(key.pub),
+ kind: kind,
+ machineId: kind == 'machine' ? 'a' * 32 : '',
+ label: label,
+ signer: b64e(signer.pub),
+ at: at,
+ ),
+ signer,
+ );
+ state = (await applyDevLogEntries(state, [e.toJson()])).state;
+ entries.add(e);
+ }
+
+ setUp(() async {
+ a = await E2eeIdentity.fromSeed(List.filled(32, 1));
+ b = await E2eeIdentity.fromSeed(List.filled(32, 2));
+ c = await E2eeIdentity.fromSeed(List.filled(32, 3));
+ state = DevLogState.empty('acct');
+ entries = [];
+ await push('add', a, a, 'mac', 10, kind: 'machine');
+ await push('add', b, b, 'phone', 20);
+ await push('add', b, b, 'pixel', 30);
+ await push('add', c, c, 'ipad', 40);
+ await push('remove', c, a, 'ipad', 50);
+ await push('remove', b, b, 'pixel', 60);
+ });
+
+ List<DevLogHistoryRow> rows({
+ List<DevLogEntry>? only,
+ List<DevLogEntry> loose = const [],
+ }) => devLogHistory(
+ only ?? entries,
+ selfPub: b64e(a.pub),
+ joinedSeq: 1,
+ pending: [b64e(b.pub)],
+ active: state.active,
+ loose: loose,
+ );
+
+ test('is newest first and tells each operation apart', () {
+ expect(
+ [for (final r in rows()) '${r.seq}:${r.op}'],
+ [
+ '6:signedOut',
+ '5:removed',
+ '4:added',
+ '3:renamed',
+ '2:added',
+ '1:added',
+ ],
+ );
+ });
+
+ test(
+ 'names who removed a key that is gone, and the old label of a rename',
+ () {
+ final r = rows();
+ expect(r[1].by?.label, 'mac');
+ expect(r[1].active, isFalse);
+ expect(r[3].previousLabel, 'phone');
+ expect(r[3].label, 'pixel');
+ },
+ );
+
+ test('flags this device, entries after joining and pending', () {
+ final r = rows();
+ expect(r[5].thisDevice, isTrue);
+ expect(r[5].afterJoin, isFalse);
+ expect(r[4].afterJoin, isTrue);
+ expect(r[4].pending, isTrue);
+ });
+
+ test(
+ 'marks loose removals as applied while frozen and does not duplicate',
+ () {
+ final out = rows(
+ only: entries.sublist(0, 4),
+ loose: [entries[4], entries[4]],
+ );
+ expect(out.first.whileFrozen, isTrue);
+ expect(out, hasLength(5));
+ },
+ );
+
+ test('reads the rows the daemon sends', () {
+ final h = DeviceLogHistory.fromJson({
+ 'complete': false,
+ 'frozen': null,
+ 'rows': [
+ {
+ 'seq': 3,
+ 'op': 'removed',
+ 'pub': 'p',
+ 'kind': 'machine',
+ 'machineId': 'm',
+ 'label': 'box',
+ 'fingerprint': 'AAAA',
+ 'by': {'pub': 'q', 'label': 'mac', 'fingerprint': 'BBBB'},
+ 'at': 5,
+ 'thisDevice': false,
+ 'afterJoin': true,
+ 'pending': false,
+ 'active': false,
+ 'whileFrozen': true,
+ },
+ 'junk',
+ ],
+ })!;
+ expect(h.complete, isFalse);
+ expect(h.rows.single.by?.label, 'mac');
+ expect(h.rows.single.whileFrozen, isTrue);
+ expect(DeviceLogHistory.fromJson('x'), isNull);
+ });
+
+ group('copy', () {
+ DeviceRemovalNotice notice({
+ String signerLabel = 'Mac',
+ bool pending = false,
+ bool self = false,
+ String label = 'iPad',
+ }) => DeviceRemovalNotice(
+ pub: 'p',
+ label: label,
+ kind: 'viewer',
+ fingerprint: 'AAAA',
+ signer: 'q',
+ signerLabel: signerLabel,
+ signerFingerprint: 'E2FB·0DF5·5FD8·E6C7',
+ signerPending: pending,
+ selfRemoved: self,
+ at: 0,
+ );
+
+ test('removal notices', () {
+ expect(notice().title, 'Device removed');
+ expect(notice().sentence, 'iPad was removed from your account by Mac.');
+ expect(
+ notice(signerLabel: '').sentence,
+ 'iPad was removed from your account by another device.',
+ );
+ expect(notice(self: true).title, 'Device signed out');
+ expect(notice(self: true).sentence, 'iPad signed out of your account.');
+ expect(notice(self: true, pending: true).red, isFalse);
+ });
+
+ test('a red notice shows two fingerprint groups', () {
+ final n = notice(pending: true);
+ expect(n.red, isTrue);
+ expect(n.title, 'Removed by a new device');
+ expect(
+ n.sentence,
+ 'iPad was removed from your account by a new device you haven’t looked at (Mac · E2FB·0DF5…).',
+ );
+ expect(
+ notice(pending: true, signerLabel: '').sentence,
+ contains('(another device · E2FB·0DF5…)'),
+ );
+ });
+
+ DeviceLogDeparted departed({
+ String removedBy = 'q',
+ String removedByLabel = 'Mac',
+ bool self = false,
+ }) => DeviceLogDeparted(
+ pub: 'p',
+ label: 'iPad',
+ kind: 'viewer',
+ machineId: '',
+ fingerprint: 'AAAA',
+ addedAt: 0,
+ removedAt: 0,
+ removedBy: removedBy,
+ removedByLabel: removedByLabel,
+ selfRemoved: self,
+ );
+
+ test('a departed key names its remover only when something removed it', () {
+ const head = 'iPad joined your account and left before you looked.';
+ expect(departed().sentence(red: false), '$head Removed by Mac.');
+ expect(
+ departed().sentence(red: true),
+ '$head Removed by Mac, a new device you haven’t looked at.',
+ );
+ expect(
+ departed(removedByLabel: '').sentence(red: false),
+ '$head Removed by another device.',
+ );
+ expect(departed(self: true).sentence(red: false), head);
+ expect(departed(removedBy: 'p').sentence(red: true), head);
+ // Taken off the list by a review of it (no signer): nothing "removed" it.
+ expect(
+ departed(removedBy: '', removedByLabel: '').sentence(red: false),
+ head,
+ );
+ expect(
+ departed(removedBy: '', removedByLabel: '').sentence(red: true),
+ head,
+ );
+ });
+
+ DevLogHistoryRow histRow(
+ String op, {
+ String label = 'Mac',
+ String? previous,
+ String? by,
+ bool frozen = false,
+ }) => DevLogHistoryRow(
+ seq: 1,
+ op: op,
+ pub: 'p',
+ kind: 'viewer',
+ machineId: '',
+ label: label,
+ previousLabel: previous,
+ fingerprint: 'AAAA',
+ by: by == null
+ ? null
+ : DevLogHistoryBy(pub: 'q', label: by, fingerprint: 'BBBB'),
+ at: 0,
+ thisDevice: false,
+ afterJoin: false,
+ pending: false,
+ active: false,
+ whileFrozen: frozen,
+ );
+
+ test('history sentences', () {
+ expect(historySentence(histRow('added')), 'Mac added');
+ expect(
+ historySentence(histRow('renamed', previous: 'Old Mac')),
+ 'Old Mac renamed to Mac',
+ );
+ expect(historySentence(histRow('renamed')), 'Mac renamed');
+ expect(
+ historySentence(histRow('removed', by: 'iPad')),
+ 'Mac removed by iPad',
+ );
+ expect(
+ historySentence(histRow('removed', by: '')),
+ 'Mac removed by another device',
+ );
+ expect(historySentence(histRow('removed')), 'Mac removed');
+ expect(historySentence(histRow('signedOut')), 'Mac signed out');
+ expect(
+ historySentence(histRow('added', frozen: true)),
+ 'Mac added · applied while the list was frozen',
+ );
+ });
+ });
+
+ group('shared vectors (cli/src/lib/e2ee/deviceHistory.vectors.json)', () {
+ final vectors = jsonDecode(
+ File('test/viewer/deviceHistory.vectors.json').readAsStringSync(),
+ ) as Map<String, dynamic>;
+ final pubs = (vectors['pubs'] as Map).cast<String, String>();
+ final all = [
+ for (final e in vectors['entries'] as List) DevLogEntry.parse(e)!,
+ ];
+
+ for (final c in (vectors['history'] as List).cast<Map<String, dynamic>>()) {
+ test('history: ${c['name']}', () async {
+ final state = (await applyDevLogEntries(
+ DevLogState.empty(vectors['acct'] as String),
+ [for (final e in all) e.toJson()],
+ )).state;
+ List<DevLogEntry> pick(List<dynamic> seqs) => [
+ for (final n in seqs) all[(n as int) - 1],
+ ];
+ final rows = devLogHistory(
+ pick(c['seqs'] as List),
+ selfPub: pubs[c['self']]!,
+ joinedSeq: c['joinedSeq'] as int?,
+ pending: [for (final k in c['pending'] as List) pubs[k]!],
+ active: state.active,
+ loose: pick(c['loose'] as List),
+ );
+ final want = (c['rows'] as List).cast<Map<String, dynamic>>();
+ expect(rows, hasLength(want.length));
+ for (var i = 0; i < want.length; i++) {
+ final r = rows[i], w = want[i];
+ expect(
+ {
+ 'seq': r.seq,
+ 'op': r.op,
+ 'label': r.label,
+ 'kind': r.kind,
+ 'previousLabel': r.previousLabel,
+ 'by': r.by?.label,
+ 'thisDevice': r.thisDevice,
+ 'afterJoin': r.afterJoin,
+ 'pending': r.pending,
+ 'active': r.active,
+ 'whileFrozen': r.whileFrozen,
+ },
+ {
+ 'seq': w['seq'],
+ 'op': w['op'],
+ 'label': w['label'],
+ 'kind': w['kind'],
+ 'previousLabel': w['previousLabel'],
+ 'by': w['by'],
+ 'thisDevice': w['thisDevice'],
+ 'afterJoin': w['afterJoin'],
+ 'pending': w['pending'],
+ 'active': w['active'],
+ 'whileFrozen': w['whileFrozen'],
+ },
+ );
+ }
+ });
+ }
+
+ for (final c
+ in (vectors['divergence'] as List).cast<Map<String, dynamic>>()) {
+ test('divergence: ${c['name']}', () async {
+ final acct = vectors['acct'] as String;
+ final mine = (await applyDevLogEntries(DevLogState.empty(acct), [
+ for (final e in vectors['entries'] as List) e,
+ ])).state;
+ final other = (await applyDevLogEntries(DevLogState.empty(acct), [
+ for (final e
+ in (c['log'] == 'fork' ? vectors['fork'] : vectors['entries'])
+ as List)
+ e,
+ ])).state;
+ final from = c['from'] as int, to = c['to'] as int;
+ final hashes = [
+ for (var seq = from; seq <= to; seq++)
+ {'seq': seq, 'hash': other.hashes[seq - 1]},
+ ];
+ Object? theirs = {
+ 'head': {'seq': to, 'hash': other.hashes[to - 1]},
+ 'hashes': hashes,
+ };
+ switch (c['tamper']) {
+ case 'gap':
+ theirs = {
+ 'head': {'seq': to, 'hash': other.hashes[to - 1]},
+ 'hashes': [
+ for (final h in hashes)
+ if (h['seq'] != 2) h,
+ ],
+ };
+ case 'head':
+ theirs = {
+ 'head': {'seq': to, 'hash': 'nope'},
+ 'hashes': hashes,
+ };
+ case 'junk':
+ theirs = {
+ 'head': {'seq': to, 'hash': other.hashes[to - 1]},
+ 'hashes': 'junk',
+ };
+ }
+ expect(devLogDivergence(mine, theirs), c['expect']);
+ });
+ }
+ });
+}
diff --git a/mobile/test/viewer/device_log_sync_test.dart b/mobile/test/viewer/device_log_sync_test.dart
index 113cea347..3217a5649 100644
--- a/mobile/test/viewer/device_log_sync_test.dart
+++ b/mobile/test/viewer/device_log_sync_test.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/core/local_key_value_store.dart';
import 'package:harness_mobile/e2ee/bytes.dart';
@@ -20,13 +22,106 @@ class _Memory implements LocalKeyValueStore {
Future<void> delete(String key) async => values.remove(key);
}
+/// A store whose next write of the device log can be held mid-way, to interleave two changes of it.
+class _GatedMemory extends _Memory {
+ Completer<void>? _hold;
+ Completer<void>? _holding;
+
+ /// Hold the next device-log write; the returned future completes once a write is being held.
+ Future<void> holdNextLogWrite(Completer<void> release) {
+ _hold = release;
+ return (_holding = Completer<void>()).future;
+ }
+
+ @override
+ Future<void> write(String key, String value) async {
+ final hold = _hold;
+ if (key == 'viewer_e2ee_devlog' && hold != null) {
+ _hold = null;
+ _holding!.complete();
+ await hold.future;
+ }
+ await super.write(key, value);
+ }
+}
+
+/// A store whose writes of one key wait while [hold] is set.
+class _HeldWrites extends _Memory {
+ _HeldWrites(this.key);
+
+ final String key;
+ Completer<void>? hold;
+
+ @override
+ Future<void> write(String key, String value) async {
+ if (key == this.key) await hold?.future;
+ await super.write(key, value);
+ }
+}
+
+/// A store whose sign-in id cannot be read once [broken] is set.
+class _NoSignIn extends _Memory {
+ bool broken = false;
+
+ @override
+ Future<String?> read(String key) async {
+ if (broken && key == 'viewer_e2ee_sign_in') throw StateError('unreadable');
+ return super.read(key);
+ }
+}
+
+/// A store whose writes of the kept logs of other accounts fail after [allowed] more, once set.
+class _FailingArchive extends _Memory {
+ int? allowed;
+
+ @override
+ Future<void> write(String key, String value) async {
+ final left = allowed;
+ if (key == 'viewer_e2ee_devlog_archive' && left != null) {
+ if (left <= 0) throw StateError('disk full');
+ allowed = left - 1;
+ }
+ await super.write(key, value);
+ }
+}
+
+/// A store whose next write of the sign-in id waits for [hold], then fails.
+class _LostSignIn extends _Memory {
+ Completer<void>? hold;
+
+ @override
+ Future<void> write(String key, String value) async {
+ final h = hold;
+ if (key == 'viewer_e2ee_sign_in' && h != null) {
+ hold = null;
+ await h.future;
+ throw StateError('disk full');
+ }
+ await super.write(key, value);
+ }
+}
+
+/// Lets whatever is runnable run (crypto included), for at most [ms].
+Future<void> _settle(Future<void> f, [int ms = 300]) =>
+ Future.any([f, Future<void>.delayed(Duration(milliseconds: ms))]);
+
const _acct = 'acct-1';
final _mid2 = 'b' * 32, _mid3 = 'c' * 32;
class _Backend {
+ _Backend([this.acct = _acct]) : state = DevLogState.empty(acct);
+
+ /// The account this backend serves.
+ final String acct;
final entries = <DevLogEntry>[];
- DevLogState state = DevLogState.empty(_acct);
+ DevLogState state;
List<DevLogEntry>? lie;
+ final fetched = <int>[];
+ bool offline = false;
+
+ /// Hold the next fetch until this completes; [fetchHeld] completes once it is being held.
+ Completer<void>? holdFetch;
+ Completer<void>? fetchHeld;
Future<void> add(E2eeIdentity who, String kind, String machineId, String label) async {
final pub = b64e(who.pub);
@@ -52,11 +147,19 @@ class _Backend {
}
Future<DeviceLogFetched?> fetch(int since) async {
+ fetched.add(since);
+ final hold = holdFetch;
+ if (hold != null) {
+ holdFetch = null;
+ fetchHeld?.complete();
+ await hold.future;
+ }
+ if (offline) return null;
final log = lie ?? entries;
final head = log.isEmpty
- ? DevLogState.empty(_acct).head
- : (await applyDevLogEntries(DevLogState.empty(_acct), [for (final e in log) e.toJson()])).state.head;
- return (acct: _acct, head: head, entries: [for (final e in log) if (e.seq > since) e.toJson()]);
+ ? DevLogState.empty(acct).head
+ : (await applyDevLogEntries(DevLogState.empty(acct), [for (final e in log) e.toJson()])).state.head;
+ return (acct: acct, head: head, entries: [for (final e in log) if (e.seq > since) e.toJson()]);
}
Future<DeviceLogAppendAnswer?> append(DevLogEntry entry) async {
@@ -76,6 +179,7 @@ void main() {
late _Backend backend;
late ViewerKeyStore keys;
late List<DevLogMember> announced;
+ late List<DeviceRemovalNotice> removed;
late int signedOut;
late E2eeIdentity box2, box3;
@@ -85,6 +189,7 @@ void main() {
append: backend.append,
label: () => 'my-phone',
onAnnounce: announced.add,
+ onRemoved: removed.add,
onSignedOut: () async => signedOut++,
now: () => 5000,
sleep: (_) async {},
@@ -94,6 +199,7 @@ void main() {
backend = _Backend();
keys = ViewerKeyStore(storage: _Memory());
announced = [];
+ removed = [];
signedOut = 0;
box2 = await E2eeIdentity.fromSeed(List.filled(32, 2));
box3 = await E2eeIdentity.fromSeed(List.filled(32, 3));
@@ -237,6 +343,1716 @@ void main() {
await log.refresh().timeout(const Duration(seconds: 5));
});
+ group('what is new, and what stays visible', () {
+ test('a key the pins and roster held before the log read that adds it is still announced and pending', () async {
+ final log = makeLog();
+ await log.register();
+ await keys.pin(_mid3, box3.pub, label: 'box3'); // the trust group got there first
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['box3']);
+ final listing = await log.list();
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.members.firstWhere((r) => r.member.pub == b64e(box3.pub)).pending, isTrue);
+ });
+
+ test('a first read announces nothing and reports the baseline; an empty log announces the first later device', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final log = makeLog();
+ await log.refresh();
+ expect(announced, isEmpty);
+ final listing = await log.list();
+ expect(listing.baselineSeen, isFalse);
+ expect(listing.joinedSeq, 2);
+ expect(listing.pending, isEmpty);
+
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final empty = makeLog();
+ await empty.refresh();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await empty.refresh();
+ expect(announced.map((m) => m.label), ['box2']);
+ });
+
+ test('pending survives a new instance on the same store; dismiss and seeBaseline persist', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final other = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ await backend.add(other, 'viewer', '', 'tablet');
+ await log.refresh();
+ final again = makeLog();
+ expect((await again.list()).pending, [b64e(box3.pub), b64e(other.pub)]);
+ await again.dismiss(pub: b64e(box3.pub));
+ expect((await makeLog().list()).pending, [b64e(other.pub)]);
+ expect((await again.list()).baselineSeen, isFalse);
+ await again.seeBaseline();
+ expect((await makeLog().list()).baselineSeen, isTrue);
+ await again.dismiss();
+ expect((await makeLog().list()).pending, isEmpty);
+ });
+
+ test('a file from before the joined point migrates: nothing up to notifiedUpTo is announced again', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final log = makeLog();
+ await log.register();
+ final stripped = Map<String, Object?>.from((await keys.deviceLog())! as Map)
+ ..remove('joinedSeq')
+ ..remove('preLog')
+ ..remove('pending')
+ ..remove('announced')
+ ..remove('baselineSeen');
+ await keys.writeDeviceLog(stripped);
+ await backend.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'late');
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['late']);
+ final listing = await log.list();
+ expect(listing.joinedSeq, 3);
+ expect(listing.baselineSeen, isTrue);
+ });
+
+ test('a write path keeps the marks (accept, freeze, dismiss)', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await log.dismiss(pub: 'nobody');
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh();
+ final file = (await keys.deviceLog())! as Map;
+ expect(file['joinedSeq'], 1);
+ expect(file['pending'], [b64e(box3.pub)]);
+ expect(file['baselineSeen'], isFalse);
+ expect(file['frozen'], isNotNull);
+ });
+ });
+
+ group('removal notices', () {
+ late E2eeIdentity tablet;
+ setUp(() async {
+ tablet = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ await backend.add(box3, 'machine', _mid3, 'box3'); // on the account before this app joined
+ });
+
+ Future<ViewerDeviceLog> joined() async {
+ final log = makeLog();
+ await log.register();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.refresh();
+ return log;
+ }
+
+ test('none for a removal this app signed', () async {
+ final log = await joined();
+ expect(await log.remove(b64e(box2.pub)), isNull);
+ expect(removed, isEmpty);
+ });
+
+ test('a device that removed itself signed out', () async {
+ final log = await joined();
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ await backend.removeBy(b64e(tablet.pub), tablet);
+ await log.refresh();
+ expect(removed.single.selfRemoved, isTrue);
+ expect(removed.single.label, 'tablet');
+ });
+
+ test('a removal by a trusted key is normal, naming the signer', () async {
+ final log = await joined();
+ await log.dismiss();
+ await backend.removeBy(b64e(box3.pub), box2);
+ await log.refresh();
+ expect(removed.single.signerLabel, 'box2');
+ expect(removed.single.signerPending, isFalse);
+ expect(removed.single.selfRemoved, isFalse);
+ });
+
+ test('a removal by a signer nobody looked at is red', () async {
+ final log = await joined();
+ await backend.removeBy(b64e(box3.pub), box2);
+ await log.refresh();
+ expect(removed.single.signerPending, isTrue);
+ });
+
+ test('a removal applied while frozen still says so, and is kept for the history', () async {
+ final log = await joined();
+ backend.lie = backend.entries.sublist(0, 2);
+ await log.refresh();
+ backend.lie = null;
+ await backend.removeBy(b64e(box3.pub), box2);
+ await log.refresh();
+ expect(removed.single.signerPending, isTrue);
+ expect(((await keys.deviceLog())! as Map)['looseRemoved'], hasLength(1));
+ expect((await log.history()).rows.firstWhere((r) => r.op == 'removed').whileFrozen, isTrue);
+ });
+ });
+
+ group('a fork', () {
+ test('suspends the new keys at or after the split, unpins them and keeps the rest', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ final other = _Backend();
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await other.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'evil');
+ await other.add(box3, 'machine', _mid3, 'box3');
+ Map<String, Object?> hashes(DevLogState s) => {
+ 'head': s.head.toJson(),
+ 'hashes': [for (var i = 0; i < s.hashes.length; i++) {'seq': i + 1, 'hash': s.hashes[i]}],
+ };
+ await log.heard(b64e(box2.pub), hashes(other.state));
+ expect((await log.list()).frozen?.reason, 'fork');
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ expect(await keys.peer(_mid3), isNull);
+ expect(await keys.peer(_mid2), isNotNull);
+ expect((await log.list()).members.firstWhere((r) => r.member.pub == b64e(box3.pub)).suspended, isTrue);
+ await log.rebaseline(confirm: true);
+ expect(await log.suspendedPubs(), isEmpty);
+ expect(await keys.peer(_mid3), isNotNull);
+ });
+
+ Map<String, Object?> gossipOf(DevLogState s) => {
+ 'head': s.head.toJson(),
+ 'hashes': [for (var i = 0; i < s.hashes.length; i++) {'seq': i + 1, 'hash': s.hashes[i]}],
+ };
+
+ Future<(ViewerDeviceLog, _Backend)> forkedSetup() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register(); // box2 (1), this app (2)
+ await backend.add(box3, 'machine', _mid3, 'box3'); // 3: new since joining
+ await log.refresh();
+ final other = _Backend();
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await other.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'evil');
+ await other.add(box3, 'machine', _mid3, 'box3');
+ return (log, other);
+ }
+
+ test('a log already frozen on a fork still learns the split from a machine that is ahead', () async {
+ final (log, other) = await forkedSetup();
+ backend.lie = other.entries; // same length, a different entry at 2
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'fork');
+ expect(await log.suspendedPubs(), isEmpty);
+ await other.add(await E2eeIdentity.fromSeed(List.filled(32, 7)), 'viewer', '', 'later');
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ expect(await keys.peer(_mid3), isNull);
+ });
+
+ test('a removal signed by a suspended key does not count while frozen', () async {
+ final (log, other) = await forkedSetup();
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ await backend.removeBy(b64e(box2.pub), box3); // the suspended key tries to take out a trusted machine
+ await log.refresh();
+ expect(removed, isEmpty);
+ expect((await log.list()).members.map((r) => r.member.pub), contains(b64e(box2.pub)));
+ expect(await keys.peer(_mid2), isNotNull);
+ expect(((await keys.deviceLog())! as Map)['looseRemoved'], isNull);
+ });
+
+ test('without hashes nothing is suspended', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ final other = _Backend();
+ await other.add(box3, 'machine', _mid3, 'box3');
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await other.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'x');
+ await log.heard(b64e(box2.pub), {'head': other.state.head.toJson()});
+ expect(await log.suspendedPubs(), isEmpty);
+ });
+
+ test('devLogDivergence finds the first differing position the one before confirms', () async {
+ final log = _Backend();
+ await log.add(box2, 'machine', _mid2, 'box2');
+ await log.add(box3, 'machine', _mid3, 'box3');
+ final mine = log.state;
+ Map<String, Object?> theirs(List<String> h) => {
+ 'head': {'seq': h.length, 'hash': h.last},
+ 'hashes': [for (var i = 0; i < h.length; i++) {'seq': i + 1, 'hash': h[i]}],
+ };
+ expect(devLogDivergence(mine, theirs([mine.hashes[0], 'x'])), 2);
+ expect(devLogDivergence(mine, theirs(['x', 'y'])), 1);
+ expect(devLogDivergence(mine, theirs(mine.hashes)), isNull);
+ expect(devLogDivergence(mine, null), isNull);
+ expect(devLogDivergence(mine, {'head': mine.head.toJson()}), isNull);
+ });
+
+ test('gossip carries the newest hashes', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final g = (await log.gossip())!;
+ expect((g['hashes']! as List).length, 2);
+ expect((g['hashes']! as List).last, {'seq': 2, 'hash': backend.state.head.hash});
+ });
+ });
+
+ group('history', () {
+ test('lists every entry newest first, caches, fetches only what is missing, and falls back offline', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.removeBy(b64e(box3.pub), box2);
+ final h = await log.history();
+ expect(h.complete, isTrue);
+ expect([for (final r in h.rows) '${r.seq}:${r.op}'], ['4:removed', '3:added', '2:added', '1:added']);
+ expect(h.rows.first.by?.label, 'box2');
+ expect(h.rows.first.active, isFalse);
+ expect(h.rows[2].thisDevice, isTrue);
+ backend.fetched.clear();
+ await backend.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'late');
+ await log.history();
+ expect(backend.fetched, [4, 4]);
+ backend.offline = true;
+ final fresh = makeLog();
+ final off = await fresh.history();
+ expect(off.complete, isFalse);
+ expect([for (final r in off.rows) r.seq], [5, 4, 3, 2, 1]);
+ });
+
+ test('freezes when the backend serves a different entry at a verified position', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final forged = _Backend();
+ await forged.add(box2, 'machine', _mid2, 'box2');
+ await forged.add(box3, 'machine', _mid3, 'not-me');
+ final fresh = ViewerDeviceLog(
+ keys: keys,
+ fetch: (since) async {
+ // The head is the real one; the entry served at position 2 is not what this app verified.
+ final real = (await backend.fetch(since))!;
+ return (acct: real.acct, head: real.head, entries: since < 2 ? [backend.entries[0].toJson(), forged.entries[1].toJson()] : real.entries);
+ },
+ append: backend.append,
+ label: () => 'my-phone',
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+ final h = await fresh.history();
+ expect(h.complete, isFalse);
+ expect((await fresh.list()).frozen?.reason, 'fork');
+ });
+ });
+
+ group('changes to the file never cross', () {
+ late _GatedMemory store;
+ late E2eeIdentity tablet;
+ setUp(() async {
+ store = _GatedMemory();
+ keys = ViewerKeyStore(storage: store);
+ tablet = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['box3']);
+ });
+
+ Future<void> expectSettled(ViewerDeviceLog log) async {
+ final listing = await log.list();
+ expect(listing.pending, [b64e(tablet.pub)], reason: 'box3 dismissed, tablet still new');
+ expect(((await keys.deviceLog())! as Map)['state']['head']['seq'], 4);
+ // Nothing was rolled back, so nothing is read — or announced — a second time.
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['box3', 'tablet']);
+ expect((await log.list()).frozen, isNull);
+ }
+
+ test('a dismissal that read the file before an accept wrote it does not roll the head back', () async {
+ final log = makeLog();
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ final release = Completer<void>();
+ final held = store.holdNextLogWrite(release);
+ final dismissed = log.dismiss(pub: b64e(box3.pub));
+ await held; // the dismissal has read the file and is writing it
+ final refreshed = log.refresh();
+ await _settle(refreshed);
+ release.complete();
+ await Future.wait([dismissed, refreshed]);
+ await expectSettled(log);
+ });
+
+ test('an accept that read the file before a dismissal wrote it does not undo the dismissal', () async {
+ final log = makeLog();
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ final release = Completer<void>();
+ final held = store.holdNextLogWrite(release);
+ final refreshed = log.refresh();
+ await held; // the accept of tablet is writing the file
+ final dismissed = log.dismiss(pub: b64e(box3.pub));
+ await _settle(dismissed);
+ release.complete();
+ await Future.wait([dismissed, refreshed]);
+ await expectSettled(log);
+ });
+
+ test('seeing the baseline while a peer hands over its tail keeps both', () async {
+ final log = makeLog();
+ final before = backend.state.head;
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ final release = Completer<void>();
+ final held = store.holdNextLogWrite(release);
+ final seen = log.seeBaseline();
+ await held;
+ final heard = log.heard(b64e(box2.pub), {
+ 'head': backend.state.head.toJson(),
+ 'frozen': false,
+ 'tail': [for (final e in backend.entries) if (e.seq > before.seq) e.toJson()],
+ });
+ await _settle(heard);
+ release.complete();
+ await Future.wait([seen, heard]);
+ final file = (await keys.deviceLog())! as Map;
+ expect(file['baselineSeen'], isTrue);
+ expect(file['state']['head']['seq'], 4);
+ expect(announced.map((m) => m.label), ['box3', 'tablet']);
+ });
+
+ test('a page that arrives after a peer moved the log is read again, not taken for a fork', () async {
+ final log = makeLog();
+ await backend.add(tablet, 'viewer', '', 'tablet');
+ final viaPeer = backend.entries[3]; // tablet, seq 4
+ final other = await E2eeIdentity.fromSeed(List.filled(32, 7));
+ await backend.add(other, 'viewer', '', 'laptop'); // seq 5
+ backend
+ ..holdFetch = Completer<void>()
+ ..fetchHeld = Completer<void>();
+ final release = backend.holdFetch!;
+ final refreshed = log.refresh(); // asks for everything after seq 3
+ await backend.fetchHeld!.future;
+ final head4 = (await applyDevLogEntries(DevLogState.empty(_acct), [for (final e in backend.entries.take(4)) e.toJson()])).state.head;
+ await log.heard(b64e(box2.pub), {'head': head4.toJson(), 'frozen': false, 'tail': [viaPeer.toJson()]});
+ release.complete();
+ await refreshed;
+ final listing = await log.list();
+ expect(listing.frozen, isNull);
+ expect(((await keys.deviceLog())! as Map)['state']['head']['seq'], 5);
+ expect(announced.map((m) => m.label), ['box3', 'tablet', 'laptop']);
+ });
+ });
+
+ group('the joined point, reviews, history and dismissals', () {
+ late E2eeIdentity evil;
+ setUp(() async => evil = await E2eeIdentity.fromSeed(List.filled(32, 9)));
+
+ ViewerDeviceLog logWith(DeviceLogFetch f) => ViewerDeviceLog(
+ keys: keys,
+ fetch: f,
+ append: backend.append,
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Map<String, Object?> gossipOf(DevLogState s) => {
+ 'head': s.head.toJson(),
+ 'hashes': [for (var i = 0; i < s.hashes.length; i++) {'seq': i + 1, 'hash': s.hashes[i]}],
+ };
+
+ test('the joined point is the VERIFIED head, never the one the backend claims', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ var first = true;
+ final log = logWith((since) async {
+ final got = await backend.fetch(since);
+ if (got == null || !first) return got;
+ first = false;
+ return (acct: got.acct, head: DevLogHead(1000, 'x' * 64), entries: got.entries);
+ });
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.frozen, isNull);
+ expect(listing.joinedSeq, 2);
+ // A key forged below the claimed 1000 is still new.
+ await backend.add(evil, 'viewer', '', 'evil');
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['evil']);
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ });
+
+ test('a head that is not a position is not read at all', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = logWith((since) async {
+ final got = await backend.fetch(since);
+ return got == null ? null : (acct: got.acct, head: DevLogHead(-1, 'h'), entries: got.entries);
+ });
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.members, isEmpty);
+ // Not read at all — judged against it, a fresh file would read as rolled back and freeze.
+ expect(listing.frozen, isNull);
+ });
+
+ group('rebaseline(confirm)', () {
+ late ViewerDeviceLog log;
+ setUp(() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ log = makeLog();
+ await log.register();
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh(); // frozen (rolled back)
+ backend.lie = null;
+ });
+
+ test('a key the preview did not show is pending and announced', () async {
+ final preview = await log.rebaseline(confirm: false);
+ expect(preview, isNotNull);
+ await backend.add(evil, 'viewer', '', 'evil'); // between preview and confirm
+ expect(await log.rebaseline(confirm: true), isNotNull);
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ expect(announced.map((m) => m.label), ['evil']);
+ });
+
+ test('refuses when the backend head is no longer the one previewed', () async {
+ final preview = (await log.rebaseline(confirm: false))!;
+ await backend.add(evil, 'viewer', '', 'evil');
+ expect((await log.rebaseline(confirm: true, expectedHead: preview.head))!.logChanged, isTrue);
+ expect((await log.list()).frozen, isNotNull);
+ expect(announced, isEmpty);
+ final again = (await log.rebaseline(confirm: false))!;
+ expect((await log.rebaseline(confirm: true, expectedHead: again.head))!.logChanged, isFalse);
+ expect((await log.list()).frozen, isNull);
+ });
+ });
+
+ group('a fork does not cost the user the devices they reviewed', () {
+ late ViewerDeviceLog log;
+ late _Backend other;
+ setUp(() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ log = makeLog();
+ await log.register(); // box2 (1), this app (2)
+ await backend.add(box3, 'machine', _mid3, 'box3'); // 3: new since joining
+ await log.refresh();
+ other = _Backend();
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await other.add(evil, 'viewer', '', 'evil');
+ await other.add(box3, 'machine', _mid3, 'box3');
+ });
+
+ test('O2: a key already marked as seen is not suspended', () async {
+ await log.dismiss(pubs: [b64e(box3.pub)]);
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect((await log.list()).frozen?.reason, 'fork');
+ expect(await log.suspendedPubs(), isEmpty);
+ });
+
+ test('O2: a key let in by a review is not suspended', () async {
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh();
+ backend.lie = null;
+ await log.rebaseline(confirm: true);
+ expect((await log.list()).pending, contains(b64e(box3.pub)));
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect(await log.suspendedPubs(), isEmpty);
+ });
+
+ test('O2: a key that is new here is still suspended', () async {
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ });
+
+ test('"It\'s mine" on a suspended key lifts its suspension; a list that was merely viewed does not', () async {
+ await log.heard(b64e(box2.pub), gossipOf(other.state));
+ await log.dismiss(pubs: [b64e(box3.pub)]);
+ expect(await log.suspendedPubs(), {b64e(box3.pub)});
+ expect((await log.list()).pending, [b64e(box3.pub)]); // still flagged
+ expect(await keys.peer(_mid3), isNull);
+ await log.dismiss(pub: b64e(box3.pub));
+ expect(await log.suspendedPubs(), isEmpty);
+ expect((await log.list()).pending, isEmpty);
+ expect(await keys.peer(_mid3), isNotNull);
+ });
+ });
+
+ test('two history() calls at once share one walk and freeze nothing', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(evil, 'viewer', '', 'evil');
+ await log.refresh();
+ // Each page takes a moment, so the two walks really are in flight together.
+ final fresh = logWith((since) async {
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ return backend.fetch(since);
+ });
+ final both = await Future.wait([fresh.history(), fresh.history()]);
+ expect((await fresh.list()).frozen, isNull);
+ expect(both[0].complete, isTrue);
+ expect([for (final r in both[1].rows) r.seq], [4, 3, 2, 1]);
+ });
+
+ test('dismiss with a list clears only what it names', () async {
+ final log = makeLog();
+ await log.register();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.refresh();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await log.dismiss(pubs: [b64e(box2.pub)]);
+ expect((await log.list()).pending, [b64e(box3.pub)]);
+ });
+
+ test('keys trusted at joining whose entry came after the joined point are in the baseline', () async {
+ await keys.pin(_mid2, box2.pub, label: 'box2'); // trusted before the log
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final log = makeLog();
+ await log.refresh();
+ await backend.add(box2, 'machine', _mid2, 'box2'); // seq 2 > joinedSeq 1
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.baseline.toSet(), {b64e(box2.pub), b64e(box3.pub)});
+ expect(listing.pending, isEmpty);
+ });
+
+ test('a removal is described by the label and kind the key had, not the remove entry\'s own', () async {
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.refresh();
+ await log.dismiss();
+ final lie = await signDevLogEntry(
+ nextDevLogEntry(backend.state, op: 'remove', pub: b64e(box2.pub), kind: 'viewer', machineId: '', label: 'Totally Fine', signer: b64e(box3.pub), at: 2000),
+ box3,
+ );
+ await backend._push(lie);
+ await log.refresh();
+ expect(removed.single.label, 'box2');
+ expect(removed.single.kind, 'machine');
+ final h = await log.history();
+ expect(h.rows.first.label, 'box2');
+ expect(h.rows.first.kind, 'machine');
+ });
+ });
+
+ group('a backend that moves the list under a running read', () {
+ late E2eeIdentity evil;
+ setUp(() async => evil = await E2eeIdentity.fromSeed(List.filled(32, 9)));
+
+ ViewerDeviceLog logWith(DeviceLogFetch f) => ViewerDeviceLog(
+ keys: keys,
+ fetch: f,
+ append: backend.append,
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Future<void> editFile(void Function(Map<String, Object?> file) edit) async {
+ final file = Map<String, Object?>.from(await keys.deviceLog() as Map);
+ edit(file);
+ await keys.writeDeviceLog(file);
+ }
+
+ test('a backend that flips the account id and back keeps a fork\'s marks', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ var wrong = false;
+ final log = logWith((since) async {
+ if (wrong) return (acct: 'x', head: DevLogState.empty('x').head, entries: <Object?>[]);
+ return backend.fetch(since);
+ });
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await editFile((f) => f['suspended'] = [b64e(box3.pub)]);
+ expect((await log.list()).pending, [b64e(box3.pub)]);
+ wrong = true;
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'invalid');
+ wrong = false;
+ await log.refresh(); // the real log again
+ final listing = await log.list();
+ expect(listing.frozen?.reason, 'invalid');
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.members.firstWhere((r) => r.member.pub == b64e(box3.pub)).suspended, isTrue);
+ });
+
+ test('rebaseline: unreadable is null, a moved list is logChanged', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ backend.offline = true;
+ expect(await log.rebaseline(confirm: false), isNull);
+ backend.offline = false;
+ final preview = (await log.rebaseline(confirm: false))!;
+ expect(preview.logChanged, isFalse);
+ await backend.add(evil, 'viewer', '', 'evil');
+ final moved = await log.rebaseline(confirm: true, expectedHead: preview.head);
+ expect(moved!.logChanged, isTrue);
+ expect(moved.added, isEmpty);
+ });
+
+ test('a rebaseline during the history walk does not freeze the fresh log', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ var armed = false;
+ final alt = _Backend();
+ await alt.add(evil, 'viewer', '', 'evil');
+ await alt.add(box2, 'machine', _mid2, 'box2');
+ final log = logWith((since) async {
+ if (armed && since == 0) {
+ // The person confirms a review while this page is on its way: the file, and what the backend
+ // serves, are another list now.
+ armed = false;
+ await editFile((f) => f['state'] = alt.state.toJson());
+ backend.lie = alt.entries;
+ }
+ return backend.fetch(since);
+ });
+ await log.register();
+ armed = true;
+ final h = await log.history();
+ expect((await log.list()).frozen, isNull);
+ expect(h.complete, isFalse);
+ });
+
+ test('a peer tail that arrives while the first read is still open announces nothing', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(evil, 'viewer', '', 'evil');
+ late ViewerDeviceLog log;
+ var calls = 0;
+ log = logWith((since) async {
+ calls++;
+ final got = await backend.fetch(since);
+ // The first read comes in one entry at a time; between its pages a peer hands over the rest.
+ if (calls == 1) return (acct: got!.acct, head: got.head, entries: got.entries.sublist(0, 1));
+ if (calls == 2) {
+ await log.heard(b64e(box2.pub), {
+ 'head': backend.state.head.toJson(),
+ 'frozen': false,
+ 'tail': [for (final e in backend.entries.skip(1)) e.toJson()],
+ });
+ }
+ return got;
+ });
+ await log.refresh();
+ expect(announced, isEmpty);
+ expect((await log.list()).joinedSeq, 3);
+ expect((await keys.deviceLog() as Map).containsKey('joining'), isFalse);
+ await backend.add(await E2eeIdentity.fromSeed(List.filled(32, 7)), 'viewer', '', 'later');
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['later']);
+ });
+ });
+
+ group('signing in again, and to other accounts', () {
+ late E2eeIdentity evil, phone;
+ setUp(() async {
+ evil = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ phone = await E2eeIdentity.fromSeed(List.filled(32, 7));
+ });
+
+ /// A log whose backend is whichever [at] says now — another account's, after a sign-in.
+ ViewerDeviceLog at(_Backend Function() at, {DeviceLogFetch? fetch}) => ViewerDeviceLog(
+ keys: keys,
+ fetch: fetch ?? (since) => at().fetch(since),
+ append: (e) => at().append(e),
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Future<Map<Object?, Object?>> file() async => await keys.deviceLog() as Map;
+
+ /// A fork suspended box3, still pending, and the list is frozen on it.
+ Future<void> forked(ViewerDeviceLog log) async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ final f = Map<String, Object?>.from(await file());
+ f['suspended'] = [b64e(box3.pub)];
+ f['frozen'] = {'reason': 'fork', 'at': 1, 'lastGoodHead': backend.state.head.toJson()};
+ await keys.writeDeviceLog(f);
+ await keys.unlink(_mid3); // as the suspension does
+ }
+
+ Future<Set<String>> rosterPubs() async => {for (final m in GroupRoster.parse(await keys.groupRoster()).members) m.pub};
+
+ test('signing in again by hand to the same account keeps the list and every mark on it', () async {
+ var current = backend;
+ final log = at(() => current);
+ await forked(log);
+ final owner = (await file())['owner'];
+ await log.register(freshSignIn: true);
+ final listing = await log.list();
+ expect((await file())['owner'], isNot(owner));
+ expect(listing.frozen?.reason, 'fork');
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.joinedSeq, 1);
+ // That sign-in is the file's now: the backend saying another account freezes, never starts over.
+ final f = Map<String, Object?>.from(await file())..['frozen'] = null;
+ await keys.writeDeviceLog(f);
+ current = _Backend('x');
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'invalid');
+ expect((await log.list()).suspended, [b64e(box3.pub)]);
+ });
+
+ test('a sign-in the backend forced, onto a made-up account and back, gives the first account its marks back', () async {
+ var current = backend;
+ final log = at(() => current);
+ await forked(log);
+ final fake = _Backend('x');
+ await fake.add(box3, 'machine', _mid3, 'box3');
+ await fake.add(evil, 'viewer', '', 'evil');
+ current = fake;
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], 'x');
+ expect(await rosterPubs(), contains(b64e(evil.pub)));
+ expect(await keys.peer(_mid3), isNull);
+ expect(await log.suspendedPubs(), contains(b64e(box3.pub)));
+ current = backend;
+ await log.register(freshSignIn: true);
+ final listing = await log.list();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(listing.frozen?.reason, 'fork');
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.joinedSeq, 1);
+ });
+
+ test('a sign-in by hand to another account starts it fresh, and switching back restores the first', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ expect((await log.list()).pending, [b64e(box3.pub)]);
+ final other = _Backend('acct-2');
+ await other.add(phone, 'viewer', '', 'theirs');
+ current = other;
+ await log.register(freshSignIn: true);
+ var listing = await log.list();
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect(listing.pending, isEmpty);
+ expect(listing.baselineSeen, isFalse);
+ current = backend;
+ await log.register(freshSignIn: true);
+ listing = await log.list();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(announced.map((m) => m.label), ['box3']);
+ });
+
+ test('only the newest few other accounts are kept', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ for (var i = 0; i < 5; i++) {
+ current = _Backend('acct-b$i');
+ await log.register(freshSignIn: true);
+ }
+ expect((await keys.deviceLogArchive()).keys, ['acct-b0', 'acct-b1', 'acct-b2', 'acct-b3']);
+ });
+
+ test('a session from before sign-in ids takes the list over but never starts it over', () async {
+ var current = backend;
+ final log = at(() => current);
+ await forked(log);
+ await keys.writeSignInEpoch('');
+ final restarted = at(() => current);
+ current = _Backend('x');
+ await restarted.refresh();
+ final listing = await restarted.list();
+ expect(listing.frozen?.reason, 'fork');
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(await keys.signInEpoch(), startsWith('adopted:'));
+ current = backend;
+ await restarted.refresh();
+ expect((await file())['owner'], await keys.signInEpoch());
+ });
+
+ test('a file from before it recorded its sign-in starts over for a sign-in by hand to another account', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register();
+ final f = Map<String, Object?>.from(await file())
+ ..remove('owner')
+ ..['pending'] = ['x'];
+ await keys.writeDeviceLog(f);
+ current = _Backend('acct-2');
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await log.list()).pending, isEmpty);
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ });
+
+ test('no sign-in id at hand (the store cannot be read) never starts the list over', () async {
+ final store = _NoSignIn();
+ keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await forked(log);
+ store.broken = true;
+ final restarted = at(() => current);
+ current = _Backend('x');
+ await restarted.refresh();
+ final listing = await restarted.list();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(listing.suspended, [b64e(box3.pub)]);
+ expect(listing.pending, [b64e(box3.pub)]);
+ expect(listing.joinedSeq, 1);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ });
+
+ test('a kept list is restored only for the account it is the list of', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ // A kept file filed under another account's id (a damaged archive) whose fork suspended evil.
+ final kept = Map<String, Object?>.from(await file())
+ ..['suspended'] = [b64e(evil.pub)]
+ ..['pending'] = <String>[];
+ await keys.writeDeviceLogArchive({'acct-2': kept});
+ expect(await log.suspendedPubs(), contains(b64e(evil.pub)));
+ current = _Backend('acct-2');
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await log.list()).frozen, isNull);
+ });
+
+ test('a read on its way when the person signs in judges by that sign-in', () async {
+ final store = _HeldWrites('viewer_e2ee_sign_in');
+ keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ final other = _Backend('acct-2');
+ current = other;
+ other.holdFetch = Completer<void>();
+ other.fetchHeld = Completer<void>();
+ final release = other.holdFetch!;
+ final reading = log.refresh();
+ await other.fetchHeld!.future;
+ // The new sign-in is not on disk yet when that read lands.
+ final saved = store.hold = Completer<void>();
+ final signingIn = log.register(freshSignIn: true);
+ release.complete();
+ await reading;
+ saved.complete();
+ await signingIn;
+ expect((await log.list()).frozen, isNull);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ // The account left is kept as it was — not frozen by a read judged by the old sign-in.
+ expect(((await keys.deviceLogArchive())[_acct] as Map)['frozen'], isNull);
+ });
+
+ test('removed by a new key, signed in again to the same account: the key is still new', () async {
+ final log = at(() => backend);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(evil, 'viewer', '', 'evil');
+ await log.refresh();
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ final me = await keys.identity();
+ await backend.removeBy(b64e(me.pub), evil);
+ await log.refresh();
+ expect(signedOut, 1);
+ await keys.forgetIdentity(); // what the app does on being signed out
+ await log.register(freshSignIn: true);
+ final listing = await log.list();
+ expect(listing.pending, [b64e(evil.pub)]);
+ expect(listing.joinedSeq, 1);
+ expect(backend.state.active[b64e((await keys.identity()).pub)], isNotNull);
+ });
+
+ test('a first read the backend cuts short ends the joining: what it held back is news', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(evil, 'viewer', '', 'evil');
+ var calls = 0;
+ final log = at(() => backend, fetch: (since) async {
+ calls++;
+ final got = await backend.fetch(since);
+ if (calls == 1) return (acct: got!.acct, head: got.head, entries: got.entries.sublist(0, 1));
+ if (calls == 2) return null; // the link drops
+ return got;
+ });
+ await log.refresh();
+ expect((await file()).containsKey('joining'), isFalse);
+ await log.heard(b64e(box2.pub), {
+ 'head': backend.state.head.toJson(),
+ 'frozen': false,
+ 'tail': [for (final e in backend.entries.skip(1)) e.toJson()],
+ });
+ expect(announced.map((m) => m.label), ['box3', 'evil']);
+ final listing = await log.list();
+ expect(listing.joinedSeq, 1);
+ expect(listing.pending, [b64e(box3.pub), b64e(evil.pub)]);
+ });
+
+ test('"Got it" on the already-on-your-account list ends the joining', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(evil, 'viewer', '', 'evil');
+ late ViewerDeviceLog log;
+ var calls = 0;
+ log = at(() => backend, fetch: (since) async {
+ calls++;
+ final got = await backend.fetch(since);
+ if (calls == 1) return (acct: got!.acct, head: got.head, entries: got.entries.sublist(0, 1));
+ if (calls == 2) await log.seeBaseline();
+ return got;
+ });
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['evil']);
+ final listing = await log.list();
+ expect(listing.pending, [b64e(evil.pub)]);
+ expect(listing.baselineSeen, isTrue);
+ });
+
+ test('a key taken into an acknowledged already-on-your-account list shows that list again', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(evil, 'viewer', '', 'evil');
+ var calls = 0;
+ final log = at(() => backend, fetch: (since) async {
+ calls++;
+ final got = await backend.fetch(since);
+ if (calls == 1) return (acct: got!.acct, head: got.head, entries: got.entries.sublist(0, 1));
+ if (calls == 2) {
+ // Acknowledged by a client that did not end the joining.
+ await keys.writeDeviceLog(Map<String, Object?>.from(await file())..['baselineSeen'] = true);
+ }
+ return got;
+ });
+ await log.refresh();
+ expect(announced, isEmpty);
+ final listing = await log.list();
+ expect(listing.baselineSeen, isFalse);
+ expect(listing.baseline, contains(b64e(evil.pub)));
+ });
+ });
+
+ group('departed keys, and lists kept across sign-ins', () {
+ late E2eeIdentity evil, phone;
+ setUp(() async {
+ evil = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ phone = await E2eeIdentity.fromSeed(List.filled(32, 7));
+ });
+
+ /// A log whose backend is whichever [at] says now — another account's, after a sign-in.
+ ViewerDeviceLog at(_Backend Function() at, {int now = 5000}) => ViewerDeviceLog(
+ keys: keys,
+ fetch: (since) => at().fetch(since),
+ append: (e) => at().append(e),
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => now,
+ sleep: (_) async {},
+ );
+
+ Future<Map<Object?, Object?>> file() async => await keys.deviceLog() as Map;
+
+ group('a new key that leaves before anyone looked stays flagged', () {
+ late ViewerDeviceLog log;
+ setUp(() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ log = makeLog();
+ await log.register(); // box2 (1), this app (2)
+ await backend.add(evil, 'viewer', '', 'evil'); // 3: new, pending
+ await log.refresh();
+ });
+ Future<List<String>> departed(ViewerDeviceLog l) async => [for (final d in (await l.list()).departed) d.pub];
+
+ test('removed by itself: survives a new instance, keeps its history rows new, goes on dismiss', () async {
+ await backend.removeBy(b64e(evil.pub), evil);
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.pending, isEmpty);
+ final d = listing.departed.single;
+ expect([d.pub, d.label, d.kind, d.addedAt, d.removedAt, d.removedBy, d.selfRemoved],
+ [b64e(evil.pub), 'evil', 'viewer', 1000, 2000, b64e(evil.pub), true]);
+ expect(d.fingerprint, fingerprint(evil.pub));
+ final again = makeLog();
+ expect(await departed(again), [b64e(evil.pub)]);
+ final rows = (await again.history()).rows.where((r) => r.pub == b64e(evil.pub));
+ expect([for (final r in rows) (r.op, r.pending)], [('signedOut', true), ('added', true)]);
+ await again.dismiss(pub: b64e(evil.pub));
+ expect(await departed(again), isEmpty);
+ expect((await again.history()).rows.any((r) => r.pending), isFalse);
+ });
+
+ test('removed by another key: says by whom', () async {
+ await backend.removeBy(b64e(evil.pub), box2);
+ await log.refresh();
+ final d = (await log.list()).departed.single;
+ expect([d.removedBy, d.removedByLabel, d.selfRemoved], [b64e(box2.pub), 'box2', false]);
+ });
+
+ test('added and removed within one page: announced, and departed', () async {
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.removeBy(b64e(phone.pub), phone);
+ await log.refresh();
+ expect(announced.map((m) => m.label), contains('phone'));
+ expect(await departed(log), [b64e(phone.pub)]);
+ });
+
+ test('removed while the list is frozen: departed too', () async {
+ final f = Map<String, Object?>.from(await file());
+ f['frozen'] = {'reason': 'fork', 'at': 1, 'lastGoodHead': backend.state.head.toJson()};
+ await keys.writeDeviceLog(f);
+ await backend.removeBy(b64e(evil.pub), box2);
+ await log.refresh();
+ expect((await file())['looseRemoved'], hasLength(1));
+ expect(await departed(log), [b64e(evil.pub)]);
+ });
+
+ test('a key already marked as seen is not departed', () async {
+ await log.dismiss(pub: b64e(evil.pub));
+ await backend.removeBy(b64e(evil.pub), evil);
+ await log.refresh();
+ expect(await departed(log), isEmpty);
+ });
+
+ test('clears for its own pub, a list naming it, or every one — never for another key', () async {
+ await backend.removeBy(b64e(evil.pub), evil);
+ await log.refresh();
+ await log.seeBaseline();
+ await log.dismiss(pubs: [b64e(box2.pub)]);
+ await log.dismiss(pub: b64e(box2.pub));
+ expect(await departed(log), [b64e(evil.pub)]);
+ await log.dismiss(pubs: [b64e(evil.pub)]);
+ expect(await departed(log), isEmpty);
+ final f = Map<String, Object?>.from(await file())..['departed'] = [
+ {'pub': 'k', 'label': 'x', 'kind': 'viewer', 'machineId': '', 'fingerprint': 'F', 'addedAt': 1,
+ 'removedAt': 2, 'removedBy': 'k', 'removedByLabel': '', 'selfRemoved': true},
+ {'pub': 'junk', 'kind': 'evil'},
+ {'pub': 'odd', 'label': 'x', 'kind': 'evil', 'machineId': '', 'fingerprint': 'F', 'addedAt': 1,
+ 'removedAt': 2, 'removedBy': 'odd', 'removedByLabel': '', 'selfRemoved': true},
+ ];
+ await keys.writeDeviceLog(f);
+ expect(await departed(log), ['k']);
+ await log.dismiss();
+ expect(await departed(log), isEmpty);
+ });
+
+ test('kept up to the cap, the oldest going first', () async {
+ for (var i = 40; i < 40 + 33; i++) {
+ final k = await E2eeIdentity.fromSeed(List.filled(32, i));
+ await backend.add(k, 'viewer', '', 'k$i');
+ await backend.removeBy(b64e(k.pub), k);
+ }
+ await log.refresh();
+ final d = (await log.list()).departed;
+ expect(d, hasLength(32));
+ expect(d.first.label, 'k41');
+ expect(d.last.label, 'k72');
+ });
+ });
+
+ group('a sign-in by hand starts the list over only shortly after it was made', () {
+ const now = 30 * 60 * 1000;
+
+ /// Signed in on [backend] (box3 new there), then the sign-in [epoch] (not yet the list's), whose
+ /// first read — at [now] — is of another account.
+ Future<void> later(String epoch) async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ expect(await keys.signInEpoch(), matches(RegExp(r'^[0-9a-f]{32}@5000$')));
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await keys.writeSignInEpoch(epoch);
+ final restarted = at(() => current, now: now);
+ current = _Backend('acct-2');
+ await restarted.refresh();
+ }
+
+ test('one made over 10 minutes ago, with no read of its account yet, only freezes', () async {
+ await later('${'f' * 32}@${now - 11 * 60 * 1000}');
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ expect((await file())['pending'], [b64e(box3.pub)]);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ });
+
+ test('one with no time recorded only freezes', () async {
+ await later('f' * 32);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ });
+
+ test('one made just now starts it over', () async {
+ await later('${'f' * 32}@${now - 9 * 60 * 1000}');
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ });
+ });
+
+ test('a restore that fails half way has the kept list live first: its marks are never lost', () async {
+ final store = _FailingArchive();
+ keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ current = _Backend('acct-2');
+ await log.register(freshSignIn: true);
+ store.allowed = 1; // the list left is kept; taking the restored one out of the archive fails
+ current = backend;
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['pending'], [b64e(box3.pub)]);
+ expect((await keys.deviceLogArchive()).keys, contains(_acct));
+ });
+
+ test('gossip waits for the new sign-in\'s first read', () async {
+ final log = at(() => backend);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ final other = _Backend();
+ await other.add(evil, 'viewer', '', 'evil');
+ await other.add(phone, 'viewer', '', 'phone'); // another entry at the same position: a fork
+ final hashes = [for (var i = 0; i < other.state.hashes.length; i++) {'seq': i + 1, 'hash': other.state.hashes[i]}];
+ log.beginSignIn(fresh: true);
+ expect(await log.gossip(), isNull);
+ await log.heard(b64e(box2.pub), {'head': other.state.head.toJson(), 'frozen': false, 'hashes': hashes});
+ expect((await file())['frozen'], isNull);
+ await log.register(); // same account: the list is this sign-in's now
+ expect(await log.gossip(), isNotNull);
+ await log.heard(b64e(box2.pub), {'head': other.state.head.toJson(), 'frozen': false, 'hashes': hashes});
+ expect((await file())['frozen'], containsPair('reason', 'fork'));
+ });
+
+ group('beginSignIn', () {
+ test('a read before register already judges by the new sign-in, and register mints nothing more', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ final before = await keys.signInEpoch();
+ current = _Backend('acct-2');
+ log.beginSignIn(fresh: true);
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['frozen'], isNull);
+ final minted = await keys.signInEpoch();
+ expect(minted, isNot(before));
+ await log.register();
+ expect(await keys.signInEpoch(), minted);
+ expect((await file())['owner'], minted);
+ });
+
+ test('a sign-in id that could not be kept is not judged by: no read starts the list over on it', () async {
+ final store = _LostSignIn();
+ keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ current = _Backend('acct-2');
+ final saving = store.hold = Completer<void>();
+ final registering = log.register(freshSignIn: true);
+ await _settle(Future<void>.delayed(const Duration(milliseconds: 50)));
+ saving.complete();
+ await registering;
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ });
+
+ test('a stored session mints nothing', () async {
+ final log = makeLog();
+ await log.register();
+ final before = await keys.signInEpoch();
+ log.beginSignIn(fresh: false);
+ await log.register();
+ expect(await keys.signInEpoch(), before);
+ });
+
+ test('this app\'s old key removed, read before register: no sign-out', () async {
+ final log = at(() => backend);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ final me = await keys.identity();
+ await backend.removeBy(b64e(me.pub), box2);
+ log.beginSignIn(fresh: true);
+ await log.refresh();
+ expect(signedOut, 0);
+ await log.register();
+ expect(signedOut, 0);
+ expect(backend.state.active[b64e((await keys.identity()).pub)], isNotNull);
+ });
+ });
+
+ group('a suspension kept in another account\'s list shows, and lifts, in this one', () {
+ /// On [backend] a fork suspended the machine evil; then signed in by hand to acct-2, whose log
+ /// has evil.
+ Future<ViewerDeviceLog> moved() async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(evil, 'machine', _mid3, 'evil');
+ await log.refresh();
+ final f = Map<String, Object?>.from(await file())..['suspended'] = [b64e(evil.pub)];
+ await keys.writeDeviceLog(f);
+ await keys.unlink(_mid3); // as the suspension does
+ final b = _Backend('acct-2');
+ await b.add(phone, 'viewer', '', 'phone');
+ await b.add(evil, 'machine', _mid3, 'evil');
+ current = b;
+ await log.register(freshSignIn: true);
+ return log;
+ }
+
+ test('is suspended and new in the list, never trusted', () async {
+ final log = await moved();
+ final row = (await log.list()).members.firstWhere((r) => r.member.pub == b64e(evil.pub));
+ expect([row.suspended, row.pending], [true, true]);
+ expect(await keys.peer(_mid3), isNull);
+ });
+
+ test('"It\'s mine" lifts it here and in the kept list', () async {
+ final log = await moved();
+ await log.dismiss(pub: b64e(evil.pub));
+ expect(await log.suspendedPubs(), isNot(contains(b64e(evil.pub))));
+ expect(b64e((await keys.peer(_mid3))!.pub), b64e(evil.pub));
+ });
+
+ test('a review does not lift it (it never showed it as suspended): only "It\'s mine" does', () async {
+ final log = await moved();
+ final r = await log.rebaseline(confirm: true);
+ expect(r, isNotNull);
+ expect(await log.suspendedPubs(), contains(b64e(evil.pub)));
+ expect(((await keys.deviceLogArchive())[_acct] as Map)['suspended'], [b64e(evil.pub)]);
+ final row = (await log.list()).members.firstWhere((r) => r.member.pub == b64e(evil.pub));
+ expect([row.suspended, row.pending], [true, true]);
+ expect(await keys.peer(_mid3), isNull);
+ });
+ });
+
+ test('a kept list restored is suspended where another kept list says so', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(phone, 'viewer', '', 'phone');
+ await log.refresh();
+ await log.dismiss(pub: b64e(phone.pub));
+ final b = _Backend('acct-2');
+ await b.add(phone, 'viewer', '', 'phone');
+ current = b;
+ await log.register(freshSignIn: true);
+ // A fork in acct-2 suspended phone; then back to the first account, where phone is on the list.
+ final f = Map<String, Object?>.from(await file())..['suspended'] = [b64e(phone.pub)];
+ await keys.writeDeviceLog(f);
+ current = backend;
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ final row = (await log.list()).members.firstWhere((r) => r.member.pub == b64e(phone.pub));
+ expect([row.suspended, row.pending], [true, true]);
+ });
+
+ test('a review of another account\'s list after a sign-in keeps the one it leaves', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await makeLog().register();
+ final f = Map<String, Object?>.from(await file());
+ f['state'] = {...(f['state'] as Map).cast<String, Object?>(), 'acct': 'old'};
+ f['suspended'] = ['k'];
+ await keys.writeDeviceLog(f);
+ await keys.writeSignInEpoch('f' * 32); // signed in again, long ago: the list is not its yet
+ final log = makeLog();
+ final r = await log.rebaseline(confirm: true);
+ expect(r!.otherAccount, isFalse);
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['owner'], 'f' * 32);
+ expect((await keys.deviceLogArchive()).keys, ['old']);
+ });
+
+ group('another account\'s list under the sign-in the live list belongs to', () {
+ /// Signed in to the first account, a new key K pending; the backend then serves an empty
+ /// "acct-2" under the same sign-in.
+ Future<ViewerDeviceLog> switched([_Memory? store]) async {
+ if (store != null) keys = ViewerKeyStore(storage: store);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(evil, 'viewer', '', 'K');
+ await log.refresh();
+ expect((await file())['pending'], [b64e(evil.pub)]);
+ current = _Backend('acct-2');
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ announced.clear();
+ return log;
+ }
+
+ test('refuses the preview and the confirm (otherAccount), writing nothing', () async {
+ final store = _Memory();
+ final log = await switched(store);
+ final before = Map.of(store.values);
+ final preview = await log.rebaseline(confirm: false);
+ expect([preview!.otherAccount, preview.logChanged, preview.added, preview.removed], [true, false, isEmpty, isEmpty]);
+ expect((await log.rebaseline(confirm: true))!.otherAccount, isTrue);
+ expect((await log.rebaseline(confirm: true, expectedHead: _Backend('acct-2').state.head))!.otherAccount, isTrue);
+ // Said before logChanged: a confirm on another head is still about another account.
+ final stale = (await log.rebaseline(confirm: true, expectedHead: const DevLogHead(99, 'x')))!;
+ expect([stale.otherAccount, stale.logChanged], [true, false]);
+ expect(store.values, before); // nothing written: the list, its marks, trust
+ expect(await keys.deviceLogArchive(), isEmpty);
+ expect(announced, isEmpty);
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ });
+
+ test('a sign-in by hand made since goes ahead', () async {
+ await switched();
+ await keys.writeSignInEpoch('f' * 32);
+ final log = at(() => _Backend('acct-2'));
+ final r = await log.rebaseline(confirm: true);
+ expect(r!.otherAccount, isFalse);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ });
+
+ test('a list stamped by a sign-in, then this app taken over by an adopted one: neither goes ahead', () async {
+ final store = _Memory();
+ await switched(store);
+ expect((await file())['owner'], isNotNull);
+ await keys.writeSignInEpoch('adopted:x'); // a session taken over (an older version refreshed the token)
+ final log = at(() => _Backend('acct-2'));
+ final before = Map.of(store.values);
+ expect((await log.rebaseline(confirm: false))!.otherAccount, isTrue);
+ expect((await log.rebaseline(confirm: true))!.otherAccount, isTrue);
+ expect(store.values, before);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ expect((await log.list()).pending, [b64e(evil.pub)]);
+ });
+
+ /// A list no sign-in stamped yet (written before sign-in ids existed, or by an older version after
+ /// a downgrade) on the first account with K pending, under [epoch] (made long ago); the backend
+ /// then serves an empty "acct-2".
+ Future<ViewerDeviceLog> unstamped(_Memory store, String epoch) async {
+ keys = ViewerKeyStore(storage: store);
+ await keys.writeSignInEpoch(epoch);
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register();
+ await backend.add(evil, 'viewer', '', 'K');
+ await log.refresh();
+ await keys.writeDeviceLog(Map<String, Object?>.from(await file())..remove('owner'));
+ current = _Backend('acct-2');
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], _acct);
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ expect((await file())['pending'], [b64e(evil.pub)]);
+ expect((await file()).containsKey('owner'), isFalse);
+ announced.clear();
+ return log;
+ }
+
+ test('an unstamped list under an adopted sign-in (the session it was written under) refuses too', () async {
+ final store = _Memory();
+ final log = await unstamped(store, 'adopted:a');
+ final before = Map.of(store.values);
+ expect((await log.rebaseline(confirm: false))!.otherAccount, isTrue);
+ expect((await log.rebaseline(confirm: true))!.otherAccount, isTrue);
+ expect(store.values, before);
+ expect(await keys.deviceLogArchive(), isEmpty);
+ });
+
+ test('an unstamped list under a sign-in by hand is that sign-in moving accounts: the review goes ahead', () async {
+ final log = await unstamped(_Memory(), 'f' * 32);
+ final r = await log.rebaseline(confirm: true);
+ expect(r!.otherAccount, isFalse);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['owner'], 'f' * 32);
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ });
+ });
+ });
+
+ group('a review (rebaseline)', () {
+ late E2eeIdentity evil, phone, k5, k6, k7;
+ setUp(() async {
+ evil = await E2eeIdentity.fromSeed(List.filled(32, 9));
+ phone = await E2eeIdentity.fromSeed(List.filled(32, 7));
+ k5 = await E2eeIdentity.fromSeed(List.filled(32, 15));
+ k6 = await E2eeIdentity.fromSeed(List.filled(32, 16));
+ k7 = await E2eeIdentity.fromSeed(List.filled(32, 17));
+ });
+
+ ViewerDeviceLog at(_Backend Function() at) => ViewerDeviceLog(
+ keys: keys,
+ fetch: (since) => at().fetch(since),
+ append: (e) => at().append(e),
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onRemoved: removed.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Future<Map<Object?, Object?>> file() async => await keys.deviceLog() as Map;
+ List<String> pubs(Object? list) => [for (final d in (list as List? ?? const [])) (d as Map)['pub'] as String];
+
+ test('after the list froze on another account, a key added below the old joined point is news', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.add(k5, 'viewer', '', 'k5');
+ await log.refresh();
+ expect((await file())['joinedSeq'], 4);
+ final b = _Backend('acct-2');
+ await b.add(k7, 'viewer', '', 'k7');
+ // Signed in again by hand long ago: the backend held the new account's list back past the window.
+ await keys.writeSignInEpoch('f' * 32);
+ final signedIn = at(() => current);
+ current = b;
+ await signedIn.refresh();
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ await signedIn.rebaseline(confirm: true); // "Trust again"
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['joinedSeq'], 0);
+ announced.clear();
+ await b.add(evil, 'viewer', '', 'evil'); // seq 2: below the old account's joined point
+ await signedIn.refresh();
+ expect(announced.map((m) => m.label), ['evil']);
+ final listing = await signedIn.list();
+ expect(listing.pending, contains(b64e(evil.pub)));
+ expect(listing.baseline, isNot(contains(b64e(evil.pub))));
+ });
+
+ test('after a rollback 4 → 1 it was reviewed on, a key added at 2 is news', () async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.add(k5, 'viewer', '', 'k5');
+ await log.refresh();
+ expect((await file())['joinedSeq'], 4);
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh();
+ expect((await file())['frozen'], containsPair('reason', 'rollback'));
+ final preview = await log.rebaseline(confirm: false);
+ expect(preview!.added, isEmpty);
+ await log.rebaseline(confirm: true, expectedHead: preview.head);
+ expect((await file())['frozen'], isNull);
+ expect((await file())['joinedSeq'], 1);
+ final rolled = _Backend();
+ await rolled.add(box2, 'machine', _mid2, 'box2'); // the same entry 1
+ await rolled.add(evil, 'viewer', '', 'evil');
+ current = rolled;
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['evil']);
+ expect((await file())['pending'], [b64e(evil.pub)]);
+ });
+
+ group('back to an account this app kept the list of', () {
+ /// The first account: phone new and pending, evil suspended by a fork, k7 joined and left before
+ /// anyone looked; then signed in by hand to acct-2; then the backend serves the first account
+ /// again with no sign-in (frozen: a review does not switch accounts — see [back]).
+ Future<ViewerDeviceLog> away() async {
+ var current = backend;
+ final log = at(() => current);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.add(evil, 'machine', _mid3, 'evil');
+ await backend.add(k7, 'viewer', '', 'k7');
+ await backend.removeBy(b64e(k7.pub), box2);
+ await log.refresh();
+ final f = Map<String, Object?>.from(await file())..['suspended'] = [b64e(evil.pub)];
+ await keys.writeDeviceLog(f);
+ await keys.unlink(_mid3); // as the suspension does
+ final b = _Backend('acct-2');
+ await b.add(k5, 'viewer', '', 'k5');
+ current = b;
+ await log.register(freshSignIn: true);
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ current = backend; // no sign-in: the backend says the first account
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ announced.clear();
+ return log;
+ }
+
+ /// …then signed in again by hand (long ago: the list froze rather than started over) — the only
+ /// way back to the first account.
+ Future<ViewerDeviceLog> back() async {
+ await away();
+ await keys.writeSignInEpoch('e' * 32);
+ final log = at(() => backend);
+ await log.refresh();
+ expect(((await file())['state'] as Map)['acct'], 'acct-2');
+ expect((await file())['frozen'], containsPair('reason', 'invalid'));
+ return log;
+ }
+
+ test('without a sign-in, neither the preview nor "Trust again" goes back to it', () async {
+ final log = await away();
+ final before = '${await keys.deviceLog()}';
+ expect((await log.rebaseline(confirm: false))!.otherAccount, isTrue);
+ expect((await log.rebaseline(confirm: true))!.otherAccount, isTrue);
+ expect('${await keys.deviceLog()}', before);
+ expect((await keys.deviceLogArchive()).keys, [_acct]);
+ expect(announced, isEmpty);
+ expect(await keys.peer(_mid3), isNull);
+ });
+
+ Future<void> wentOn(ViewerDeviceLog log) async {
+ final f = await file();
+ expect((f['state'] as Map)['acct'], _acct);
+ expect(f['frozen'], isNull);
+ expect(f['pending'], containsAll([b64e(phone.pub), b64e(evil.pub)]));
+ expect(f['suspended'], [b64e(evil.pub)]);
+ expect(pubs(f['departed']), [b64e(k7.pub)]);
+ expect(announced, isEmpty);
+ expect(await keys.peer(_mid3), isNull);
+ final row = (await log.list()).members.firstWhere((r) => r.member.pub == b64e(evil.pub));
+ expect([row.suspended, row.pending], [true, true]);
+ expect((await keys.deviceLogArchive()).keys, isNot(contains(_acct)));
+ }
+
+ test('the preview compares against the kept list, not the account being left', () async {
+ final log = await back();
+ final preview = await log.rebaseline(confirm: false);
+ expect(preview!.added, isEmpty);
+ expect(preview.removed, isEmpty);
+ });
+
+ test('"Trust again" goes on from its marks: pending, departed, suspended, nothing re-announced', () async {
+ final log = await back();
+ await log.rebaseline(confirm: true);
+ await wentOn(log);
+ expect((await file())['owner'], 'e' * 32);
+ expect((await keys.deviceLogArchive()).keys, ['acct-2']);
+ });
+
+ test('…even when keeping the account left pushes it out of the archive', () async {
+ final log = await back();
+ final live = Map<String, Object?>.from(await file());
+ final all = await keys.deviceLogArchive();
+ for (final acct in ['x1', 'x2', 'x3']) {
+ all[acct] = {...live, 'state': {...(live['state'] as Map).cast<String, Object?>(), 'acct': acct}};
+ }
+ await keys.writeDeviceLogArchive(all);
+ await log.rebaseline(confirm: true);
+ await wentOn(log);
+ });
+ });
+
+ group('what the reviewed list took out', () {
+ late ViewerDeviceLog log;
+ setUp(() async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(k5, 'viewer', '', 'k5');
+ log = makeLog();
+ await log.register(); // this app: 3
+ await backend.add(phone, 'viewer', '', 'phone'); // 4: new, pending
+ await log.refresh();
+ expect((await file())['pending'], [b64e(phone.pub)]);
+ });
+
+ Future<void> freeze(int keep) async {
+ backend.lie = backend.entries.sublist(0, keep);
+ await log.refresh();
+ expect((await file())['frozen'], containsPair('reason', 'rollback'));
+ backend.lie = null;
+ }
+
+ test('a pending key the reviewed list does not have stays flagged as departed', () async {
+ backend.lie = backend.entries.sublist(0, 3);
+ await log.refresh();
+ await log.rebaseline(confirm: true);
+ expect((await file())['pending'], isEmpty);
+ final d = (await log.list()).departed.single;
+ expect([d.pub, d.label, d.removedBy, d.selfRemoved], [b64e(phone.pub), 'phone', '', false]);
+ });
+
+ test('a pending key removed while frozen is departed, with who removed it', () async {
+ await freeze(3);
+ await backend.removeBy(b64e(phone.pub), box2);
+ await log.rebaseline(confirm: true);
+ final d = (await log.list()).departed.single;
+ expect([d.pub, d.removedBy, d.removedByLabel], [b64e(phone.pub), b64e(box2.pub), 'box2']);
+ });
+
+ test('a key added and removed while frozen is departed; a reviewed-out key nobody flagged is not', () async {
+ await freeze(3);
+ await backend.add(evil, 'viewer', '', 'evil');
+ await backend.removeBy(b64e(evil.pub), box2);
+ await backend.removeBy(b64e(k5.pub), box2); // known since joining: not new
+ await log.rebaseline(confirm: true);
+ final d = (await log.list()).departed;
+ expect([for (final x in d) x.pub], [b64e(evil.pub)]);
+ expect([d.single.label, d.single.removedBy], ['evil', b64e(box2.pub)]);
+ });
+
+ test('a key that joined and left before the freeze, and was looked at, is not flagged again', () async {
+ await backend.add(k6, 'viewer', '', 'k6');
+ await backend.removeBy(b64e(k6.pub), box2);
+ await log.refresh();
+ expect([for (final d in (await log.list()).departed) d.pub], [b64e(k6.pub)]);
+ await log.dismiss(pub: b64e(k6.pub));
+ await freeze(5);
+ await log.rebaseline(confirm: true);
+ expect((await log.list()).departed, isEmpty);
+ });
+ });
+
+ test('a sign-in by hand that never registers expects this app\'s removal for one read only', () async {
+ final log = at(() => backend);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ log.beginSignIn(fresh: true);
+ await log.refresh(); // the read it was waiting for: nothing removed
+ final me = await keys.identity();
+ await backend.removeBy(b64e(me.pub), box2);
+ await log.refresh();
+ expect(signedOut, 1);
+ });
+ });
+
test('forgetting the identity mints a new one', () async {
final before = b64e((await keys.identity()).pub);
await keys.forgetIdentity();
diff --git a/mobile/test/viewer/group_sync_test.dart b/mobile/test/viewer/group_sync_test.dart
index 79bbcaa0f..980f6afe4 100644
--- a/mobile/test/viewer/group_sync_test.dart
+++ b/mobile/test/viewer/group_sync_test.dart
@@ -174,6 +174,78 @@ void main() {
expect(socket.closedByPhone, isTrue);
});
+ test(
+ 'a suspended key is neither pinned nor seeded into the roster',
+ () async {
+ final keys = ViewerKeyStore(storage: MemoryKeyValueStore());
+ final machine = await E2eeIdentity.generate();
+ final cPub = await _pub();
+ final dPub = await _pub();
+ final dId = 'd' * 32;
+ await keys.pin(ms.machineId, machine.pub);
+ await keys.pin(
+ dId,
+ b64d(dPub),
+ label: 'd',
+ ); // a pin the roster does not name yet
+ Map<String, dynamic>? seen;
+ final socket = _machineSocket(
+ machine,
+ (_) => {
+ 'members': [_machine(cPub, _c, 50).toJson()],
+ 'removed': [],
+ },
+ onRequest: (r) => seen = r,
+ );
+ final outcome = await syncTrustGroup(
+ machineId: ms.machineId,
+ keys: keys,
+ accessToken: 't',
+ wsBaseUrl: 'wss://relay.test',
+ autonomousEnv: 'prod',
+ label: 'p',
+ socket: socket.factory,
+ suspended: () async => {cPub, dPub},
+ );
+ expect(outcome.pinned, isEmpty);
+ expect(await keys.peer(_c), isNull);
+ expect([
+ for (final m in seen!['members'] as List) (m as Map)['pub'],
+ ], isNot(contains(dPub)));
+ },
+ );
+
+ test('a key suspended by the devlog this very exchange carries is not pinned either', () async {
+ final keys = ViewerKeyStore(storage: MemoryKeyValueStore());
+ final machine = await E2eeIdentity.generate();
+ final cPub = await _pub();
+ await keys.pin(ms.machineId, machine.pub);
+ final socket = _machineSocket(
+ machine,
+ (_) => {
+ 'members': [_machine(cPub, _c, 50).toJson()],
+ 'removed': [],
+ 'devlog': {
+ 'head': {'seq': 1, 'hash': 'x'},
+ },
+ },
+ );
+ final suspendedNow = <String>{};
+ final outcome = await syncTrustGroup(
+ machineId: ms.machineId,
+ keys: keys,
+ accessToken: 't',
+ wsBaseUrl: 'wss://relay.test',
+ autonomousEnv: 'prod',
+ label: 'p',
+ socket: socket.factory,
+ onDevlog: (_, _) async => suspendedNow.add(cPub),
+ suspended: () async => {...suspendedNow},
+ );
+ expect(outcome.pinned, isEmpty);
+ expect(await keys.peer(_c), isNull);
+ });
+
test(
'a pin the roster already names is not restamped by re-pinning',
() async {