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: device key log — signing in is what makes an account's devices trust each other (#518)

0xken1501b47da85426
diff --git a/SECURITY.md b/SECURITY.md
index b2cce671d..fe882df81 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -19,6 +19,13 @@ asking, inside the directory it is configured with. That is deliberate and docum
its README: it exists to demonstrate a real agent, not to be deployed. Point it at a scratch
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.
+
## For implementers
Two obligations in the protocol are security-relevant, and both are easy to get subtly wrong:
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 1086dd385..f82c816b3 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -12,6 +12,7 @@
"@fastify/cors": "^10.1.0",
"@fastify/multipart": "^9.4.0",
"@noble/curves": "^2.4.0",
+ "@noble/hashes": "^2.4.0",
"@prisma/client": "^5.22.0",
"@types/ws": "^8.18.1",
"dotenv": "^17.2.3",
diff --git a/backend/package.json b/backend/package.json
index e2adfb820..56891dc13 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -26,6 +26,7 @@
"@fastify/cors": "^10.1.0",
"@fastify/multipart": "^9.4.0",
"@noble/curves": "^2.4.0",
+ "@noble/hashes": "^2.4.0",
"@prisma/client": "^5.22.0",
"@types/ws": "^8.18.1",
"dotenv": "^17.2.3",
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index e266f53b1..bec1ff445 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -720,6 +720,28 @@ model HarnessSession {
@@map("harness_sessions")
}
+/// One entry of an account's device key log (lib/deviceKeyLog.ts): the identity keys its machines and
+/// viewer apps hold, append-only and hash-chained. Every device trusts the keys the log leaves active,
+/// so signing in is enough for an account's devices to reach each other end to end.
+///
+/// `entry` is the JSON the device sent, kept verbatim; its signature and hash cover a binary encoding
+/// of its fields, so nothing here depends on how Mongo orders keys. The unique `(userId, seq)` is what
+/// makes appending atomic: two devices appending at one head cannot both win.
+model DeviceKeyLogEntry {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ userId String
+ seq Int
+ hash String
+ entry String
+ /// The Harness session (a phone signed in by a QR) that added this key, so removing the key signs
+ /// that session out too. Null for anything else.
+ sessionId String?
+ createdAt DateTime @default(now())
+
+ @@unique([userId, seq])
+ @@map("device_key_log")
+}
+
/// Public/private link metadata only. The owner daemon keeps the final policy and encrypted discussion.
model HarnessLink {
id String @id @map("_id")
diff --git a/backend/src/lib/adapterAccountPushes.test.ts b/backend/src/lib/adapterAccountPushes.test.ts
index a02a01488..2beaf67d2 100644
--- a/backend/src/lib/adapterAccountPushes.test.ts
+++ b/backend/src/lib/adapterAccountPushes.test.ts
@@ -1,10 +1,13 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const m = vi.hoisted(() => ({
- desk: vi.fn(), zoo: vi.fn(), machines: vi.fn(),
- deskUnsub: vi.fn(), zooUnsub: vi.fn(), machinesUnsub: vi.fn(),
+ desk: vi.fn(), zoo: vi.fn(), machines: vi.fn(), keys: vi.fn(),
+ deskUnsub: vi.fn(), zooUnsub: vi.fn(), machinesUnsub: vi.fn(), keysUnsub: vi.fn(),
+}))
+vi.mock('./bus.js', () => ({
+ subscribeDeskChanged: m.desk, subscribeZooChanged: m.zoo, subscribeDeviceMachineListChanged: m.machines,
+ subscribeDeviceKeysChanged: m.keys,
}))
-vi.mock('./bus.js', () => ({ subscribeDeskChanged: m.desk, subscribeZooChanged: m.zoo, subscribeDeviceMachineListChanged: m.machines }))
import { relayAccountPushes } from './adapterAccountPushes.js'
@@ -17,6 +20,7 @@ describe('account pushes on a daemon socket', () => {
m.desk.mockResolvedValue(m.deskUnsub)
m.zoo.mockResolvedValue(m.zooUnsub)
m.machines.mockResolvedValue(m.machinesUnsub)
+ m.keys.mockResolvedValue(m.keysUnsub)
})
it('listens on the channels of the account that owns the socket', async () => {
@@ -24,6 +28,14 @@ describe('account pushes on a daemon socket', () => {
expect(m.desk).toHaveBeenCalledWith('user-1', expect.any(Function))
expect(m.zoo).toHaveBeenCalledWith('user-1', expect.any(Function))
expect(m.machines).toHaveBeenCalledWith('user-1', expect.any(Function))
+ expect(m.keys).toHaveBeenCalledWith('user-1', expect.any(Function))
+ })
+
+ it('hands the daemon a device-key-log change with the new head, for the daemon itself to re-read', async () => {
+ const send = vi.fn()
+ await relayAccountPushes('user-1', send, on)
+ m.keys.mock.calls[0][1]({ seq: 4, hash: 'h' })
+ expect(send).toHaveBeenCalledWith({ t: 'down', connId: '', frame: { type: 'device_keys_changed', payload: { seq: 4, hash: 'h' } } })
})
it('hands the daemon a desk change as a connection-less down frame carrying the revision', async () => {
@@ -54,6 +66,7 @@ describe('account pushes on a daemon socket', () => {
expect(m.deskUnsub).toHaveBeenCalledOnce()
expect(m.zooUnsub).toHaveBeenCalledOnce()
expect(m.machinesUnsub).toHaveBeenCalledOnce()
+ expect(m.keysUnsub).toHaveBeenCalledOnce()
})
it('does not leave the earlier subscriptions behind when a later subscribe fails', async () => {
diff --git a/backend/src/lib/adapterAccountPushes.ts b/backend/src/lib/adapterAccountPushes.ts
index 8fc9a28cc..9f8ec7fb0 100644
--- a/backend/src/lib/adapterAccountPushes.ts
+++ b/backend/src/lib/adapterAccountPushes.ts
@@ -1,4 +1,4 @@
-import { subscribeDeskChanged, subscribeDeviceMachineListChanged, subscribeZooChanged } from './bus.js'
+import { subscribeDeskChanged, subscribeDeviceKeysChanged, subscribeDeviceMachineListChanged, subscribeZooChanged } from './bus.js'
/**
* The pushes a daemon socket carries for its ACCOUNT rather than for its machine: something the
@@ -14,6 +14,8 @@ import { subscribeDeskChanged, subscribeDeviceMachineListChanged, subscribeZooCh
* - `machines_changed` — the account's machine list: a machine created / renamed / deleted, or a
* shared harness invited / taken back (routes/harnessShares.ts pokes the recipient). This is what
* lets the app discover invitations without polling `/api/machines` + `/api/harness-shares`.
+ * - `device_keys_changed` — the account's device key log grew (lib/deviceKeyLog.ts). Unlike the rest it
+ * is for the DAEMON itself, which trusts the keys the log holds: it re-reads from its own head.
*
* `zoo` is the server's daemons switch (lib/daemonsSwitch.ts): off, the zoo channel is not even listened
* on, since nothing publishes it.
@@ -35,6 +37,9 @@ export async function relayAccountPushes(userId: string, send: (frame: unknown)
unsubs.push(await subscribeDeviceMachineListChanged(userId, (msg) => {
send({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: msg.reason } } })
}))
+ unsubs.push(await subscribeDeviceKeysChanged(userId, (msg) => {
+ send({ t: 'down', connId: '', frame: { type: 'device_keys_changed', payload: { seq: msg.seq, hash: msg.hash } } })
+ }))
} catch (err) {
stop()
throw err
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index f1c06aa3b..20481f6dc 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -38,6 +38,7 @@ import { relayAccountPushes } from './adapterAccountPushes.js'
import { DAEMONS } from '../config/env.js'
import { parseAutonomousEnvironment } from './autonomousEnvironment.js'
import { machineService } from '../services/MachineService.js'
+import { appendDeviceKey } from './deviceKeyLog.js'
import { AppError } from '../errors/index.js'
import {
isEncryptedTerminalFrame,
@@ -224,6 +225,13 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
return ++turnWindowCount <= TURN_WRITES_PER_MINUTE
}
const p2pSignalRate = new P2pSignalRateGuard()
+ // A machine appends its own key once per sign-in, a removal when someone asks for one: a few a minute
+ // is generous, and it keeps a looping daemon from rebuilding the log on every frame.
+ const devlogRate = { windowStart: 0, count: 0, allow(): boolean {
+ const now = Date.now()
+ if (now - this.windowStart >= 60_000) { this.windowStart = now; this.count = 0 }
+ return ++this.count <= 10
+ } }
// Buffer messages from RIGHT NOW, because the real handler cannot be installed until after the
// `await attachNodeRole(...)` below — and `ws` drops any message emitted with no listener attached.
@@ -434,6 +442,26 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
touchUserPresence(kind as 'open' | 'ping')
return
}
+ // The machine appending to its account's device key log (lib/deviceKeyLog.ts): its own key, or a
+ // removal it signs. Over THIS socket so the entry is tied to the machine that sent it — a
+ // machine can only register a key under its own id. Answered to the machine alone, never published.
+ if (app.type === 'devlog_append') {
+ const p = (app.payload ?? {}) as { requestId?: unknown; entry?: unknown }
+ const requestId = typeof p.requestId === 'string' ? p.requestId.slice(0, 64) : ''
+ if (!devlogRate.allow()) {
+ send({ t: 'down', connId: '', frame: { type: 'devlog_append_result', payload: { requestId, error: 'RATE_LIMITED' } } })
+ return
+ }
+ void appendDeviceKey(userId, p.entry, { kind: 'machine', machineId })
+ .then((r) => send({ t: 'down', connId: '', frame: { type: 'devlog_append_result', payload: r.ok
+ ? { requestId, head: r.head }
+ : { requestId, error: r.code, ...('head' in r ? { head: r.head } : {}) } } }))
+ .catch((err) => {
+ logger.warn('devlog append failed', { machineId, error: String(err) })
+ send({ t: 'down', connId: '', frame: { type: 'devlog_append_result', payload: { requestId, error: 'UNAVAILABLE' } } })
+ })
+ return
+ }
// Hub tap (mirrors managerWs): keep `machine_agents` in sync from the adapter's agent
// lifecycle frames. Needed so the device voice path's agent-ownership check
// (deviceWs: `machineAgent.findFirst`) recognizes remote tmux sessions.
diff --git a/backend/src/lib/backendOnlyFrames.ts b/backend/src/lib/backendOnlyFrames.ts
index 91f6792f5..2d3a71dc5 100644
--- a/backend/src/lib/backendOnlyFrames.ts
+++ b/backend/src/lib/backendOnlyFrames.ts
@@ -7,9 +7,10 @@
*
* Senders, all backend-side: `lib/adapterWs.ts` (on connect), `services/MachineService.ts`
* (rename, revoke) and `lib/adapterAccountPushes.ts` (desk_changed, zoo_changed, machines_changed —
- * forged, each one makes every window on that computer re-read from this backend).
+ * forged, each one makes every window on that computer re-read from this backend, device_keys_changed),
+ * and `lib/adapterWs.ts` again for `devlog_append_result`, the answer to a machine's own log append.
*/
-export const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'zoo_changed', 'machines_changed'])
+export const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'zoo_changed', 'machines_changed', 'device_keys_changed', 'devlog_append_result'])
/** A type no client may send down: the backend's own `__` control frames and the named ones above. */
export function isBackendOnlyDownType(type: unknown): boolean {
diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.ts
index f8bf563c4..c1ac43cd0 100644
--- a/backend/src/lib/bus.ts
+++ b/backend/src/lib/bus.ts
@@ -682,6 +682,20 @@ export function subscribeZooChanged(userId: string, cb: (msg: ZooChangedMsg) =>
return addSub(zooChannel(userId), cb as Cb)
}
+// Per-USER device key log invalidation: an entry was appended to the account's log (lib/deviceKeyLog.ts).
+// Every device re-reads from its own head, so the message only needs the new head to decide whether to.
+export interface DeviceKeysChangedMsg { seq: number; hash: string }
+
+const deviceKeysChannel = (userId: string): string => `devkeys:${userId}`
+
+export function publishDeviceKeysChanged(userId: string, msg: DeviceKeysChangedMsg): Promise<number> {
+ return safePublish(deviceKeysChannel(userId), JSON.stringify(msg))
+}
+
+export function subscribeDeviceKeysChanged(userId: string, cb: (msg: DeviceKeysChangedMsg) => void): Promise<() => void> {
+ return addSub(deviceKeysChannel(userId), cb as Cb)
+}
+
export interface DeviceE2eePairMsg {
kind: 'pending' | 'cleared'
machineId: string
diff --git a/backend/src/lib/deviceKeyLog.test.ts b/backend/src/lib/deviceKeyLog.test.ts
new file mode 100644
index 000000000..d37b1fc28
--- /dev/null
+++ b/backend/src/lib/deviceKeyLog.test.ts
@@ -0,0 +1,174 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { ed25519 } from '@noble/curves/ed25519.js'
+
+type Row = { userId: string; seq: number; hash: string; entry: string; sessionId: string | null }
+const m = vi.hoisted(() => ({
+ rows: [] as Array<{ userId: string; seq: number; hash: string; entry: string; sessionId: string | null }>,
+ failNextCreate: null as unknown,
+ publishChanged: vi.fn(), publishDown: vi.fn(), revoke: vi.fn(),
+ seen: {} as Record<string, Record<string, string>>,
+ hsetCalls: 0,
+}))
+vi.mock('./prisma.js', () => ({
+ prisma: {
+ deviceKeyLogEntry: {
+ findMany: vi.fn(async ({ where }: { where: { userId: string; seq?: { gt: number } } }) =>
+ m.rows.filter(r => r.userId === where.userId && r.seq > (where.seq?.gt ?? 0)).sort((a, b) => a.seq - b.seq)),
+ findFirst: vi.fn(async ({ where }: { where: { userId: string } }) =>
+ m.rows.filter(r => r.userId === where.userId).sort((a, b) => b.seq - a.seq)[0] ?? null),
+ create: vi.fn(async ({ data }: { data: Row }) => {
+ if (m.failNextCreate) { const err = m.failNextCreate; m.failNextCreate = null; throw err }
+ m.rows.push(data); return data
+ }),
+ },
+ harnessSession: { updateMany: m.revoke },
+ },
+}))
+vi.mock('./bus.js', () => ({
+ publishDeviceKeysChanged: m.publishChanged,
+ publishDown: m.publishDown,
+ pub: {
+ multi: () => {
+ const ops: Array<() => void> = []
+ const chain = {
+ hset: (key: string, field: string, value: string) => { ops.push(() => { m.hsetCalls++; (m.seen[key] ??= {})[field] = value }); return chain },
+ expire: () => chain,
+ exec: async () => { for (const op of ops) op(); return [] },
+ }
+ return chain
+ },
+ hgetall: async (key: string) => m.seen[key] ?? {},
+ },
+}))
+import { appendDeviceKey, deviceKeysSeen, readDeviceKeyLog, touchDeviceKey } from './deviceKeyLog.js'
+import { emptyDevLogState, nextDevLogEntry, signDevLogEntry, applyDevLogEntries, type DevLogState } from './deviceLogCore.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)) } }
+const box1 = key(1), box2 = key(2), phone = key(3)
+const USER = 'user-1'
+const MID1 = 'a'.repeat(32), MID2 = 'b'.repeat(32)
+
+async function state(): Promise<DevLogState> {
+ const { entries } = await readDeviceKeyLog(USER, 0)
+ return applyDevLogEntries(emptyDevLogState(USER), entries).state
+}
+async function addEntry(k: { priv: Uint8Array; pub: string }, kind: 'machine' | 'viewer', machineId: string, label: string) {
+ return signDevLogEntry(nextDevLogEntry(await state(), { op: 'add', pub: k.pub, kind, machineId, label, signer: k.pub }, 1_000), k.priv)
+}
+async function removeEntry(target: string, by: { priv: Uint8Array; pub: string }) {
+ const s = await state()
+ const t = s.active[target]
+ return signDevLogEntry(nextDevLogEntry(s, { op: 'remove', pub: t.pub, kind: t.kind, machineId: t.machineId, label: t.label, signer: by.pub }, 2_000), by.priv)
+}
+
+describe('appendDeviceKey', () => {
+ beforeEach(() => {
+ m.rows.length = 0
+ m.failNextCreate = null
+ m.seen = {}
+ m.hsetCalls = 0
+ vi.clearAllMocks()
+ m.publishChanged.mockResolvedValue(1)
+ m.publishDown.mockResolvedValue(1)
+ m.revoke.mockResolvedValue({ count: 1 })
+ })
+
+ it('lets a machine add its own key over its socket and pushes the new head', async () => {
+ const r = await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })
+ expect(r).toMatchObject({ ok: true, head: { seq: 1 } })
+ expect(m.publishChanged).toHaveBeenCalledWith(USER, (r as { head: unknown }).head)
+ expect((await readDeviceKeyLog(USER, 0)).entries).toHaveLength(1)
+ })
+
+ it('refuses a machine registering a key under another machine id', async () => {
+ const r = await appendDeviceKey(USER, await addEntry(box1, 'machine', MID2, 'box2?'), { kind: 'machine', machineId: MID1 })
+ expect(r).toMatchObject({ ok: false, status: 403, code: 'WRONG_CHANNEL' })
+ expect(m.rows).toHaveLength(0)
+ })
+
+ it('refuses a machine entry over the viewer channel', async () => {
+ const r = await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'viewer' })
+ expect(r).toMatchObject({ ok: false, status: 403, code: 'WRONG_CHANNEL' })
+ })
+
+ it('refuses an entry for another account', async () => {
+ const e = await addEntry(phone, 'viewer', '', 'phone')
+ const r = await appendDeviceKey('someone-else', e, { kind: 'viewer' })
+ expect(r).toMatchObject({ ok: false, status: 400, code: 'WRONG_ACCOUNT' })
+ })
+
+ it('answers a stale head with 409 and the current head', async () => {
+ const stale = await addEntry(phone, 'viewer', '', 'phone')
+ await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })
+ const r = await appendDeviceKey(USER, stale, { kind: 'viewer' })
+ expect(r).toMatchObject({ ok: false, status: 409, code: 'STALE_HEAD', head: { seq: 1 } })
+ })
+
+ it('answers a lost insert race with 409', async () => {
+ m.failNextCreate = Object.assign(new Error('Unique constraint failed'), { code: 'P2002' })
+ const r = await appendDeviceKey(USER, await addEntry(phone, 'viewer', '', 'phone'), { kind: 'viewer' })
+ expect(r).toMatchObject({ ok: false, status: 409, code: 'STALE_HEAD' })
+ expect(m.publishChanged).not.toHaveBeenCalled()
+ })
+
+ it('refuses a tampered entry', async () => {
+ const e = { ...(await addEntry(phone, 'viewer', '', 'phone')), label: 'evil' }
+ expect(await appendDeviceKey(USER, e, { kind: 'viewer' })).toMatchObject({ ok: false, status: 400, code: 'BAD_SIGNATURE' })
+ })
+
+ it('signs a removed machine out', async () => {
+ await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })
+ await appendDeviceKey(USER, await addEntry(box2, 'machine', MID2, 'box2'), { kind: 'machine', machineId: MID2 })
+ const r = await appendDeviceKey(USER, await removeEntry(box2.pub, box1), { kind: 'machine', machineId: MID1 })
+ expect(r).toMatchObject({ ok: true, head: { seq: 3 } })
+ expect(m.publishDown).toHaveBeenCalledWith(MID2, { connId: '', frame: { type: 'machine_revoked', payload: { reason: 'device_removed', pub: box2.pub } } })
+ })
+
+ it('refuses a machine signing a removal with another machine key', async () => {
+ await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })
+ await appendDeviceKey(USER, await addEntry(box2, 'machine', MID2, 'box2'), { kind: 'machine', machineId: MID2 })
+ const r = await appendDeviceKey(USER, await removeEntry(box2.pub, box1), { kind: 'machine', machineId: MID2 })
+ expect(r).toMatchObject({ ok: false, status: 403, code: 'WRONG_CHANNEL' })
+ })
+
+ it('ends the Harness session of a removed phone', async () => {
+ await appendDeviceKey(USER, await addEntry(phone, 'viewer', '', 'phone'), { kind: 'viewer', harnessSessionId: 'sess-1' })
+ await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })
+ await appendDeviceKey(USER, await removeEntry(phone.pub, box1), { kind: 'machine', machineId: MID1 })
+ expect(m.revoke).toHaveBeenCalledWith({ where: { id: 'sess-1', userId: USER, OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }, data: { revokedAt: expect.any(Date) } })
+ expect(m.publishDown).not.toHaveBeenCalled()
+ })
+
+ it('reads from a head, with the head itself', async () => {
+ await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })
+ await appendDeviceKey(USER, await addEntry(phone, 'viewer', '', 'phone'), { kind: 'viewer' })
+ const page = await readDeviceKeyLog(USER, 1)
+ expect(page.acct).toBe(USER)
+ expect(page.head.seq).toBe(2)
+ expect(page.entries).toHaveLength(1)
+ expect((await readDeviceKeyLog('nobody', 0)).head.seq).toBe(0)
+ })
+})
+
+describe('when a key was last seen', () => {
+ beforeEach(() => { m.seen = {}; m.hsetCalls = 0 })
+
+ it('records a key once per hour, and reads it back', async () => {
+ const pubKey = key(7).pub
+ touchDeviceKey('user-seen', pubKey, 1_000_000)
+ touchDeviceKey('user-seen', pubKey, 1_000_000 + 60_000)
+ await vi.waitFor(() => expect(m.hsetCalls).toBe(1))
+ expect(await deviceKeysSeen('user-seen')).toEqual({ [pubKey]: 1_000_000 })
+ touchDeviceKey('user-seen', pubKey, 1_000_000 + 2 * 60 * 60 * 1000)
+ await vi.waitFor(() => expect(m.hsetCalls).toBe(2))
+ })
+
+ it('ignores anything that is not a key', async () => {
+ touchDeviceKey('user-seen-2', 'not a key')
+ touchDeviceKey('user-seen-2', undefined)
+ expect(await deviceKeysSeen('user-seen-2')).toEqual({})
+ })
+})
diff --git a/backend/src/lib/deviceKeyLog.ts b/backend/src/lib/deviceKeyLog.ts
new file mode 100644
index 000000000..99ca5c7a3
--- /dev/null
+++ b/backend/src/lib/deviceKeyLog.ts
@@ -0,0 +1,165 @@
+import { prisma } from './prisma.js'
+import { pub, publishDeviceKeysChanged, publishDown } from './bus.js'
+import { logger } from '../utils/logger.js'
+import {
+ applyDevLogEntries, DevLogError, emptyDevLogState, parseDevLogEntry,
+ type DevLogEntry, type DevLogHead, type DevLogState,
+} from './deviceLogCore.js'
+
+/**
+ * The account's device key log, as the backend keeps it (the format and every rule are
+ * lib/deviceLogCore.ts). This side stores and serves it, and refuses an entry that breaks a rule, so a
+ * device never has to throw a bad one away — but no device takes the backend's word for anything: each
+ * verifies the whole chain itself, and gossips the head with the others.
+ *
+ * Who may append what is decided by the CHANNEL, on top of the signatures:
+ * - a machine appends over its own adapter socket, and only about ITSELF (`kind: 'machine'`, its own
+ * machineId) — so no device can register a key under another machine's id;
+ * - a viewer app appends over REST, only `kind: 'viewer'` entries, and signs removals with a viewer key.
+ */
+
+/** A page is enough for any real account (256 active keys at most); a device asks again from its head. */
+const PAGE = 500
+
+export type DeviceKeyAppendError =
+ | { status: 409; code: 'STALE_HEAD'; head: DevLogHead }
+ | { status: 400; code: string }
+ | { status: 403; code: 'WRONG_CHANNEL' }
+
+export type DeviceKeyAppendResult = { ok: true; head: DevLogHead } | ({ ok: false } & DeviceKeyAppendError)
+
+/** Who is appending: a machine over its adapter socket, or a viewer over REST. */
+export type DeviceKeyChannel =
+ | { kind: 'machine'; machineId: string }
+ | { kind: 'viewer'; harnessSessionId?: string }
+
+export async function readDeviceKeyLog(userId: string, since: number): Promise<{ acct: string; head: DevLogHead; entries: unknown[] }> {
+ const [rows, last] = await Promise.all([
+ prisma.deviceKeyLogEntry.findMany({ where: { userId, seq: { gt: since } }, orderBy: { seq: 'asc' }, take: PAGE }),
+ prisma.deviceKeyLogEntry.findFirst({ where: { userId }, orderBy: { seq: 'desc' }, select: { seq: true, hash: true } }),
+ ])
+ const head = last ?? emptyDevLogState(userId).head
+ return { acct: userId, head: { seq: head.seq, hash: head.hash }, entries: rows.map(r => JSON.parse(r.entry) as unknown) }
+}
+
+/** The whole log, verified. It is small and read only when something is appended. */
+async function currentState(userId: string): Promise<{ state: DevLogState; sessions: Map<string, string> }> {
+ const rows = await prisma.deviceKeyLogEntry.findMany({ where: { userId }, orderBy: { seq: 'asc' } })
+ const { state } = applyDevLogEntries(emptyDevLogState(userId), rows.map(r => JSON.parse(r.entry) as unknown))
+ const sessions = new Map<string, string>()
+ for (const r of rows) {
+ const e = JSON.parse(r.entry) as DevLogEntry
+ if (r.sessionId && e.op === 'add') sessions.set(e.pub, r.sessionId)
+ }
+ return { state, sessions }
+}
+
+function channelAllows(entry: DevLogEntry, state: DevLogState, channel: DeviceKeyChannel): boolean {
+ const signer = state.active[entry.signer]
+ if (channel.kind === 'machine') {
+ // A machine speaks only as itself: its own key, under its own id.
+ if (entry.op === 'add') return entry.kind === 'machine' && entry.machineId === channel.machineId
+ return signer?.kind === 'machine' && signer.machineId === channel.machineId
+ }
+ if (entry.op === 'add') return entry.kind === 'viewer'
+ return signer?.kind === 'viewer'
+}
+
+function isUniqueViolation(err: unknown): boolean {
+ return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'P2002'
+}
+
+export async function appendDeviceKey(userId: string, raw: unknown, channel: DeviceKeyChannel): Promise<DeviceKeyAppendResult> {
+ const entry = parseDevLogEntry(raw)
+ if (!entry) return { ok: false, status: 400, code: 'BAD_ENTRY' }
+ if (entry.acct !== userId) return { ok: false, status: 400, code: 'WRONG_ACCOUNT' }
+ const { state, sessions } = await currentState(userId)
+ if (entry.seq !== state.head.seq + 1 || entry.prev !== state.head.hash) {
+ return { ok: false, status: 409, code: 'STALE_HEAD', head: state.head }
+ }
+ if (!channelAllows(entry, state, channel)) return { ok: false, status: 403, code: 'WRONG_CHANNEL' }
+ let applied
+ try {
+ applied = applyDevLogEntries(state, [entry])
+ } catch (err) {
+ if (err instanceof DevLogError) return { ok: false, status: 400, code: err.code }
+ throw err
+ }
+ const head = applied.state.head
+ try {
+ await prisma.deviceKeyLogEntry.create({
+ data: {
+ userId, seq: entry.seq, hash: head.hash, entry: JSON.stringify(entry),
+ sessionId: entry.op === 'add' && channel.kind === 'viewer' ? channel.harnessSessionId ?? null : null,
+ },
+ })
+ } catch (err) {
+ // Another device appended at this head first.
+ if (isUniqueViolation(err)) {
+ const { state: now } = await currentState(userId)
+ return { ok: false, status: 409, code: 'STALE_HEAD', head: now.head }
+ }
+ throw err
+ }
+ await publishDeviceKeysChanged(userId, head).catch(() => { /* best effort: devices also re-read on their own */ })
+ touchDeviceKey(userId, entry.signer)
+ for (const gone of applied.removed) await signOut(userId, gone.kind, gone.machineId, gone.pub, sessions.get(gone.pub))
+ logger.info('device key log appended', { userId, seq: entry.seq, op: entry.op, kind: entry.kind })
+ return { ok: true, head }
+}
+
+/**
+ * A removed key is banned from the log for good, which is what keeps it out. Signing the device out is
+ * on top of that, where the backend can: a machine is told to drop its sign-in (the same frame a deleted
+ * machine gets), a phone signed in by a QR loses its session. An Autonomous sign-in is not ours to end.
+ */
+async function signOut(userId: string, kind: string, machineId: string, pubKey: string, sessionId: string | undefined): Promise<void> {
+ try {
+ if (kind === 'machine' && machineId) {
+ // Named, so the machine knows its KEY is gone (not just its sign-in) and signs in again with a new
+ // one; a daemon that predates the log reads only the type, as for a deleted machine.
+ await publishDown(machineId, { connId: '', frame: { type: 'machine_revoked', payload: { reason: 'device_removed', pub: pubKey } } })
+ } else if (sessionId) {
+ await prisma.harnessSession.updateMany({ where: { id: sessionId, userId, OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }, data: { revokedAt: new Date() } })
+ }
+ } catch (err) {
+ logger.warn('device key removal sign-out failed', { userId, kind, error: String(err) })
+ }
+}
+
+// ── when each key was last seen ────────────────────────────────────────────────────────────────────
+// A viewer app whose browser data was cleared never signs its own removal: its key stays active in
+// the log, unused, forever. The Devices list offers to remove the ones not seen in a long while, and
+// this is what "seen" means: the key opened an E2EE session (`e2e_hello` carries it in the clear, on
+// its way to a machine). Only a hint for that list — nothing trusts or distrusts a key by it — so a
+// client claiming someone else's key here can at most keep that one off the suggestion.
+
+const SEEN_TTL_SEC = 400 * 24 * 60 * 60
+/** One write per key per this long, per process: a phone opens a session per machine it shows. */
+const SEEN_WRITE_EVERY_MS = 60 * 60 * 1000
+const SEEN_MEMORY_MAX = 10_000
+const seenWritten = new Map<string, number>()
+const seenKey = (userId: string): string => `devkeys:seen:${userId}`
+const PUB_RE = /^[A-Za-z0-9+/]{43}=$/
+
+export function touchDeviceKey(userId: string, pubKey: unknown, now = Date.now()): void {
+ if (typeof pubKey !== 'string' || !PUB_RE.test(pubKey)) return
+ const memo = `${userId}:${pubKey}`
+ const last = seenWritten.get(memo)
+ if (last !== undefined && now - last < SEEN_WRITE_EVERY_MS) return
+ if (seenWritten.size >= SEEN_MEMORY_MAX) seenWritten.clear()
+ seenWritten.set(memo, now)
+ void pub.multi().hset(seenKey(userId), pubKey, String(now)).expire(seenKey(userId), SEEN_TTL_SEC).exec()
+ .catch(() => { seenWritten.delete(memo) })
+}
+
+/** When each of the account's keys was last seen, by pub (ms). Empty when nothing was recorded. */
+export async function deviceKeysSeen(userId: string): Promise<Record<string, number>> {
+ const raw = await pub.hgetall(seenKey(userId))
+ const out: Record<string, number> = {}
+ for (const [k, v] of Object.entries(raw ?? {})) {
+ const n = Number(v)
+ if (PUB_RE.test(k) && Number.isSafeInteger(n) && n > 0) out[k] = n
+ }
+ return out
+}
diff --git a/backend/src/lib/deviceLog.vectors.json b/backend/src/lib/deviceLog.vectors.json
new file mode 100644
index 000000000..223b62521
--- /dev/null
+++ b/backend/src/lib/deviceLog.vectors.json
@@ -0,0 +1,375 @@
+{
+ "comment": "Generated by cli/scripts/gen-devlog-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4, box2b=5).",
+ "acct": "acct-vectors-1",
+ "seeds": {
+ "box1": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
+ "box2": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=",
+ "browser": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "stranger": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ=",
+ "box2b": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU="
+ },
+ "pubs": {
+ "box1": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "box2": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "browser": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "stranger": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "box2b": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E="
+ },
+ "valid": {
+ "entries": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 1000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "PQ79548gYy1fR00xYYrAqGYQer//uS3fGo1Xwwih7v6Jpw8lLHsM/plOYoenu8qjIWhPTSPlVSghlAt9C6MMCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 2000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "bHi9oSluvJ/RKgTw7RZrPaplcR45FGkVMmnOjm4dQnTzchKsMN6D6WKTNphHLjthUYhcznmjIJDLjplJ5TKsAg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 3000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "Browser · macOS — “Dee”",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "NK0FM6TeU5KyGr78swAvqDRYvHQafuMj/pBBxMANdNdALGrcA3pA+h4WMarQT81Ker2W0ALWvAcufmSkOxjiCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "qNFvpVnzstkVYeTrds5NiQ6EyfyImRIhjndzUjzO/eA=",
+ "at": 4000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1 (renamed)",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "ccsh5GRy/OZkP+l50LN90T+8O1Ca0dcOmdm2pCJlF1ccTNC+ZPwoZ3NujkS2uJORP/xwu9xZ7gSqBhQ3XaWzCg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 5,
+ "prev": "NiCtLf6zNhboU5bHOg8pggpUZxeuey5a0KGQ4lHyehE=",
+ "at": 5000,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "1LAIjj3C77/H5v7LxR1QFYfxTrjJbRFTdk/0nvAmTIOYAoH42xLvqwh3e8bHsvH32GmfNNvARRSGTuXKTkZMBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 6,
+ "prev": "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "at": 6000,
+ "op": "add",
+ "pub": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "sig": "cwe4qUy9BDLShHXA8IhIMxs/ZbdF/a2Js7IqpQyNBV/FjcCS/eoGDEufpS0+sPPAhDlky2K1vpgwVS0PIakyCw=="
+ }
+ ],
+ "hashes": [
+ "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "qNFvpVnzstkVYeTrds5NiQ6EyfyImRIhjndzUjzO/eA=",
+ "NiCtLf6zNhboU5bHOg8pggpUZxeuey5a0KGQ4lHyehE=",
+ "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "f5WzxT87hry0q9rj895yyaiCax/xP2PRZCCfpGPKDTw="
+ ],
+ "head": {
+ "seq": 6,
+ "hash": "f5WzxT87hry0q9rj895yyaiCax/xP2PRZCCfpGPKDTw="
+ },
+ "active": [
+ "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w="
+ ],
+ "removed": [
+ "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q="
+ ]
+ },
+ "invalid": [
+ {
+ "name": "tampered label",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "evil",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "udynDrC1h7IK8lrCs+AqPLpTCNeQxD4DlkQP6BOQZD+oNquOndvYqEPmU60wE9JTin8YYVFboZ6jyzxl5YSQAw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "add signed by another key",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "RL5wtkxLhLIkWpUBZ+njRYIh0KqeuYc1pIoEQQ9oAfs2xFa5UwpLJhI4sia2HXI+dovYK+igVD0HnE4QoF3BDA=="
+ },
+ "code": "NOT_SELF_SIGNED"
+ },
+ {
+ "name": "machine id of another active machine",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "imposter",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "KJulD+38Nt9i6HNhMZwVemE3wXIrLOLsMbd1A2BxIC4hke7aKwN6itY04iSRbLqOGlDzOPwi0GUGj0ZrW0DcCQ=="
+ },
+ "code": "MACHINE_TAKEN"
+ },
+ {
+ "name": "removed key comes back",
+ "after": 5,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 6,
+ "prev": "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "at": 9000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2 again",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "AyV+EkrCunkAI12uokVnsclD26e2n5ZDIvNqxxoABvxdvgDvSXnXDdJ8EVFFro3FK9ROh0ATNh3FQVoUWa/9CQ=="
+ },
+ "code": "KEY_REMOVED"
+ },
+ {
+ "name": "remove signed by a key not in the log",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "remove",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "xkp6fed+m63wylf9c1Zaz3YXtwPhOgbMzpKqCkXuNo06UfKfPmJx4/BD2OY+Wt+E03hUUrB438ME1gLjzp4VBg=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "remove of a key not in the log",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "remove",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "Vh2WinwrdWHv46djCCkZ+p0QtWlALCHXBIPHgYkSi9Zpys93JPYhaJIJhEcdQYwQuYvEF2IVtxK2um1IaQgJDg=="
+ },
+ "code": "NOT_ACTIVE"
+ },
+ {
+ "name": "wrong prev",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "nPbFpdYE1xqmdxxL8fj77CeBVrosx4N847Zy9gqngg5bBdcyqzMRsHSm/q0OTuW6VEwIzk66/OCMcwuT1HERBA=="
+ },
+ "code": "BROKEN_CHAIN"
+ },
+ {
+ "name": "skipped seq",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "wJqA4rLVUCIewTr/eeeMxSKX2yv9wQOFhqGVws0+1QITAdgkZwGNIWbpBptIlFrcNyh3oRTFMdGWykfeqkTcAA=="
+ },
+ "code": "OUT_OF_ORDER"
+ },
+ {
+ "name": "other account",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-other",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "eXH3aVMs0jDDzFg3xehB+Z7G6h2jyvjZcHGm128CIvVwcWDSytwHRAY+g4iXpYkBeJxhksoCOdgpNQds69xMDQ=="
+ },
+ "code": "WRONG_ACCOUNT"
+ },
+ {
+ "name": "machine changes kind",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "c2mJ6r5OoEW7bY0EERqWBt8z37H5ExY59f5KiP6mtRSv5adSQjT5HxzlGXgcILOjLUPIFijE16cGPM++CdJXCg=="
+ },
+ "code": "KIND_CHANGED"
+ },
+ {
+ "name": "re-add with nothing changed",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "fjF5dBSdSDddFJdLDmYWaleR4RniUf62lI0Fbdb4vTkXp8cXo4rwqAcGncZt5yCHOK2F7pYg56FUbbospfIuAg=="
+ },
+ "code": "NO_CHANGE"
+ },
+ {
+ "name": "viewer with a machine id",
+ "after": 0,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 9000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "b",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "2t+mAiwKKqhImNoq+7HVp7bXdf1UeL7Vd4QOmEiS1fsGG1Ux6+HVKjosKKzX/wzQo9ju84Yd3x12teETgIsjAQ=="
+ },
+ "code": "BAD_ENTRY"
+ },
+ {
+ "name": "control character in label",
+ "after": 0,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 9000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "a\nb",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "lzDA+QfWL9V5issDES2f9vRw/CX2Tv6dk8nF6ZmwcJ87kyegBoWh1TkUL6RXVS+8vacy9vLJd+keCMwpsCOqAA=="
+ },
+ "code": "BAD_ENTRY"
+ }
+ ]
+}
diff --git a/backend/src/lib/deviceLogCore.test.ts b/backend/src/lib/deviceLogCore.test.ts
new file mode 100644
index 000000000..c66ca0ff3
--- /dev/null
+++ b/backend/src/lib/deviceLogCore.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { applyDevLogEntries, DevLogError, devLogHash, emptyDevLogState } from './deviceLogCore.js'
+
+// The same fixture the CLI and both Dart ports are held to (cli/scripts/gen-devlog-vectors.ts).
+const vectors = JSON.parse(readFileSync(join(import.meta.dirname, 'deviceLog.vectors.json'), 'utf-8'))
+
+describe('device log core against the shared vectors', () => {
+ it('applies every valid entry to the fixture hashes, head and active set', () => {
+ const { state } = applyDevLogEntries(emptyDevLogState(vectors.acct), vectors.valid.entries)
+ expect(state.hashes).toEqual(vectors.valid.hashes)
+ expect(state.head).toEqual(vectors.valid.head)
+ expect(Object.keys(state.active).sort()).toEqual(vectors.valid.active)
+ expect(state.removed).toEqual(vectors.valid.removed)
+ vectors.valid.entries.forEach((e: never, i: number) => expect(devLogHash(e)).toBe(vectors.valid.hashes[i]))
+ })
+
+ for (const c of vectors.invalid as Array<{ name: string; after: number; entry: unknown; code: string }>) {
+ it(`refuses: ${c.name} (${c.code})`, () => {
+ const base = applyDevLogEntries(emptyDevLogState(vectors.acct), vectors.valid.entries.slice(0, c.after)).state
+ let code: string | null = null
+ try { applyDevLogEntries(base, [c.entry]) } catch (err) { code = err instanceof DevLogError ? err.code : String(err) }
+ expect(code).toBe(c.code)
+ })
+ }
+})
diff --git a/backend/src/lib/deviceLogCore.ts b/backend/src/lib/deviceLogCore.ts
new file mode 100644
index 000000000..8489835fc
--- /dev/null
+++ b/backend/src/lib/deviceLogCore.ts
@@ -0,0 +1,274 @@
+/**
+ * The device key log — an account's append-only, hash-chained list of the identity keys its devices
+ * (machines and viewer apps) hold. Every device trusts the keys the log says are active, so signing in
+ * is all it takes for an account's machines to reach each other end to end, with no remote password.
+ *
+ * The backend stores and serves the log but cannot forge an entry: an `add` is signed by the key it
+ * adds, a `remove` by a key that is active at that point. What the backend CAN do — add a device of its
+ * own — is not prevented, only made visible: every device announces a key it has not trusted before
+ * ("New device: X"), and devices gossip the log's head over their E2EE sessions (`group_sync`), so a
+ * backend that shows two devices different logs, or hides an entry from one, is caught.
+ *
+ * Pure: no I/O. Signatures and hashes cover a length-prefixed binary encoding of the fields in a fixed
+ * order (as `helloSig` does) — never JSON, whose canonical form drifts between TS and Dart. JSON is
+ * only the wire format.
+ *
+ * ⚠ A copy of cli/src/lib/e2ee/deviceLog.ts, identical below the imports (noble v2 import paths here).
+ * Also ported to Dart (desktop/lib/viewer/device_log.dart, mobile/lib/viewer/device_log.dart). All of them are
+ * held to deviceLog.vectors.json; change the format in every copy together.
+ */
+import { ed25519 } from '@noble/curves/ed25519.js'
+import { sha256 } from '@noble/hashes/sha2.js'
+
+export const DEVLOG_VERSION = 1
+/** How many keys one account may have active at once. */
+export const DEVLOG_MAX_ACTIVE = 256
+export const DEVLOG_LABEL_MAX = 60
+
+export type DevLogOp = 'add' | 'remove'
+export type DevLogKind = 'machine' | 'viewer'
+
+export interface DevLogEntry {
+ v: number
+ /** The account (backend User id) the log belongs to. */
+ acct: string
+ /** 1-based position in the log. */
+ seq: number
+ /** base64 hash of the previous entry; 32 zero bytes for the first. */
+ prev: string
+ op: DevLogOp
+ /** base64 Ed25519 key the entry is about. */
+ pub: string
+ kind: DevLogKind
+ /** A machine's id; '' for a viewer. */
+ machineId: string
+ label: string
+ /** Milliseconds since the epoch, as the signer's clock read it. */
+ at: number
+ /** base64 Ed25519 key that signed the entry. */
+ signer: string
+ sig: string
+}
+
+export type UnsignedDevLogEntry = Omit<DevLogEntry, 'sig'>
+
+export interface DevLogMember {
+ pub: string
+ kind: DevLogKind
+ machineId: string
+ label: string
+ /** `at` of the entry that added it. */
+ addedAt: number
+ /** seq of the entry that added it. */
+ seq: number
+}
+
+export interface DevLogHead { seq: number; hash: string }
+
+export interface DevLogState {
+ acct: string
+ head: DevLogHead
+ /** hashes[i] is the hash of the entry with seq i + 1. */
+ hashes: string[]
+ /** Active keys, by pub. */
+ active: Record<string, DevLogMember>
+ /** Keys a `remove` took out. A removed key never comes back: a device that returns uses a new one. */
+ removed: string[]
+}
+
+export type DevLogErrorCode =
+ | 'BAD_ENTRY'
+ | 'WRONG_ACCOUNT'
+ | 'OUT_OF_ORDER'
+ | 'BROKEN_CHAIN'
+ | 'BAD_SIGNATURE'
+ | 'NOT_SELF_SIGNED'
+ | 'KEY_REMOVED'
+ | 'KIND_CHANGED'
+ | 'NO_CHANGE'
+ | 'MACHINE_TAKEN'
+ | 'TOO_MANY'
+ | 'SIGNER_NOT_ACTIVE'
+ | 'NOT_ACTIVE'
+
+export class DevLogError extends Error {
+ constructor(readonly code: DevLogErrorCode, readonly seq: number) {
+ super(`device log entry ${seq}: ${code}`)
+ }
+}
+
+const HAS_BUFFER = typeof Buffer !== 'undefined'
+const MACHINE_ID_RE = /^[a-f0-9]{32}$/
+const ZERO_HASH = b64e(new Uint8Array(32))
+
+function b64e(u: Uint8Array): string {
+ if (HAS_BUFFER) return Buffer.from(u).toString('base64')
+ let s = ''
+ for (let i = 0; i < u.length; i++) s += String.fromCharCode(u[i])
+ return btoa(s)
+}
+function b64d(s: string): Uint8Array {
+ if (HAS_BUFFER) return new Uint8Array(Buffer.from(s, 'base64'))
+ const bin = atob(s)
+ const u = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i)
+ return u
+}
+/** base64 of exactly [n] bytes, in its one canonical spelling; null otherwise. */
+function bytesOf(s: unknown, n: number): Uint8Array | null {
+ if (typeof s !== 'string' || s.length > 128) return null
+ try {
+ const u = b64d(s)
+ return u.length === n && b64e(u) === s ? u : null
+ } catch { return null }
+}
+function lvCat(...parts: Array<Uint8Array | string>): Uint8Array {
+ const chunks: Uint8Array[] = []
+ let total = 0
+ for (const p of parts) {
+ const b = typeof p === 'string' ? new TextEncoder().encode(p) : p
+ const len = new Uint8Array(4)
+ new DataView(len.buffer).setUint32(0, b.length, false)
+ chunks.push(len, b)
+ total += 4 + b.length
+ }
+ const out = new Uint8Array(total)
+ let off = 0
+ for (const c of chunks) { out.set(c, off); off += c.length }
+ return out
+}
+
+/** The bytes a signature covers. Numbers are written in decimal, so every language agrees. */
+export function devLogMessage(e: UnsignedDevLogEntry): Uint8Array {
+ return lvCat(
+ 'harness-devlog-v1', String(e.v), e.acct, String(e.seq), b64d(e.prev), e.op, b64d(e.pub),
+ e.kind, e.machineId, e.label, String(e.at), b64d(e.signer),
+ )
+}
+
+/** The entry's hash: what the next entry's `prev` names. */
+export function devLogHash(e: DevLogEntry): string {
+ return b64e(sha256(lvCat(devLogMessage(e), b64d(e.sig))))
+}
+
+export function signDevLogEntry(e: UnsignedDevLogEntry, priv: Uint8Array): DevLogEntry {
+ return { ...e, sig: b64e(ed25519.sign(devLogMessage(e), priv)) }
+}
+
+export function emptyDevLogState(acct: string): DevLogState {
+ return { acct, head: { seq: 0, hash: ZERO_HASH }, hashes: [], active: {}, removed: [] }
+}
+
+/** Every field present, of its type and within bounds; null when anything is off. */
+export function parseDevLogEntry(raw: unknown): DevLogEntry | null {
+ if (!raw || typeof raw !== 'object') return null
+ const r = raw as Record<string, unknown>
+ const { v, acct, seq, prev, op, pub, kind, machineId, label, at, signer, sig } = r
+ if (v !== DEVLOG_VERSION) return null
+ if (typeof acct !== 'string' || !acct || acct.length > 128) return null
+ if (!Number.isSafeInteger(seq) || (seq as number) < 1) return null
+ if (!bytesOf(prev, 32) || !bytesOf(pub, 32) || !bytesOf(signer, 32) || !bytesOf(sig, 64)) return null
+ if (op !== 'add' && op !== 'remove') return null
+ if (kind !== 'machine' && kind !== 'viewer') return null
+ if (typeof machineId !== 'string') return null
+ if (kind === 'machine' ? !MACHINE_ID_RE.test(machineId) : machineId !== '') return null
+ // A label is shown as is: refuse control characters rather than rewrite what was signed.
+ if (typeof label !== 'string' || label.length > DEVLOG_LABEL_MAX || /[\u0000-\u001f\u007f]/.test(label)) return null
+ if (!Number.isSafeInteger(at) || (at as number) <= 0) return null
+ return {
+ v, acct, seq: seq as number, prev: prev as string, op, pub: pub as string, kind, machineId, label,
+ at: at as number, signer: signer as string, sig: sig as string,
+ }
+}
+
+function cloneState(s: DevLogState): DevLogState {
+ return { acct: s.acct, head: { ...s.head }, hashes: [...s.hashes], active: { ...s.active }, removed: [...s.removed] }
+}
+
+export interface DevLogApplied {
+ state: DevLogState
+ /** Keys that became active (a label change is not one). */
+ added: DevLogMember[]
+ /** Keys that were active and are not any more. */
+ removed: DevLogMember[]
+ /** Keys whose label changed. */
+ relabeled: DevLogMember[]
+}
+
+/**
+ * Apply [entries], in order, on top of [state]. All or nothing: the first entry that breaks a rule
+ * throws a [DevLogError] and [state] is left as it was.
+ */
+export function applyDevLogEntries(state: DevLogState, entries: readonly unknown[]): DevLogApplied {
+ const s = cloneState(state)
+ const out: DevLogApplied = { state: s, added: [], removed: [], relabeled: [] }
+ for (const raw of entries) {
+ const expectedSeq = s.head.seq + 1
+ const e = parseDevLogEntry(raw)
+ if (!e) throw new DevLogError('BAD_ENTRY', expectedSeq)
+ if (e.acct !== s.acct) throw new DevLogError('WRONG_ACCOUNT', e.seq)
+ if (e.seq !== expectedSeq) throw new DevLogError('OUT_OF_ORDER', e.seq)
+ if (e.prev !== s.head.hash) throw new DevLogError('BROKEN_CHAIN', e.seq)
+ let signed = false
+ try { signed = ed25519.verify(b64d(e.sig), devLogMessage(e), b64d(e.signer)) } catch { signed = false }
+ if (!signed) throw new DevLogError('BAD_SIGNATURE', e.seq)
+
+ if (e.op === 'add') {
+ if (e.signer !== e.pub) throw new DevLogError('NOT_SELF_SIGNED', e.seq)
+ if (s.removed.includes(e.pub)) throw new DevLogError('KEY_REMOVED', e.seq)
+ const current = s.active[e.pub]
+ if (current) {
+ if (current.kind !== e.kind || current.machineId !== e.machineId) throw new DevLogError('KIND_CHANGED', e.seq)
+ if (current.label === e.label) throw new DevLogError('NO_CHANGE', e.seq)
+ const relabeled = { ...current, label: e.label }
+ s.active[e.pub] = relabeled
+ out.relabeled.push(relabeled)
+ } else {
+ if (e.kind === 'machine' && Object.values(s.active).some(m => m.kind === 'machine' && m.machineId === e.machineId)) {
+ throw new DevLogError('MACHINE_TAKEN', e.seq)
+ }
+ if (Object.keys(s.active).length >= DEVLOG_MAX_ACTIVE) throw new DevLogError('TOO_MANY', e.seq)
+ const member: DevLogMember = { pub: e.pub, kind: e.kind, machineId: e.machineId, label: e.label, addedAt: e.at, seq: e.seq }
+ s.active[e.pub] = member
+ out.added.push(member)
+ }
+ } else {
+ if (!s.active[e.signer]) throw new DevLogError('SIGNER_NOT_ACTIVE', e.seq)
+ const gone = s.active[e.pub]
+ if (!gone) throw new DevLogError('NOT_ACTIVE', e.seq)
+ delete s.active[e.pub]
+ s.removed.push(e.pub)
+ out.removed.push(gone)
+ }
+ const hash = devLogHash(e)
+ s.hashes.push(hash)
+ s.head = { seq: e.seq, hash }
+ }
+ return out
+}
+
+/** The hash this state holds for [seq]; null when it does not reach that far. */
+export function devLogHashAt(state: DevLogState, seq: number): string | null {
+ if (seq === 0) return ZERO_HASH
+ return seq >= 1 && seq <= state.hashes.length ? state.hashes[seq - 1] : null
+}
+
+/**
+ * How another device's head relates to ours: the same log, one of us ahead of the other on the same
+ * log, or a FORK — two different entries at one position, which only a lying backend produces.
+ */
+export function compareDevLogHead(state: DevLogState, theirs: DevLogHead): 'same' | 'behind' | 'ahead' | 'fork' {
+ if (theirs.seq > state.head.seq) return 'behind'
+ const ours = devLogHashAt(state, theirs.seq)
+ if (ours !== theirs.hash) return 'fork'
+ return theirs.seq === state.head.seq ? 'same' : 'ahead'
+}
+
+/** The next entry to append on top of [state], unsigned. */
+export function nextDevLogEntry(
+ state: DevLogState,
+ fields: Pick<DevLogEntry, 'op' | 'pub' | 'kind' | 'machineId' | 'label' | 'signer'>,
+ at: number,
+): UnsignedDevLogEntry {
+ return { v: DEVLOG_VERSION, acct: state.acct, seq: state.head.seq + 1, prev: state.head.hash, at, ...fields }
+}
diff --git a/backend/src/lib/harnessSession.test.ts b/backend/src/lib/harnessSession.test.ts
index 1c1d24c2d..33ccc755d 100644
--- a/backend/src/lib/harnessSession.test.ts
+++ b/backend/src/lib/harnessSession.test.ts
@@ -33,7 +33,8 @@ const fakes = vi.hoisted(() => {
}
const harnessSession = {
create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
- const row = { id: `s${sessions.length + 1}`, revokedAt: null, createdAt: new Date(), lastUsedAt: new Date(), ...data }
+ // Like MongoDB: a new row has no `revokedAt` at all, and `revokedAt: null` does not match that.
+ const row = { id: `s${sessions.length + 1}`, createdAt: new Date(), lastUsedAt: new Date(), ...data }
sessions.push(row); return row
}),
findUnique: vi.fn(async ({ where }: { where: Record<string, unknown> }) => pick(where)),
@@ -41,7 +42,11 @@ const fakes = vi.hoisted(() => {
const row = pick(where)!; Object.assign(row, data); return row
}),
updateMany: vi.fn(async ({ where, data }: { where: Record<string, unknown>; data: Record<string, unknown> }) => {
- const rows = sessions.filter((s) => Object.entries(where).every(([k, v]) => s[k] === v))
+ const field = (s: Record<string, unknown>, k: string, v: unknown): boolean =>
+ v !== null && typeof v === 'object' && 'isSet' in v ? (k in s) === (v as { isSet: boolean }).isSet : k in s && s[k] === v
+ const matches = (s: Record<string, unknown>, w: Record<string, unknown>): boolean => Object.entries(w).every(([k, v]) =>
+ k === 'OR' ? (v as Record<string, unknown>[]).some((o) => matches(s, o)) : field(s, k, v))
+ const rows = sessions.filter((s) => matches(s, where))
rows.forEach((r) => Object.assign(r, data)); return { count: rows.length }
}),
}
diff --git a/backend/src/lib/harnessSession.ts b/backend/src/lib/harnessSession.ts
index 2a2453d1a..2222af456 100644
--- a/backend/src/lib/harnessSession.ts
+++ b/backend/src/lib/harnessSession.ts
@@ -1,4 +1,5 @@
import { pub } from './bus.js'
+import type { Prisma } from '@prisma/client'
import { prisma } from './prisma.js'
import { userService } from '../services/UserService.js'
import { storedAutonomousEnvironment, type AutonomousEnvironment } from './autonomousEnvironment.js'
@@ -122,11 +123,15 @@ export async function refreshHarnessSession(refreshToken: string): Promise<Harne
}
}
+// Not yet revoked. A session is created without `revokedAt`, and on MongoDB `revokedAt: null` alone
+// does not match a field that is absent — so a revoke filtered on it alone never revoked anything.
+const notRevoked: Prisma.HarnessSessionWhereInput = { OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }
+
/** Sign out: the session's refresh token stops working, and so, at once, does its access token. */
export async function revokeHarnessSession(refreshToken: string): Promise<void> {
if (!isHarnessRefreshToken(refreshToken)) return
await prisma.harnessSession.updateMany({
- where: { refreshHash: harnessTokenHash(refreshToken), revokedAt: null },
+ where: { refreshHash: harnessTokenHash(refreshToken), ...notRevoked },
data: { revokedAt: new Date() },
})
}
diff --git a/backend/src/lib/webAccountPushes.test.ts b/backend/src/lib/webAccountPushes.test.ts
index d06d147ca..1e373871a 100644
--- a/backend/src/lib/webAccountPushes.test.ts
+++ b/backend/src/lib/webAccountPushes.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const m = vi.hoisted(() => ({ desk: vi.fn(), zoo: vi.fn(), deskUnsub: vi.fn(), zooUnsub: vi.fn() }))
-vi.mock('./bus.js', () => ({ subscribeDeskChanged: m.desk, subscribeZooChanged: m.zoo }))
+const m = vi.hoisted(() => ({ desk: vi.fn(), zoo: vi.fn(), keys: vi.fn(), deskUnsub: vi.fn(), zooUnsub: vi.fn(), keysUnsub: vi.fn() }))
+vi.mock('./bus.js', () => ({ subscribeDeskChanged: m.desk, subscribeZooChanged: m.zoo, subscribeDeviceKeysChanged: m.keys }))
import { relayWebDocumentPushes } from './webAccountPushes.js'
@@ -13,12 +13,14 @@ describe('account documents on a web or phone socket', () => {
vi.resetAllMocks()
m.desk.mockResolvedValue(m.deskUnsub)
m.zoo.mockResolvedValue(m.zooUnsub)
+ m.keys.mockResolvedValue(m.keysUnsub)
})
- it('listens on the desk and zoo channels of the account that owns the socket', async () => {
+ it('listens on the desk, zoo and device key channels of the account that owns the socket', async () => {
await relayWebDocumentPushes('user-1', vi.fn(), on)
expect(m.desk).toHaveBeenCalledWith('user-1', expect.any(Function))
expect(m.zoo).toHaveBeenCalledWith('user-1', expect.any(Function))
+ expect(m.keys).toHaveBeenCalledWith('user-1', expect.any(Function))
})
it('hands the client each change as its own plain frame carrying the revision', async () => {
@@ -26,18 +28,21 @@ describe('account documents on a web or phone socket', () => {
await relayWebDocumentPushes('user-1', send, on)
m.desk.mock.calls[0][1]({ revision: 7 })
m.zoo.mock.calls[0][1]({ revision: 3 })
+ m.keys.mock.calls[0][1]({ seq: 4, hash: 'h' })
expect(send.mock.calls).toEqual([
[{ type: 'desk_changed', payload: { revision: 7 } }],
[{ type: 'zoo_changed', payload: { revision: 3 } }],
+ [{ type: 'device_keys_changed', payload: { seq: 4, hash: 'h' } }],
])
})
- it('stops listening on both when the socket goes away', async () => {
+ it('stops listening on all of them when the socket goes away', async () => {
const stop = await relayWebDocumentPushes('user-1', vi.fn(), on)
stop()
stop()
expect(m.deskUnsub).toHaveBeenCalledOnce()
expect(m.zooUnsub).toHaveBeenCalledOnce()
+ expect(m.keysUnsub).toHaveBeenCalledOnce()
})
it('does not leave the desk subscription behind when the zoo subscribe fails', async () => {
@@ -46,7 +51,7 @@ describe('account documents on a web or phone socket', () => {
expect(m.deskUnsub).toHaveBeenCalledOnce()
})
- it('listens on the desk alone while the server has daemons off', async () => {
+ it('leaves the zoo out while the server has daemons off', async () => {
const send = vi.fn()
const stop = await relayWebDocumentPushes('user-1', send, { zoo: false })
expect(m.zoo).not.toHaveBeenCalled()
diff --git a/backend/src/lib/webAccountPushes.ts b/backend/src/lib/webAccountPushes.ts
index 250e088ec..45b91e10f 100644
--- a/backend/src/lib/webAccountPushes.ts
+++ b/backend/src/lib/webAccountPushes.ts
@@ -1,4 +1,4 @@
-import { subscribeDeskChanged, subscribeZooChanged } from './bus.js'
+import { subscribeDeskChanged, subscribeDeviceKeysChanged, subscribeZooChanged } from './bus.js'
/**
* The account documents a WEB socket hears about — the desk and the zoo — forwarded to the clients
@@ -9,13 +9,15 @@ import { subscribeDeskChanged, subscribeZooChanged } from './bus.js'
* - `desk_changed` — the account's tabs.
* - `zoo_changed` — the account's daemons and eggs (routes/zoo.ts), its own frame: a desk change
* never re-fetches the zoo and the other way round.
+ * - `device_keys_changed` — the account's device key log grew (lib/deviceKeyLog.ts): the app re-reads
+ * from its own head and trusts the machines the log adds.
*
* ⚠️ A phone holds one of these sockets PER MACHINE, so it hears each change once per machine. The
* revision is what makes that harmless: an app already at that revision fetches nothing.
*
* `zoo` is the server's daemons switch (lib/daemonsSwitch.ts): off, only the desk is listened on.
*
- * Resolves to the unsubscribe for both.
+ * Resolves to the unsubscribe for all of them.
*/
export async function relayWebDocumentPushes(userId: string, send: (frame: unknown) => unknown, opts: { zoo: boolean }): Promise<() => void> {
const unsubs: Array<() => void> = []
@@ -23,6 +25,7 @@ export async function relayWebDocumentPushes(userId: string, send: (frame: unkno
try {
unsubs.push(await subscribeDeskChanged(userId, (msg) => { send({ type: 'desk_changed', payload: { revision: msg.revision } }) }))
if (opts.zoo) unsubs.push(await subscribeZooChanged(userId, (msg) => { send({ type: 'zoo_changed', payload: { revision: msg.revision } }) }))
+ unsubs.push(await subscribeDeviceKeysChanged(userId, (msg) => { send({ type: 'device_keys_changed', payload: { seq: msg.seq, hash: msg.hash } }) }))
} catch (err) {
stop()
throw err
diff --git a/backend/src/lib/webWs.test.ts b/backend/src/lib/webWs.test.ts
index 10fd9b203..e3cd11b16 100644
--- a/backend/src/lib/webWs.test.ts
+++ b/backend/src/lib/webWs.test.ts
@@ -13,8 +13,9 @@ describe('frames a web client may never forge', () => {
// machine_meta names the account's private grid — the inference endpoint every agent on that
// computer is then pointed at. machine_revoked makes the adapter clear its session and exit.
// desk_changed / zoo_changed / machines_changed make every window on that computer re-read from the backend:
- // forged in a loop, that is request amplification against our own API.
- expect([...BACKEND_ONLY_DOWN_TYPES].sort()).toEqual(['desk_changed', 'machine_meta', 'machine_revoked', 'machines_changed', 'zoo_changed'])
+ // forged in a loop, that is request amplification against our own API. device_keys_changed makes the
+ // daemon re-read its device key log; devlog_append_result is the backend's answer to its own append.
+ expect([...BACKEND_ONLY_DOWN_TYPES].sort()).toEqual(['desk_changed', 'device_keys_changed', 'devlog_append_result', 'machine_meta', 'machine_revoked', 'machines_changed', 'zoo_changed'])
})
it('covers only frames that are NOT already caught by the `__` rule', () => {
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.ts
index 802010de3..7d866e06c 100644
--- a/backend/src/lib/webWs.ts
+++ b/backend/src/lib/webWs.ts
@@ -23,6 +23,7 @@ import { createWss, WS_LIMITS } from './wsServer.js'
import { extractKey } from '../utils/crypto.js'
import { machineIdFromKey } from '../utils/crypto.js'
import { prisma, machineAlive } from './prisma.js'
+import { touchDeviceKey } from './deviceKeyLog.js'
import { getAgentPresence, getAgentPresenceMany, subscribeStatus, getDevicePresence, subscribeDeviceStatus, subscribeDeviceMachineListChanged, subscribeDeviceE2eePair } from './bus.js'
import { relayWebDocumentPushes } from './webAccountPushes.js'
import { DAEMONS } from '../config/env.js'
@@ -361,6 +362,8 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
// are never a web client's to send. Refused here, on the legacy key path and on device-ws alike; the
// adapter also takes them only on the backend's own `connId: ''`, so each check stands on its own.
if (isBackendOnlyDownType(type)) return
+ // The key opening this E2EE session was seen now (lib/deviceKeyLog.ts, a hint for the Devices list).
+ if (type === 'e2e_hello') touchDeviceKey(user.sub, (frame.payload as { identityPub?: unknown } | undefined)?.identityPub)
const isTerminal = typeof type === 'string' && TERMINAL_DOWN_TYPES.has(type)
const terminalNamespace = typeof type === 'string' && type.startsWith('terminal_')
if (terminalNamespace && !isTerminal) {
diff --git a/backend/src/routes/deviceKeys.test.ts b/backend/src/routes/deviceKeys.test.ts
new file mode 100644
index 000000000..131dc6fd1
--- /dev/null
+++ b/backend/src/routes/deviceKeys.test.ts
@@ -0,0 +1,83 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Fastify, { type FastifyInstance } from 'fastify'
+const m = vi.hoisted(() => ({ auth: vi.fn(), read: vi.fn(), append: vi.fn(), seen: vi.fn() }))
+vi.mock('../lib/deviceKeyLog.js', () => ({ readDeviceKeyLog: m.read, appendDeviceKey: m.append, deviceKeysSeen: m.seen }))
+vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: m.auth }))
+import { deviceKeyRoutes } from './deviceKeys.js'
+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
+import { errorHandler } from '../middlewares/errorHandler.js'
+
+const user = { sub: 'user-1', email: '[email protected]', role: 'user', autonomousEnv: 'prod' as const }
+const auth = { authorization: 'Bearer fixture' }
+const head = { seq: 3, hash: Buffer.alloc(32, 7).toString('base64') }
+
+describe('device key routes', () => {
+ let app: FastifyInstance
+ beforeEach(async () => {
+ vi.resetAllMocks()
+ m.auth.mockResolvedValue(user)
+ app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, m.auth)
+ await app.register(deviceKeyRoutes); await app.ready()
+ })
+ afterEach(async () => { await app.close() })
+
+ it('needs a sign-in', async () => {
+ expect((await app.inject({ method: 'GET', url: '/api/device-keys' })).statusCode).toBe(401)
+ })
+
+ it('reads the caller log from a head, uncached', async () => {
+ m.read.mockResolvedValue({ acct: 'user-1', head, entries: [] })
+ const r = await app.inject({ method: 'GET', url: '/api/device-keys?since=2', headers: auth })
+ expect(r.statusCode).toBe(200)
+ expect(r.headers['cache-control']).toBe('no-store')
+ expect(r.json().data).toEqual({ acct: 'user-1', head, entries: [] })
+ expect(m.read).toHaveBeenCalledWith('user-1', 2)
+ })
+
+ it('appends over the viewer channel, carrying a Harness session', async () => {
+ m.auth.mockResolvedValue({ ...user, harnessSessionId: 'sess-9' })
+ m.append.mockResolvedValue({ ok: true, head })
+ const r = await app.inject({ method: 'POST', url: '/api/device-keys', headers: auth, payload: { entry: { v: 1 } } })
+ expect(r.statusCode).toBe(200)
+ expect(r.json().data).toEqual({ head })
+ expect(m.append).toHaveBeenCalledWith('user-1', { v: 1 }, { kind: 'viewer', harnessSessionId: 'sess-9' })
+ })
+
+ it('answers a stale head with 409 and the head to rebuild on', async () => {
+ m.append.mockResolvedValue({ ok: false, status: 409, code: 'STALE_HEAD', head })
+ const r = await app.inject({ method: 'POST', url: '/api/device-keys', headers: auth, payload: { entry: {} } })
+ expect(r.statusCode).toBe(409)
+ expect(r.json()).toMatchObject({ success: false, error: { code: 'STALE_HEAD' }, data: { head } })
+ })
+
+ it('passes a refusal through with its code', async () => {
+ m.append.mockResolvedValue({ ok: false, status: 403, code: 'WRONG_CHANNEL' })
+ const r = await app.inject({ method: 'POST', url: '/api/device-keys', headers: auth, payload: { entry: {} } })
+ expect(r.statusCode).toBe(403)
+ expect(r.json().error.code).toBe('WRONG_CHANNEL')
+ })
+
+ it('says when each key was last seen, and nothing when that cannot be read', async () => {
+ m.seen.mockResolvedValue({ k: 5 })
+ const r = await app.inject({ method: 'GET', url: '/api/device-keys/seen', headers: auth })
+ expect(r.json().data).toEqual({ seen: { k: 5 } })
+ expect(m.seen).toHaveBeenCalledWith('user-1')
+ m.seen.mockRejectedValue(new Error('redis down'))
+ expect((await app.inject({ method: 'GET', url: '/api/device-keys/seen', headers: auth })).json().data).toEqual({ seen: {} })
+ })
+
+ it('limits how often one account appends', async () => {
+ m.auth.mockResolvedValue({ ...user, sub: 'user-busy' })
+ m.append.mockResolvedValue({ ok: true, head })
+ const codes: number[] = []
+ for (let i = 0; i < 21; i++) codes.push((await app.inject({ method: 'POST', url: '/api/device-keys', headers: auth, payload: { entry: {} } })).statusCode)
+ expect(codes.slice(0, 20).every((c) => c === 200)).toBe(true)
+ expect(codes[20]).toBe(429)
+ })
+
+ it('refuses a body without an entry', async () => {
+ const r = await app.inject({ method: 'POST', url: '/api/device-keys', headers: auth, payload: { other: 1 } })
+ expect(r.statusCode).toBe(400)
+ expect(m.append).not.toHaveBeenCalled()
+ })
+})
diff --git a/backend/src/routes/deviceKeys.ts b/backend/src/routes/deviceKeys.ts
new file mode 100644
index 000000000..b83728745
--- /dev/null
+++ b/backend/src/routes/deviceKeys.ts
@@ -0,0 +1,58 @@
+import type { FastifyInstance } from 'fastify'
+import { z } from 'zod'
+import { appendDeviceKey, deviceKeysSeen, readDeviceKeyLog } from '../lib/deviceKeyLog.js'
+import { validateBody, validateQuery } from '../middlewares/validation.js'
+import { sendError, sendSuccess } from '../utils/response.js'
+
+const query = z.object({ since: z.coerce.number().int().min(0).default(0) })
+
+/** Appends per account per minute, per process — a viewer appends its key once per sign-in and a
+ * removal when someone asks. Generous for that; a loop cannot rebuild the log on every request. */
+const APPENDS_PER_MINUTE = 20
+const appendWindows = new Map<string, { start: number; count: number }>()
+function allowAppend(userId: string, now = Date.now()): boolean {
+ const w = appendWindows.get(userId)
+ if (!w || now - w.start >= 60_000) {
+ if (appendWindows.size >= 10_000) appendWindows.clear()
+ appendWindows.set(userId, { start: now, count: 1 })
+ return true
+ }
+ return ++w.count <= APPENDS_PER_MINUTE
+}
+const body = z.object({ entry: z.record(z.string(), z.unknown()) }).strict()
+
+/**
+ * The account's device key log (lib/deviceKeyLog.ts), for the viewer apps: read it from a head, append a
+ * viewer's own key or a viewer-signed removal. Machines append over their adapter socket instead
+ * (`devlog_append`), which is what ties an entry to the machine that sent it.
+ *
+ * A Harness session (a phone signed in by a QR) may append: that phone is one of the account's devices.
+ */
+export async function deviceKeyRoutes(app: FastifyInstance): Promise<void> {
+ app.get<{ Querystring: z.infer<typeof query> }>('/api/device-keys', { preHandler: validateQuery(query) }, async (req, reply) => {
+ reply.header('Cache-Control', 'no-store')
+ sendSuccess(reply, await readDeviceKeyLog(req.user!.sub, req.query.since))
+ })
+
+ // When each key last opened a session — a hint for the Devices list, which offers to remove apps not
+ // seen in a long while (a browser whose data was cleared never signs its own removal).
+ app.get('/api/device-keys/seen', async (req, reply) => {
+ reply.header('Cache-Control', 'no-store')
+ try {
+ sendSuccess(reply, { seen: await deviceKeysSeen(req.user!.sub) })
+ } catch {
+ sendSuccess(reply, { seen: {} })
+ }
+ })
+
+ app.post<{ Body: z.infer<typeof body> }>('/api/device-keys', { preHandler: validateBody(body) }, async (req, reply) => {
+ const user = req.user!
+ if (!allowAppend(user.sub)) return sendError(reply, 'Too many changes to your devices. Try again in a minute.', 'RATE_LIMITED', 429)
+ const result = await appendDeviceKey(user.sub, req.body.entry, { kind: 'viewer', harnessSessionId: user.harnessSessionId })
+ if (result.ok) return sendSuccess(reply, { head: result.head })
+ if (result.status === 409) {
+ return reply.code(409).send({ success: false, error: { code: result.code, message: 'The log moved on; read it again.' }, data: { head: result.head } })
+ }
+ sendError(reply, 'This entry was refused.', result.code, result.status)
+ })
+}
diff --git a/backend/src/server.ts b/backend/src/server.ts
index e399542f0..f739a7287 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -11,6 +11,7 @@ import { cursorRoutes } from './routes/cursor.js'
import { voiceRoutes } from './routes/voice.js'
import { harnessShareRoutes } from './routes/harnessShares.js'
import { harnessLinkRoutes } from './routes/harnessLinks.js'
+import { deviceKeyRoutes } from './routes/deviceKeys.js'
import { deskRoutes } from './routes/desk.js'
import { tabChannelRoutes } from './routes/tabChannels.js'
import { zooRoutes } from './routes/zoo.js'
@@ -170,6 +171,7 @@ async function start(): Promise<void> {
await app.register(storeRoutes) // the Harness Store's ratings and reviews; the catalogue is the CLI's registry
await app.register(harnessShareRoutes)
await app.register(harnessLinkRoutes)
+ await app.register(deviceKeyRoutes) // the account's device key log: signing in is what trusts a device
await app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)
if (env.HARNESS_CHANNELS) await app.register(tabChannelRoutes)
await app.register(experimentalSettingsRoutes, { daemons: DAEMONS })
diff --git a/cli/scripts/gen-devlog-vectors.ts b/cli/scripts/gen-devlog-vectors.ts
new file mode 100644
index 000000000..4e9ca2b62
--- /dev/null
+++ b/cli/scripts/gen-devlog-vectors.ts
@@ -0,0 +1,86 @@
+/**
+ * Regenerates src/lib/e2ee/deviceLog.vectors.json — the fixture every implementation of the device key
+ * log (CLI, backend, desktop and mobile Dart) is held to. Deterministic: fixed seeds, Ed25519 signs
+ * deterministically. Run: `npx tsx scripts/gen-devlog-vectors.ts`, then copy the file to the other trees.
+ */
+import { writeFileSync } from 'fs'
+import { join } from 'path'
+import { ed25519 } from '@noble/curves/ed25519'
+import {
+ applyDevLogEntries, DevLogError, emptyDevLogState, nextDevLogEntry, signDevLogEntry,
+ type DevLogEntry, type DevLogState,
+} from '../src/lib/e2ee/deviceLog.js'
+
+const b64 = (u: Uint8Array): string => Buffer.from(u).toString('base64')
+const seed = (n: number): Uint8Array => new Uint8Array(32).fill(n)
+const keys = {
+ box1: seed(1), box2: seed(2), browser: seed(3), stranger: seed(4), box2b: seed(5),
+}
+const pub = (k: keyof typeof keys): string => b64(ed25519.getPublicKey(keys[k]))
+const acct = 'acct-vectors-1'
+const MID1 = 'a'.repeat(32)
+const MID2 = 'b'.repeat(32)
+
+let state: DevLogState = emptyDevLogState(acct)
+const entries: DevLogEntry[] = []
+function add(k: keyof typeof keys, kind: 'machine' | 'viewer', machineId: string, label: string, at: number): void {
+ const e = signDevLogEntry(nextDevLogEntry(state, { op: 'add', pub: pub(k), kind, machineId, label, signer: pub(k) }, at), keys[k])
+ state = applyDevLogEntries(state, [e]).state
+ entries.push(e)
+}
+function remove(target: keyof typeof keys, by: keyof typeof keys, at: number): void {
+ const m = state.active[pub(target)]
+ const e = signDevLogEntry(nextDevLogEntry(state, { op: 'remove', pub: m.pub, kind: m.kind, machineId: m.machineId, label: m.label, signer: pub(by) }, at), keys[by])
+ state = applyDevLogEntries(state, [e]).state
+ entries.push(e)
+}
+
+add('box1', 'machine', MID1, 'box1', 1_000)
+add('box2', 'machine', MID2, 'box2', 2_000)
+add('browser', 'viewer', '', 'Browser · macOS — “Dee”', 3_000)
+add('box1', 'machine', MID1, 'box1 (renamed)', 4_000)
+remove('box2', 'browser', 5_000)
+add('box2b', 'machine', MID2, 'box2', 6_000)
+
+const valid = { entries, hashes: state.hashes, head: state.head, active: Object.keys(state.active).sort(), removed: state.removed }
+
+/** Each invalid case: apply `after` valid entries, then `entry` must fail with `code`. */
+const invalid: Array<{ name: string; after: number; entry: unknown; code: string }> = []
+function bad(name: string, after: number, build: (s: DevLogState) => unknown, code: string): void {
+ const s = applyDevLogEntries(emptyDevLogState(acct), entries.slice(0, after)).state
+ const entry = build(s)
+ try {
+ applyDevLogEntries(s, [entry])
+ throw new Error(`${name}: expected ${code}, got success`)
+ } catch (err) {
+ if (!(err instanceof DevLogError) || err.code !== code) throw new Error(`${name}: expected ${code}, got ${String(err)}`)
+ }
+ invalid.push({ name, after, entry, code })
+}
+const selfAdd = (s: DevLogState, k: keyof typeof keys, kind: 'machine' | 'viewer', machineId: string, label: string) =>
+ signDevLogEntry(nextDevLogEntry(s, { op: 'add', pub: pub(k), kind, machineId, label, signer: pub(k) }, 9_000), keys[k])
+
+bad('tampered label', 1, s => ({ ...selfAdd(s, 'box2', 'machine', MID2, 'box2'), label: 'evil' }), 'BAD_SIGNATURE')
+bad('add signed by another key', 1, s => signDevLogEntry(nextDevLogEntry(s, { op: 'add', pub: pub('stranger'), kind: 'viewer', machineId: '', label: 'x', signer: pub('box1') }, 9_000), keys.box1), 'NOT_SELF_SIGNED')
+bad('machine id of another active machine', 2, s => selfAdd(s, 'stranger', 'machine', MID2, 'imposter'), 'MACHINE_TAKEN')
+bad('removed key comes back', 5, s => selfAdd(s, 'box2', 'machine', MID2, 'box2 again'), 'KEY_REMOVED')
+bad('remove signed by a key not in the log', 2, s => signDevLogEntry(nextDevLogEntry(s, { op: 'remove', pub: pub('box1'), kind: 'machine', machineId: MID1, label: 'box1', signer: pub('stranger') }, 9_000), keys.stranger), 'SIGNER_NOT_ACTIVE')
+bad('remove of a key not in the log', 2, s => signDevLogEntry(nextDevLogEntry(s, { op: 'remove', pub: pub('stranger'), kind: 'viewer', machineId: '', label: '', signer: pub('box1') }, 9_000), keys.box1), 'NOT_ACTIVE')
+bad('wrong prev', 2, s => signDevLogEntry({ ...nextDevLogEntry(s, { op: 'add', pub: pub('stranger'), kind: 'viewer', machineId: '', label: 'x', signer: pub('stranger') }, 9_000), prev: s.hashes[0] }, keys.stranger), 'BROKEN_CHAIN')
+bad('skipped seq', 2, s => signDevLogEntry({ ...nextDevLogEntry(s, { op: 'add', pub: pub('stranger'), kind: 'viewer', machineId: '', label: 'x', signer: pub('stranger') }, 9_000), seq: 4 }, keys.stranger), 'OUT_OF_ORDER')
+bad('other account', 2, s => signDevLogEntry({ ...nextDevLogEntry(s, { op: 'add', pub: pub('stranger'), kind: 'viewer', machineId: '', label: 'x', signer: pub('stranger') }, 9_000), acct: 'acct-other' }, keys.stranger), 'WRONG_ACCOUNT')
+bad('machine changes kind', 1, s => selfAdd(s, 'box1', 'viewer', '', 'box1'), 'KIND_CHANGED')
+bad('re-add with nothing changed', 1, s => selfAdd(s, 'box1', 'machine', MID1, 'box1'), 'NO_CHANGE')
+bad('viewer with a machine id', 0, s => selfAdd(s, 'browser', 'viewer', MID1, 'b'), 'BAD_ENTRY')
+bad('control character in label', 0, s => selfAdd(s, 'browser', 'viewer', '', 'a\nb'), 'BAD_ENTRY')
+
+const out = {
+ comment: 'Generated by cli/scripts/gen-devlog-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4, box2b=5).',
+ acct,
+ seeds: Object.fromEntries(Object.entries(keys).map(([k, v]) => [k, b64(v)])),
+ pubs: Object.fromEntries(Object.keys(keys).map(k => [k, pub(k as keyof typeof keys)])),
+ valid,
+ invalid,
+}
+writeFileSync(join(import.meta.dirname, '../src/lib/e2ee/deviceLog.vectors.json'), JSON.stringify(out, null, 2) + '\n')
+console.log(`wrote ${entries.length} valid entries, ${invalid.length} invalid cases`)
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 58cf25ce6..0e838b386 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -2849,6 +2849,31 @@ describe('machine_meta carries the grid name without clobbering it on rename', (
await socket.stop()
})
+
+ it('says whose key a device-key-log removal spent before signing out, and nothing for a plain revoke', async () => {
+ const socket = new BackendSocket('token')
+ const order: string[] = []
+ socket.onDeviceRemoved = (pub) => { order.push(`removed:${pub}`) }
+ socket.onRevoked = () => { order.push('revoked') }
+ socket.connect()
+ const ws = wsMock.instances.at(-1)!
+ ws.open()
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_revoked', payload: { reason: 'device_removed', pub: 'PUB' } } })
+ await vi.waitFor(() => expect(order).toEqual(['removed:PUB', 'revoked']))
+ await socket.stop()
+
+ const plain = new BackendSocket('token')
+ let removed = 0
+ plain.onDeviceRemoved = () => { removed += 1 }
+ plain.onRevoked = () => {}
+ plain.connect()
+ const ws2 = wsMock.instances.at(-1)!
+ ws2.open()
+ ws2.message({ t: 'down', connId: '', frame: { type: 'machine_revoked', payload: {} } })
+ await new Promise((r) => setTimeout(r, 50))
+ expect(removed).toBe(0)
+ 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 950b4cdc2..c64db04a5 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -213,8 +213,12 @@ export type DownTransport = 'relay' | 'local' | 'p2p'
* `backend/src/services/MachineService.ts` — so there is nothing to stay compatible with. The
* backend blocks its OWN `__`-prefixed control frames from web clients for the same reason; these
* two escaped that rule because they are not `__`-prefixed.
+ *
+ * `device_keys_changed` and `devlog_append_result` are the backend's own too (the device key log,
+ * lib/e2ee/deviceLogSyncer.ts): forged, the first only makes this daemon re-read and verify the log,
+ * the second could fake an answer to its own append — neither is anything a client should be sending.
*/
-const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'zoo_changed', 'machines_changed'])
+const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'zoo_changed', 'machines_changed', 'device_keys_changed', 'devlog_append_result'])
/** A frame type as the sender spelled it, fit for one log line: the relay chooses it, so it is bounded
* and escaped rather than trusted not to carry a newline that forges the next line. */
@@ -771,6 +775,14 @@ export class BackendSocket {
pairControl: { verbs: ReadonlySet<string>; local: (payload: Record<string, unknown>, connId: string) => Promise<Record<string, unknown>> } | null = null
/** The account's zoo changed (a `zoo_changed` from the backend) — cli.ts re-reads which daemon is paired. */
onZooChanged: ((revision: number) => void) | null = null
+ /** The account's device key log grew (lib/e2ee/deviceLogSyncer.ts): re-read it from this machine's head. */
+ 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
+ /** 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. */
+ private readonly devlogAppends = new Map<string, (payload: Record<string, unknown> | null) => void>()
/**
* Whether daemons run at all (lib/daemonsSwitch.ts). Off, the loopback `pair` request (`harness pair`, the
* MCP server) is answered DAEMONS_OFF before any verb runs. Null: always on, as before the switch.
@@ -1071,6 +1083,7 @@ export class BackendSocket {
console.log(`[backend] connected → ${this.url}`)
this.onStatus(true)
this.drainQueue()
+ this.onLinkUp?.()
this.heartbeat = watchSocketLiveness(ws, {
onIdle: (idleMs) => console.log(`[backend] no traffic for ${Math.round(idleMs / 1000)}s — terminating the link`),
@@ -1308,6 +1321,21 @@ export class BackendSocket {
try { this.ws.send(packet); return true } catch { return false }
}
+ /**
+ * Append one entry to the account's device key log, over this machine's own socket — the backend
+ * ties a machine's entries to the machine that sent them. Resolves to the backend's answer
+ * (`{head}` or `{error, head?}`), or null when it did not come in time.
+ */
+ appendDeviceLog(entry: Record<string, unknown>, timeoutMs = 15_000): Promise<Record<string, unknown> | null> {
+ const requestId = `dl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => { this.devlogAppends.delete(requestId); resolve(null) }, timeoutMs)
+ timer.unref?.()
+ this.devlogAppends.set(requestId, (payload) => { clearTimeout(timer); resolve(payload) })
+ this.enqueue({ t: 'up', webEligible: false, frame: { type: 'devlog_append', payload: { requestId, entry } } })
+ })
+ }
+
/** Send a user-level notification to every logged-in browser that owns this machine. */
sendUser(frame: Frame): void {
this.enqueue({ t: 'up', userEligible: true, webEligible: false, frame })
@@ -1845,7 +1873,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') { this.closed = true; this.onRevoked?.(); return }
+ if (type === 'machine_revoked') {
+ 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 */ }
+ }
+ this.onRevoked?.()
+ return
+ }
// The account's tabs changed on another computer (or in another window of this one): hand the
// window the revision and let it fetch `/api/desk` through this daemon. Backend-only, like
@@ -1867,6 +1904,21 @@ export class BackendSocket {
return
}
+ // The account's device key log grew: this daemon re-reads and verifies it (deviceLogSyncer.ts), and
+ // the window re-reads its Devices list. Backend-only for the same reason as desk_changed.
+ if (type === 'device_keys_changed') {
+ this.onDeviceKeysChanged?.()
+ this.sendLocal({ type: 'device_keys_changed', payload: {} })
+ return
+ }
+ // The backend's answer to this machine's own append to the device key log.
+ if (type === 'devlog_append_result') {
+ const p = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as Record<string, unknown>
+ const done = typeof p.requestId === 'string' ? this.devlogAppends.get(p.requestId) : undefined
+ if (done) { this.devlogAppends.delete(p.requestId as string); done(p) }
+ return
+ }
+
// The account's machine list changed on some worker — a machine created / renamed / deleted, or a
// shared harness invited / taken back. The window re-reads `/api/machines` through this daemon; this
// push is why it does not have to poll for that. Backend-only for the same reason as desk_changed.
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 1f6a781e4..dc69e803d 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -26,7 +26,7 @@ import { AutonomousDeviceDirect } from './lib/autonomous-device/direct.js'
*/
import 'dotenv/config'
-import { readFileSync, readdirSync, writeFileSync, mkdirSync, openSync, existsSync, rmSync, statSync } from 'fs'
+import { readFileSync, readdirSync, writeFileSync, mkdirSync, openSync, existsSync, rmSync, statSync, renameSync } from 'fs'
import { dirname, join, resolve } from 'path'
import { fileURLToPath } from 'url'
import { execFile as execFileCb, spawn } from 'child_process'
@@ -230,6 +230,8 @@ import { MachinePeerStore } from './lib/e2ee/machinePeers.js'
import { connectWithPassword, type PwConnectProgress } from './lib/e2ee/relayClient.js'
import type { LinkedPeer } from './lib/e2ee/manager.js'
import { GroupSyncer, relayRequester, SELF_STAMP } from './lib/e2ee/groupSyncer.js'
+import { DeviceLogSyncer, type DeviceLogFetched } from './lib/e2ee/deviceLogSyncer.js'
+import { DeviceLogStore } from './lib/e2ee/deviceLogStore.js'
import { TrustGroupStore, type GroupMember } from './lib/e2ee/trustGroup.js'
import {
startSelfUpdater, restore as restoreUpdate, confirm as confirmUpdate,
@@ -466,6 +468,11 @@ every future connect, until you change or clear it:
machine and every member reaches it both ways, no more passwords
harness group sync compare with every reachable member now (it also happens on its own)
harness group remove <id> drop a member (machine id, # or fingerprint) from every member
+ harness devices list the account's devices — signing in on one is what makes the others trust
+ it; a device you do not recognise is someone else signed in as you
+ harness devices remove <fp> take a device (# or fingerprint) out of the account on every device
+ 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
line from stdin with --stdin; add --json for NDJSON output instead of the human-readable text)
@@ -1948,6 +1955,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The trust group (lib/e2ee/groupSyncer.ts). Built once the relay pool exists, far below; the hook
// handlers and the backend callbacks declared before then reach it through this.
let groupSyncer: GroupSyncer | null = null
+ // The account's device key log (lib/e2ee/deviceLogSyncer.ts): signing in is what makes this machine's
+ // devices trust it, and it them. Built beside the trust group, which it feeds.
+ let devLogSyncer: DeviceLogSyncer | null = null
+ /** The identity this machine was removed under is never used again: the next start mints a new one. */
+ const spendIdentity = (): void => {
+ const identityFile = join(env.ADAPTER_DATA_DIR, 'e2e', 'identity.json')
+ try { renameSync(identityFile, `${identityFile}.removed-${Date.now()}`) } catch { /* already gone */ }
+ }
const backend = new BackendSocket(session?.machineId ?? computerId(), auth, (connected) => {
if (!connected) return
const sessions = registry.advertised()
@@ -4168,8 +4183,31 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const found = findGroupMember(selector)
if (!found.ok) return { status: found.error === 'AMBIGUOUS' ? 409 : 404, body: { error: found.error } }
groupSyncer?.remove(found.pub)
+ // And out of the device key log, or the next read of it would put the device back.
+ void devLogSyncer?.remove(found.pub)
return { status: 200, body: { label: found.label, fingerprint: found.fingerprint } }
},
+ onDevicesList: async () => {
+ if (!devLogSyncer) return { status: 503, body: { error: 'UNAVAILABLE' } }
+ // When each key last opened a session, from the backend — a hint for removing apps not used in a
+ // long while. Without it the list is still the list.
+ const seen = await proxyBackend('GET', '/api/device-keys/seen').catch(() => null)
+ const lastSeen = seen?.status === 200 ? (seen.body.data as { seen?: unknown } | undefined)?.seen : undefined
+ return { status: 200, body: { ...devLogSyncer.list(), lastSeen: lastSeen && typeof lastSeen === 'object' ? lastSeen : {} } }
+ },
+ onDevicesRemove: async (pub) => {
+ if (!devLogSyncer) return { status: 503, body: { error: 'UNAVAILABLE' } }
+ groupSyncer?.remove(pub)
+ const r = await devLogSyncer.remove(pub)
+ if (r.ok) return { status: 200, body: { ok: true } }
+ 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) => {
+ if (!devLogSyncer) return { status: 503, body: { error: 'UNAVAILABLE' } }
+ const r = await devLogSyncer.rebaseline(confirm)
+ 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
// deliberately does NOT expose chat/transcripts — those live in the cloud web (WEB_URL/commander).
onStatus: async () => ({
@@ -4295,7 +4333,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {
env.BACKEND_WS_URL.replace(/\/$/, ''),
relayIdentityStore.getIdentity(),
relayPeers,
- { onSessionReady: (machineId) => groupSyncer?.sessionOpened(machineId) },
+ {
+ onSessionReady: (machineId) => groupSyncer?.sessionOpened(machineId),
+ // A machine the account's device key log names under this very key will trust us as soon as it
+ // 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
+ if (expected) void devLogSyncer?.refresh()
+ return expected
+ },
+ },
)
// Every machine and phone linked to this one, directly or through another member, trusts every other:
// rosters are swapped over any session that opens, and pushed on whenever they change.
@@ -4317,8 +4365,74 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
backend.groupSync = groupSyncer
backend.onPeerLinked = (peer) => groupSyncer?.linked(peer)
- backend.onUnpaired = (pub) => groupSyncer?.unpaired(pub)
+ backend.onUnpaired = (pub) => {
+ groupSyncer?.unpaired(pub)
+ // Unpairing a device here takes it out of the account's log too — or the log would trust it again.
+ void devLogSyncer?.remove(pub)
+ }
if (session?.machineId) groupSyncer.start()
+ devLogSyncer = new DeviceLogSyncer({
+ store: new DeviceLogStore(),
+ identity: () => { const id = relayIdentityStore.getIdentity(); return { pub: b64e(id.pub), priv: id.priv } },
+ self: () => ({ machineId: readAuthSession()?.machineId ?? null, label: hostname().slice(0, 60) }),
+ 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
+ return { acct: data.acct, head: { seq: head.seq, hash: head.hash }, entries: data.entries }
+ },
+ append: async (entry) => {
+ const p = await backend.appendDeviceLog(entry as unknown as Record<string, unknown>)
+ if (!p) return null
+ const head = p.head as { seq?: unknown; hash?: unknown } | undefined
+ const parsedHead = typeof head?.seq === 'number' && typeof head.hash === 'string' ? { seq: head.seq, hash: head.hash } : undefined
+ if (typeof p.error === 'string') return { error: p.error, ...(parsedHead ? { head: parsedHead } : {}) }
+ return parsedHead ? { head: parsedHead } : null
+ },
+ 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),
+ tombstoned: (pub) => !!groupSyncer?.tombstoned(pub),
+ blocked: (pub) => !!groupSyncer?.isBlocked(pub),
+ announce: (m) => {
+ const fp = e2eeCoreFingerprint(e2eeCoreDecode(m.pub))
+ 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 } })
+ },
+ 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.
+ console.log('[devlog] this machine was removed from the account\'s devices — signing out')
+ spendIdentity()
+ backend.onRevoked?.()
+ },
+ changed: () => backend.sendLocal({ type: 'device_keys_changed', payload: {} }),
+ log: (line) => console.log(line),
+ })
+ groupSyncer.devlog = devLogSyncer
+ // Removed while online: the backend's `machine_revoked` arrives before this machine reads the log, and
+ // stops it. The key is spent all the same, or the next `harness login` would come back under a banned
+ // key and be signed out again.
+ backend.onDeviceRemoved = (pub) => {
+ if (pub === b64e(relayIdentityStore.getIdentity().pub)) spendIdentity()
+ }
+ // 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.
+ groupSyncer.onDropped = (pub) => {
+ if (devLogSyncer?.list().members.some((m) => m.pub === pub && !m.self)) void devLogSyncer.remove(pub)
+ }
+ backend.onDeviceKeysChanged = () => { void devLogSyncer?.refresh() }
+ if (session?.machineId) {
+ // 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()
+ 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
// THIS daemon — the computer you are at. Other linked machines are read over background relay sessions
// (never the window's own) with sealed `pair_*`. Everything it says goes out through sendLocal.
@@ -7758,6 +7872,70 @@ async function groupCommand(sub: string | undefined, arg: string | undefined, js
process.exit(1)
}
+/** `harness devices list|remove|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> }> => {
+ try {
+ const { res, json: out } = await daemonCall(method, path, body)
+ return { status: res.status, json: out }
+ } catch {
+ console.error('\n ✗ Harness is not running here. Run: harness start\n')
+ process.exit(1)
+ }
+ }
+ type Row = { pub: string; label: string; kind: string; machineId: string; addedAt: number; fingerprint: string; self: boolean }
+ const listing = async (): Promise<{ members: Row[]; frozen: { reason: string } | null; frozenPeers: string[]; lastSeen?: Record<string, number> }> => {
+ 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
+ }
+ if (!sub || sub === 'list') {
+ const out = await listing()
+ if (json) { console.log(JSON.stringify(out)); process.exit(0) }
+ if (out.frozen) console.log(`\n ⚠ FROZEN (${out.frozen.reason}): the backend served a device list that does not match what this machine verified. No device is added until you review it: harness devices rebaseline`)
+ if (out.frozenPeers.length) console.log(`\n ⚠ Frozen on: ${out.frozenPeers.join(', ')}`)
+ console.log('\n Devices on this account — each one trusts every other:\n')
+ out.members.forEach((m, i) => {
+ const what = m.kind === 'machine' ? `machine ${m.machineId.slice(0, 8)}` : 'app'
+ const seen = out.lastSeen?.[m.pub]
+ console.log(` ${String(i + 1).padStart(2)}. ${m.label || '(no name)'} ${what} ${m.fingerprint} added ${new Date(m.addedAt).toLocaleString()}`
+ + `${seen ? ` last seen ${new Date(seen).toLocaleDateString()}` : ''}${m.self ? ' (this machine)' : ''}`)
+ })
+ console.log('\n Not yours? harness devices remove <#|fingerprint>\n')
+ process.exit(0)
+ }
+ if (sub === 'remove') {
+ if (!arg) { console.error('Usage: harness devices remove <#|fingerprint> (see: harness devices list)'); process.exit(1) }
+ const { members } = await listing()
+ const norm = (v: string): string => v.toUpperCase().replace(/[·\s-]/g, '')
+ const byIndex = /^\d+$/.test(arg) ? members[Number(arg) - 1] : undefined
+ const matches = byIndex ? [byIndex] : members.filter((m) => norm(m.fingerprint).startsWith(norm(arg)))
+ if (matches.length !== 1) { console.error(`\n ✗ ${matches.length ? 'More than one device matches' : 'No device matches'} "${arg}".\n`); process.exit(1) }
+ const target = matches[0]
+ if (target.self) { console.error('\n ✗ That is this machine. Sign out with: harness logout\n'); process.exit(1) }
+ const { status, json: out } = await call('POST', '/api/devices/remove', { pub: target.pub })
+ if (status !== 200) { console.error(`\n ✗ Could not remove ${target.label}: ${String(out.error ?? status)}${out.detail ? ` (${String(out.detail)})` : ''}\n`); process.exit(1) }
+ console.log(`\n ✓ Removed ${target.label}. Every device stops trusting it; it is signed out.\n`)
+ process.exit(0)
+ }
+ if (sub === 'rebaseline') {
+ const confirm = flags.includes('--yes')
+ const { status, json: out } = await call('POST', '/api/devices/rebaseline', { confirm })
+ 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')
+ process.exit(0)
+ }
+ console.error(`Unknown command: devices ${sub}`)
+ process.exit(1)
+}
+
/** One row of `GET /api/machines`. Only the fields this CLI shows are declared. */
interface OwnerMachineRow {
machineId: string
@@ -8245,6 +8423,9 @@ switch (cmd) {
case 'group':
groupCommand(args[0], args[1], flags.includes('--json')).catch(onError)
break
+ case 'devices':
+ devicesCommand(args[0], args[1], flags).catch(onError)
+ break
case 'remote-password':
if (args[0] === 'set') remotePasswordSetCommand(flags.includes('--json'), flags.includes('--stdin')).catch(onError)
else if (args[0] === 'clear') remotePasswordClearCommand(flags.includes('--json')).catch(onError)
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 8444fb681..832ba33c6 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -119,6 +119,11 @@ export interface HookServerHandlers {
onGroupList?: () => PairOutcome
onGroupSync?: () => PairOutcome
onGroupRemove?: (selector: string) => PairOutcome
+ /** `harness devices list|remove|rebaseline` and the window's Devices list — the account's device key
+ * log as this machine verified it (lib/e2ee/deviceLogSyncer.ts). */
+ onDevicesList?: () => Promise<PairOutcome>
+ onDevicesRemove?: (pub: string) => Promise<PairOutcome>
+ onDevicesRebaseline?: (confirm: boolean) => Promise<PairOutcome>
/** Local dashboard status snapshot (GET /api/status). */
onStatus?: () => Record<string, unknown> | Promise<Record<string, unknown>>
/** Recent adapter log tail (GET /api/logs). */
@@ -706,6 +711,31 @@ export function startHookServer(
const out = handlers.onGroupRemove(body.selector.trim()); json(out.status, out.body); return
}
+ // `harness devices list` / the window's Devices list → the account's devices, as this machine's
+ // verified copy of the device key log has them. Read-only (public keys and labels).
+ if (req.method === 'GET' && url === '/api/devices') {
+ if (!handlers.onDevicesList) { json(503, { error: 'UNAVAILABLE' }); return }
+ const out = await handlers.onDevicesList(); json(out.status, out.body); return
+ }
+ // `harness devices remove <fp>` / Remove in the window → out of the log, signed by this machine.
+ if (req.method === 'POST' && url === '/api/devices/remove') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onDevicesRemove) { json(503, { error: 'UNAVAILABLE' }); return }
+ let body: { pub?: unknown }
+ try { body = JSON.parse(await readBody(req)) as typeof body } catch { json(400, { error: 'bad json' }); return }
+ if (typeof body.pub !== 'string' || !body.pub) { json(400, { error: 'MISSING_PUB' }); return }
+ const out = await handlers.onDevicesRemove(body.pub); json(out.status, out.body); return
+ }
+ // `harness devices rebaseline` → what trusting the backend's log again would change; `confirm`
+ // does it (the only way out of a frozen log).
+ 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 }
+ 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
+ }
+
// `harness remote-password status` → whether one is set, and its fingerprint. Read-only, same
// gating tier as /api/pairs.
if (req.method === 'GET' && url === '/api/remote-password/status') {
diff --git a/cli/src/lib/e2ee/deviceLog.spec.ts b/cli/src/lib/e2ee/deviceLog.spec.ts
new file mode 100644
index 000000000..a675ed124
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceLog.spec.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from 'vitest'
+import { ed25519 } from '@noble/curves/ed25519'
+import vectors from './deviceLog.vectors.json' with { type: 'json' }
+import {
+ applyDevLogEntries, compareDevLogHead, DevLogError, devLogHash, devLogHashAt, emptyDevLogState,
+ nextDevLogEntry, signDevLogEntry, type DevLogState,
+} from './deviceLog.js'
+
+const b64d = (s: string): Uint8Array => new Uint8Array(Buffer.from(s, 'base64'))
+
+describe('device key log vectors', () => {
+ it('derives the fixture keys from their seeds', () => {
+ for (const [name, seed] of Object.entries(vectors.seeds)) {
+ expect(Buffer.from(ed25519.getPublicKey(b64d(seed))).toString('base64')).toBe((vectors.pubs as Record<string, string>)[name])
+ }
+ })
+
+ it('applies every valid entry to the fixture hashes, head and active set', () => {
+ const { state } = applyDevLogEntries(emptyDevLogState(vectors.acct), vectors.valid.entries)
+ expect(state.hashes).toEqual(vectors.valid.hashes)
+ expect(state.head).toEqual(vectors.valid.head)
+ expect(Object.keys(state.active).sort()).toEqual(vectors.valid.active)
+ expect(state.removed).toEqual(vectors.valid.removed)
+ vectors.valid.entries.forEach((e, i) => expect(devLogHash(e as never)).toBe(vectors.valid.hashes[i]))
+ })
+
+ it('re-signs every valid entry to the same signature (Ed25519 is deterministic)', () => {
+ const seeds = vectors.seeds as Record<string, string>
+ const byPub = new Map(Object.entries(vectors.pubs).map(([name, pub]) => [pub, b64d(seeds[name])]))
+ for (const e of vectors.valid.entries) {
+ const { sig, ...unsigned } = e
+ expect(signDevLogEntry(unsigned as never, byPub.get(e.signer)!).sig).toBe(sig)
+ }
+ })
+
+ for (const c of vectors.invalid) {
+ it(`refuses: ${c.name} (${c.code})`, () => {
+ const base = applyDevLogEntries(emptyDevLogState(vectors.acct), vectors.valid.entries.slice(0, c.after)).state
+ let code: string | null = null
+ try { applyDevLogEntries(base, [c.entry]) } catch (err) { code = err instanceof DevLogError ? err.code : String(err) }
+ expect(code).toBe(c.code)
+ })
+ }
+})
+
+describe('applyDevLogEntries', () => {
+ const full = (): DevLogState => applyDevLogEntries(emptyDevLogState(vectors.acct), vectors.valid.entries).state
+
+ it('is all or nothing: a bad entry after good ones leaves the state untouched', () => {
+ const start = emptyDevLogState(vectors.acct)
+ const bad = { ...vectors.valid.entries[1], label: 'tampered' }
+ expect(() => applyDevLogEntries(start, [vectors.valid.entries[0], bad])).toThrow(DevLogError)
+ expect(start.head.seq).toBe(0)
+ expect(start.hashes).toEqual([])
+ })
+
+ it('applies incrementally to the same result as all at once', () => {
+ let s = emptyDevLogState(vectors.acct)
+ for (const e of vectors.valid.entries) s = applyDevLogEntries(s, [e]).state
+ expect(s).toEqual(full())
+ })
+
+ it('reports what each step added, removed and relabeled', () => {
+ const e = vectors.valid.entries
+ const upTo3 = applyDevLogEntries(emptyDevLogState(vectors.acct), e.slice(0, 3))
+ expect(upTo3.added.map(m => m.label)).toEqual(['box1', 'box2', e[2].label])
+ const step = applyDevLogEntries(upTo3.state, e.slice(3, 5))
+ expect(step.added).toEqual([])
+ expect(step.relabeled.map(m => m.label)).toEqual(['box1 (renamed)'])
+ expect(step.removed.map(m => m.pub)).toEqual([vectors.pubs.box2])
+ })
+
+ it('lets a device leave on its own signature', () => {
+ const s = full()
+ const seed = b64d(vectors.seeds.browser)
+ const m = s.active[vectors.pubs.browser]
+ const leave = signDevLogEntry(nextDevLogEntry(s, { op: 'remove', pub: m.pub, kind: m.kind, machineId: m.machineId, label: m.label, signer: m.pub }, 10_000), seed)
+ const after = applyDevLogEntries(s, [leave]).state
+ expect(after.active[vectors.pubs.browser]).toBeUndefined()
+ expect(after.removed).toContain(vectors.pubs.browser)
+ })
+})
+
+describe('compareDevLogHead', () => {
+ const s = applyDevLogEntries(emptyDevLogState(vectors.acct), vectors.valid.entries.slice(0, 4)).state
+
+ it('tells same, ahead, behind and fork apart', () => {
+ expect(compareDevLogHead(s, s.head)).toBe('same')
+ expect(compareDevLogHead(s, { seq: 2, hash: devLogHashAt(s, 2)! })).toBe('ahead')
+ expect(compareDevLogHead(s, { seq: 0, hash: devLogHashAt(s, 0)! })).toBe('ahead')
+ expect(compareDevLogHead(s, { seq: 6, hash: vectors.valid.hashes[5] })).toBe('behind')
+ expect(compareDevLogHead(s, { seq: 3, hash: vectors.valid.hashes[1] })).toBe('fork')
+ })
+})
diff --git a/cli/src/lib/e2ee/deviceLog.ts b/cli/src/lib/e2ee/deviceLog.ts
new file mode 100644
index 000000000..00afd09a7
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceLog.ts
@@ -0,0 +1,274 @@
+/**
+ * The device key log — an account's append-only, hash-chained list of the identity keys its devices
+ * (machines and viewer apps) hold. Every device trusts the keys the log says are active, so signing in
+ * is all it takes for an account's machines to reach each other end to end, with no remote password.
+ *
+ * The backend stores and serves the log but cannot forge an entry: an `add` is signed by the key it
+ * adds, a `remove` by a key that is active at that point. What the backend CAN do — add a device of its
+ * own — is not prevented, only made visible: every device announces a key it has not trusted before
+ * ("New device: X"), and devices gossip the log's head over their E2EE sessions (`group_sync`), so a
+ * backend that shows two devices different logs, or hides an entry from one, is caught.
+ *
+ * Pure: no I/O. Signatures and hashes cover a length-prefixed binary encoding of the fields in a fixed
+ * order (as `helloSig` does) — never JSON, whose canonical form drifts between TS and Dart. JSON is
+ * only the wire format.
+ *
+ * ⚠ Ported to Dart (desktop/lib/viewer/device_log.dart, mobile/lib/viewer/device_log.dart) and copied
+ * into the backend (backend/src/lib/deviceLogCore.ts, identical below the imports). All of them are
+ * held to deviceLog.vectors.json; change the format in every copy together.
+ */
+import { ed25519 } from '@noble/curves/ed25519'
+import { sha256 } from '@noble/hashes/sha2'
+
+export const DEVLOG_VERSION = 1
+/** How many keys one account may have active at once. */
+export const DEVLOG_MAX_ACTIVE = 256
+export const DEVLOG_LABEL_MAX = 60
+
+export type DevLogOp = 'add' | 'remove'
+export type DevLogKind = 'machine' | 'viewer'
+
+export interface DevLogEntry {
+ v: number
+ /** The account (backend User id) the log belongs to. */
+ acct: string
+ /** 1-based position in the log. */
+ seq: number
+ /** base64 hash of the previous entry; 32 zero bytes for the first. */
+ prev: string
+ op: DevLogOp
+ /** base64 Ed25519 key the entry is about. */
+ pub: string
+ kind: DevLogKind
+ /** A machine's id; '' for a viewer. */
+ machineId: string
+ label: string
+ /** Milliseconds since the epoch, as the signer's clock read it. */
+ at: number
+ /** base64 Ed25519 key that signed the entry. */
+ signer: string
+ sig: string
+}
+
+export type UnsignedDevLogEntry = Omit<DevLogEntry, 'sig'>
+
+export interface DevLogMember {
+ pub: string
+ kind: DevLogKind
+ machineId: string
+ label: string
+ /** `at` of the entry that added it. */
+ addedAt: number
+ /** seq of the entry that added it. */
+ seq: number
+}
+
+export interface DevLogHead { seq: number; hash: string }
+
+export interface DevLogState {
+ acct: string
+ head: DevLogHead
+ /** hashes[i] is the hash of the entry with seq i + 1. */
+ hashes: string[]
+ /** Active keys, by pub. */
+ active: Record<string, DevLogMember>
+ /** Keys a `remove` took out. A removed key never comes back: a device that returns uses a new one. */
+ removed: string[]
+}
+
+export type DevLogErrorCode =
+ | 'BAD_ENTRY'
+ | 'WRONG_ACCOUNT'
+ | 'OUT_OF_ORDER'
+ | 'BROKEN_CHAIN'
+ | 'BAD_SIGNATURE'
+ | 'NOT_SELF_SIGNED'
+ | 'KEY_REMOVED'
+ | 'KIND_CHANGED'
+ | 'NO_CHANGE'
+ | 'MACHINE_TAKEN'
+ | 'TOO_MANY'
+ | 'SIGNER_NOT_ACTIVE'
+ | 'NOT_ACTIVE'
+
+export class DevLogError extends Error {
+ constructor(readonly code: DevLogErrorCode, readonly seq: number) {
+ super(`device log entry ${seq}: ${code}`)
+ }
+}
+
+const HAS_BUFFER = typeof Buffer !== 'undefined'
+const MACHINE_ID_RE = /^[a-f0-9]{32}$/
+const ZERO_HASH = b64e(new Uint8Array(32))
+
+function b64e(u: Uint8Array): string {
+ if (HAS_BUFFER) return Buffer.from(u).toString('base64')
+ let s = ''
+ for (let i = 0; i < u.length; i++) s += String.fromCharCode(u[i])
+ return btoa(s)
+}
+function b64d(s: string): Uint8Array {
+ if (HAS_BUFFER) return new Uint8Array(Buffer.from(s, 'base64'))
+ const bin = atob(s)
+ const u = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i)
+ return u
+}
+/** base64 of exactly [n] bytes, in its one canonical spelling; null otherwise. */
+function bytesOf(s: unknown, n: number): Uint8Array | null {
+ if (typeof s !== 'string' || s.length > 128) return null
+ try {
+ const u = b64d(s)
+ return u.length === n && b64e(u) === s ? u : null
+ } catch { return null }
+}
+function lvCat(...parts: Array<Uint8Array | string>): Uint8Array {
+ const chunks: Uint8Array[] = []
+ let total = 0
+ for (const p of parts) {
+ const b = typeof p === 'string' ? new TextEncoder().encode(p) : p
+ const len = new Uint8Array(4)
+ new DataView(len.buffer).setUint32(0, b.length, false)
+ chunks.push(len, b)
+ total += 4 + b.length
+ }
+ const out = new Uint8Array(total)
+ let off = 0
+ for (const c of chunks) { out.set(c, off); off += c.length }
+ return out
+}
+
+/** The bytes a signature covers. Numbers are written in decimal, so every language agrees. */
+export function devLogMessage(e: UnsignedDevLogEntry): Uint8Array {
+ return lvCat(
+ 'harness-devlog-v1', String(e.v), e.acct, String(e.seq), b64d(e.prev), e.op, b64d(e.pub),
+ e.kind, e.machineId, e.label, String(e.at), b64d(e.signer),
+ )
+}
+
+/** The entry's hash: what the next entry's `prev` names. */
+export function devLogHash(e: DevLogEntry): string {
+ return b64e(sha256(lvCat(devLogMessage(e), b64d(e.sig))))
+}
+
+export function signDevLogEntry(e: UnsignedDevLogEntry, priv: Uint8Array): DevLogEntry {
+ return { ...e, sig: b64e(ed25519.sign(devLogMessage(e), priv)) }
+}
+
+export function emptyDevLogState(acct: string): DevLogState {
+ return { acct, head: { seq: 0, hash: ZERO_HASH }, hashes: [], active: {}, removed: [] }
+}
+
+/** Every field present, of its type and within bounds; null when anything is off. */
+export function parseDevLogEntry(raw: unknown): DevLogEntry | null {
+ if (!raw || typeof raw !== 'object') return null
+ const r = raw as Record<string, unknown>
+ const { v, acct, seq, prev, op, pub, kind, machineId, label, at, signer, sig } = r
+ if (v !== DEVLOG_VERSION) return null
+ if (typeof acct !== 'string' || !acct || acct.length > 128) return null
+ if (!Number.isSafeInteger(seq) || (seq as number) < 1) return null
+ if (!bytesOf(prev, 32) || !bytesOf(pub, 32) || !bytesOf(signer, 32) || !bytesOf(sig, 64)) return null
+ if (op !== 'add' && op !== 'remove') return null
+ if (kind !== 'machine' && kind !== 'viewer') return null
+ if (typeof machineId !== 'string') return null
+ if (kind === 'machine' ? !MACHINE_ID_RE.test(machineId) : machineId !== '') return null
+ // A label is shown as is: refuse control characters rather than rewrite what was signed.
+ if (typeof label !== 'string' || label.length > DEVLOG_LABEL_MAX || /[\u0000-\u001f\u007f]/.test(label)) return null
+ if (!Number.isSafeInteger(at) || (at as number) <= 0) return null
+ return {
+ v, acct, seq: seq as number, prev: prev as string, op, pub: pub as string, kind, machineId, label,
+ at: at as number, signer: signer as string, sig: sig as string,
+ }
+}
+
+function cloneState(s: DevLogState): DevLogState {
+ return { acct: s.acct, head: { ...s.head }, hashes: [...s.hashes], active: { ...s.active }, removed: [...s.removed] }
+}
+
+export interface DevLogApplied {
+ state: DevLogState
+ /** Keys that became active (a label change is not one). */
+ added: DevLogMember[]
+ /** Keys that were active and are not any more. */
+ removed: DevLogMember[]
+ /** Keys whose label changed. */
+ relabeled: DevLogMember[]
+}
+
+/**
+ * Apply [entries], in order, on top of [state]. All or nothing: the first entry that breaks a rule
+ * throws a [DevLogError] and [state] is left as it was.
+ */
+export function applyDevLogEntries(state: DevLogState, entries: readonly unknown[]): DevLogApplied {
+ const s = cloneState(state)
+ const out: DevLogApplied = { state: s, added: [], removed: [], relabeled: [] }
+ for (const raw of entries) {
+ const expectedSeq = s.head.seq + 1
+ const e = parseDevLogEntry(raw)
+ if (!e) throw new DevLogError('BAD_ENTRY', expectedSeq)
+ if (e.acct !== s.acct) throw new DevLogError('WRONG_ACCOUNT', e.seq)
+ if (e.seq !== expectedSeq) throw new DevLogError('OUT_OF_ORDER', e.seq)
+ if (e.prev !== s.head.hash) throw new DevLogError('BROKEN_CHAIN', e.seq)
+ let signed = false
+ try { signed = ed25519.verify(b64d(e.sig), devLogMessage(e), b64d(e.signer)) } catch { signed = false }
+ if (!signed) throw new DevLogError('BAD_SIGNATURE', e.seq)
+
+ if (e.op === 'add') {
+ if (e.signer !== e.pub) throw new DevLogError('NOT_SELF_SIGNED', e.seq)
+ if (s.removed.includes(e.pub)) throw new DevLogError('KEY_REMOVED', e.seq)
+ const current = s.active[e.pub]
+ if (current) {
+ if (current.kind !== e.kind || current.machineId !== e.machineId) throw new DevLogError('KIND_CHANGED', e.seq)
+ if (current.label === e.label) throw new DevLogError('NO_CHANGE', e.seq)
+ const relabeled = { ...current, label: e.label }
+ s.active[e.pub] = relabeled
+ out.relabeled.push(relabeled)
+ } else {
+ if (e.kind === 'machine' && Object.values(s.active).some(m => m.kind === 'machine' && m.machineId === e.machineId)) {
+ throw new DevLogError('MACHINE_TAKEN', e.seq)
+ }
+ if (Object.keys(s.active).length >= DEVLOG_MAX_ACTIVE) throw new DevLogError('TOO_MANY', e.seq)
+ const member: DevLogMember = { pub: e.pub, kind: e.kind, machineId: e.machineId, label: e.label, addedAt: e.at, seq: e.seq }
+ s.active[e.pub] = member
+ out.added.push(member)
+ }
+ } else {
+ if (!s.active[e.signer]) throw new DevLogError('SIGNER_NOT_ACTIVE', e.seq)
+ const gone = s.active[e.pub]
+ if (!gone) throw new DevLogError('NOT_ACTIVE', e.seq)
+ delete s.active[e.pub]
+ s.removed.push(e.pub)
+ out.removed.push(gone)
+ }
+ const hash = devLogHash(e)
+ s.hashes.push(hash)
+ s.head = { seq: e.seq, hash }
+ }
+ return out
+}
+
+/** The hash this state holds for [seq]; null when it does not reach that far. */
+export function devLogHashAt(state: DevLogState, seq: number): string | null {
+ if (seq === 0) return ZERO_HASH
+ return seq >= 1 && seq <= state.hashes.length ? state.hashes[seq - 1] : null
+}
+
+/**
+ * How another device's head relates to ours: the same log, one of us ahead of the other on the same
+ * log, or a FORK — two different entries at one position, which only a lying backend produces.
+ */
+export function compareDevLogHead(state: DevLogState, theirs: DevLogHead): 'same' | 'behind' | 'ahead' | 'fork' {
+ if (theirs.seq > state.head.seq) return 'behind'
+ const ours = devLogHashAt(state, theirs.seq)
+ if (ours !== theirs.hash) return 'fork'
+ return theirs.seq === state.head.seq ? 'same' : 'ahead'
+}
+
+/** The next entry to append on top of [state], unsigned. */
+export function nextDevLogEntry(
+ state: DevLogState,
+ fields: Pick<DevLogEntry, 'op' | 'pub' | 'kind' | 'machineId' | 'label' | 'signer'>,
+ at: number,
+): UnsignedDevLogEntry {
+ return { v: DEVLOG_VERSION, acct: state.acct, seq: state.head.seq + 1, prev: state.head.hash, at, ...fields }
+}
diff --git a/cli/src/lib/e2ee/deviceLog.vectors.json b/cli/src/lib/e2ee/deviceLog.vectors.json
new file mode 100644
index 000000000..223b62521
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceLog.vectors.json
@@ -0,0 +1,375 @@
+{
+ "comment": "Generated by cli/scripts/gen-devlog-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4, box2b=5).",
+ "acct": "acct-vectors-1",
+ "seeds": {
+ "box1": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
+ "box2": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=",
+ "browser": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "stranger": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ=",
+ "box2b": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU="
+ },
+ "pubs": {
+ "box1": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "box2": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "browser": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "stranger": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "box2b": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E="
+ },
+ "valid": {
+ "entries": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 1000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "PQ79548gYy1fR00xYYrAqGYQer//uS3fGo1Xwwih7v6Jpw8lLHsM/plOYoenu8qjIWhPTSPlVSghlAt9C6MMCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 2000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "bHi9oSluvJ/RKgTw7RZrPaplcR45FGkVMmnOjm4dQnTzchKsMN6D6WKTNphHLjthUYhcznmjIJDLjplJ5TKsAg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 3000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "Browser · macOS — “Dee”",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "NK0FM6TeU5KyGr78swAvqDRYvHQafuMj/pBBxMANdNdALGrcA3pA+h4WMarQT81Ker2W0ALWvAcufmSkOxjiCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "qNFvpVnzstkVYeTrds5NiQ6EyfyImRIhjndzUjzO/eA=",
+ "at": 4000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1 (renamed)",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "ccsh5GRy/OZkP+l50LN90T+8O1Ca0dcOmdm2pCJlF1ccTNC+ZPwoZ3NujkS2uJORP/xwu9xZ7gSqBhQ3XaWzCg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 5,
+ "prev": "NiCtLf6zNhboU5bHOg8pggpUZxeuey5a0KGQ4lHyehE=",
+ "at": 5000,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "1LAIjj3C77/H5v7LxR1QFYfxTrjJbRFTdk/0nvAmTIOYAoH42xLvqwh3e8bHsvH32GmfNNvARRSGTuXKTkZMBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 6,
+ "prev": "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "at": 6000,
+ "op": "add",
+ "pub": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "sig": "cwe4qUy9BDLShHXA8IhIMxs/ZbdF/a2Js7IqpQyNBV/FjcCS/eoGDEufpS0+sPPAhDlky2K1vpgwVS0PIakyCw=="
+ }
+ ],
+ "hashes": [
+ "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "qNFvpVnzstkVYeTrds5NiQ6EyfyImRIhjndzUjzO/eA=",
+ "NiCtLf6zNhboU5bHOg8pggpUZxeuey5a0KGQ4lHyehE=",
+ "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "f5WzxT87hry0q9rj895yyaiCax/xP2PRZCCfpGPKDTw="
+ ],
+ "head": {
+ "seq": 6,
+ "hash": "f5WzxT87hry0q9rj895yyaiCax/xP2PRZCCfpGPKDTw="
+ },
+ "active": [
+ "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w="
+ ],
+ "removed": [
+ "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q="
+ ]
+ },
+ "invalid": [
+ {
+ "name": "tampered label",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "evil",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "udynDrC1h7IK8lrCs+AqPLpTCNeQxD4DlkQP6BOQZD+oNquOndvYqEPmU60wE9JTin8YYVFboZ6jyzxl5YSQAw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "add signed by another key",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "RL5wtkxLhLIkWpUBZ+njRYIh0KqeuYc1pIoEQQ9oAfs2xFa5UwpLJhI4sia2HXI+dovYK+igVD0HnE4QoF3BDA=="
+ },
+ "code": "NOT_SELF_SIGNED"
+ },
+ {
+ "name": "machine id of another active machine",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "imposter",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "KJulD+38Nt9i6HNhMZwVemE3wXIrLOLsMbd1A2BxIC4hke7aKwN6itY04iSRbLqOGlDzOPwi0GUGj0ZrW0DcCQ=="
+ },
+ "code": "MACHINE_TAKEN"
+ },
+ {
+ "name": "removed key comes back",
+ "after": 5,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 6,
+ "prev": "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "at": 9000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2 again",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "AyV+EkrCunkAI12uokVnsclD26e2n5ZDIvNqxxoABvxdvgDvSXnXDdJ8EVFFro3FK9ROh0ATNh3FQVoUWa/9CQ=="
+ },
+ "code": "KEY_REMOVED"
+ },
+ {
+ "name": "remove signed by a key not in the log",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "remove",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "xkp6fed+m63wylf9c1Zaz3YXtwPhOgbMzpKqCkXuNo06UfKfPmJx4/BD2OY+Wt+E03hUUrB438ME1gLjzp4VBg=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "remove of a key not in the log",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "remove",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "Vh2WinwrdWHv46djCCkZ+p0QtWlALCHXBIPHgYkSi9Zpys93JPYhaJIJhEcdQYwQuYvEF2IVtxK2um1IaQgJDg=="
+ },
+ "code": "NOT_ACTIVE"
+ },
+ {
+ "name": "wrong prev",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "nPbFpdYE1xqmdxxL8fj77CeBVrosx4N847Zy9gqngg5bBdcyqzMRsHSm/q0OTuW6VEwIzk66/OCMcwuT1HERBA=="
+ },
+ "code": "BROKEN_CHAIN"
+ },
+ {
+ "name": "skipped seq",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "wJqA4rLVUCIewTr/eeeMxSKX2yv9wQOFhqGVws0+1QITAdgkZwGNIWbpBptIlFrcNyh3oRTFMdGWykfeqkTcAA=="
+ },
+ "code": "OUT_OF_ORDER"
+ },
+ {
+ "name": "other account",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-other",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "eXH3aVMs0jDDzFg3xehB+Z7G6h2jyvjZcHGm128CIvVwcWDSytwHRAY+g4iXpYkBeJxhksoCOdgpNQds69xMDQ=="
+ },
+ "code": "WRONG_ACCOUNT"
+ },
+ {
+ "name": "machine changes kind",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "c2mJ6r5OoEW7bY0EERqWBt8z37H5ExY59f5KiP6mtRSv5adSQjT5HxzlGXgcILOjLUPIFijE16cGPM++CdJXCg=="
+ },
+ "code": "KIND_CHANGED"
+ },
+ {
+ "name": "re-add with nothing changed",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "fjF5dBSdSDddFJdLDmYWaleR4RniUf62lI0Fbdb4vTkXp8cXo4rwqAcGncZt5yCHOK2F7pYg56FUbbospfIuAg=="
+ },
+ "code": "NO_CHANGE"
+ },
+ {
+ "name": "viewer with a machine id",
+ "after": 0,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 9000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "b",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "2t+mAiwKKqhImNoq+7HVp7bXdf1UeL7Vd4QOmEiS1fsGG1Ux6+HVKjosKKzX/wzQo9ju84Yd3x12teETgIsjAQ=="
+ },
+ "code": "BAD_ENTRY"
+ },
+ {
+ "name": "control character in label",
+ "after": 0,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 9000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "a\nb",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "lzDA+QfWL9V5issDES2f9vRw/CX2Tv6dk8nF6ZmwcJ87kyegBoWh1TkUL6RXVS+8vacy9vLJd+keCMwpsCOqAA=="
+ },
+ "code": "BAD_ENTRY"
+ }
+ ]
+}
diff --git a/cli/src/lib/e2ee/deviceLogStore.ts b/cli/src/lib/e2ee/deviceLogStore.ts
new file mode 100644
index 000000000..0baa50107
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceLogStore.ts
@@ -0,0 +1,60 @@
+/**
+ * This machine's copy of its account's device key log (deviceLog.ts): the verified state, the last few
+ * 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.
+ */
+import { mkdirSync, readFileSync, writeFileSync } from 'fs'
+import { join } from 'path'
+import { env } from '../../config/env.js'
+import type { DevLogEntry, DevLogHead, DevLogState } from './deviceLog.js'
+
+/** How many of the newest entries are kept verbatim, for a peer that is behind. */
+export const DEVLOG_RECENT = 64
+
+export interface DevLogFreeze {
+ /** 'fork' — two different entries at one position; 'rollback' — the backend served a log older than
+ * one already verified; 'invalid' — the backend served an entry that breaks a rule. */
+ reason: 'fork' | 'rollback' | 'invalid'
+ at: number
+ /** The last head this machine verified before it froze. */
+ lastGoodHead: DevLogHead
+}
+
+export interface DevLogFile {
+ state: DevLogState | null
+ recent: DevLogEntry[]
+ frozen: DevLogFreeze | null
+ /** Entries up to this seq have been announced ("New device: X") — never twice. */
+ notifiedUpTo: number
+}
+
+const empty = (): DevLogFile => ({ state: null, recent: [], frozen: null, notifiedUpTo: 0 })
+
+export class DeviceLogStore {
+ constructor(private readonly file = join(env.ADAPTER_DATA_DIR, 'e2e', 'devlog.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,
+ }
+ } 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 })
+ }
+
+ update(change: (current: DevLogFile) => DevLogFile): DevLogFile {
+ const next = change(this.read())
+ this.write(next)
+ return next
+ }
+}
diff --git a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts
new file mode 100644
index 000000000..5932abd1c
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts
@@ -0,0 +1,284 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { ed25519 } from '@noble/curves/ed25519'
+import {
+ applyDevLogEntries, DevLogError, emptyDevLogState, nextDevLogEntry, signDevLogEntry,
+ type DevLogEntry, type DevLogState,
+} from './deviceLog.js'
+import { DeviceLogStore } from './deviceLogStore.js'
+import { DeviceLogSyncer, type DeviceLogAppendAnswer, type DeviceLogFetched } from './deviceLogSyncer.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)) } }
+const ACCT = 'acct-1'
+const me = key(1), box2 = key(2), phone = key(3), evil = key(9)
+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 {
+ entries: DevLogEntry[] = []
+ state: DevLogState = emptyDevLogState(ACCT)
+ /** When set, what `fetch` serves instead of the real log. */
+ lie: DevLogEntry[] | null = null
+ offline = false
+
+ add(k: { priv: Uint8Array; pub: string }, kind: 'machine' | 'viewer', machineId: string, label: string, at = 1_000): DevLogEntry {
+ const e = signDevLogEntry(nextDevLogEntry(this.state, { op: 'add', pub: k.pub, kind, machineId, label, signer: k.pub }, at), k.priv)
+ this.push(e)
+ return e
+ }
+
+ removeBy(target: string, by: { priv: Uint8Array; pub: string }): DevLogEntry {
+ const t = this.state.active[target]
+ const e = signDevLogEntry(nextDevLogEntry(this.state, { op: 'remove', pub: t.pub, kind: t.kind, machineId: t.machineId, label: t.label, signer: by.pub }, 2_000), by.priv)
+ this.push(e)
+ return e
+ }
+
+ private push(e: DevLogEntry): void {
+ this.state = applyDevLogEntries(this.state, [e]).state
+ this.entries.push(e)
+ }
+
+ 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) }
+ })
+
+ append = vi.fn(async (entry: DevLogEntry): Promise<DeviceLogAppendAnswer | null> => {
+ if (this.offline) return null
+ if (entry.seq !== this.state.head.seq + 1 || entry.prev !== this.state.head.hash) return { error: 'STALE_HEAD', head: this.state.head }
+ try { this.push(entry) } catch (err) { return { error: err instanceof DevLogError ? err.code : 'X' } }
+ return { head: this.state.head }
+ })
+}
+
+function setup(opts: { known?: string[]; tombstoned?: string[]; blocked?: string[] } = {}) {
+ const backend = new FakeBackend()
+ const 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(),
+ }
+ const tombstoned = new Set(opts.tombstoned ?? [])
+ const syncer = new DeviceLogSyncer({
+ store,
+ identity: () => me,
+ 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),
+ tombstoned: (pub) => tombstoned.has(pub),
+ blocked: (pub) => (opts.blocked ?? []).includes(pub),
+ announce: calls.announce,
+ signedOut: calls.signedOut,
+ changed: calls.changed,
+ now: () => 5_000,
+ sleep: async () => {},
+ })
+ return { backend, store, syncer, calls }
+}
+
+describe('DeviceLogSyncer', () => {
+ let t: ReturnType<typeof setup>
+ beforeEach(() => { t = setup() })
+
+ it('registers this machine into an empty log, without announcing anything', async () => {
+ await t.syncer.register()
+ expect(t.backend.state.active[me.pub]).toMatchObject({ kind: 'machine', machineId: MID_ME, label: 'my-mac' })
+ expect(t.store.read().state?.head).toEqual(t.backend.state.head)
+ expect(t.calls.announce).not.toHaveBeenCalled()
+ })
+
+ it('does not register twice', async () => {
+ await t.syncer.register()
+ await t.syncer.register()
+ expect(t.backend.entries).toHaveLength(1)
+ })
+
+ it('on first read of an existing log trusts every device but announces none (an old sign-in joining)', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.register()
+ expect(t.calls.adopt).toHaveBeenCalledWith(expect.arrayContaining([
+ expect.objectContaining({ pub: box2.pub }), expect.objectContaining({ pub: phone.pub }),
+ ]))
+ expect(t.calls.announce).not.toHaveBeenCalled()
+ })
+
+ it('announces a device it never trusted, once, and trusts it', async () => {
+ await t.syncer.register()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ await t.syncer.refresh()
+ expect(t.calls.adopt).toHaveBeenLastCalledWith([expect.objectContaining({ pub: box2.pub, machineId: MID2 })])
+ expect(t.calls.announce).toHaveBeenCalledOnce()
+ expect(t.calls.announce).toHaveBeenCalledWith(expect.objectContaining({ pub: box2.pub, label: 'box2' }))
+ })
+
+ it('does not announce a device this machine already trusted before the log', async () => {
+ t = setup({ known: [box2.pub] })
+ await t.syncer.register()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.refresh()
+ expect(t.calls.adopt).toHaveBeenCalled()
+ expect(t.calls.announce).not.toHaveBeenCalled()
+ })
+
+ it('forgets a removed device', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.removeBy(box2.pub, me)
+ await t.syncer.refresh()
+ expect(t.calls.drop).toHaveBeenCalledWith(box2.pub)
+ })
+
+ it('signs out when its own key is removed', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.removeBy(me.pub, box2)
+ await t.syncer.refresh()
+ expect(t.calls.signedOut).toHaveBeenCalled()
+ })
+
+ it('removes a device with an entry it signs, and drops it at once', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ expect(await t.syncer.remove(box2.pub)).toEqual({ ok: true })
+ expect(t.backend.state.active[box2.pub]).toBeUndefined()
+ expect(t.backend.entries.at(-1)).toMatchObject({ op: 'remove', pub: box2.pub, signer: me.pub })
+ expect(t.calls.drop).toHaveBeenCalledWith(box2.pub)
+ })
+
+ it('two removals of one key at once append one entry', async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ const [a, b] = await Promise.all([t.syncer.remove(box2.pub), t.syncer.remove(box2.pub)])
+ expect(a).toEqual({ ok: true })
+ expect(b).toEqual({ ok: true })
+ expect(t.backend.entries.filter((e) => e.op === 'remove')).toHaveLength(1)
+ })
+
+ it('retries an append that lost the race to another device', async () => {
+ await t.syncer.refresh()
+ // Another device appends between this machine's read and its append.
+ const original = t.backend.append.getMockImplementation()!
+ t.backend.append.mockImplementationOnce(async (e) => { t.backend.add(phone, 'viewer', '', 'phone'); return original(e) })
+ await t.syncer.register()
+ expect(t.backend.state.active[me.pub]).toBeDefined()
+ expect(t.backend.append).toHaveBeenCalledTimes(2)
+ })
+
+ it('writes a removal the trust group made before the log into the log', async () => {
+ t = setup({ tombstoned: [box2.pub] })
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ await vi.waitFor(() => expect(t.backend.state.removed).toContain(box2.pub))
+ expect(t.calls.adopt.mock.calls.flat(2).some((m: { pub: string }) => m.pub === box2.pub)).toBe(false)
+ })
+
+ it('never adopts a key this machine unpaired locally', async () => {
+ t = setup({ blocked: [box2.pub] })
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ expect(t.calls.adopt.mock.calls.flat(2).some((m: { pub: string }) => m.pub === box2.pub)).toBe(false)
+ })
+
+ describe('a backend that lies', () => {
+ beforeEach(async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ })
+
+ it('freezes on a rewritten log and adds nothing more from it', async () => {
+ const forged = new FakeBackend()
+ forged.add(box2, 'machine', MID2, 'box2')
+ forged.add(evil, 'viewer', '', 'evil')
+ forged.add(phone, 'viewer', '', 'phone')
+ t.backend.lie = forged.entries
+ await t.syncer.refresh()
+ expect(t.store.read().frozen?.reason).toBe('fork')
+ expect(t.calls.adopt.mock.calls.flat(2).some((m: { pub: string }) => m.pub === evil.pub)).toBe(false)
+ expect(t.syncer.list().frozen).not.toBeNull()
+ })
+
+ it('freezes on a log rolled back behind what it verified', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ expect(t.store.read().frozen?.reason).toBe('rollback')
+ })
+
+ it('still honours a removal signed by a trusted key while frozen', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ t.backend.lie = null
+ t.backend.removeBy(box2.pub, me)
+ await t.syncer.refresh()
+ expect(t.calls.drop).toHaveBeenCalledWith(box2.pub)
+ expect(t.store.read().frozen).not.toBeNull()
+ })
+
+ it('shows what trusting the log again changes, and does it only when confirmed', async () => {
+ t.backend.lie = t.backend.entries.slice(0, 1)
+ await t.syncer.refresh()
+ 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(t.store.read().frozen).not.toBeNull()
+ await t.syncer.rebaseline(true)
+ expect(t.store.read().frozen).toBeNull()
+ expect(t.store.read().state?.head).toEqual(t.backend.state.head)
+ })
+ })
+
+ describe('gossip over group_sync', () => {
+ beforeEach(async () => {
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ })
+
+ it('sends its head', () => {
+ expect(t.syncer.gossip()).toEqual({ head: t.backend.state.head, frozen: false })
+ })
+
+ it('freezes when a peer holds a different entry at a position it verified', () => {
+ const other = new FakeBackend()
+ other.add(evil, 'viewer', '', 'evil')
+ other.add(phone, 'viewer', '', 'phone')
+ t.syncer.heard(box2.pub, { head: other.state.head })
+ expect(t.store.read().frozen?.reason).toBe('fork')
+ })
+
+ it('hands a peer that is behind the entries it lacks', () => {
+ const answer = t.syncer.heard(box2.pub, { head: { seq: 1, hash: t.backend.state.hashes[0] } })
+ expect((answer?.tail as DevLogEntry[]).map((e) => e.seq)).toEqual([2])
+ })
+
+ it('takes a removal the backend held back from a peer that is ahead, then freezes on the rollback', async () => {
+ const heldBack = t.backend.removeBy(box2.pub, me)
+ t.backend.lie = t.backend.entries.slice(0, 2)
+ t.syncer.heard(box2.pub, { head: t.backend.state.head, tail: [heldBack] })
+ expect(t.calls.drop).toHaveBeenCalledWith(box2.pub)
+ await t.syncer.refresh()
+ expect(t.store.read().frozen?.reason).toBe('rollback')
+ })
+
+ 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'])
+ })
+ })
+
+ it('does nothing without a backend log (an older backend)', async () => {
+ t.backend.offline = true
+ await t.syncer.register()
+ expect(t.store.read().state).toBeNull()
+ expect(t.calls.adopt).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/lib/e2ee/deviceLogSyncer.ts b/cli/src/lib/e2ee/deviceLogSyncer.ts
new file mode 100644
index 000000000..c44e25b60
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceLogSyncer.ts
@@ -0,0 +1,358 @@
+/**
+ * Keeps this machine in step with its account's device key log (deviceLog.ts) and turns what the log
+ * says into trust: every key the log leaves active is trusted here, through the same path a trust-group
+ * member is (GroupSyncer), and every key a `remove` takes out is forgotten.
+ *
+ * - register(): this machine's own key goes into the log, once per sign-in — so an existing sign-in,
+ * from before the log existed, joins it with no action from anyone.
+ * - refresh(): read the log from the head this machine already verified; verify every new entry.
+ * A backend that rewrote the log (a different entry at a position already verified) or rolled it
+ * back (a head older than one verified) FREEZES it here: no key is added from the log until someone
+ * 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.
+ */
+import {
+ applyDevLogEntries, compareDevLogHead, DevLogError, 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 { b64d, fingerprint, verify } from './core.js'
+
+export interface DeviceLogFetched { acct: string; head: DevLogHead; entries: unknown[] }
+export type DeviceLogAppendAnswer = { head: DevLogHead } | { error: string; head?: DevLogHead }
+
+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 }
+ /** 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. */
+ append: (entry: DevLogEntry) => Promise<DeviceLogAppendAnswer | null>
+ /** Trust these keys here (and tell the trust group, so devices that predate the log learn of them). */
+ 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
+ /** 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". */
+ announce: (member: DevLogMember) => 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). */
+ changed?: () => void
+ log?: (line: string) => void
+ now?: () => number
+ sleep?: (ms: number) => Promise<void>
+}
+
+export interface DeviceLogListing {
+ head: DevLogHead | null
+ frozen: DevLogFreeze | null
+ self: string
+ members: Array<DevLogMember & { fingerprint: string; self: boolean }>
+ /** Machines whose own copy of the log is frozen, as their last `group_sync` said. */
+ frozenPeers: string[]
+}
+
+export type DeviceLogRemoveResult = { ok: true } | { ok: false; error: 'NOT_ACTIVE' | 'NOT_IN_LOG' | 'UNAVAILABLE' | 'REFUSED'; detail?: string }
+
+export interface DeviceLogRebaseline {
+ head: DevLogHead
+ added: DevLogMember[]
+ removed: DevLogMember[]
+}
+
+const APPEND_ATTEMPTS = 5
+const PAGES = 20
+
+export class DeviceLogSyncer {
+ private readonly now: () => number
+ private readonly sleep: (ms: number) => Promise<void>
+ private refreshing: Promise<void> | null = null
+ private readonly frozenPeers = new Map<string, boolean>()
+ private readonly removing = new Set<string>()
+ private readonly inFlightRemovals = new Map<string, Promise<DeviceLogRemoveResult>>()
+
+ constructor(private readonly deps: DeviceLogSyncerDeps) {
+ this.now = deps.now ?? (() => Date.now())
+ this.sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
+ }
+
+ /** Read the log and put this machine's own key into it. Never throws. */
+ async register(): Promise<void> {
+ try {
+ const self = this.deps.self()
+ if (!self.machineId) return
+ await this.refresh()
+ const { pub, priv } = this.deps.identity()
+ for (let attempt = 0; attempt < APPEND_ATTEMPTS; attempt++) {
+ const file = this.deps.store.read()
+ 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) {
+ 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
+ }
+ }
+ const entry = signDevLogEntry(nextDevLogEntry(state, {
+ op: 'add', pub, kind: 'machine', machineId: self.machineId, label: self.label, signer: pub,
+ }, this.now()), priv)
+ const answer = await this.deps.append(entry)
+ if (!answer) return
+ if ('head' in answer && !('error' in answer)) { await this.refresh(); return }
+ if (answer.error !== 'STALE_HEAD') { this.deps.log?.(`[devlog] register refused: ${answer.error}`); return }
+ await this.refresh()
+ await this.sleep(200 + Math.floor(Math.random() * 800) * (attempt + 1))
+ }
+ } catch (err) {
+ this.deps.log?.(`[devlog] register failed: ${err instanceof Error ? err.message : String(err)}`)
+ }
+ }
+
+ /** Read and verify whatever the log gained. Concurrent calls share one read. Never throws. */
+ refresh(): Promise<void> {
+ if (this.refreshing) return this.refreshing
+ this.refreshing = this.doRefresh()
+ .catch((err) => { this.deps.log?.(`[devlog] refresh failed: ${err instanceof Error ? err.message : String(err)}`) })
+ .finally(() => { this.refreshing = null })
+ return this.refreshing
+ }
+
+ private async doRefresh(): Promise<void> {
+ // 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.
+ 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 }
+ this.deps.store.write(fresh)
+ bootstrap = true
+ if (got.head.seq === 0) return
+ if (since !== 0) continue
+ }
+ const current = this.deps.store.read()
+ const state = current.state!
+ if (current.frozen) { this.looseRemovals(got.entries); return }
+ if (got.head.seq < state.head.seq) { this.freeze('rollback'); return }
+ if (got.head.seq === state.head.seq) {
+ if (got.head.hash !== state.head.hash) this.freeze('fork')
+ return
+ }
+ if (!got.entries.length) { this.freeze('invalid'); return }
+ if (!this.accept(got.entries, bootstrap)) return
+ if (this.deps.store.read().state!.head.seq >= got.head.seq) return
+ }
+ }
+
+ /** 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()
+ let applied
+ try {
+ applied = applyDevLogEntries(file.state!, entries)
+ } catch (err) {
+ if (!(err instanceof DevLogError)) throw err
+ this.freeze(err.code === 'BROKEN_CHAIN' || err.code === 'OUT_OF_ORDER' ? 'fork' : 'invalid')
+ 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))
+ const parsed = entries.map((e) => parseDevLogEntry(e)).filter((e): e is DevLogEntry => e !== null)
+ this.deps.store.write({
+ state: applied.state,
+ recent: [...file.recent, ...parsed].slice(-DEVLOG_RECENT),
+ frozen: null,
+ notifiedUpTo: applied.state.head.seq,
+ })
+ 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)
+ if (applied.state.removed.includes(selfPub)) this.deps.signedOut()
+ void this.carryOverTombstones(applied.state)
+ this.deps.changed?.()
+ 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))
+ if (adopt.length) this.deps.adopt(adopt)
+ }
+
+ /** A removal made in the trust group before the log existed must not be undone by the log: this
+ * machine, holding that removal, writes it into the log. */
+ private async carryOverTombstones(state: DevLogState): Promise<void> {
+ const selfPub = this.deps.identity().pub
+ if (!state.active[selfPub]) return
+ for (const m of Object.values(state.active)) {
+ if (m.pub !== selfPub && this.deps.tombstoned(m.pub) && !this.removing.has(m.pub)) await this.remove(m.pub)
+ }
+ }
+
+ /** While frozen, a removal still counts — if a key this machine trusts signed it. */
+ private looseRemovals(entries: readonly unknown[]): void {
+ const file = this.deps.store.read()
+ const state = file.state
+ if (!state) return
+ let changed = false
+ for (const raw of entries) {
+ const e = parseDevLogEntry(raw)
+ if (!e || e.op !== 'remove' || !state.active[e.signer] || !state.active[e.pub]) continue
+ if (!verify(b64d(e.signer), devLogMessage(e), b64d(e.sig))) continue
+ delete state.active[e.pub]
+ state.removed.push(e.pub)
+ this.deps.drop(e.pub)
+ changed = true
+ }
+ if (changed) { this.deps.store.write({ ...file, state }); 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 } })
+ 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?.()
+ }
+
+ /** Remove a device from the log (and so from every device). Signed by this machine. */
+ remove(pub: string): Promise<DeviceLogRemoveResult> {
+ // One removal per key at a time: taking it out here tombstones it in the trust group, which hands
+ // it straight back through `onDropped` — that second ask joins this one.
+ const running = this.inFlightRemovals.get(pub)
+ if (running) return running
+ this.removing.add(pub)
+ const task = this.removeOnce(pub).finally(() => { this.removing.delete(pub); this.inFlightRemovals.delete(pub) })
+ this.inFlightRemovals.set(pub, task)
+ return task
+ }
+
+ private async removeOnce(pub: string): Promise<DeviceLogRemoveResult> {
+ const { pub: selfPub, priv } = this.deps.identity()
+ for (let attempt = 0; attempt < APPEND_ATTEMPTS; attempt++) {
+ const file = this.deps.store.read()
+ const state = file.state
+ if (!state) return { ok: false, error: 'UNAVAILABLE' }
+ const target = state.active[pub]
+ if (!target) return { ok: false, error: 'NOT_IN_LOG' }
+ if (!state.active[selfPub]) return { ok: false, error: 'NOT_ACTIVE' }
+ // Take effect here at once, whatever the backend does with it.
+ this.deps.drop(pub)
+ const entry = signDevLogEntry(nextDevLogEntry(state, {
+ op: 'remove', pub, kind: target.kind, machineId: target.machineId, label: target.label, signer: selfPub,
+ }, this.now()), priv)
+ const answer = await this.deps.append(entry)
+ if (!answer) return { ok: false, error: 'UNAVAILABLE' }
+ if (!('error' in answer)) { await this.refresh(); return { ok: true } }
+ if (answer.error !== 'STALE_HEAD') return { ok: false, error: 'REFUSED', detail: answer.error }
+ await this.refresh()
+ await this.sleep(200 + Math.floor(Math.random() * 800) * (attempt + 1))
+ }
+ 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> {
+ 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
+ acct = got.acct
+ head = got.head
+ entries.push(...got.entries)
+ if (!got.entries.length || entries.length >= got.head.seq) break
+ }
+ let next: DevLogState
+ try {
+ 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 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 })
+ this.trustState(next, Object.values(next.active))
+ for (const m of removed) this.deps.drop(m.pub)
+ this.deps.changed?.()
+ }
+ return { head: next.head, added, removed }
+ }
+
+ /** 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 }
+ }
+
+ /**
+ * A peer's side of a `group_sync`. Returns what to answer (a responder hands back its own head, and
+ * 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 state = file.state
+ const mine = this.gossip()
+ if (!state || !raw || typeof raw !== 'object') return mine
+ const p = raw as { head?: unknown; frozen?: unknown; tail?: unknown }
+ this.frozenPeers.set(peerPub, p.frozen === true)
+ const head = p.head as { seq?: unknown; hash?: unknown } | undefined
+ 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 === '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)
+ // 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()
+ return this.gossip()
+ }
+ if (relation === 'ahead') {
+ const tail = file.recent.filter((e) => e.seq > theirs.seq)
+ if (tail.length && tail[0].seq === theirs.seq + 1) return { ...mine, tail }
+ }
+ return mine
+ }
+
+ /** The account's devices as this machine's log has them, for the Devices list. */
+ list(): DeviceLogListing {
+ const file = this.deps.store.read()
+ const selfPub = this.deps.identity().pub
+ 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 }))
+ 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)))
+ return { head: file.state?.head ?? null, frozen: file.frozen, self: selfPub, members, frozenPeers }
+ }
+}
diff --git a/cli/src/lib/e2ee/groupSyncer.spec.ts b/cli/src/lib/e2ee/groupSyncer.spec.ts
index ba070ee58..6bc4f1191 100644
--- a/cli/src/lib/e2ee/groupSyncer.spec.ts
+++ b/cli/src/lib/e2ee/groupSyncer.spec.ts
@@ -319,6 +319,41 @@ describe('GroupSyncer', () => {
expect(spy).toHaveBeenCalledTimes(1)
for (const n of f.nodes) n.syncer.stop()
})
+
+ it('carries the device key log head both ways, and still works with a peer that has no log', async () => {
+ vi.useFakeTimers()
+ const f = fleet()
+ const [a, b] = [f.add('a'), f.add('b')]
+ f.link(a, b)
+ const heardByA = vi.fn(), heardByB = vi.fn(() => ({ head: { seq: 2, hash: 'hb' }, frozen: false }))
+ a.syncer.devlog = { gossip: () => ({ head: { seq: 1, hash: 'ha' }, frozen: false }), heard: heardByA }
+ b.syncer.devlog = { gossip: () => undefined, heard: heardByB }
+ await a.syncer.syncWith(b.machineId!)
+ expect(heardByB).toHaveBeenCalledWith(a.pub, { head: { seq: 1, hash: 'ha' }, frozen: false })
+ expect(heardByA).toHaveBeenCalledWith(b.pub, { head: { seq: 2, hash: 'hb' }, frozen: false })
+ // An older peer: nothing about the log on the wire, and the roster exchange is unchanged.
+ a.syncer.devlog = null
+ heardByB.mockClear()
+ expect(await a.syncer.syncWith(b.machineId!)).toBe(true)
+ expect(heardByB).toHaveBeenCalledWith(a.pub, undefined)
+ for (const n of f.nodes) n.syncer.stop()
+ })
+
+ it('a key the device key log holds joins the group, so a member that predates the log learns it', async () => {
+ vi.useFakeTimers()
+ const f = fleet()
+ const [a, b] = [f.add('a'), f.add('b')]
+ f.link(a, b)
+ const phonePub = C.b64e(C.newIdentity().pub)
+ a.syncer.adoptFromLog([{ pub: phonePub, kind: 'viewer', machineId: '', label: 'phone', addedAt: 500 }])
+ expect(a.trusted.has(phonePub)).toBe(true)
+ await a.syncer.syncWith(b.machineId!)
+ expect(b.trusted.has(phonePub)).toBe(true)
+ // A removal the group made first is not undone by the log.
+ a.syncer.remove(phonePub)
+ expect(a.syncer.tombstoned(phonePub)).toBe(true)
+ for (const n of f.nodes) n.syncer.stop()
+ })
})
describe('relayRequester', () => {
@@ -350,4 +385,19 @@ describe('relayRequester', () => {
expect(await silent('m', { type: 'group_sync', payload: { requestId: 'r2' } }, 20)).toBeNull()
expect(detached).toBe(2)
})
+
+ it('a removal that arrives through the group is handed on (so the device key log hears of it)', async () => {
+ vi.useFakeTimers()
+ const f = fleet()
+ const [a, b, c] = [f.add('a'), f.add('b'), f.add('c')]
+ f.link(a, b)
+ f.link(a, c)
+ await a.syncer.syncAll()
+ const dropped: string[] = []
+ b.syncer.onDropped = (pub) => dropped.push(pub)
+ a.syncer.remove(c.pub)
+ await a.syncer.syncWith(b.machineId!)
+ expect(dropped).toEqual([c.pub])
+ for (const n of f.nodes) n.syncer.stop()
+ })
})
diff --git a/cli/src/lib/e2ee/groupSyncer.ts b/cli/src/lib/e2ee/groupSyncer.ts
index 8b0891d5d..f1af4ee33 100644
--- a/cli/src/lib/e2ee/groupSyncer.ts
+++ b/cli/src/lib/e2ee/groupSyncer.ts
@@ -16,6 +16,15 @@ import type { LinkedPeer } from './manager.js'
import type { PairedClient } from './store.js'
import { parseMember, parseRoster, rosterDigest, type GroupMember, type MergeResult, type Roster, type TrustGroupStore } from './trustGroup.js'
+/** The device key log's side of a `group_sync` (deviceLogSyncer.ts): its head rides every exchange, so
+ * two devices shown different logs find out, and one that is behind is handed what it is missing. */
+export interface GroupSyncLogGossip {
+ /** What this machine sends with its roster. */
+ gossip: () => Record<string, unknown> | undefined
+ /** What a peer sent; returns what to answer with (a responder's own head, and entries the peer lacks). */
+ heard: (peerPub: string, raw: unknown) => Record<string, unknown> | undefined
+}
+
export const GROUP_SYNC = 'group_sync'
/** The stamp a device's description of ITSELF carries: older than anything, so any removal beats it and
* a removed device cannot sync its way back in — only a new link (stamped now) can. */
@@ -58,6 +67,11 @@ export class GroupSyncer {
private fanOutTimer: ReturnType<typeof setTimeout> | null = null
private periodic: ReturnType<typeof setInterval> | null = null
private retryRound = 0
+ /** Set once the device key log is wired up; the exchange works without it, as with an older peer. */
+ devlog: GroupSyncLogGossip | null = null
+ /** A member the GROUP removed (a tombstone that arrived by `group_sync` — from a device that
+ * predates the device key log, say): the log must hear of it too, or it would trust the key again. */
+ onDropped: ((pub: string) => void) | null = null
constructor(private readonly deps: GroupSyncerDeps) {
this.now = deps.now ?? (() => Date.now())
@@ -111,6 +125,36 @@ export class GroupSyncer {
this.forget(pub)
}
+ /** Keys the device key log holds (deviceLogSyncer.ts): members of the group like any link, stamped
+ * when they joined the log, so a device that predates the log hears of them through the group. */
+ adoptFromLog(members: Array<{ pub: string; kind: GroupMember['kind']; machineId: string; label: string; addedAt: number }>): void {
+ const now = this.now()
+ const parsed = members
+ .map((m) => parseMember({ pub: m.pub, kind: m.kind, label: m.label, at: Math.min(m.addedAt, now), ...(m.machineId ? { machineId: m.machineId } : {}) }, now))
+ .filter((m): m is GroupMember => m !== null)
+ if (!parsed.length) return
+ const before = rosterDigest(this.deps.store.read())
+ const result = this.deps.store.merge({ members: parsed, removed: [] }, this.selfPub())
+ this.apply(result)
+ if (rosterDigest(result.roster) !== before) this.scheduleFanOut(1_000)
+ }
+
+ /** Whether the group removed `pub` and nothing has put it back. */
+ tombstoned(pub: string): boolean {
+ const roster = this.deps.store.read()
+ return roster.removed.some((t) => t.pub === pub) && !roster.members.some((m) => m.pub === pub)
+ }
+
+ /** Whether `pub` is a member of the group. */
+ isMember(pub: string): boolean {
+ return this.deps.store.read().members.some((m) => m.pub === pub)
+ }
+
+ /** Whether this machine's user unpaired `pub` here. */
+ isBlocked(pub: string): boolean {
+ return this.deps.store.blocked().has(pub)
+ }
+
/** A session to `machineId` just opened: a good moment to compare rosters, unless we just did. */
sessionOpened(machineId: string): void {
const last = this.lastSynced.get(machineId) ?? 0
@@ -132,7 +176,8 @@ export class GroupSyncer {
// dialed it before it had heard of us (remoteRelay.ts unlinks a peer that answers e2e_denied).
this.applyAll()
if (rosterDigest(result.roster) !== before) this.scheduleFanOut(1_000)
- return { self: this.deps.self(), ...result.roster, digest: rosterDigest(result.roster) }
+ const devlog = this.devlog?.heard(peerPub, payload.devlog)
+ return { self: this.deps.self(), ...result.roster, digest: rosterDigest(result.roster), ...(devlog ? { devlog } : {}) }
}
/** Initiator side: exchange rosters with one machine; true when it answered. Never throws. */
@@ -173,9 +218,13 @@ export class GroupSyncer {
const pin = this.deps.peers.get(machineId)
if (!pin) return false
const local = this.deps.store.read()
+ const devlog = this.devlog?.gossip()
const reply = await this.deps.request(machineId, {
type: GROUP_SYNC,
- payload: { requestId: `gs-${this.now()}-${Math.random().toString(36).slice(2, 8)}`, self: this.deps.self(), ...local, digest: rosterDigest(local) },
+ payload: {
+ requestId: `gs-${this.now()}-${Math.random().toString(36).slice(2, 8)}`, self: this.deps.self(), ...local, digest: rosterDigest(local),
+ ...(devlog ? { devlog } : {}),
+ },
}, SYNC_TIMEOUT_MS).catch(() => null)
if (!reply) return false
this.lastSynced.set(machineId, this.now())
@@ -186,6 +235,7 @@ export class GroupSyncer {
const theirSelf = parseMember(payload.self, now)
// The answering machine may describe only itself, as the key this machine dialed and verified.
if (theirSelf && theirSelf.pub === pin.pub && theirSelf.machineId === machineId) incoming.members.push(theirSelf)
+ if (payload.devlog !== undefined) this.devlog?.heard(pin.pub, payload.devlog)
// Compared with the roster as it is now, not the one sent: a link can land while this was in flight.
const before = rosterDigest(this.deps.store.read())
const result = this.deps.store.merge(incoming, this.selfPub())
@@ -248,7 +298,10 @@ export class GroupSyncer {
this.deps.log?.(`[group] could not apply ${m.pub.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`)
}
}
- for (const m of result.dropped) this.forget(m.pub)
+ for (const m of result.dropped) {
+ this.forget(m.pub)
+ try { this.onDropped?.(m.pub) } catch { /* the removal here stands */ }
+ }
}
private forget(pub: string): void {
diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.ts
index 5dd5bcdc6..d1682f7f0 100644
--- a/cli/src/lib/e2ee/relayLink.spec.ts
+++ b/cli/src/lib/e2ee/relayLink.spec.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeAll, beforeEach } from 'vitest'
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'
import { mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
@@ -570,6 +570,37 @@ describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
}
})
+ it('e2e_denied from a machine the device key log names keeps the pin for a few tries, then drops it', async () => {
+ const wss = new WebSocketServer({ port: 0 })
+ wss.on('connection', (ws) => {
+ ws.on('message', (raw) => {
+ let frame: Frame
+ try { frame = JSON.parse(raw.toString()) as Frame } catch { return }
+ if (frame.type === 'machine_select') ws.send(JSON.stringify({ type: 'connected', payload: { machineId: MACHINE_ID } }))
+ // A machine that has not read the log yet, so does not know this identity.
+ if (frame.type === 'e2e_hello') ws.send(JSON.stringify({ type: 'e2e_denied', payload: { reason: 'unpaired' } }))
+ })
+ })
+ try {
+ const port = (wss.address() as AddressInfo).port
+ const peers = new MachinePeerStore()
+ const pinned = C.b64e(C.newIdentity().pub)
+ peers.pin(MACHINE_ID, pinned, 'box2')
+ const expectsTrust = vi.fn((machineId: string, pub: string) => machineId === MACHINE_ID && pub === pinned)
+ const pool = new RemoteRelayPool(fakeAuth, `ws://127.0.0.1:${port}`, C.newIdentity(), peers, { expectsTrust })
+ const sink = { sendFrame: () => true, sendBinary: () => true }
+ const dial = () => pool.acquire(MACHINE_ID, 'prod', { type: 'machine_select', payload: { machineId: MACHINE_ID } }, sink, () => {})
+ await expect(dial()).rejects.toThrow('NO_PEER_LINK')
+ await expect(dial()).rejects.toThrow('NO_PEER_LINK')
+ expect(peers.get(MACHINE_ID)?.pub).toBe(pinned)
+ await expect(dial()).rejects.toThrow('NO_PEER_LINK')
+ expect(peers.get(MACHINE_ID)).toBeNull()
+ expect(expectsTrust).toHaveBeenCalledTimes(3)
+ } finally {
+ await new Promise<void>((resolve) => wss.close(() => resolve()))
+ }
+ })
+
it('a mid-session e2e_denied unlinks the peer and closes the local session with 4404', async () => {
const inbox: Frame[] = []
const wss = new WebSocketServer({ port: 0 })
diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.ts
index be4d13c8c..b4ba9158b 100644
--- a/cli/src/lib/remoteRelay.ts
+++ b/cli/src/lib/remoteRelay.ts
@@ -243,8 +243,18 @@ export interface RemoteRelayPoolOptions {
/** A fresh E2EE session to `machineId` is up (the trust group compares rosters then). Not passed on
* to the background pools — the group's own exchange runs on one of those. */
onSessionReady?: (machineId: string) => void
+ /** Whether a machine that just answered `e2e_denied` is one the account's device key log names, under
+ * the key pinned for it: then it most likely has not read the log yet, and the pin is kept for a few
+ * tries (DENIED_TRIES within DENIED_WINDOW_MS) instead of being dropped at once. Shared with the
+ * background pools. */
+ expectsTrust?: (machineId: string, pub: string) => boolean
+ /** Shared record of recent denials per machine, for the above. */
+ denials?: Map<string, number[]>
}
+const DENIED_TRIES = 3
+const DENIED_WINDOW_MS = 60_000
+
export class RemoteRelayPool {
private entries = new Map<string, Entry>()
private pending = new Map<string, Promise<Entry>>()
@@ -254,6 +264,8 @@ export class RemoteRelayPool {
private readonly lingerMs: number
private readonly dialCooldownMs: number
private readonly onSessionReady: ((machineId: string) => void) | null
+ private readonly expectsTrust: ((machineId: string, pub: string) => boolean) | null
+ private readonly denials: Map<string, number[]>
/** Warm background pools per machine, each holding one lingering session nobody is attached to —
* see acquireIsolated(). A pool is either here (idle) or in a client's hands, never both. */
private readonly idleIsolated = new Map<string, RemoteRelayPool[]>()
@@ -270,6 +282,23 @@ export class RemoteRelayPool {
this.dialCooldownMs = opts.dialCooldownMs ?? 0
this.onSessionReady = opts.onSessionReady ?? null
this.lastDialFailure = opts.dialFailures ?? new Map()
+ this.expectsTrust = opts.expectsTrust ?? null
+ this.denials = opts.denials ?? new Map()
+ }
+
+ /** `machineId` denied this machine's key. Drop the pin — unless the device key log says it should
+ * trust us, and it has not denied us DENIED_TRIES times within DENIED_WINDOW_MS yet. */
+ private denied(machineId: string): void {
+ const pub = this.peers.get(machineId)?.pub
+ if (pub && this.expectsTrust?.(machineId, pub)) {
+ const now = Date.now()
+ const recent = (this.denials.get(machineId) ?? []).filter((at) => now - at < DENIED_WINDOW_MS)
+ recent.push(now)
+ this.denials.set(machineId, recent)
+ if (recent.length < DENIED_TRIES) return
+ }
+ this.denials.delete(machineId)
+ this.peers.unlink(machineId)
}
/** Background CLI jobs (a monitor pane polling `agents_list`, a script) must not replace the
@@ -288,7 +317,8 @@ export class RemoteRelayPool {
): Promise<RelaySession> {
const shelf = this.idleIsolated.get(machineId) ?? []
const pool = shelf.pop() ?? new RemoteRelayPool(this.auth, this.backendWsBase, this.selfIdentity, this.peers,
- { p2p: false, lingerMs: ISOLATED_LINGER_MS, dialCooldownMs: ISOLATED_DIAL_COOLDOWN_MS, dialFailures: this.lastDialFailure })
+ { p2p: false, lingerMs: ISOLATED_LINGER_MS, dialCooldownMs: ISOLATED_DIAL_COOLDOWN_MS, dialFailures: this.lastDialFailure,
+ ...(this.expectsTrust ? { expectsTrust: this.expectsTrust } : {}), denials: this.denials })
const session = await pool.acquire(machineId, autonomousEnv, selectFrame, {
...sink,
sendFrame: frame => sink.sendFrame(frame.type === 'connected'
@@ -534,7 +564,7 @@ export class RemoteRelayPool {
// repeating a handshake that will only be denied again. The handshake never got as far
// as being usable, so there is nothing more to read from this socket — close it rather
// than leaving it dangling open.
- this.peers.unlink(machineId)
+ this.denied(machineId)
try { ws.close(1000, 'peer denied') } catch { ws.terminate() }
reject(new RelayConnectError('NO_PEER_LINK'))
}
@@ -570,7 +600,7 @@ export class RemoteRelayPool {
// trust and close with the same 4404 the app already knows how to turn into "needs to be
// linked": the `ws.on('close', ...)` handler below forwards this code verbatim to
// `entry.onClosed`, which `localWsServer.ts` wires straight to the local client's own close.
- this.peers.unlink(machineId)
+ this.denied(machineId)
try { ws.close(4404, 'peer revoked trust') } catch { ws.terminate() }
return
}
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 6b06e36da..c4583a400 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -6,6 +6,8 @@ import '../auth/auth_session.dart';
import '../core/config.dart';
import '../core/models.dart';
import '../logging/http_log.dart';
+import '../viewer/device_log.dart';
+import '../viewer/device_log_sync.dart' show DeviceLogAppendAnswer, DeviceLogFetched;
import '../ws/local_daemon_transport.dart';
import 'access_token_source.dart';
import 'bearer_auth_interceptor.dart';
@@ -288,6 +290,107 @@ class ApiClient {
}
}
+ // -- the account's device key log (viewer builds: straight to the backend, signed) --
+
+ /// `GET /api/device-keys?since=` — the log from [since]; null when there is none to read (an older
+ /// backend, signed out, or unreachable). See `viewer/device_log_sync.dart`.
+ Future<DeviceLogFetched?> deviceKeys(int since) async {
+ try {
+ final res = await _dio.get('/api/device-keys', queryParameters: {'since': since});
+ if (res.statusCode != 200) return null;
+ final data = unwrapApiResponse(res);
+ if (data is! Map) return null;
+ final acct = data['acct'], head = DevLogHead.fromJson(data['head']), entries = data['entries'];
+ if (acct is! String || head == null || entries is! List) return null;
+ return (acct: acct, head: head, entries: entries.cast<Object?>());
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// `POST /api/device-keys` — append one entry this app signed. Null when the backend could not be
+ /// reached; a refusal comes back as its code (`STALE_HEAD` with the current head).
+ Future<DeviceLogAppendAnswer?> appendDeviceKey(DevLogEntry entry) async {
+ try {
+ final res = await _dio.post('/api/device-keys', data: {'entry': entry.toJson()});
+ final body = res.data;
+ if (body is! Map) return null;
+ final data = body['data'];
+ final head = data is Map ? DevLogHead.fromJson(data['head']) : null;
+ if (res.statusCode == 200) return (head: head, error: null);
+ final error = body['error'];
+ final code = error is Map && error['code'] is String ? error['code'] as String : 'HTTP_${res.statusCode}';
+ return (head: head, error: code);
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// `GET /api/device-keys/seen` — when each key last opened a session, `{pub: ms}`; empty when it
+ /// cannot be read. A hint for offering to remove apps not used in a long while.
+ Future<Map<String, int>> deviceKeysSeen() async {
+ try {
+ final res = await _dio.get('/api/device-keys/seen');
+ if (res.statusCode != 200) return const {};
+ final data = unwrapApiResponse(res);
+ final seen = data is Map ? data['seen'] : null;
+ return {
+ if (seen is Map)
+ for (final e in seen.entries)
+ if (e.key is String && e.value is int) e.key as String: e.value as int,
+ };
+ } catch (_) {
+ return const {};
+ }
+ }
+
+ // -- the same list on a desktop build, as this computer's daemon verified it --
+
+ /// `GET /api/devices` — the account's devices as the daemon's copy of the log has them; null when
+ /// the daemon cannot say (an older CLI, signed out).
+ Future<Map<String, dynamic>?> daemonDevices() async {
+ try {
+ final res = await _dio.get('/api/devices');
+ final data = res.data;
+ return res.statusCode == 200 && data is Map<String, dynamic> ? data : null;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// `POST /api/devices/remove` — out of the account, signed by this computer. Null when done,
+ /// else the reason.
+ Future<String?> daemonRemoveDevice(String pub) async {
+ try {
+ final res = await _dio.post(
+ '/api/devices/remove',
+ data: {'pub': pub},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ );
+ if (res.statusCode == 200) return null;
+ final data = res.data;
+ return data is Map && data['error'] is String ? data['error'] as String : 'HTTP_${res.statusCode}';
+ } catch (_) {
+ return 'UNAVAILABLE';
+ }
+ }
+
+ /// `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 {
+ try {
+ final res = await _dio.post(
+ '/api/devices/rebaseline',
+ data: {'confirm': confirm},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ );
+ final data = res.data;
+ return res.statusCode == 200 && data is Map<String, dynamic> ? data : null;
+ } catch (_) {
+ return null;
+ }
+ }
+
// -- the Harness Store: ratings and reviews (control plane, proxied by the local CLI) --
Future<Map<String, dynamic>?> storeRatings() async {
final res = await _dio.get('/api/store/ratings');
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dart
index 473997aae..7985e7eca 100644
--- a/desktop/lib/app_shell.dart
+++ b/desktop/lib/app_shell.dart
@@ -34,6 +34,7 @@ import 'logging/install.dart';
import 'shortcuts/app_keymap.dart';
import 'shortcuts/keyboard_practice.dart';
import 'widgets/shortcuts_sheet.dart';
+import 'widgets/new_device_notice.dart';
import 'widgets/update_notice.dart';
import 'widgets/window_chrome.dart';
import 'sharing/shared_agent_location.dart';
@@ -354,6 +355,8 @@ class _RootShellState extends ConsumerState<RootShell>
app.status != AppStatus.checkingEnvironment &&
app.status != AppStatus.preparingEnvironment)
UpdateNotice(notifier: app),
+ if (app.newDevices.isNotEmpty && app.status == AppStatus.authenticated)
+ NewDeviceNotice(notifier: app),
Expanded(child: framed),
],
);
diff --git a/desktop/lib/core/harness_file_store_web.dart b/desktop/lib/core/harness_file_store_web.dart
index 70c68b3c1..a70d247c8 100644
--- a/desktop/lib/core/harness_file_store_web.dart
+++ b/desktop/lib/core/harness_file_store_web.dart
@@ -18,6 +18,7 @@ class HarnessFileStore
'auth_access_token_expires_at',
'viewer_e2ee_identity_seed',
'viewer_e2ee_machine_peers',
+ 'viewer_e2ee_devlog',
];
Future<void>? _migration;
diff --git a/desktop/lib/notify/system_notifications.dart b/desktop/lib/notify/system_notifications.dart
index 690b3c163..cb9298137 100644
--- a/desktop/lib/notify/system_notifications.dart
+++ b/desktop/lib/notify/system_notifications.dart
@@ -365,6 +365,24 @@ class SystemNotifications {
);
}
+ /// News about the ACCOUNT rather than an agent — a device joined it. The same switch and the same
+ /// rules as [post]; a click on it opens no agent.
+ void postNotice({required String id, required String title, required String body}) {
+ if (!store.value || !supported) return;
+ if (permission.value == NotificationPermission.unavailable) return;
+ _ordered(
+ id,
+ () => notifier
+ .show(id: id, title: title, body: body, machineId: '', agentId: '')
+ .then((answer) {
+ if (answer != NotificationPermission.unknown) {
+ permission.value = answer;
+ }
+ })
+ .catchError((_) {}),
+ );
+ }
+
/// The person got to this agent some other way. Its notification is old news.
void withdraw(String machineId, String agentId) {
if (!supported) return;
diff --git a/desktop/lib/settings/sections/account_devices_section.dart b/desktop/lib/settings/sections/account_devices_section.dart
new file mode 100644
index 000000000..cfcc570d3
--- /dev/null
+++ b/desktop/lib/settings/sections/account_devices_section.dart
@@ -0,0 +1,275 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/app_dialog.dart';
+import '../../shared/widgets/section_scaffold.dart';
+import '../../shared/widgets/setting_row.dart';
+import '../../shared/widgets/skeleton.dart';
+import '../../state/account_devices.dart';
+import '../../state/app_state.dart';
+
+/// 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
+/// device that is not yours, and to take it out.
+class AccountDevicesSection extends StatefulWidget {
+ const AccountDevicesSection({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ State<AccountDevicesSection> createState() => _AccountDevicesSectionState();
+}
+
+class _AccountDevicesSectionState extends State<AccountDevicesSection> {
+ AccountDevices? _devices;
+ bool _loaded = false;
+ int _revision = -1;
+ final Set<String> _removing = {};
+ String? _error;
+
+ AppNotifier get _app => widget.notifier;
+
+ @override
+ void initState() {
+ super.initState();
+ _app.addListener(_changed);
+ 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
+ void dispose() {
+ _app.removeListener(_changed);
+ super.dispose();
+ }
+
+ void _changed() {
+ if (_app.devicesRevision != _revision) unawaited(_load());
+ }
+
+ Future<void> _load() async {
+ _revision = _app.devicesRevision;
+ final devices = await _app.loadDevices();
+ if (!mounted) return;
+ setState(() {
+ _devices = devices;
+ _loaded = true;
+ });
+ }
+
+ Future<void> _remove(AccountDevice device) async {
+ final name = device.label.isEmpty ? 'this device' : device.label;
+ final confirmed = await _confirm(
+ 'Remove $name?',
+ 'It stops reaching your machines on every device, and is signed out. '
+ 'Signing in on it again adds it back as a new device.',
+ 'Remove',
+ destructive: true,
+ );
+ if (!confirmed || !mounted) return;
+ setState(() {
+ _removing.add(device.pub);
+ _error = null;
+ });
+ 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.";
+ });
+ }
+
+ bool _removingUnused = false;
+
+ Future<void> _removeUnused(List<AccountDevice> unused) async {
+ final confirmed = await _confirm(
+ 'Remove ${unused.length} unused app${unused.length == 1 ? '' : 's'}?',
+ [for (final d in unused) '${d.label.isEmpty ? 'Unnamed app' : d.label} — last seen ${_date(d.lastSeen!)}'].join('\n'),
+ 'Remove',
+ destructive: true,
+ );
+ if (!confirmed || !mounted) return;
+ setState(() {
+ _removingUnused = true;
+ _error = null;
+ });
+ final failed = <String>[];
+ for (final d in unused) {
+ if (await _app.removeDevice(d.pub) != null) failed.add(d.label.isEmpty ? 'an app' : d.label);
+ }
+ if (!mounted) return;
+ setState(() {
+ _removingUnused = false;
+ _error = failed.isEmpty ? null : "Couldn't remove ${failed.join(', ')}. Try again.";
+ });
+ }
+
+ Future<void> _trustAgain() async {
+ 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.");
+ return;
+ }
+ final lines = [
+ for (final name in preview.added) '+ $name',
+ for (final name in preview.removed) '− $name',
+ ];
+ final confirmed = await _confirm(
+ 'Trust this device list again?',
+ lines.isEmpty
+ ? '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',
+ );
+ if (!confirmed || !mounted) return;
+ await _app.rebaselineDevices(confirm: true);
+ }
+
+ Future<bool> _confirm(String title, String detail, String action, {bool destructive = false}) async =>
+ await showAppDialog<bool>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: Text(title),
+ content: SizedBox(
+ width: 360,
+ child: Text(detail, style: grid.AppType.body(height: 1.4)),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context, false),
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ overlayColor: grid.AppSurface.hoverFill,
+ ),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ key: const Key('account-device-confirm'),
+ style: destructive
+ ? FilledButton.styleFrom(
+ backgroundColor: grid.AppPalette.dangerFill,
+ overlayColor: const Color(0x1FFFFFFF),
+ )
+ : null,
+ onPressed: () => Navigator.pop(context, true),
+ child: Text(action),
+ ),
+ ],
+ ),
+ ) ??
+ false;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final devices = _devices;
+ return SectionScaffold(
+ title: 'Your devices',
+ subtitle: 'Every computer and app signed in to your account. Each one reaches your machines '
+ 'end to end encrypted — no password. Remove one you do not recognise.',
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (devices != null && devices.frozen) _FrozenLine(devices: devices, onTrustAgain: _trustAgain),
+ if (_error case final error?)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Text(error, style: grid.AppType.body(color: grid.AppPalette.warn)),
+ ),
+ if (devices != null && devices.unused(DateTime.now()).isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: SettingRow(
+ key: const Key('account-devices-unused'),
+ title: '${devices.unused(DateTime.now()).length} app${devices.unused(DateTime.now()).length == 1 ? '' : 's'} not used in 90 days',
+ detail: 'Most likely a browser whose data was cleared. Removing them changes nothing you use.',
+ control: OutlinedButton(
+ onPressed: _removingUnused ? null : () => unawaited(_removeUnused(devices.unused(DateTime.now()))),
+ child: Text(_removingUnused ? 'Removing…' : 'Remove them'),
+ ),
+ ),
+ ),
+ if (!_loaded)
+ const SkeletonList(rows: 3)
+ else if (devices == null)
+ Text(
+ 'The device list is not available here yet.',
+ style: grid.AppType.body(color: grid.AppPalette.textSecondary),
+ )
+ else
+ for (final device in devices.devices)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: SettingRow(
+ key: ValueKey('account-device-${device.pub}'),
+ title: '${device.label.isEmpty ? 'Unnamed device' : device.label}${device.self ? ' (this device)' : ''}',
+ detail: '${device.isMachine ? 'Computer' : 'App'} · added ${_date(device.addedAt)}'
+ '${device.lastSeen != null ? ' · last seen ${_date(device.lastSeen!)}' : ''} · ${device.fingerprint}',
+ control: device.self
+ ? const SizedBox.shrink()
+ : OutlinedButton(
+ onPressed: _removing.contains(device.pub) ? null : () => unawaited(_remove(device)),
+ child: Text(_removing.contains(device.pub) ? 'Removing…' : 'Remove'),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _FrozenLine extends StatelessWidget {
+ const _FrozenLine({required this.devices, required this.onTrustAgain});
+
+ final AccountDevices devices;
+ final VoidCallback onTrustAgain;
+
+ @override
+ Widget build(BuildContext context) {
+ final where = devices.frozenReason != null
+ ? 'this device'
+ : devices.frozenPeers.join(', ');
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: DecoratedBox(
+ 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: Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'The device list froze on $where: Harness served a list that does not match what '
+ 'was verified before. No device is added until you review it.',
+ style: grid.AppType.body(color: grid.AppPalette.textPrimary),
+ ),
+ ),
+ if (devices.frozenReason != null) ...[
+ const SizedBox(width: 12),
+ OutlinedButton(onPressed: onTrustAgain, child: const Text('Review…')),
+ ],
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+String _date(DateTime at) {
+ String two(int n) => n.toString().padLeft(2, '0');
+ return '${at.year}-${two(at.month)}-${two(at.day)}';
+}
diff --git a/desktop/lib/settings/settings_body.dart b/desktop/lib/settings/settings_body.dart
index 624c40446..4f1233cda 100644
--- a/desktop/lib/settings/settings_body.dart
+++ b/desktop/lib/settings/settings_body.dart
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import '../state/app_state.dart';
import 'experimental_features.dart';
import 'sections/about_section.dart';
+import 'sections/account_devices_section.dart';
import 'sections/account_section.dart';
import 'sections/profiles_section.dart';
import 'sections/debug_section.dart';
@@ -33,6 +34,7 @@ class SettingsBody extends StatelessWidget {
Widget build(BuildContext context) {
final screen = switch (section) {
SettingsSection.account => AccountSection(notifier: notifier),
+ SettingsSection.accountDevices => AccountDevicesSection(notifier: notifier),
SettingsSection.profiles => ProfilesSection(notifier: notifier),
SettingsSection.usage => const UsageSection(),
SettingsSection.customize => throw StateError(
diff --git a/desktop/lib/settings/settings_section.dart b/desktop/lib/settings/settings_section.dart
index adb1ced98..44e85c1b2 100644
--- a/desktop/lib/settings/settings_section.dart
+++ b/desktop/lib/settings/settings_section.dart
@@ -12,6 +12,7 @@ import '../logging/debug_surface.dart';
/// be listed without a screen behind it or reachable without a row.
enum SettingsSection {
account(AppIcons.user, 'Account'),
+ accountDevices(AppIcons.shieldCheck, 'Your devices'),
profiles(AppIcons.monitor, 'Profiles'),
usage(AppIcons.chartNoAxesColumn, 'Usage'),
customize(AppIcons.palette, 'Customize'),
@@ -96,6 +97,8 @@ const _kSettingsGroups = [
SettingsSection.experimental,
SettingsSection.devices,
SettingsSection.account,
+ // Beside Account: the devices signed in to it, each trusted by the others because of that.
+ SettingsSection.accountDevices,
SettingsSection.profiles,
]),
// Debug sits between the two things it is most often reached from: the keys
diff --git a/desktop/lib/state/account_devices.dart b/desktop/lib/state/account_devices.dart
new file mode 100644
index 000000000..a502e4d16
--- /dev/null
+++ b/desktop/lib/state/account_devices.dart
@@ -0,0 +1,156 @@
+import '../viewer/device_log.dart';
+import '../viewer/device_log_sync.dart';
+
+/// One device on the account, as the Devices list draws it — whichever end verified the log: this
+/// computer's daemon (a desktop build, `GET /api/devices`) or this app itself (a viewer build,
+/// `viewer/device_log_sync.dart`).
+class AccountDevice {
+ const AccountDevice({
+ required this.pub,
+ required this.label,
+ required this.kind,
+ required this.machineId,
+ required this.addedAt,
+ required this.fingerprint,
+ required this.self,
+ this.lastSeen,
+ });
+
+ final String pub;
+ final String label;
+
+ /// `machine` | `viewer`.
+ final String kind;
+ final String machineId;
+ final DateTime addedAt;
+ final String fingerprint;
+
+ /// This computer (or this app).
+ final bool self;
+
+ /// When this key last opened an E2EE session, as the backend saw it; null when it does not know.
+ final DateTime? lastSeen;
+
+ 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,
+ );
+
+ static AccountDevice? fromDaemon(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'], label = raw['label'], kind = raw['kind'], machineId = raw['machineId'];
+ final addedAt = raw['addedAt'], fp = raw['fingerprint'], self = raw['self'];
+ if (pub is! String || label is! String || kind is! String || addedAt is! int || fp is! String) return null;
+ return AccountDevice(
+ pub: pub, label: label, kind: kind, machineId: machineId is String ? machineId : '',
+ addedAt: DateTime.fromMillisecondsSinceEpoch(addedAt), fingerprint: fp, self: self == 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,
+ );
+}
+
+/// 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 []});
+
+ final List<AccountDevice> devices;
+
+ /// Set when this end's copy of the log is FROZEN: the backend served a list that does not match
+ /// what was verified before (`fork`, `rollback` or `invalid`). No device is added until someone
+ /// reviews the change.
+ final String? frozenReason;
+
+ /// Machines that say their own copy is frozen.
+ final List<String> frozenPeers;
+
+ bool get frozen => frozenReason != null || frozenPeers.isNotEmpty;
+
+ /// 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.
+ List<AccountDevice> unused(DateTime now, {Duration unusedAfter = const Duration(days: 90)}) => [
+ for (final d in devices)
+ if (!d.self && !d.isMachine && d.lastSeen != null && now.difference(d.lastSeen!) > unusedAfter) d,
+ ];
+
+ AccountDevices withLastSeen(Map<String, int> seen) => AccountDevices(
+ devices: [
+ for (final d in devices)
+ d.withLastSeen(seen[d.pub] == null ? null : DateTime.fromMillisecondsSinceEpoch(seen[d.pub]!)),
+ ],
+ frozenReason: frozenReason,
+ frozenPeers: frozenPeers,
+ );
+
+ static AccountDevices? fromDaemon(Map<String, dynamic>? raw) {
+ if (raw == null) return null;
+ final members = raw['members'];
+ final frozen = raw['frozen'];
+ final peers = raw['frozenPeers'];
+ 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 [],
+ ).withLastSeen(parseLastSeen(raw['lastSeen']));
+ }
+
+ static AccountDevices fromListing(DeviceLogListing listing) => AccountDevices(
+ devices: listing.members.map(AccountDevice.fromRow).toList(),
+ frozenReason: listing.frozen?.reason,
+ frozenPeers: listing.frozenPeers,
+ );
+}
+
+/// What trusting the backend's list again would change.
+class DevicesRebaseline {
+ const DevicesRebaseline({required this.added, required this.removed});
+
+ final List<String> added;
+ final List<String> removed;
+
+ static DevicesRebaseline? fromDaemon(Map<String, dynamic>? raw) {
+ if (raw == null) return null;
+ 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 [],
+ );
+ }
+
+ 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],
+ );
+}
+
+/// 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});
+
+ final String pub;
+ final String label;
+ final String kind;
+
+ String get sentence {
+ final name = label.isEmpty ? 'A device' : label;
+ return kind == 'machine'
+ ? '$name joined your account and can reach your machines.'
+ : '$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);
+}
+
+/// `{pub: ms}` as the backend answers `GET /api/device-keys/seen`; anything else is dropped.
+Map<String, int> parseLastSeen(Object? raw) => {
+ if (raw is Map)
+ for (final e in raw.entries)
+ if (e.key is String && e.value is int) e.key as String: e.value as int,
+};
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 653979001..8320735e3 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -99,6 +99,8 @@ import '../notify/agent_alerts.dart';
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_sync.dart';
enum AppStatus {
bootstrapping,
@@ -2159,6 +2161,7 @@ class AppNotifier extends ChangeNotifier {
this.peerLinks = peerLinks ?? this.viewer?.links ?? this.cliLink;
_autonomousEnv = this.config.autonomousEnv;
api = _newApiClient();
+ _initDeviceLog();
// `grid.AppTheme.palette`, not the prefs store: main.dart copies the saved
// choice into the palette notifier while rebuilding, so the store fires
// before the colours the panes actually use have moved.
@@ -3613,6 +3616,13 @@ class AppNotifier extends ChangeNotifier {
// desk (`Desk{userId}`), so a guest has none — asking for one would earn a
// 401 on every poll for a document that cannot exist.
if (signedIn) _deskEnsure(revision);
+ // The account's device key log: this app's key joins it (an existing sign-in too, from before
+ // 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));
+ }
+ }
try {
await refreshMachines();
} catch (error) {
@@ -4604,6 +4614,13 @@ class AppNotifier extends ChangeNotifier {
}
Future<void> _logout() async {
+ // Signing out takes this app's key out of the account's devices, while the sign-in still works
+ // to say so. Best effort, and brief: signing out must not wait on the network.
+ if (_deviceLog case final log?) {
+ try {
+ await log.leave().timeout(const Duration(seconds: 5));
+ } catch (_) {}
+ }
final revision = _invalidateAuthWork();
final previousMachineId = localMachineState?.machine.machineId;
cliLogin.cancel();
@@ -4661,6 +4678,9 @@ class AppNotifier extends ChangeNotifier {
return;
}
if (code != 4404) return;
+ // A machine the account's device key log names may simply not have read it yet: read it again,
+ // and the link retry below picks the machine up once it has.
+ if (_deviceLog case final log?) unawaited(log.refresh());
// The local CLI's relay found no linked trust for this machine — it now owns E2EE entirely.
// A `harness link connect` run in a terminal (or another app instance) has no way to notify
// this one directly, so poll every few seconds until it's picked up instead of waiting for
@@ -4761,6 +4781,7 @@ class AppNotifier extends ChangeNotifier {
machine.connectionStatus = nextStatus;
if (nextStatus == ConnectionStatus.connected) {
_onMachineConnected(machineId, machine);
+ _refreshDeviceLogAfterReconnect();
} else if (nextStatus == ConnectionStatus.reconnecting ||
nextStatus == ConnectionStatus.disconnected) {
_stopAgentSyncTimer(machineId);
@@ -5585,6 +5606,125 @@ class AppNotifier extends ChangeNotifier {
}
}
+ // -- the account's devices: the device key log (viewer/device_log_sync.dart) --------------------
+
+ /// Viewer builds only: this app's copy of the account's device key log. A desktop build's daemon
+ /// keeps its own (`harness devices`), and the Devices list reads it from there.
+ ViewerDeviceLog? _deviceLog;
+
+ /// Devices that joined the account and this end had never trusted, not yet dismissed.
+ final List<NewDeviceNotice> newDevices = [];
+
+ /// Bumped whenever the account's devices may have changed; the Devices list re-reads on it.
+ int devicesRevision = 0;
+
+ void _initDeviceLog() {
+ final services = viewer;
+ if (services == null) return;
+ final log = _deviceLog = ViewerDeviceLog(
+ keys: services.keys,
+ fetch: (since) => api.deviceKeys(since),
+ append: (entry) => api.appendDeviceKey(entry),
+ label: _deviceLabel,
+ onAnnounce: (m) => _announceDevice(NewDeviceNotice.fromMember(m)),
+ onSignedOut: _deviceRemovedHere,
+ onChanged: () {
+ devicesRevision++;
+ if (!_disposed) notifyListeners();
+ },
+ );
+ services.links.deviceLog = log;
+ }
+
+ /// How this app names itself in the account's devices.
+ String _deviceLabel() {
+ final host = localHostnameOrNull();
+ if (host != null && host.isNotEmpty) return host;
+ return kIsWeb ? 'Browser · ${defaultTargetPlatform.name}' : 'Desktop app';
+ }
+
+ DateTime? _deviceLogReadAt;
+
+ /// A socket came back: a `device_keys_changed` sent while this app was offline reached nobody, so
+ /// read the log again — at most every half minute, since a reconnect is every machine at once.
+ void _refreshDeviceLogAfterReconnect() {
+ final log = _deviceLog;
+ if (log == null) return;
+ final now = DateTime.now();
+ if (_deviceLogReadAt case final last? when now.difference(last) < const Duration(seconds: 30)) return;
+ _deviceLogReadAt = now;
+ unawaited(log.refresh());
+ }
+
+ void _announceDevice(NewDeviceNotice notice) {
+ if (newDevices.any((d) => d.pub == notice.pub)) return;
+ newDevices.add(notice);
+ devicesRevision++;
+ systemNotifications.postNotice(
+ id: 'harness-device:${notice.pub}',
+ title: 'New device on your account',
+ body: '${notice.sentence} Not yours? Remove it in Settings ▸ Devices.',
+ );
+ notifyListeners();
+ }
+
+ /// The devices list was opened: every device announced so far has been seen.
+ void seenNewDevices() {
+ if (newDevices.isEmpty) return;
+ newDevices.clear();
+ notifyListeners();
+ }
+
+ void dismissNewDevice(String pub) {
+ newDevices.removeWhere((d) => d.pub == pub);
+ notifyListeners();
+ }
+
+ /// This app's key was removed from the account: its identity is spent, and it signs out. The
+ /// next sign-in is a new device, which every other device announces.
+ Future<void> _deviceRemovedHere() async {
+ final services = viewer;
+ if (services == null) return;
+ // Sign out first: it takes this app's key out of the log, which needs the key it is about.
+ await logout();
+ await services.keys.forgetIdentity();
+ }
+
+ /// The account's devices, from whichever end verified the log. Null when it cannot be read.
+ Future<AccountDevices?> loadDevices() async {
+ if (_deviceLog case final log?) {
+ final listing = AccountDevices.fromListing(await log.list());
+ return listing.withLastSeen(await api.deviceKeysSeen());
+ }
+ return AccountDevices.fromDaemon(await api.daemonDevices());
+ }
+
+ /// Take [pub] out of the account on every device. Null when done, else why not.
+ Future<String?> removeDevice(String pub) async {
+ final error = _deviceLog != null ? await _deviceLog!.remove(pub) : await api.daemonRemoveDevice(pub);
+ if (error == null) newDevices.removeWhere((d) => d.pub == pub);
+ devicesRevision++;
+ notifyListeners();
+ return error;
+ }
+
+ /// 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 {
+ final DevicesRebaseline? result;
+ if (_deviceLog case final log?) {
+ final r = await log.rebaseline(confirm: confirm);
+ result = r == null ? null : DevicesRebaseline.fromViewer(r);
+ } else {
+ result = DevicesRebaseline.fromDaemon(await api.daemonRebaselineDevices(confirm: confirm));
+ }
+ if (confirm) {
+ devicesRevision++;
+ notifyListeners();
+ }
+ return result;
+ }
+
final Map<String, DateTime> _groupSyncedAt = {};
static const _groupResync = Duration(minutes: 5);
@@ -13134,6 +13274,23 @@ class AppNotifier extends ChangeNotifier {
// payload is only a reason; the list itself is re-read.
unawaited(_rereadMachinesInBackground(pushed: true));
break;
+ 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());
+ devicesRevision++;
+ notifyListeners();
+ 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) {
+ final pub = payload['pub'], label = payload['label'], kind = payload['kind'];
+ if (pub is String && kind is String) {
+ _announceDevice(NewDeviceNotice(pub: pub, label: label is String ? label : '', kind: kind));
+ }
+ }
+ break;
case 'desk_changed':
unawaited(experimentalFeatures.refresh());
if (_swarmSettings case final settings?) unawaited(settings.refresh());
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 85dfde91f..cf3682b72 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -961,7 +961,7 @@ class SwarmSearchController extends ChangeNotifier {
? '[ Add ]'
: 'New Harness';
String get createDescription => isMachineMode
- ? 'On the other computer:\n\n1. Install the app or CLI.\n2. Sign in to the same account.\n3. Set its password.\n\nThen select it here and Connect.'
+ ? 'On the other computer:\n\n1. Install the app or CLI.\n2. Sign in to the same account.\n\nIt appears here and connects on its own — no password.'
: isModelMode
? 'Add an API key\n\n'
'OpenRouter or a Custom API: Use its models to run a harness.\n'
diff --git a/desktop/lib/viewer/device_log.dart b/desktop/lib/viewer/device_log.dart
new file mode 100644
index 000000000..0bb6d5131
--- /dev/null
+++ b/desktop/lib/viewer/device_log.dart
@@ -0,0 +1,330 @@
+import 'dart:typed_data';
+
+import '../e2ee/bytes.dart';
+import '../e2ee/keys.dart';
+import '../e2ee/primitives.dart';
+
+/// The device key log — an account's append-only, hash-chained list of the identity keys its devices
+/// hold (cli/src/lib/e2ee/deviceLog.ts, ported). Every device trusts the keys the log leaves active,
+/// so signing in is all it takes for an app to reach the account's machines, with no remote password.
+///
+/// Pure: no I/O. Signatures and hashes cover [devLogMessage] — the fields length-prefixed in a fixed
+/// order, numbers in decimal — never JSON. ⚠️ Held, with the CLI, the backend and
+/// mobile/lib/viewer/device_log.dart, to `test/viewer/device_log.vectors.json`: change the format
+/// in every copy together.
+
+const devLogVersion = 1;
+const devLogMaxActive = 256;
+const devLogLabelMax = 60;
+
+final _machineIdRe = RegExp(r'^[a-f0-9]{32}$');
+final _controlRe = RegExp(r'[\u0000-\u001f\u007f]');
+const _maxSafe = 9007199254740991;
+final String devLogZeroHash = b64e(Uint8List(32));
+
+class DevLogEntry {
+ const DevLogEntry({
+ required this.v,
+ required this.acct,
+ required this.seq,
+ required this.prev,
+ required this.op,
+ required this.pub,
+ required this.kind,
+ required this.machineId,
+ required this.label,
+ required this.at,
+ required this.signer,
+ this.sig = '',
+ });
+
+ final int v;
+ final String acct;
+ final int seq;
+ final String prev;
+
+ /// `add` | `remove`.
+ final String op;
+ final String pub;
+
+ /// `machine` | `viewer`.
+ final String kind;
+ final String machineId;
+ final String label;
+ final int at;
+ final String signer;
+ final String sig;
+
+ DevLogEntry withSig(String sig) => DevLogEntry(
+ v: v, acct: acct, seq: seq, prev: prev, op: op, pub: pub, kind: kind,
+ machineId: machineId, label: label, at: at, signer: signer, sig: sig,
+ );
+
+ Map<String, Object?> toJson() => {
+ 'v': v, 'acct': acct, 'seq': seq, 'prev': prev, 'op': op, 'pub': pub, 'kind': kind,
+ 'machineId': machineId, 'label': label, 'at': at, 'signer': signer, 'sig': sig,
+ };
+
+ /// deviceLog.ts `parseDevLogEntry`: every field present, of its type and within bounds.
+ static DevLogEntry? parse(Object? raw) {
+ if (raw is! Map) return null;
+ final v = raw['v'], acct = raw['acct'], seq = raw['seq'], prev = raw['prev'];
+ final op = raw['op'], pub = raw['pub'], kind = raw['kind'];
+ final machineId = raw['machineId'], label = raw['label'], at = raw['at'];
+ final signer = raw['signer'], sig = raw['sig'];
+ if (v != devLogVersion) return null;
+ if (acct is! String || acct.isEmpty || acct.length > 128) return null;
+ if (seq is! int || seq < 1 || seq > _maxSafe) return null;
+ if (!_bytesOf(prev, 32) || !_bytesOf(pub, 32) || !_bytesOf(signer, 32) || !_bytesOf(sig, 64)) {
+ return null;
+ }
+ if (op != 'add' && op != 'remove') return null;
+ if (kind != 'machine' && kind != 'viewer') return null;
+ if (machineId is! String) return null;
+ if (kind == 'machine' ? !_machineIdRe.hasMatch(machineId) : machineId != '') return null;
+ if (label is! String || label.length > devLogLabelMax || _controlRe.hasMatch(label)) return null;
+ if (at is! int || at <= 0 || at > _maxSafe) return null;
+ return DevLogEntry(
+ v: v as int, acct: acct, seq: seq, prev: prev as String, op: op as String, pub: pub as String,
+ kind: kind as String, machineId: machineId, label: label, at: at,
+ signer: signer as String, sig: sig as String,
+ );
+ }
+}
+
+bool _bytesOf(Object? s, int n) {
+ if (s is! String || s.length > 128) return false;
+ try {
+ final u = b64d(s);
+ return u.length == n && b64e(u) == s;
+ } catch (_) {
+ return false;
+ }
+}
+
+class DevLogMember {
+ const DevLogMember({
+ required this.pub,
+ required this.kind,
+ required this.machineId,
+ required this.label,
+ required this.addedAt,
+ required this.seq,
+ });
+
+ final String pub;
+ final String kind;
+ final String machineId;
+ final String label;
+ final int addedAt;
+ final int seq;
+
+ DevLogMember withLabel(String label) => DevLogMember(
+ pub: pub, kind: kind, machineId: machineId, label: label, addedAt: addedAt, seq: seq,
+ );
+
+ Map<String, Object?> toJson() => {
+ 'pub': pub, 'kind': kind, 'machineId': machineId, 'label': label, 'addedAt': addedAt, 'seq': seq,
+ };
+
+ static DevLogMember? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'], kind = raw['kind'], machineId = raw['machineId'];
+ final label = raw['label'], addedAt = raw['addedAt'], seq = raw['seq'];
+ if (pub is! String || kind is! String || machineId is! String || label is! String) return null;
+ if (addedAt is! int || seq is! int) return null;
+ return DevLogMember(pub: pub, kind: kind, machineId: machineId, label: label, addedAt: addedAt, seq: seq);
+ }
+}
+
+class DevLogHead {
+ const DevLogHead(this.seq, this.hash);
+
+ final int seq;
+ final String hash;
+
+ Map<String, Object?> toJson() => {'seq': seq, 'hash': hash};
+
+ static DevLogHead? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final seq = raw['seq'], hash = raw['hash'];
+ if (seq is! int || seq < 0 || hash is! String) return null;
+ return DevLogHead(seq, hash);
+ }
+
+ @override
+ bool operator ==(Object other) => other is DevLogHead && other.seq == seq && other.hash == hash;
+
+ @override
+ int get hashCode => Object.hash(seq, hash);
+}
+
+class DevLogState {
+ DevLogState({
+ required this.acct,
+ required this.head,
+ required this.hashes,
+ required this.active,
+ required this.removed,
+ });
+
+ factory DevLogState.empty(String acct) => DevLogState(
+ acct: acct, head: DevLogHead(0, devLogZeroHash), hashes: [], active: {}, removed: [],
+ );
+
+ final String acct;
+ DevLogHead head;
+
+ /// hashes[i] is the hash of the entry with seq i + 1.
+ final List<String> hashes;
+
+ /// Active keys, by pub.
+ final Map<String, DevLogMember> active;
+
+ /// Keys a `remove` took out. A removed key never comes back.
+ final List<String> removed;
+
+ DevLogState copy() => DevLogState(
+ acct: acct, head: head, hashes: [...hashes], active: {...active}, removed: [...removed],
+ );
+
+ Map<String, Object?> toJson() => {
+ 'acct': acct,
+ 'head': head.toJson(),
+ 'hashes': hashes,
+ 'active': {for (final e in active.entries) e.key: e.value.toJson()},
+ 'removed': removed,
+ };
+
+ static DevLogState? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final acct = raw['acct'], head = DevLogHead.fromJson(raw['head']);
+ final hashes = raw['hashes'], active = raw['active'], removed = raw['removed'];
+ if (acct is! String || head == null || hashes is! List || active is! Map || removed is! List) return null;
+ final members = <String, DevLogMember>{};
+ for (final e in active.entries) {
+ final m = DevLogMember.fromJson(e.value);
+ if (e.key is String && m != null) members[e.key as String] = m;
+ }
+ return DevLogState(
+ acct: acct,
+ head: head,
+ hashes: hashes.whereType<String>().toList(),
+ active: members,
+ removed: removed.whereType<String>().toList(),
+ );
+ }
+}
+
+class DevLogError implements Exception {
+ const DevLogError(this.code, this.seq);
+
+ final String code;
+ final int seq;
+
+ @override
+ String toString() => 'device log entry $seq: $code';
+}
+
+class DevLogApplied {
+ DevLogApplied(this.state);
+
+ final DevLogState state;
+ final List<DevLogMember> added = [];
+ final List<DevLogMember> removed = [];
+ final List<DevLogMember> relabeled = [];
+}
+
+/// The bytes a signature covers.
+Uint8List devLogMessage(DevLogEntry e) => lvCat([
+ 'harness-devlog-v1', '${e.v}', e.acct, '${e.seq}', b64d(e.prev), e.op, b64d(e.pub),
+ e.kind, e.machineId, e.label, '${e.at}', b64d(e.signer),
+]);
+
+/// The entry's hash: what the next entry's `prev` names.
+String devLogHash(DevLogEntry e) => b64e(sha256(lvCat([devLogMessage(e), b64d(e.sig)])));
+
+Future<DevLogEntry> signDevLogEntry(DevLogEntry unsigned, E2eeIdentity identity) async =>
+ unsigned.withSig(b64e(await identity.sign(devLogMessage(unsigned))));
+
+/// The next entry to append on top of [state], unsigned.
+DevLogEntry nextDevLogEntry(
+ DevLogState state, {
+ required String op,
+ required String pub,
+ required String kind,
+ required String machineId,
+ required String label,
+ required String signer,
+ required int at,
+}) => DevLogEntry(
+ v: devLogVersion, acct: state.acct, seq: state.head.seq + 1, prev: state.head.hash, op: op,
+ pub: pub, kind: kind, machineId: machineId, label: label, at: at, signer: signer,
+);
+
+/// Apply [entries], in order, on top of [state]. All or nothing: the first entry that breaks a rule
+/// throws a [DevLogError] and [state] is left as it was.
+Future<DevLogApplied> applyDevLogEntries(DevLogState state, List<Object?> entries) async {
+ final s = state.copy();
+ final out = DevLogApplied(s);
+ for (final raw in entries) {
+ final expectedSeq = s.head.seq + 1;
+ final e = DevLogEntry.parse(raw);
+ if (e == null) throw DevLogError('BAD_ENTRY', expectedSeq);
+ if (e.acct != s.acct) throw DevLogError('WRONG_ACCOUNT', e.seq);
+ if (e.seq != expectedSeq) throw DevLogError('OUT_OF_ORDER', e.seq);
+ if (e.prev != s.head.hash) throw DevLogError('BROKEN_CHAIN', e.seq);
+ if (!await verifySignature(b64d(e.signer), devLogMessage(e), b64d(e.sig))) {
+ throw DevLogError('BAD_SIGNATURE', e.seq);
+ }
+ if (e.op == 'add') {
+ if (e.signer != e.pub) throw DevLogError('NOT_SELF_SIGNED', e.seq);
+ if (s.removed.contains(e.pub)) throw DevLogError('KEY_REMOVED', e.seq);
+ final current = s.active[e.pub];
+ if (current != null) {
+ if (current.kind != e.kind || current.machineId != e.machineId) {
+ throw DevLogError('KIND_CHANGED', e.seq);
+ }
+ if (current.label == e.label) throw DevLogError('NO_CHANGE', e.seq);
+ final relabeled = current.withLabel(e.label);
+ s.active[e.pub] = relabeled;
+ out.relabeled.add(relabeled);
+ } else {
+ if (e.kind == 'machine' &&
+ s.active.values.any((m) => m.kind == 'machine' && m.machineId == e.machineId)) {
+ throw DevLogError('MACHINE_TAKEN', e.seq);
+ }
+ if (s.active.length >= devLogMaxActive) throw DevLogError('TOO_MANY', e.seq);
+ final member = DevLogMember(
+ pub: e.pub, kind: e.kind, machineId: e.machineId, label: e.label, addedAt: e.at, seq: e.seq,
+ );
+ s.active[e.pub] = member;
+ out.added.add(member);
+ }
+ } else {
+ if (s.active[e.signer] == null) throw DevLogError('SIGNER_NOT_ACTIVE', e.seq);
+ final gone = s.active.remove(e.pub);
+ if (gone == null) throw DevLogError('NOT_ACTIVE', e.seq);
+ s.removed.add(e.pub);
+ out.removed.add(gone);
+ }
+ final hash = devLogHash(e);
+ s.hashes.add(hash);
+ s.head = DevLogHead(e.seq, hash);
+ }
+ return out;
+}
+
+/// The hash [state] holds for [seq]; null when it does not reach that far.
+String? devLogHashAt(DevLogState state, int seq) {
+ if (seq == 0) return devLogZeroHash;
+ return seq >= 1 && seq <= state.hashes.length ? state.hashes[seq - 1] : null;
+}
+
+/// How another device's head relates to ours: `same`, `behind` (they are ahead of us), `ahead`
+/// (we are ahead of them), or `fork` — two different entries at one position.
+String compareDevLogHead(DevLogState state, DevLogHead theirs) {
+ if (theirs.seq > state.head.seq) return 'behind';
+ if (devLogHashAt(state, theirs.seq) != theirs.hash) return 'fork';
+ return theirs.seq == state.head.seq ? 'same' : 'ahead';
+}
diff --git a/desktop/lib/viewer/device_log_sync.dart b/desktop/lib/viewer/device_log_sync.dart
new file mode 100644
index 000000000..8057241ca
--- /dev/null
+++ b/desktop/lib/viewer/device_log_sync.dart
@@ -0,0 +1,507 @@
+import 'dart:async';
+import 'dart:math';
+
+import '../e2ee/bytes.dart';
+import '../e2ee/keys.dart';
+import 'device_log.dart';
+import 'group_sync.dart';
+import 'viewer_key_store.dart';
+
+/// 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").
+
+/// 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});
+
+/// `POST /api/device-keys`: the new head, or a refusal (with the current head on `STALE_HEAD`).
+typedef DeviceLogAppendAnswer = ({DevLogHead? head, String? error});
+
+typedef DeviceLogFetch = Future<DeviceLogFetched?> Function(int since);
+typedef DeviceLogAppend = Future<DeviceLogAppendAnswer?> Function(DevLogEntry entry);
+
+class DeviceLogFreeze {
+ const DeviceLogFreeze(this.reason, this.at, this.lastGoodHead);
+
+ /// `fork` | `rollback` | `invalid` — see deviceLogStore.ts.
+ final String reason;
+ final int at;
+ final DevLogHead lastGoodHead;
+
+ Map<String, Object?> toJson() => {'reason': reason, 'at': at, 'lastGoodHead': lastGoodHead.toJson()};
+
+ static DeviceLogFreeze? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final reason = raw['reason'], at = raw['at'], head = DevLogHead.fromJson(raw['lastGoodHead']);
+ if (reason is! String || at is! int || head == null) return null;
+ return DeviceLogFreeze(reason, at, head);
+ }
+}
+
+class _File {
+ _File(this.state, this.recent, this.frozen, this.notifiedUpTo);
+
+ DevLogState? state;
+ List<DevLogEntry> recent;
+ DeviceLogFreeze? frozen;
+ int notifiedUpTo;
+
+ 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,
+ };
+
+ static _File parse(Object? raw) {
+ if (raw is! Map) return _File(null, [], null, 0);
+ final recent = raw['recent'];
+ 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,
+ );
+ }
+}
+
+const _recentKept = 64;
+const _appendAttempts = 5;
+const _pages = 20;
+
+/// One device on the account, for the Devices list.
+class DeviceLogRow {
+ const DeviceLogRow(this.member, {required this.fingerprint, required this.self});
+
+ final DevLogMember member;
+ final String fingerprint;
+ final bool self;
+}
+
+class DeviceLogListing {
+ const DeviceLogListing({required this.members, required this.frozen, required this.frozenPeers});
+
+ static const empty = DeviceLogListing(members: [], frozen: null, frozenPeers: []);
+
+ final List<DeviceLogRow> members;
+ final DeviceLogFreeze? frozen;
+
+ /// Machines whose own copy of the log is frozen, as their last `group_sync` said.
+ final List<String> frozenPeers;
+}
+
+class DeviceLogRebaseline {
+ const DeviceLogRebaseline(this.head, this.added, this.removed);
+
+ final DevLogHead head;
+ final List<DevLogMember> added;
+ final List<DevLogMember> removed;
+}
+
+class ViewerDeviceLog {
+ ViewerDeviceLog({
+ required this.keys,
+ required this.fetch,
+ required this.append,
+ required this.label,
+ this.onAnnounce,
+ this.onSignedOut,
+ this.onChanged,
+ int Function()? now,
+ Future<void> Function(Duration)? sleep,
+ }) : _now = now ?? (() => DateTime.now().millisecondsSinceEpoch),
+ _sleep = sleep ?? Future.delayed;
+
+ final ViewerKeyStore keys;
+ final DeviceLogFetch fetch;
+ final DeviceLogAppend append;
+
+ /// 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".
+ final void Function(DevLogMember member)? onAnnounce;
+
+ /// This app's own key was removed from the account: it is signed out.
+ final Future<void> Function()? onSignedOut;
+
+ /// The list, or whether it is frozen, changed.
+ final void Function()? onChanged;
+
+ final int Function() _now;
+ final Future<void> Function(Duration) _sleep;
+ final Map<String, bool> _frozenPeers = {};
+ Future<void>? _refreshing;
+ final _random = Random();
+ final Set<String> _removing = {};
+
+ /// 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;
+
+ /// This app's key is gone from the log: sign out, once.
+ Future<void> _signOut() async {
+ if (_signedOut) return;
+ _signedOut = true;
+ await onSignedOut?.call();
+ }
+
+ Future<_File> _read() async => _File.parse(await keys.deviceLog());
+ Future<void> _write(_File f) => keys.writeDeviceLog(f.toJson());
+ Future<String> _selfPub() async => b64e((await keys.identity()).pub);
+
+ /// Read the log and put this app's key into it. Never throws.
+ ///
+ /// [freshSignIn]: the person has just signed in, by hand. A key the log removed is then spent, not
+ /// 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.
+ Future<void> register({bool freshSignIn = false}) async {
+ _signingInAgain = freshSignIn;
+ _signedOut = false;
+ try {
+ await refresh();
+ var identity = await keys.identity();
+ var pub = b64e(identity.pub);
+ final name = _clip(label());
+ for (var attempt = 0; attempt < _appendAttempts; attempt++) {
+ final file = await _read();
+ final state = file.state;
+ if (state == null || file.frozen != null) return;
+ if (state.removed.contains(pub)) {
+ if (!freshSignIn) {
+ await _signOut();
+ return;
+ }
+ await keys.forgetIdentity();
+ await refresh();
+ identity = await keys.identity();
+ pub = b64e(identity.pub);
+ continue;
+ }
+ final mine = state.active[pub];
+ if (mine != null && (mine.label == name || mine.kind != 'viewer')) return;
+ final entry = await signDevLogEntry(
+ nextDevLogEntry(state, op: 'add', pub: pub, kind: 'viewer', machineId: '', label: name, signer: pub, at: _now()),
+ identity,
+ );
+ final answer = await append(entry);
+ if (answer == null) return;
+ if (answer.error == null) {
+ await refresh();
+ return;
+ }
+ if (answer.error != 'STALE_HEAD') return;
+ await refresh();
+ await _sleep(Duration(milliseconds: 200 + _random.nextInt(800) * (attempt + 1)));
+ }
+ } catch (_) {
+ // The next sign-in, resume or push tries again.
+ } finally {
+ _signingInAgain = false;
+ }
+ }
+
+ /// Read and verify whatever the log gained. Concurrent calls share one read. Never throws.
+ Future<void> refresh() => _refreshing ??= _doRefresh().catchError((Object _) {}).whenComplete(() => _refreshing = null);
+
+ Future<void> _doRefresh() async {
+ 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 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;
+ }
+ }
+
+ Future<bool> _accept(List<Object?> entries, bool bootstrap) async {
+ final file = await _read();
+ 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');
+ 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,
+ ));
+ 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();
+ 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.
+ Future<Set<String>> _knownPubs() async {
+ final roster = GroupRoster.parse(await keys.groupRoster());
+ return {
+ for (final p in await keys.peers()) b64e(p.pub),
+ for (final m in roster.members) m.pub,
+ };
+ }
+
+ /// Pin every machine the log adds, and put it in the trust group this app swaps with machines, so
+ /// a machine that predates the log hears of it too. A removal the group made first stands.
+ Future<void> _trust(List<DevLogMember> members) async {
+ final selfPub = await _selfPub();
+ 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 now = _now();
+ final adopt = [
+ for (final m in members)
+ if (m.pub != selfPub && !tombstoned.contains(m.pub)) m,
+ ];
+ final incoming = [
+ for (final m in adopt)
+ ?GroupMember.tryParse({
+ 'pub': m.pub,
+ 'kind': m.kind,
+ 'label': m.label,
+ 'at': min(m.addedAt, now),
+ if (m.machineId.isNotEmpty) 'machineId': m.machineId,
+ }),
+ ];
+ if (incoming.isNotEmpty) {
+ final merged = mergeGroupRoster(stored, GroupRoster(incoming, const []), selfPub);
+ await keys.writeGroupRoster(merged.roster.toJson());
+ }
+ for (final m in adopt) {
+ if (m.kind != 'machine') continue;
+ final current = await keys.peer(m.machineId);
+ if (current != null && b64e(current.pub) == m.pub) continue;
+ await keys.pin(m.machineId, b64d(m.pub), label: m.label);
+ }
+ // A removal the group made before the log existed must not be undone by the log. Not awaited:
+ // this runs inside a read of the log, and a removal reads the log again when it lands — waiting
+ // for it here would wait for this very read to finish.
+ final state = (await _read()).state;
+ if (state != null && state.active[selfPub] != null) {
+ for (final pub in tombstoned) {
+ if (state.active[pub] != null && !_removing.contains(pub)) unawaited(remove(pub));
+ }
+ }
+ }
+
+ Future<void> _drop(DevLogMember m) async {
+ final selfPub = await _selfPub();
+ final stored = GroupRoster.parse(await keys.groupRoster());
+ final merged = mergeGroupRoster(stored, GroupRoster(const [], [GroupTombstone(m.pub, _now())]), selfPub);
+ await keys.writeGroupRoster(merged.roster.toJson());
+ if (m.kind == 'machine') {
+ final current = await keys.peer(m.machineId);
+ if (current != null && b64e(current.pub) == m.pub) await keys.unlink(m.machineId);
+ }
+ }
+
+ /// 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();
+ final state = file.state;
+ if (state == null) return;
+ var changed = false;
+ for (final raw in entries) {
+ final e = DevLogEntry.parse(raw);
+ if (e == null || e.op != 'remove' || state.active[e.signer] == null) continue;
+ final target = state.active[e.pub];
+ if (target == null) continue;
+ if (!await verifySignature(b64d(e.signer), devLogMessage(e), b64d(e.sig))) continue;
+ state.active.remove(e.pub);
+ state.removed.add(e.pub);
+ await _drop(target);
+ changed = true;
+ }
+ if (changed) {
+ await _write(file);
+ onChanged?.call();
+ }
+ }
+
+ Future<void> _freeze(String reason) async {
+ final file = await _read();
+ if (file.frozen != null || file.state == null) return;
+ file.frozen = DeviceLogFreeze(reason, _now(), file.state!.head);
+ await _write(file);
+ onChanged?.call();
+ }
+
+ /// Remove a device from the account, signed by this app. It stops being trusted here at once.
+ /// Null when done, else why not.
+ Future<String?> remove(String pub) async {
+ _removing.add(pub);
+ try {
+ return await _removeOnce(pub);
+ } finally {
+ _removing.remove(pub);
+ }
+ }
+
+ Future<String?> _removeOnce(String pub) async {
+ final identity = await keys.identity();
+ final selfPub = b64e(identity.pub);
+ for (var attempt = 0; attempt < _appendAttempts; attempt++) {
+ final file = await _read();
+ final state = file.state;
+ if (state == null) return 'UNAVAILABLE';
+ final target = state.active[pub];
+ if (target == null) return 'NOT_IN_LOG';
+ if (state.active[selfPub] == null) return 'NOT_ACTIVE';
+ await _drop(target);
+ final entry = await signDevLogEntry(
+ nextDevLogEntry(state, op: 'remove', pub: pub, kind: target.kind, machineId: target.machineId,
+ label: target.label, signer: selfPub, at: _now()),
+ identity,
+ );
+ final answer = await append(entry);
+ if (answer == null) return 'UNAVAILABLE';
+ if (answer.error == null) {
+ await refresh();
+ return null;
+ }
+ if (answer.error != 'STALE_HEAD') return answer.error;
+ await refresh();
+ await _sleep(Duration(milliseconds: 200 + _random.nextInt(800) * (attempt + 1)));
+ }
+ return 'UNAVAILABLE';
+ }
+
+ /// Signing out of this app: its key leaves the account's devices (best effort).
+ Future<void> leave() async {
+ try {
+ await remove(await _selfPub());
+ } catch (_) {}
+ }
+
+ /// What trusting the backend's log again would change; with [confirm], do it.
+ Future<DeviceLogRebaseline?> rebaseline({required bool confirm}) 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;
+ acct = got.acct;
+ head = got.head;
+ entries.addAll(got.entries);
+ if (got.entries.isEmpty || entries.length >= got.head.seq) break;
+ }
+ final DevLogState next;
+ try {
+ next = (await applyDevLogEntries(DevLogState.empty(acct), entries)).state;
+ } on DevLogError {
+ 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);
+ }
+ onChanged?.call();
+ }
+ return DeviceLogRebaseline(next.head, added, removed);
+ }
+
+ /// 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};
+ }
+
+ /// 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 state = file.state;
+ if (state == null || raw is! Map) 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 == '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);
+ unawaited(refresh());
+ }
+ }
+
+ /// The account's devices as this app's log has them.
+ Future<DeviceLogListing> list() async {
+ final file = await _read();
+ 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};
+ return DeviceLogListing(
+ members: [
+ for (final m in members) DeviceLogRow(m, fingerprint: fingerprint(b64d(m.pub)), self: m.pub == selfPub),
+ ],
+ frozen: file.frozen,
+ frozenPeers: [
+ for (final e in _frozenPeers.entries)
+ if (e.value) labels[e.key] ?? fingerprint(b64d(e.key)),
+ ],
+ );
+ }
+}
+
+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_auth.dart b/desktop/lib/viewer/direct_auth.dart
index 66b27a0bd..02033f3cd 100644
--- a/desktop/lib/viewer/direct_auth.dart
+++ b/desktop/lib/viewer/direct_auth.dart
@@ -27,7 +27,19 @@ class DirectAuth implements AccessTokenSource {
return (token ?? '').isNotEmpty;
}
+ /// Whether a sign-in by hand happened since this was last asked — the device key log reads it to
+ /// tell signing in again after a removal from an app opening under a removed key
+ /// (`device_log_sync.dart` `register`). Asking clears it.
+ bool consumeFreshSignIn() {
+ final fresh = _freshSignIn;
+ _freshSignIn = false;
+ return fresh;
+ }
+
+ bool _freshSignIn = false;
+
Future<void> signIn(IssuedTokens tokens, {bool Function()? stillCurrent}) {
+ _freshSignIn = true;
final revision = ++_revision;
_refreshing = null;
return _write(revision, () async {
diff --git a/desktop/lib/viewer/direct_link.dart b/desktop/lib/viewer/direct_link.dart
index 977d1c1b0..165f5816f 100644
--- a/desktop/lib/viewer/direct_link.dart
+++ b/desktop/lib/viewer/direct_link.dart
@@ -5,6 +5,7 @@ import '../core/config.dart';
import '../e2ee/keys.dart';
import 'direct_auth.dart';
import 'direct_auth_api.dart';
+import 'device_log_sync.dart';
import 'group_sync.dart';
import 'password_link.dart';
import 'viewer_key_store.dart';
@@ -24,6 +25,10 @@ class DirectLink implements PeerLinkClient {
final AppConfig config;
final RelaySocketFactory socket;
+ /// The account's device key log, once the app has one: its head rides every roster swap, so a
+ /// machine shown a different log than this app is found out (`device_log_sync.dart`).
+ ViewerDeviceLog? deviceLog;
+
@override
Future<CliLinkConnectResult> connect(
String machineId,
@@ -78,6 +83,7 @@ class DirectLink implements PeerLinkClient {
} catch (_) {
return GroupSyncOutcome.none;
}
+ final log = deviceLog;
return syncTrustGroup(
machineId: machineId,
keys: keys,
@@ -86,6 +92,8 @@ class DirectLink implements PeerLinkClient {
autonomousEnv: config.autonomousEnv,
label: label,
socket: socket,
+ devlog: await log?.gossip(),
+ onDevlog: log?.heard,
);
}
diff --git a/desktop/lib/viewer/group_sync.dart b/desktop/lib/viewer/group_sync.dart
index 3c61bca06..bbab7a8f0 100644
--- a/desktop/lib/viewer/group_sync.dart
+++ b/desktop/lib/viewer/group_sync.dart
@@ -215,6 +215,8 @@ Future<GroupSyncOutcome> syncTrustGroup({
required String label,
RelaySocketFactory socket = defaultRelaySocket,
Duration timeout = const Duration(seconds: 20),
+ Map<String, Object?>? devlog,
+ Future<void> Function(String machinePub, Object? devlog)? onDevlog,
}) async {
WebSocketChannel? channel;
try {
@@ -243,9 +245,12 @@ Future<GroupSyncOutcome> syncTrustGroup({
'requestId': b64e(secureRandomBytes(12)),
'self': self.toJson(),
...local.toJson(),
+ // The device key log's head (device_log_sync.dart): the machine answers with its own.
+ 'devlog': ?devlog,
});
}().timeout(timeout, onTimeout: () => null);
if (reply == null || reply['error'] != null) return GroupSyncOutcome.none;
+ if (reply['devlog'] != null) await onDevlog?.call(b64e(pin.pub), reply['devlog']);
final incoming = GroupRoster.parse(reply);
final theirs = GroupMember.tryParse(reply['self']);
diff --git a/desktop/lib/viewer/platform_auth_web.dart b/desktop/lib/viewer/platform_auth_web.dart
index 8932d4f68..cd0729c55 100644
--- a/desktop/lib/viewer/platform_auth_web.dart
+++ b/desktop/lib/viewer/platform_auth_web.dart
@@ -81,6 +81,9 @@ class BrowserAuth extends DirectAuth {
@override
Future<bool> hasSession() => _run(_delegate.hasSession);
+ @override
+ bool consumeFreshSignIn() => _delegate.consumeFreshSignIn();
+
@override
Future<void> signIn(IssuedTokens tokens, {bool Function()? stillCurrent}) {
final revision = ++_revision;
diff --git a/desktop/lib/viewer/viewer_key_store.dart b/desktop/lib/viewer/viewer_key_store.dart
index 1487fbc3c..c9b40e7e1 100644
--- a/desktop/lib/viewer/viewer_key_store.dart
+++ b/desktop/lib/viewer/viewer_key_store.dart
@@ -63,6 +63,7 @@ class ViewerKeyStore {
static const _seedKey = 'viewer_e2ee_identity_seed';
static const _peersKey = 'viewer_e2ee_machine_peers';
static const _groupKey = 'viewer_e2ee_group';
+ static const _devLogKey = 'viewer_e2ee_devlog';
/// Minted on first use and kept: every linked machine has pinned it.
Future<E2eeIdentity> identity() => _identity ??= _loadOrMintIdentity();
@@ -139,6 +140,30 @@ class ViewerKeyStore {
Future<void> writeGroupRoster(Map<String, Object> roster) =>
_storage.write(_groupKey, jsonEncode(roster));
+ /// This device's verified copy of the account's device key log (`device_log_sync.dart`), as stored
+ /// JSON; null when there is none yet or it cannot be read.
+ Future<Object?> deviceLog() async {
+ final raw = await _storage.read(_devLogKey);
+ if (raw == null) return null;
+ try {
+ return jsonDecode(raw);
+ } on FormatException {
+ return null;
+ }
+ }
+
+ Future<void> writeDeviceLog(Map<String, Object?> log) =>
+ _storage.write(_devLogKey, jsonEncode(log));
+
+ /// 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.
+ 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(
_peersKey,
jsonEncode([for (final peer in peers) peer.toJson()]),
diff --git a/desktop/lib/widgets/machine_picker_form.dart b/desktop/lib/widgets/machine_picker_form.dart
index d7fa206ad..1a6e7e438 100644
--- a/desktop/lib/widgets/machine_picker_form.dart
+++ b/desktop/lib/widgets/machine_picker_form.dart
@@ -715,10 +715,6 @@ class MachinePickerFormState extends State<MachinePickerForm> {
line(
'2. Sign in ${email == null ? 'to the same account' : 'as $email'}.',
),
- gap,
- line(
- '3. Set its password in Cmd P → @ → this computer → Password.',
- ),
] else ...[
line('1. Install the CLI (skip if installed).'),
line(kLinkServerInstallCommand, selectable: true),
@@ -728,11 +724,12 @@ class MachinePickerFormState extends State<MachinePickerForm> {
),
line(kLinkServerLoginCommand, selectable: true),
gap,
- line('3. Start Harness and set its password.'),
+ line('3. Start Harness.'),
line(kLinkServerStartCommand, selectable: true),
],
gap,
- line('Then select the machine here and Connect.'),
+ // Signing in is what makes this app trust it (the device key log): no password to set.
+ line('It appears here and connects on its own.'),
] else if (widget.kind == MachinePickerFormKind.delete) ...[
line('Delete this machine from your account?'),
line('Its panes in this window will close.'),
diff --git a/desktop/lib/widgets/new_device_notice.dart b/desktop/lib/widgets/new_device_notice.dart
new file mode 100644
index 000000000..f50ec4898
--- /dev/null
+++ b/desktop/lib/widgets/new_device_notice.dart
@@ -0,0 +1,77 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+
+import '../settings/settings_screen.dart';
+import '../settings/settings_section.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../state/app_state.dart';
+import 'window_chrome.dart';
+
+/// The band across the top of the window when a device this end had never trusted joined the
+/// account ("New device: X"). Signing in is what makes a device trusted, so this is how a device
+/// signed in by someone else — or added by whoever runs the backend — is seen. One notice at a
+/// time, newest last; each stays until it is looked at or dismissed.
+class NewDeviceNotice extends StatelessWidget {
+ const NewDeviceNotice({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ if (notifier.newDevices.isEmpty) return const SizedBox.shrink();
+ final notice = notifier.newDevices.first;
+ final more = notifier.newDevices.length - 1;
+ final tint = Color.alphaBlend(grid.AppPalette.warn.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: grid.AppPalette.warn.withValues(alpha: 0.28))),
+ ),
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(14 + trafficLightClearance, 7, 10, 7),
+ child: Row(
+ children: [
+ Icon(AppIcons.shield, size: 16, color: grid.AppPalette.warn),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ '${notice.sentence}${more > 0 ? ' (+$more more)' : ''} Not yours? Remove it.',
+ key: const Key('new-device-notice'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.body(color: grid.AppPalette.textPrimary),
+ ),
+ ),
+ const SizedBox(width: 12),
+ TextButton(
+ key: const Key('new-device-dismiss'),
+ onPressed: () => notifier.dismissNewDevice(notice.pub),
+ child: const Text('It’s mine'),
+ ),
+ const SizedBox(width: 6),
+ OutlinedButton(
+ key: const Key('new-device-review'),
+ onPressed: () => unawaited(
+ showSettingsScreen(
+ context,
+ notifier,
+ initialSection: SettingsSection.accountDevices,
+ source: 'new-device-notice',
+ ),
+ ),
+ child: const Text('Review devices'),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/test/account_devices_section_test.dart b/desktop/test/account_devices_section_test.dart
new file mode 100644
index 000000000..72ba759d0
--- /dev/null
+++ b/desktop/test/account_devices_section_test.dart
@@ -0,0 +1,24 @@
+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/state/account_devices.dart';
+import 'package:harness/state/app_state.dart';
+
+/// Settings ▸ Your devices: opening it is reviewing the devices the banner announced.
+void main() {
+ testWidgets('opening the devices list takes the new-device banner down', (tester) async {
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null);
+ 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();
+ 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));
+ });
+}
diff --git a/desktop/test/account_devices_test.dart b/desktop/test/account_devices_test.dart
new file mode 100644
index 000000000..69a451522
--- /dev/null
+++ b/desktop/test/account_devices_test.dart
@@ -0,0 +1,40 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/account_devices.dart';
+
+/// The Devices list's model (`lib/state/account_devices.dart`): what a daemon answers, and which apps
+/// it offers to remove as unused.
+void main() {
+ final now = DateTime(2026, 10, 1);
+ Map<String, Object?> row(String pub, {String kind = 'viewer', bool self = false}) => {
+ 'pub': pub, 'label': pub, 'kind': kind, 'machineId': kind == 'machine' ? 'a' * 32 : '',
+ 'addedAt': DateTime(2026, 1, 1).millisecondsSinceEpoch, 'fingerprint': 'FP', 'self': self,
+ };
+
+ test('reads a daemon listing with its frozen state and when each key was last seen', () {
+ final devices = AccountDevices.fromDaemon({
+ 'members': [row('old'), row('me', self: true), row('box', kind: 'machine'), {'bad': true}],
+ 'frozen': {'reason': 'fork'},
+ 'frozenPeers': ['box2'],
+ 'lastSeen': {'old': DateTime(2026, 5, 1).millisecondsSinceEpoch, 'junk': 'x'},
+ })!;
+ expect(devices.devices.map((d) => d.pub), ['old', 'me', 'box']);
+ expect(devices.frozenReason, 'fork');
+ expect(devices.frozen, isTrue);
+ expect(devices.devices.first.lastSeen, DateTime(2026, 5, 1));
+ expect(devices.devices[1].lastSeen, isNull);
+ });
+
+ test('offers only apps seen long ago — never this one, a computer, or one never recorded', () {
+ final long = DateTime(2026, 5, 1).millisecondsSinceEpoch;
+ final devices = AccountDevices.fromDaemon({
+ 'members': [
+ row('stale'), row('fresh'), row('never'), row('me', self: true), row('box', kind: 'machine'),
+ ],
+ 'lastSeen': {
+ 'stale': long, 'me': long, 'box': long,
+ 'fresh': DateTime(2026, 9, 20).millisecondsSinceEpoch,
+ },
+ })!;
+ expect(devices.unused(now).map((d) => d.pub), ['stale']);
+ });
+}
diff --git a/desktop/test/settings_section_test.dart b/desktop/test/settings_section_test.dart
index bd3c4103d..ce605cd82 100644
--- a/desktop/test/settings_section_test.dart
+++ b/desktop/test/settings_section_test.dart
@@ -38,6 +38,7 @@ void main() {
SettingsSection.experimental,
if (!kIsWeb) SettingsSection.devices,
SettingsSection.account,
+ SettingsSection.accountDevices,
SettingsSection.profiles,
SettingsSection.shortcuts,
SettingsSection.about,
diff --git a/desktop/test/viewer/device_log.vectors.json b/desktop/test/viewer/device_log.vectors.json
new file mode 100644
index 000000000..223b62521
--- /dev/null
+++ b/desktop/test/viewer/device_log.vectors.json
@@ -0,0 +1,375 @@
+{
+ "comment": "Generated by cli/scripts/gen-devlog-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4, box2b=5).",
+ "acct": "acct-vectors-1",
+ "seeds": {
+ "box1": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
+ "box2": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=",
+ "browser": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "stranger": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ=",
+ "box2b": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU="
+ },
+ "pubs": {
+ "box1": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "box2": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "browser": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "stranger": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "box2b": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E="
+ },
+ "valid": {
+ "entries": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 1000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "PQ79548gYy1fR00xYYrAqGYQer//uS3fGo1Xwwih7v6Jpw8lLHsM/plOYoenu8qjIWhPTSPlVSghlAt9C6MMCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 2000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "bHi9oSluvJ/RKgTw7RZrPaplcR45FGkVMmnOjm4dQnTzchKsMN6D6WKTNphHLjthUYhcznmjIJDLjplJ5TKsAg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 3000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "Browser · macOS — “Dee”",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "NK0FM6TeU5KyGr78swAvqDRYvHQafuMj/pBBxMANdNdALGrcA3pA+h4WMarQT81Ker2W0ALWvAcufmSkOxjiCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "qNFvpVnzstkVYeTrds5NiQ6EyfyImRIhjndzUjzO/eA=",
+ "at": 4000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1 (renamed)",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "ccsh5GRy/OZkP+l50LN90T+8O1Ca0dcOmdm2pCJlF1ccTNC+ZPwoZ3NujkS2uJORP/xwu9xZ7gSqBhQ3XaWzCg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 5,
+ "prev": "NiCtLf6zNhboU5bHOg8pggpUZxeuey5a0KGQ4lHyehE=",
+ "at": 5000,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "1LAIjj3C77/H5v7LxR1QFYfxTrjJbRFTdk/0nvAmTIOYAoH42xLvqwh3e8bHsvH32GmfNNvARRSGTuXKTkZMBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 6,
+ "prev": "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "at": 6000,
+ "op": "add",
+ "pub": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "sig": "cwe4qUy9BDLShHXA8IhIMxs/ZbdF/a2Js7IqpQyNBV/FjcCS/eoGDEufpS0+sPPAhDlky2K1vpgwVS0PIakyCw=="
+ }
+ ],
+ "hashes": [
+ "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "qNFvpVnzstkVYeTrds5NiQ6EyfyImRIhjndzUjzO/eA=",
+ "NiCtLf6zNhboU5bHOg8pggpUZxeuey5a0KGQ4lHyehE=",
+ "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "f5WzxT87hry0q9rj895yyaiCax/xP2PRZCCfpGPKDTw="
+ ],
+ "head": {
+ "seq": 6,
+ "hash": "f5WzxT87hry0q9rj895yyaiCax/xP2PRZCCfpGPKDTw="
+ },
+ "active": [
+ "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w="
+ ],
+ "removed": [
+ "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q="
+ ]
+ },
+ "invalid": [
+ {
+ "name": "tampered label",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "evil",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "udynDrC1h7IK8lrCs+AqPLpTCNeQxD4DlkQP6BOQZD+oNquOndvYqEPmU60wE9JTin8YYVFboZ6jyzxl5YSQAw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "add signed by another key",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "RL5wtkxLhLIkWpUBZ+njRYIh0KqeuYc1pIoEQQ9oAfs2xFa5UwpLJhI4sia2HXI+dovYK+igVD0HnE4QoF3BDA=="
+ },
+ "code": "NOT_SELF_SIGNED"
+ },
+ {
+ "name": "machine id of another active machine",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "imposter",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "KJulD+38Nt9i6HNhMZwVemE3wXIrLOLsMbd1A2BxIC4hke7aKwN6itY04iSRbLqOGlDzOPwi0GUGj0ZrW0DcCQ=="
+ },
+ "code": "MACHINE_TAKEN"
+ },
+ {
+ "name": "removed key comes back",
+ "after": 5,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 6,
+ "prev": "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "at": 9000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2 again",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "AyV+EkrCunkAI12uokVnsclD26e2n5ZDIvNqxxoABvxdvgDvSXnXDdJ8EVFFro3FK9ROh0ATNh3FQVoUWa/9CQ=="
+ },
+ "code": "KEY_REMOVED"
+ },
+ {
+ "name": "remove signed by a key not in the log",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "remove",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "xkp6fed+m63wylf9c1Zaz3YXtwPhOgbMzpKqCkXuNo06UfKfPmJx4/BD2OY+Wt+E03hUUrB438ME1gLjzp4VBg=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "remove of a key not in the log",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "remove",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "Vh2WinwrdWHv46djCCkZ+p0QtWlALCHXBIPHgYkSi9Zpys93JPYhaJIJhEcdQYwQuYvEF2IVtxK2um1IaQgJDg=="
+ },
+ "code": "NOT_ACTIVE"
+ },
+ {
+ "name": "wrong prev",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "nPbFpdYE1xqmdxxL8fj77CeBVrosx4N847Zy9gqngg5bBdcyqzMRsHSm/q0OTuW6VEwIzk66/OCMcwuT1HERBA=="
+ },
+ "code": "BROKEN_CHAIN"
+ },
+ {
+ "name": "skipped seq",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "wJqA4rLVUCIewTr/eeeMxSKX2yv9wQOFhqGVws0+1QITAdgkZwGNIWbpBptIlFrcNyh3oRTFMdGWykfeqkTcAA=="
+ },
+ "code": "OUT_OF_ORDER"
+ },
+ {
+ "name": "other account",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-other",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "eXH3aVMs0jDDzFg3xehB+Z7G6h2jyvjZcHGm128CIvVwcWDSytwHRAY+g4iXpYkBeJxhksoCOdgpNQds69xMDQ=="
+ },
+ "code": "WRONG_ACCOUNT"
+ },
+ {
+ "name": "machine changes kind",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "c2mJ6r5OoEW7bY0EERqWBt8z37H5ExY59f5KiP6mtRSv5adSQjT5HxzlGXgcILOjLUPIFijE16cGPM++CdJXCg=="
+ },
+ "code": "KIND_CHANGED"
+ },
+ {
+ "name": "re-add with nothing changed",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "fjF5dBSdSDddFJdLDmYWaleR4RniUf62lI0Fbdb4vTkXp8cXo4rwqAcGncZt5yCHOK2F7pYg56FUbbospfIuAg=="
+ },
+ "code": "NO_CHANGE"
+ },
+ {
+ "name": "viewer with a machine id",
+ "after": 0,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 9000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "b",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "2t+mAiwKKqhImNoq+7HVp7bXdf1UeL7Vd4QOmEiS1fsGG1Ux6+HVKjosKKzX/wzQo9ju84Yd3x12teETgIsjAQ=="
+ },
+ "code": "BAD_ENTRY"
+ },
+ {
+ "name": "control character in label",
+ "after": 0,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 9000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "a\nb",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "lzDA+QfWL9V5issDES2f9vRw/CX2Tv6dk8nF6ZmwcJ87kyegBoWh1TkUL6RXVS+8vacy9vLJd+keCMwpsCOqAA=="
+ },
+ "code": "BAD_ENTRY"
+ }
+ ]
+}
diff --git a/desktop/test/viewer/device_log_sync_test.dart b/desktop/test/viewer/device_log_sync_test.dart
new file mode 100644
index 000000000..947180ff9
--- /dev/null
+++ b/desktop/test/viewer/device_log_sync_test.dart
@@ -0,0 +1,245 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/viewer/device_log.dart';
+import 'package:harness/viewer/device_log_sync.dart';
+import 'package:harness/viewer/group_sync.dart';
+import 'package:harness/viewer/viewer_key_store.dart';
+
+/// The viewer's half of the device key log (`lib/viewer/device_log_sync.dart`), against a backend
+/// that keeps the log honestly — or is told to lie.
+
+class _Memory 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);
+}
+
+const _acct = 'acct-1';
+final _mid2 = 'b' * 32, _mid3 = 'c' * 32;
+
+class _Backend {
+ final entries = <DevLogEntry>[];
+ DevLogState state = DevLogState.empty(_acct);
+ List<DevLogEntry>? lie;
+
+ Future<void> add(E2eeIdentity who, String kind, String machineId, String label) async {
+ final pub = b64e(who.pub);
+ final e = await signDevLogEntry(
+ nextDevLogEntry(state, op: 'add', pub: pub, kind: kind, machineId: machineId, label: label, signer: pub, at: 1000),
+ who,
+ );
+ await _push(e);
+ }
+
+ Future<void> removeBy(String target, E2eeIdentity by) async {
+ final t = state.active[target]!;
+ final e = 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,
+ );
+ await _push(e);
+ }
+
+ Future<void> _push(DevLogEntry e) async {
+ state = (await applyDevLogEntries(state, [e.toJson()])).state;
+ entries.add(e);
+ }
+
+ Future<DeviceLogFetched?> fetch(int since) async {
+ 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()]);
+ }
+
+ 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');
+ }
+ try {
+ await _push(entry);
+ } on DevLogError catch (e) {
+ return (head: null, error: e.code);
+ }
+ return (head: state.head, error: null);
+ }
+}
+
+void main() {
+ late _Backend backend;
+ late ViewerKeyStore keys;
+ late List<DevLogMember> announced;
+ late int signedOut;
+ late E2eeIdentity box2, box3;
+
+ ViewerDeviceLog makeLog() => ViewerDeviceLog(
+ keys: keys,
+ fetch: backend.fetch,
+ append: backend.append,
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ setUp(() async {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ announced = [];
+ signedOut = 0;
+ box2 = await E2eeIdentity.fromSeed(List.filled(32, 2));
+ box3 = await E2eeIdentity.fromSeed(List.filled(32, 3));
+ });
+
+ test('registers this app and pins every machine already in the log, announcing none', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final me = b64e((await keys.identity()).pub);
+ expect(backend.state.active[me]?.kind, 'viewer');
+ expect(backend.state.active[me]?.label, 'my-phone');
+ expect(b64e((await keys.peer(_mid2))!.pub), b64e(box2.pub));
+ expect(announced, isEmpty);
+ });
+
+ test('a machine added later is pinned and announced once', () async {
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await log.refresh();
+ expect(await keys.peer(_mid3), isNotNull);
+ expect(announced.map((m) => m.label), ['box3']);
+ // …and the trust group this app swaps with machines names it, for machines that predate the log.
+ final roster = GroupRoster.parse(await keys.groupRoster());
+ expect(roster.members.map((m) => m.pub), contains(b64e(box3.pub)));
+ });
+
+ test('a machine this app had already linked is not news', () async {
+ await keys.pin(_mid3, box3.pub, label: 'box3');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ expect(announced, isEmpty);
+ });
+
+ test('a removed machine is unpinned', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ expect(await log.remove(b64e(box2.pub)), isNull);
+ expect(await keys.peer(_mid2), isNull);
+ expect(backend.state.active[b64e(box2.pub)], isNull);
+ });
+
+ test('its own key removed signs it out', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.removeBy(b64e((await keys.identity()).pub), box2);
+ await log.refresh();
+ expect(signedOut, 1);
+ });
+
+ test('signing in again after a removal comes back under a new key, without signing out', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final old = b64e((await keys.identity()).pub);
+ await backend.removeBy(old, box2);
+ // Signed out by the removal before reading the log (a revoked session answers 401 first)…
+ await log.register(freshSignIn: true);
+ final now = b64e((await keys.identity()).pub);
+ expect(now, isNot(old));
+ expect(backend.state.active[now]?.kind, 'viewer');
+ expect(signedOut, 0);
+ });
+
+ test('opening under a removed key still signs out', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.removeBy(b64e((await keys.identity()).pub), box2);
+ await log.register();
+ expect(signedOut, 1);
+ });
+
+ test('freezes on a rewritten log and pins nothing more from it', () 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, 'evil');
+ await forged.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'x');
+ backend.lie = forged.entries;
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'fork');
+ expect(await keys.peer(_mid3), isNull);
+ });
+
+ test('freezes on a rollback, and trusting again shows the change first', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'rollback');
+ backend.lie = null;
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final preview = await log.rebaseline(confirm: false);
+ expect(preview!.added.map((m) => m.label), ['box3']);
+ expect((await log.list()).frozen, isNotNull);
+ await log.rebaseline(confirm: true);
+ expect((await log.list()).frozen, isNull);
+ expect(await keys.peer(_mid3), isNotNull);
+ });
+
+ test('a machine answering with a different entry at a verified position freezes it', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final other = _Backend();
+ await other.add(box3, 'machine', _mid3, 'box3');
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await log.heard(b64e(box2.pub), {'head': other.state.head.toJson(), 'frozen': false});
+ expect((await log.list()).frozen?.reason, 'fork');
+ });
+
+ test('says which machines report a frozen log', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await log.heard(b64e(box2.pub), {'head': backend.state.head.toJson(), 'frozen': true});
+ expect((await log.list()).frozenPeers, ['box2']);
+ });
+
+ test('a removal the trust group made before the log is written into it, without hanging the read', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await keys.writeGroupRoster(GroupRoster(const [], [GroupTombstone(b64e(box2.pub), 900)]).toJson());
+ final log = makeLog();
+ await log.register().timeout(const Duration(seconds: 5));
+ for (var i = 0; i < 50 && backend.state.active[b64e(box2.pub)] != null; i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ }
+ expect(backend.state.removed, contains(b64e(box2.pub)));
+ expect(await keys.peer(_mid2), isNull);
+ // …and the log is still readable afterwards.
+ await log.refresh().timeout(const Duration(seconds: 5));
+ });
+
+ test('forgetting the identity mints a new one', () async {
+ final before = b64e((await keys.identity()).pub);
+ await keys.forgetIdentity();
+ expect(b64e((await keys.identity()).pub), isNot(before));
+ });
+}
diff --git a/desktop/test/viewer/device_log_test.dart b/desktop/test/viewer/device_log_test.dart
new file mode 100644
index 000000000..4e3d87bdf
--- /dev/null
+++ b/desktop/test/viewer/device_log_test.dart
@@ -0,0 +1,72 @@
+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_log.dart';
+
+/// The Dart port of the device key log, held to the fixture every implementation shares
+/// (cli/scripts/gen-devlog-vectors.ts).
+void main() {
+ final vectors = jsonDecode(File('test/viewer/device_log.vectors.json').readAsStringSync()) as Map<String, dynamic>;
+ final acct = vectors['acct'] as String;
+ final valid = vectors['valid'] as Map<String, dynamic>;
+ final entries = (valid['entries'] as List).cast<Object?>();
+
+ test('derives the fixture keys from their seeds', () async {
+ final seeds = (vectors['seeds'] as Map).cast<String, String>();
+ final pubs = (vectors['pubs'] as Map).cast<String, String>();
+ for (final name in seeds.keys) {
+ final id = await E2eeIdentity.fromSeed(b64d(seeds[name]!));
+ expect(b64e(id.pub), pubs[name]);
+ }
+ });
+
+ test('applies every valid entry to the fixture hashes, head and active set', () async {
+ final applied = await applyDevLogEntries(DevLogState.empty(acct), entries);
+ expect(applied.state.hashes, valid['hashes']);
+ expect(applied.state.head.toJson(), valid['head']);
+ expect(applied.state.active.keys.toList()..sort(), valid['active']);
+ expect(applied.state.removed, valid['removed']);
+ });
+
+ test('re-signs every valid entry to the same signature', () async {
+ final seeds = (vectors['seeds'] as Map).cast<String, String>();
+ final pubs = (vectors['pubs'] as Map).cast<String, String>();
+ final byPub = {for (final n in seeds.keys) pubs[n]!: seeds[n]!};
+ for (final raw in entries) {
+ final e = DevLogEntry.parse(raw)!;
+ final id = await E2eeIdentity.fromSeed(b64d(byPub[e.signer]!));
+ expect((await signDevLogEntry(e.withSig(''), id)).sig, e.sig);
+ }
+ });
+
+ for (final c in (vectors['invalid'] as List).cast<Map<String, dynamic>>()) {
+ test('refuses: ${c['name']} (${c['code']})', () async {
+ final base = (await applyDevLogEntries(DevLogState.empty(acct), entries.sublist(0, c['after'] as int))).state;
+ Object? error;
+ try {
+ await applyDevLogEntries(base, [c['entry']]);
+ } catch (err) {
+ error = err;
+ }
+ expect(error, isA<DevLogError>().having((e) => e.code, 'code', c['code']));
+ });
+ }
+
+ test('round-trips its state through JSON', () async {
+ final s = (await applyDevLogEntries(DevLogState.empty(acct), entries)).state;
+ final back = DevLogState.fromJson(jsonDecode(jsonEncode(s.toJson())))!;
+ expect(back.toJson(), s.toJson());
+ });
+
+ test('tells same, ahead, behind and fork apart', () async {
+ final s = (await applyDevLogEntries(DevLogState.empty(acct), entries.sublist(0, 4))).state;
+ final hashes = (valid['hashes'] as List).cast<String>();
+ expect(compareDevLogHead(s, s.head), 'same');
+ expect(compareDevLogHead(s, DevLogHead(2, hashes[1])), 'ahead');
+ expect(compareDevLogHead(s, DevLogHead(6, hashes[5])), 'behind');
+ expect(compareDevLogHead(s, DevLogHead(3, hashes[1])), 'fork');
+ });
+}
diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dart
index 857134db4..6a8794e63 100644
--- a/mobile/lib/api/api_client.dart
+++ b/mobile/lib/api/api_client.dart
@@ -6,6 +6,8 @@ import '../auth/auth_session.dart';
import '../core/config.dart';
import '../core/models.dart';
import '../logging/http_log.dart';
+import '../viewer/device_log.dart';
+import '../viewer/device_log_sync.dart' show DeviceLogAppendAnswer, DeviceLogFetched;
import 'access_token_source.dart';
import 'bearer_auth_interceptor.dart';
import 'multipart_body.dart';
@@ -89,6 +91,60 @@ class ApiClient {
unwrapApiResponse(res);
}
+ // -- the account's device key log (viewer/device_log_sync.dart) --
+
+ /// `GET /api/device-keys?since=` — the log from [since]; null when there is none to read (an older
+ /// backend, signed out, or unreachable).
+ Future<DeviceLogFetched?> deviceKeys(int since) async {
+ try {
+ final res = await _dio.get('/api/device-keys', queryParameters: {'since': since});
+ if (res.statusCode != 200) return null;
+ final data = unwrapApiResponse(res);
+ if (data is! Map) return null;
+ final acct = data['acct'], head = DevLogHead.fromJson(data['head']), entries = data['entries'];
+ if (acct is! String || head == null || entries is! List) return null;
+ return (acct: acct, head: head, entries: entries.cast<Object?>());
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// `POST /api/device-keys` — append one entry this phone signed. Null when the backend could not
+ /// be reached; a refusal comes back as its code (`STALE_HEAD` with the current head).
+ Future<DeviceLogAppendAnswer?> appendDeviceKey(DevLogEntry entry) async {
+ try {
+ final res = await _dio.post('/api/device-keys', data: {'entry': entry.toJson()});
+ final body = res.data;
+ if (body is! Map) return null;
+ final data = body['data'];
+ final head = data is Map ? DevLogHead.fromJson(data['head']) : null;
+ if (res.statusCode == 200) return (head: head, error: null);
+ final error = body['error'];
+ final code = error is Map && error['code'] is String ? error['code'] as String : 'HTTP_${res.statusCode}';
+ return (head: head, error: code);
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// `GET /api/device-keys/seen` — when each key last opened a session, `{pub: ms}`; empty when it
+ /// cannot be read. A hint for offering to remove apps not used in a long while.
+ Future<Map<String, int>> deviceKeysSeen() async {
+ try {
+ final res = await _dio.get('/api/device-keys/seen');
+ if (res.statusCode != 200) return const {};
+ final data = unwrapApiResponse(res);
+ final seen = data is Map ? data['seen'] : null;
+ return {
+ if (seen is Map)
+ for (final e in seen.entries)
+ if (e.key is String && e.value is int) e.key as String: e.value as int,
+ };
+ } catch (_) {
+ return const {};
+ }
+ }
+
// -- the desk: the account's tabs, the same on every computer --
/// `{revision, tabs}` as the backend holds it (its `routes/desk.ts`); null on
diff --git a/mobile/lib/notify/system_notices.dart b/mobile/lib/notify/system_notices.dart
index ae32bca75..695daf213 100644
--- a/mobile/lib/notify/system_notices.dart
+++ b/mobile/lib/notify/system_notices.dart
@@ -35,6 +35,10 @@ abstract interface class SystemNotices {
/// The agent whose notice was tapped last — what the shell opens. Reset to
/// null by whoever acts on it.
ValueNotifier<AgentRef?> get opened;
+
+ /// News about the ACCOUNT rather than an agent: a device joined it. [key] names the notice, so the
+ /// same news posted twice replaces itself. Tapping it just opens the app, where the banner waits.
+ Future<void> showAccountNotice({required String key, required String title, required String body});
}
/// Nothing leaves the process. What a test notifier is given.
@@ -50,6 +54,9 @@ class SilentSystemNotices implements SystemNotices {
@override
Future<void> cancel(AgentRef agent) async {}
+
+ @override
+ Future<void> showAccountNotice({required String key, required String title, required String body}) async {}
}
/// The real centre, through flutter_local_notifications.
@@ -170,6 +177,30 @@ class LocalSystemNotices implements SystemNotices {
}
}
+ @override
+ Future<void> showAccountNotice({required String key, required String title, required String body}) async {
+ try {
+ await _init();
+ await _plugin.show(
+ id: accountNoticeIdFor(key),
+ title: title,
+ body: body,
+ notificationDetails: const NotificationDetails(
+ android: AndroidNotificationDetails(
+ 'account-device',
+ 'New device on your account',
+ channelDescription: 'A computer or app signed in to your account and can reach your machines.',
+ importance: Importance.high,
+ priority: Priority.high,
+ ),
+ iOS: DarwinNotificationDetails(threadIdentifier: 'account-device'),
+ ),
+ );
+ } catch (error) {
+ appLog.warn('notify', 'account notice failed', error: error);
+ }
+ }
+
@override
Future<void> cancel(AgentRef agent) async {
try {
@@ -193,6 +224,17 @@ int noticeIdFor(AgentRef agent) {
return hash;
}
+/// A stable, positive id per account notice — the same FNV-1a as [noticeIdFor], over its own key,
+/// so it never lands on an agent's.
+@visibleForTesting
+int accountNoticeIdFor(String key) {
+ var hash = 0x811c9dc5;
+ for (final unit in 'account\n$key'.codeUnits) {
+ hash = ((hash ^ unit) * 0x01000193) & 0x7fffffff;
+ }
+ return hash;
+}
+
@visibleForTesting
String encodeAgentPayload(AgentRef agent) =>
'${agent.machineId}\n${agent.agentId}';
diff --git a/mobile/lib/phone/devices_page.dart b/mobile/lib/phone/devices_page.dart
new file mode 100644
index 000000000..640f0fb37
--- /dev/null
+++ b/mobile/lib/phone/devices_page.dart
@@ -0,0 +1,277 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.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 'phone_sheet.dart';
+import 'settings_row.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// 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.
+class DevicesPage extends StatefulWidget {
+ const DevicesPage({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ State<DevicesPage> createState() => _DevicesPageState();
+}
+
+class _DevicesPageState extends State<DevicesPage> {
+ DeviceLogListing? _listing;
+ Map<String, int> _seen = const {};
+ bool _removingUnused = false;
+ int _revision = -1;
+ final Set<String> _removing = {};
+ String? _error;
+
+ AppNotifier get _app => widget.notifier;
+
+ @override
+ void initState() {
+ super.initState();
+ _app.addListener(_changed);
+ 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
+ void dispose() {
+ _app.removeListener(_changed);
+ super.dispose();
+ }
+
+ void _changed() {
+ if (_app.devicesRevision != _revision) unawaited(_load());
+ }
+
+ Future<void> _load() async {
+ _revision = _app.devicesRevision;
+ final listing = await _app.deviceLog?.list();
+ final seen = await _app.devicesLastSeen();
+ if (!mounted) return;
+ setState(() {
+ _listing = listing ?? DeviceLogListing.empty;
+ _seen = seen;
+ });
+ }
+
+ Future<void> _remove(DeviceLogRow row) async {
+ final name = row.member.label.isEmpty ? 'this device' : row.member.label;
+ final confirmed = await confirmPhoneAction(
+ context,
+ title: 'Remove $name?',
+ message:
+ 'It stops reaching your machines on every device, and is signed out. '
+ 'Signing in on it again adds it back as a new device.',
+ confirmLabel: 'Remove',
+ icon: LucideIcons.shieldOff300,
+ );
+ if (!confirmed || !mounted) return;
+ setState(() {
+ _removing.add(row.member.pub);
+ _error = null;
+ });
+ final error = await _app.removeDevice(row.member.pub);
+ if (!mounted) return;
+ setState(() {
+ _removing.remove(row.member.pub);
+ _error = error == null ? null : "Couldn't remove $name. Try again.";
+ });
+ }
+
+ /// Apps not seen in 90 days: most likely a browser whose data was cleared, which never signs its
+ /// own removal. Never this phone, never a computer, never one the backend has no record of.
+ List<DeviceLogRow> _unused(DeviceLogListing listing) {
+ final cutoff = DateTime.now()
+ .subtract(const Duration(days: 90))
+ .millisecondsSinceEpoch;
+ return [
+ for (final row in listing.members)
+ if (!row.self &&
+ row.member.kind == 'viewer' &&
+ (_seen[row.member.pub] ?? cutoff) < cutoff)
+ row,
+ ];
+ }
+
+ Future<void> _removeUnused(List<DeviceLogRow> rows) async {
+ final confirmed = await confirmPhoneAction(
+ context,
+ title: 'Remove ${rows.length} unused app${rows.length == 1 ? '' : 's'}?',
+ message:
+ 'Not used in 90 days — most likely a browser whose data was cleared. '
+ 'Removing them changes nothing you use.',
+ confirmLabel: 'Remove',
+ icon: LucideIcons.shieldOff300,
+ );
+ if (!confirmed || !mounted) return;
+ setState(() {
+ _removingUnused = true;
+ _error = null;
+ });
+ var failed = 0;
+ for (final row in rows) {
+ if (await _app.removeDevice(row.member.pub) != null) failed++;
+ }
+ if (!mounted) return;
+ setState(() {
+ _removingUnused = false;
+ _error = failed == 0
+ ? null
+ : "Couldn't remove $failed of them. Try again.";
+ });
+ }
+
+ 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.",
+ );
+ return;
+ }
+ final lines = [
+ for (final m in preview.added)
+ '+ ${m.label.isEmpty ? 'A device' : m.label}',
+ for (final m in preview.removed)
+ '− ${m.label.isEmpty ? 'A device' : m.label}',
+ ];
+ final confirmed = await confirmPhoneAction(
+ context,
+ 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')}',
+ confirmLabel: 'Trust again',
+ icon: LucideIcons.shieldAlert300,
+ );
+ if (!confirmed || !mounted) return;
+ await log.rebaseline(confirm: true);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ final listing = _listing;
+ final frozen =
+ listing != null &&
+ (listing.frozen != null || listing.frozenPeers.isNotEmpty);
+ 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(
+ 'Your devices',
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 8),
+ TtyText(
+ 'Every computer and app signed in to your account. Each reaches your machines '
+ 'end to end encrypted, with no password. Remove one you do not recognise.',
+ color: tty.dim,
+ ),
+ if (frozen) ...[
+ const SizedBox(height: 12),
+ SettingsGroup(
+ children: [
+ SettingsRow(
+ title: 'The device list froze',
+ detail: listing.frozen != null
+ ? 'Harness served a list that does not match what this phone verified. '
+ 'No device is added until you review it.'
+ : 'Frozen on ${listing.frozenPeers.join(', ')}. Review it on that computer.',
+ destructive: true,
+ onTap: listing.frozen != null
+ ? () => unawaited(_trustAgain())
+ : null,
+ value: listing.frozen != null ? 'Review' : null,
+ ),
+ ],
+ ),
+ ],
+ if (_error case final error?) ...[
+ const SizedBox(height: 12),
+ TtyText(error, color: tty.red),
+ ],
+ if (listing != null && _unused(listing).isNotEmpty) ...[
+ const SizedBox(height: 12),
+ SettingsGroup(
+ children: [
+ SettingsRow(
+ key: const Key('account-devices-unused'),
+ title:
+ '${_unused(listing).length} app${_unused(listing).length == 1 ? '' : 's'} not used in 90 days',
+ detail: 'Most likely a browser whose data was cleared.',
+ value: _removingUnused ? 'Removing…' : 'Remove',
+ destructive: true,
+ onTap: _removingUnused
+ ? null
+ : () => unawaited(_removeUnused(_unused(listing))),
+ ),
+ ],
+ ),
+ ],
+ const SizedBox(height: 12),
+ if (listing == null)
+ const SizedBox.shrink()
+ else
+ SettingsGroup(
+ children: [
+ for (final row in listing.members)
+ SettingsRow(
+ key: ValueKey('account-device-${row.member.pub}'),
+ title:
+ '${row.member.label.isEmpty ? 'Unnamed device' : row.member.label}'
+ '${row.self ? ' (this phone)' : ''}',
+ detail:
+ '${row.member.kind == 'machine' ? 'Computer' : 'App'}'
+ '${_seen[row.member.pub] != null ? ' · last seen ${_date(_seen[row.member.pub]!)}' : ''}'
+ ' · ${row.fingerprint}',
+ destructive: !row.self,
+ value: row.self
+ ? null
+ : (_removing.contains(row.member.pub)
+ ? 'Removing…'
+ : 'Remove'),
+ onTap: row.self || _removing.contains(row.member.pub)
+ ? null
+ : () => unawaited(_remove(row)),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+String _date(int ms) {
+ final at = DateTime.fromMillisecondsSinceEpoch(ms);
+ String two(int n) => n.toString().padLeft(2, '0');
+ return '${at.year}-${two(at.month)}-${two(at.day)}';
+}
diff --git a/mobile/lib/phone/new_device_banner.dart b/mobile/lib/phone/new_device_banner.dart
new file mode 100644
index 000000000..68e93d2fb
--- /dev/null
+++ b/mobile/lib/phone/new_device_banner.dart
@@ -0,0 +1,65 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'devices_page.dart';
+import 'phone_navigation.dart' show phoneRoute;
+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.
+class NewDeviceBanner extends StatelessWidget {
+ const NewDeviceBanner({
+ super.key,
+ required this.notifier,
+ required this.navigator,
+ });
+
+ final AppNotifier notifier;
+ final GlobalKey<NavigatorState> navigator;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ if (notifier.newDevices.isEmpty) return const SizedBox.shrink();
+ 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'),
+ ),
+ ),
+ TextButton(
+ onPressed: () => notifier.dismissNewDevice(m.pub),
+ child: const Text('Mine'),
+ ),
+ TextButton(
+ onPressed: () => unawaited(
+ navigator.currentState?.push(
+ phoneRoute((_) => DevicesPage(notifier: notifier)),
+ ),
+ ),
+ child: const Text('Review'),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 247a1263d..a13184f21 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -1,3 +1,5 @@
+import 'new_device_banner.dart';
+
import 'package:flutter/material.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -198,23 +200,34 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
//
// `MaterialApp` installs one controller for the ROOT navigator only; a nested
// `Navigator` inherits nothing, so its routes have no observer to drive a flight.
- body: 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,
+ body: Column(
+ children: [
+ // A device this phone had never trusted joined the account (device key log).
+ NewDeviceBanner(
+ notifier: widget.notifier,
+ 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,
+ ),
+ ),
+ ),
),
),
- ),
+ ],
),
),
),
diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dart
index eada6baa8..95d7ba271 100644
--- a/mobile/lib/phone/settings_page.dart
+++ b/mobile/lib/phone/settings_page.dart
@@ -16,6 +16,7 @@ import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/terminal/terminal_font_store.dart';
import 'package:harness_mobile/terminal/terminal_theme_store.dart';
+import 'devices_page.dart';
import 'machines_tab.dart';
import 'phone_navigation.dart' show phoneRoute;
import 'phone_name_store.dart';
@@ -168,6 +169,15 @@ class _Body extends StatelessWidget {
phoneRoute((_) => MachinesTab(notifier: notifier, large: false)),
),
),
+ // Every device signed in to the account — each trusted by the others because of that, so
+ // this is where one that is not yours is seen and taken out.
+ SettingsRow(
+ title: 'Your devices',
+ value: notifier.newDevices.isEmpty ? null : '${notifier.newDevices.length} new',
+ onTap: () => Navigator.of(context).push(
+ phoneRoute((_) => DevicesPage(notifier: notifier)),
+ ),
+ ),
// The name those computers show when this phone takes a harness over — which makes it a
// fact about the account's computers, not about how the terminal looks.
_PhoneNameRow(notifier: notifier),
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index c933ab08c..9fa347a25 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -59,6 +59,8 @@ import 'session_content_search.dart';
import '../usage/remote_usage.dart';
import '../usage/usage_accounts.dart';
import '../phone/phone_name_store.dart';
+import '../viewer/device_log.dart';
+import '../viewer/device_log_sync.dart';
enum AppStatus { bootstrapping, unauthenticated, authenticated }
@@ -994,6 +996,7 @@ class AppNotifier extends ChangeNotifier {
_groupSyncOverride = groupSync;
_autonomousEnv = this.config.autonomousEnv;
api = _newApiClient();
+ _initDeviceLog();
}
/// Straight to the backend, signed with this app's own session.
@@ -1465,6 +1468,13 @@ class AppNotifier extends ChangeNotifier {
}
Future<void> logout() async {
+ // Signing out takes this phone's key out of the account's devices, while the sign-in still works
+ // to say so. Best effort, and brief.
+ if (_deviceLog case final log?) {
+ try {
+ await log.leave().timeout(const Duration(seconds: 5));
+ } catch (_) {}
+ }
final revision = _invalidateAuthWork();
signingIn = false;
// A scanned code belongs to the session it was scanned into. Held past this,
@@ -1524,6 +1534,9 @@ class AppNotifier extends ChangeNotifier {
void _onLocalFailure(String machineId, int code, String reason) {
final machine = machineStates[machineId];
if (machine == null || code != 4404) return;
+ // A machine the account's device key log names may simply not have read it yet: read it again;
+ // a machine it pins is dialled again as soon as it lands.
+ if (_deviceLog case final log?) unawaited(log.refresh());
// The relay found no linked trust for this machine: it waits for this phone's password form (or
// a scanned code), which reconnects when it lands. Nothing is polled — the desktop retries every
// few seconds for a `harness link connect` run elsewhere, which a phone's links never come from.
@@ -1582,6 +1595,7 @@ class AppNotifier extends ChangeNotifier {
if (machine == null) return;
machine.connectionStatus = nextStatus;
if (nextStatus == ConnectionStatus.connected) {
+ _refreshDeviceLogAfterReconnect();
machine.needsLink = false;
// A relay socket reports `connected` only after the machine's welcome
// proved the link (`WsConn._markReady`), so a code held to pair this
@@ -1654,6 +1668,12 @@ 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.
@@ -1958,6 +1978,104 @@ class AppNotifier extends ChangeNotifier {
return null;
}
+ // -- the account's devices: the device key log (viewer/device_log_sync.dart) --------------------
+
+ ViewerDeviceLog? _deviceLog;
+ int? _deviceLogRegistered;
+
+ /// Devices that joined the account and this phone had never trusted, not yet dismissed.
+ final List<DevLogMember> newDevices = [];
+
+ /// Bumped whenever the account's devices may have changed; the Devices page re-reads on it.
+ int devicesRevision = 0;
+
+ ViewerDeviceLog? get deviceLog => _deviceLog;
+
+ void _initDeviceLog() {
+ final log = _deviceLog = ViewerDeviceLog(
+ keys: viewer.keys,
+ fetch: (since) => api.deviceKeys(since),
+ append: (entry) => api.appendDeviceKey(entry),
+ label: () => phoneClientDescriptor().name,
+ onAnnounce: (m) {
+ if (newDevices.any((d) => d.pub == m.pub)) return;
+ newDevices.add(m);
+ devicesRevision++;
+ final name = m.label.isEmpty ? 'A device' : m.label;
+ unawaited(agentNotices.system.showAccountNotice(
+ key: m.pub,
+ title: 'New device on your account',
+ body: '$name ${m.kind == 'machine' ? 'joined' : 'signed in to'} your account and can reach '
+ 'your machines. Not yours? Remove it in Settings ▸ Your devices.',
+ ));
+ if (!_disposed) notifyListeners();
+ },
+ onSignedOut: () async {
+ // Sign out first: it takes this phone's key out of the log, which needs the key it is about.
+ await logout();
+ await viewer.keys.forgetIdentity();
+ },
+ onChanged: () {
+ devicesRevision++;
+ unawaited(_redialNewlyTrusted());
+ if (!_disposed) notifyListeners();
+ },
+ );
+ final links = peerLinks;
+ if (links is DirectLink) links.deviceLog = log;
+ }
+
+ /// 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]) {
+ if (!state.needsLink) continue;
+ if (await viewer.keys.peer(state.machine.machineId) == null) continue;
+ state.needsLink = false;
+ state.agentLoadStatus = AgentLoadStatus.idle;
+ await _pool?.closeMachine(state.machine.machineId);
+ _connectMachine(state);
+ }
+ if (!_disposed) notifyListeners();
+ }
+
+ /// When each of the account's keys last opened a session (`{pub: ms}`), for the Devices page.
+ Future<Map<String, int>> devicesLastSeen() => api.deviceKeysSeen();
+
+ DateTime? _deviceLogReadAt;
+
+ /// A socket came back: a `device_keys_changed` sent while this phone was offline reached nobody, so
+ /// read the log again — at most every half minute, since a reconnect is every machine at once.
+ void _refreshDeviceLogAfterReconnect() {
+ final log = _deviceLog;
+ if (log == null) return;
+ final now = DateTime.now();
+ if (_deviceLogReadAt case final last? when now.difference(last) < const Duration(seconds: 30)) return;
+ _deviceLogReadAt = now;
+ unawaited(log.refresh());
+ }
+
+ /// The devices list was opened: every device announced so far has been seen.
+ void seenNewDevices() {
+ if (newDevices.isEmpty) return;
+ newDevices.clear();
+ notifyListeners();
+ }
+
+ void dismissNewDevice(String pub) {
+ newDevices.removeWhere((d) => d.pub == pub);
+ notifyListeners();
+ }
+
+ /// Take [pub] out of the account on every device. Null when done, else why not.
+ Future<String?> removeDevice(String pub) async {
+ final log = _deviceLog;
+ final error = log == null ? 'UNAVAILABLE' : await log.remove(pub);
+ if (error == null) newDevices.removeWhere((d) => d.pub == pub);
+ devicesRevision++;
+ notifyListeners();
+ return error;
+ }
+
/// A code scanned from a desktop app's "Add phone" QR, held across sign-in: once its machine shows
/// up locked, the phone pairs with the code ([connectWithCode]) instead of asking for a password.
/// See `phone/welcome/connect_code.dart`. Null the rest of the time.
@@ -5336,6 +5454,11 @@ class AppNotifier extends ChangeNotifier {
final swarmId = payload['swarmId'];
if (swarmId is String && swarmId.isNotEmpty) selectSwarm(swarmId);
break;
+ case 'device_keys_changed':
+ // The account's device key log grew: read and verify it from this phone's head.
+ // Arrives once per machine socket, like desk_changed; concurrent reads share one.
+ unawaited(_deviceLog?.refresh());
+ return;
case 'desk_changed':
// The account's tabs changed — in a window on some computer, or on
// another phone. The frame carries only the revision; the document
@@ -5678,6 +5801,8 @@ class AppNotifier extends ChangeNotifier {
// whatever they were when the phone went into a pocket, until something
// else happened to change them.
unawaited(_desk.refresh());
+ // The device key log too: a `device_keys_changed` sent while the phone was away reached nobody.
+ if (status == AppStatus.authenticated) unawaited(_deviceLog?.refresh());
// The zoo too, for the same reason: a `zoo_changed` sent while the phone
// was in a pocket reached nobody.
if (status == AppStatus.authenticated) unawaited(zoo.refresh());
diff --git a/mobile/lib/viewer/device_log.dart b/mobile/lib/viewer/device_log.dart
new file mode 100644
index 000000000..66e3ad7e4
--- /dev/null
+++ b/mobile/lib/viewer/device_log.dart
@@ -0,0 +1,330 @@
+import 'dart:typed_data';
+
+import '../e2ee/bytes.dart';
+import '../e2ee/keys.dart';
+import '../e2ee/primitives.dart';
+
+/// The device key log — an account's append-only, hash-chained list of the identity keys its devices
+/// hold (cli/src/lib/e2ee/deviceLog.ts, ported). Every device trusts the keys the log leaves active,
+/// so signing in is all it takes for an app to reach the account's machines, with no remote password.
+///
+/// Pure: no I/O. Signatures and hashes cover [devLogMessage] — the fields length-prefixed in a fixed
+/// order, numbers in decimal — never JSON. ⚠️ Held, with the CLI, the backend and
+/// desktop/lib/viewer/device_log.dart, to `test/viewer/device_log.vectors.json`: change the format
+/// in every copy together.
+
+const devLogVersion = 1;
+const devLogMaxActive = 256;
+const devLogLabelMax = 60;
+
+final _machineIdRe = RegExp(r'^[a-f0-9]{32}$');
+final _controlRe = RegExp(r'[\u0000-\u001f\u007f]');
+const _maxSafe = 9007199254740991;
+final String devLogZeroHash = b64e(Uint8List(32));
+
+class DevLogEntry {
+ const DevLogEntry({
+ required this.v,
+ required this.acct,
+ required this.seq,
+ required this.prev,
+ required this.op,
+ required this.pub,
+ required this.kind,
+ required this.machineId,
+ required this.label,
+ required this.at,
+ required this.signer,
+ this.sig = '',
+ });
+
+ final int v;
+ final String acct;
+ final int seq;
+ final String prev;
+
+ /// `add` | `remove`.
+ final String op;
+ final String pub;
+
+ /// `machine` | `viewer`.
+ final String kind;
+ final String machineId;
+ final String label;
+ final int at;
+ final String signer;
+ final String sig;
+
+ DevLogEntry withSig(String sig) => DevLogEntry(
+ v: v, acct: acct, seq: seq, prev: prev, op: op, pub: pub, kind: kind,
+ machineId: machineId, label: label, at: at, signer: signer, sig: sig,
+ );
+
+ Map<String, Object?> toJson() => {
+ 'v': v, 'acct': acct, 'seq': seq, 'prev': prev, 'op': op, 'pub': pub, 'kind': kind,
+ 'machineId': machineId, 'label': label, 'at': at, 'signer': signer, 'sig': sig,
+ };
+
+ /// deviceLog.ts `parseDevLogEntry`: every field present, of its type and within bounds.
+ static DevLogEntry? parse(Object? raw) {
+ if (raw is! Map) return null;
+ final v = raw['v'], acct = raw['acct'], seq = raw['seq'], prev = raw['prev'];
+ final op = raw['op'], pub = raw['pub'], kind = raw['kind'];
+ final machineId = raw['machineId'], label = raw['label'], at = raw['at'];
+ final signer = raw['signer'], sig = raw['sig'];
+ if (v != devLogVersion) return null;
+ if (acct is! String || acct.isEmpty || acct.length > 128) return null;
+ if (seq is! int || seq < 1 || seq > _maxSafe) return null;
+ if (!_bytesOf(prev, 32) || !_bytesOf(pub, 32) || !_bytesOf(signer, 32) || !_bytesOf(sig, 64)) {
+ return null;
+ }
+ if (op != 'add' && op != 'remove') return null;
+ if (kind != 'machine' && kind != 'viewer') return null;
+ if (machineId is! String) return null;
+ if (kind == 'machine' ? !_machineIdRe.hasMatch(machineId) : machineId != '') return null;
+ if (label is! String || label.length > devLogLabelMax || _controlRe.hasMatch(label)) return null;
+ if (at is! int || at <= 0 || at > _maxSafe) return null;
+ return DevLogEntry(
+ v: v as int, acct: acct, seq: seq, prev: prev as String, op: op as String, pub: pub as String,
+ kind: kind as String, machineId: machineId, label: label, at: at,
+ signer: signer as String, sig: sig as String,
+ );
+ }
+}
+
+bool _bytesOf(Object? s, int n) {
+ if (s is! String || s.length > 128) return false;
+ try {
+ final u = b64d(s);
+ return u.length == n && b64e(u) == s;
+ } catch (_) {
+ return false;
+ }
+}
+
+class DevLogMember {
+ const DevLogMember({
+ required this.pub,
+ required this.kind,
+ required this.machineId,
+ required this.label,
+ required this.addedAt,
+ required this.seq,
+ });
+
+ final String pub;
+ final String kind;
+ final String machineId;
+ final String label;
+ final int addedAt;
+ final int seq;
+
+ DevLogMember withLabel(String label) => DevLogMember(
+ pub: pub, kind: kind, machineId: machineId, label: label, addedAt: addedAt, seq: seq,
+ );
+
+ Map<String, Object?> toJson() => {
+ 'pub': pub, 'kind': kind, 'machineId': machineId, 'label': label, 'addedAt': addedAt, 'seq': seq,
+ };
+
+ static DevLogMember? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final pub = raw['pub'], kind = raw['kind'], machineId = raw['machineId'];
+ final label = raw['label'], addedAt = raw['addedAt'], seq = raw['seq'];
+ if (pub is! String || kind is! String || machineId is! String || label is! String) return null;
+ if (addedAt is! int || seq is! int) return null;
+ return DevLogMember(pub: pub, kind: kind, machineId: machineId, label: label, addedAt: addedAt, seq: seq);
+ }
+}
+
+class DevLogHead {
+ const DevLogHead(this.seq, this.hash);
+
+ final int seq;
+ final String hash;
+
+ Map<String, Object?> toJson() => {'seq': seq, 'hash': hash};
+
+ static DevLogHead? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final seq = raw['seq'], hash = raw['hash'];
+ if (seq is! int || seq < 0 || hash is! String) return null;
+ return DevLogHead(seq, hash);
+ }
+
+ @override
+ bool operator ==(Object other) => other is DevLogHead && other.seq == seq && other.hash == hash;
+
+ @override
+ int get hashCode => Object.hash(seq, hash);
+}
+
+class DevLogState {
+ DevLogState({
+ required this.acct,
+ required this.head,
+ required this.hashes,
+ required this.active,
+ required this.removed,
+ });
+
+ factory DevLogState.empty(String acct) => DevLogState(
+ acct: acct, head: DevLogHead(0, devLogZeroHash), hashes: [], active: {}, removed: [],
+ );
+
+ final String acct;
+ DevLogHead head;
+
+ /// hashes[i] is the hash of the entry with seq i + 1.
+ final List<String> hashes;
+
+ /// Active keys, by pub.
+ final Map<String, DevLogMember> active;
+
+ /// Keys a `remove` took out. A removed key never comes back.
+ final List<String> removed;
+
+ DevLogState copy() => DevLogState(
+ acct: acct, head: head, hashes: [...hashes], active: {...active}, removed: [...removed],
+ );
+
+ Map<String, Object?> toJson() => {
+ 'acct': acct,
+ 'head': head.toJson(),
+ 'hashes': hashes,
+ 'active': {for (final e in active.entries) e.key: e.value.toJson()},
+ 'removed': removed,
+ };
+
+ static DevLogState? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final acct = raw['acct'], head = DevLogHead.fromJson(raw['head']);
+ final hashes = raw['hashes'], active = raw['active'], removed = raw['removed'];
+ if (acct is! String || head == null || hashes is! List || active is! Map || removed is! List) return null;
+ final members = <String, DevLogMember>{};
+ for (final e in active.entries) {
+ final m = DevLogMember.fromJson(e.value);
+ if (e.key is String && m != null) members[e.key as String] = m;
+ }
+ return DevLogState(
+ acct: acct,
+ head: head,
+ hashes: hashes.whereType<String>().toList(),
+ active: members,
+ removed: removed.whereType<String>().toList(),
+ );
+ }
+}
+
+class DevLogError implements Exception {
+ const DevLogError(this.code, this.seq);
+
+ final String code;
+ final int seq;
+
+ @override
+ String toString() => 'device log entry $seq: $code';
+}
+
+class DevLogApplied {
+ DevLogApplied(this.state);
+
+ final DevLogState state;
+ final List<DevLogMember> added = [];
+ final List<DevLogMember> removed = [];
+ final List<DevLogMember> relabeled = [];
+}
+
+/// The bytes a signature covers.
+Uint8List devLogMessage(DevLogEntry e) => lvCat([
+ 'harness-devlog-v1', '${e.v}', e.acct, '${e.seq}', b64d(e.prev), e.op, b64d(e.pub),
+ e.kind, e.machineId, e.label, '${e.at}', b64d(e.signer),
+]);
+
+/// The entry's hash: what the next entry's `prev` names.
+String devLogHash(DevLogEntry e) => b64e(sha256(lvCat([devLogMessage(e), b64d(e.sig)])));
+
+Future<DevLogEntry> signDevLogEntry(DevLogEntry unsigned, E2eeIdentity identity) async =>
+ unsigned.withSig(b64e(await identity.sign(devLogMessage(unsigned))));
+
+/// The next entry to append on top of [state], unsigned.
+DevLogEntry nextDevLogEntry(
+ DevLogState state, {
+ required String op,
+ required String pub,
+ required String kind,
+ required String machineId,
+ required String label,
+ required String signer,
+ required int at,
+}) => DevLogEntry(
+ v: devLogVersion, acct: state.acct, seq: state.head.seq + 1, prev: state.head.hash, op: op,
+ pub: pub, kind: kind, machineId: machineId, label: label, at: at, signer: signer,
+);
+
+/// Apply [entries], in order, on top of [state]. All or nothing: the first entry that breaks a rule
+/// throws a [DevLogError] and [state] is left as it was.
+Future<DevLogApplied> applyDevLogEntries(DevLogState state, List<Object?> entries) async {
+ final s = state.copy();
+ final out = DevLogApplied(s);
+ for (final raw in entries) {
+ final expectedSeq = s.head.seq + 1;
+ final e = DevLogEntry.parse(raw);
+ if (e == null) throw DevLogError('BAD_ENTRY', expectedSeq);
+ if (e.acct != s.acct) throw DevLogError('WRONG_ACCOUNT', e.seq);
+ if (e.seq != expectedSeq) throw DevLogError('OUT_OF_ORDER', e.seq);
+ if (e.prev != s.head.hash) throw DevLogError('BROKEN_CHAIN', e.seq);
+ if (!await verifySignature(b64d(e.signer), devLogMessage(e), b64d(e.sig))) {
+ throw DevLogError('BAD_SIGNATURE', e.seq);
+ }
+ if (e.op == 'add') {
+ if (e.signer != e.pub) throw DevLogError('NOT_SELF_SIGNED', e.seq);
+ if (s.removed.contains(e.pub)) throw DevLogError('KEY_REMOVED', e.seq);
+ final current = s.active[e.pub];
+ if (current != null) {
+ if (current.kind != e.kind || current.machineId != e.machineId) {
+ throw DevLogError('KIND_CHANGED', e.seq);
+ }
+ if (current.label == e.label) throw DevLogError('NO_CHANGE', e.seq);
+ final relabeled = current.withLabel(e.label);
+ s.active[e.pub] = relabeled;
+ out.relabeled.add(relabeled);
+ } else {
+ if (e.kind == 'machine' &&
+ s.active.values.any((m) => m.kind == 'machine' && m.machineId == e.machineId)) {
+ throw DevLogError('MACHINE_TAKEN', e.seq);
+ }
+ if (s.active.length >= devLogMaxActive) throw DevLogError('TOO_MANY', e.seq);
+ final member = DevLogMember(
+ pub: e.pub, kind: e.kind, machineId: e.machineId, label: e.label, addedAt: e.at, seq: e.seq,
+ );
+ s.active[e.pub] = member;
+ out.added.add(member);
+ }
+ } else {
+ if (s.active[e.signer] == null) throw DevLogError('SIGNER_NOT_ACTIVE', e.seq);
+ final gone = s.active.remove(e.pub);
+ if (gone == null) throw DevLogError('NOT_ACTIVE', e.seq);
+ s.removed.add(e.pub);
+ out.removed.add(gone);
+ }
+ final hash = devLogHash(e);
+ s.hashes.add(hash);
+ s.head = DevLogHead(e.seq, hash);
+ }
+ return out;
+}
+
+/// The hash [state] holds for [seq]; null when it does not reach that far.
+String? devLogHashAt(DevLogState state, int seq) {
+ if (seq == 0) return devLogZeroHash;
+ return seq >= 1 && seq <= state.hashes.length ? state.hashes[seq - 1] : null;
+}
+
+/// How another device's head relates to ours: `same`, `behind` (they are ahead of us), `ahead`
+/// (we are ahead of them), or `fork` — two different entries at one position.
+String compareDevLogHead(DevLogState state, DevLogHead theirs) {
+ if (theirs.seq > state.head.seq) return 'behind';
+ if (devLogHashAt(state, theirs.seq) != theirs.hash) return 'fork';
+ return theirs.seq == state.head.seq ? 'same' : 'ahead';
+}
diff --git a/mobile/lib/viewer/device_log_sync.dart b/mobile/lib/viewer/device_log_sync.dart
new file mode 100644
index 000000000..8057241ca
--- /dev/null
+++ b/mobile/lib/viewer/device_log_sync.dart
@@ -0,0 +1,507 @@
+import 'dart:async';
+import 'dart:math';
+
+import '../e2ee/bytes.dart';
+import '../e2ee/keys.dart';
+import 'device_log.dart';
+import 'group_sync.dart';
+import 'viewer_key_store.dart';
+
+/// 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").
+
+/// 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});
+
+/// `POST /api/device-keys`: the new head, or a refusal (with the current head on `STALE_HEAD`).
+typedef DeviceLogAppendAnswer = ({DevLogHead? head, String? error});
+
+typedef DeviceLogFetch = Future<DeviceLogFetched?> Function(int since);
+typedef DeviceLogAppend = Future<DeviceLogAppendAnswer?> Function(DevLogEntry entry);
+
+class DeviceLogFreeze {
+ const DeviceLogFreeze(this.reason, this.at, this.lastGoodHead);
+
+ /// `fork` | `rollback` | `invalid` — see deviceLogStore.ts.
+ final String reason;
+ final int at;
+ final DevLogHead lastGoodHead;
+
+ Map<String, Object?> toJson() => {'reason': reason, 'at': at, 'lastGoodHead': lastGoodHead.toJson()};
+
+ static DeviceLogFreeze? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final reason = raw['reason'], at = raw['at'], head = DevLogHead.fromJson(raw['lastGoodHead']);
+ if (reason is! String || at is! int || head == null) return null;
+ return DeviceLogFreeze(reason, at, head);
+ }
+}
+
+class _File {
+ _File(this.state, this.recent, this.frozen, this.notifiedUpTo);
+
+ DevLogState? state;
+ List<DevLogEntry> recent;
+ DeviceLogFreeze? frozen;
+ int notifiedUpTo;
+
+ 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,
+ };
+
+ static _File parse(Object? raw) {
+ if (raw is! Map) return _File(null, [], null, 0);
+ final recent = raw['recent'];
+ 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,
+ );
+ }
+}
+
+const _recentKept = 64;
+const _appendAttempts = 5;
+const _pages = 20;
+
+/// One device on the account, for the Devices list.
+class DeviceLogRow {
+ const DeviceLogRow(this.member, {required this.fingerprint, required this.self});
+
+ final DevLogMember member;
+ final String fingerprint;
+ final bool self;
+}
+
+class DeviceLogListing {
+ const DeviceLogListing({required this.members, required this.frozen, required this.frozenPeers});
+
+ static const empty = DeviceLogListing(members: [], frozen: null, frozenPeers: []);
+
+ final List<DeviceLogRow> members;
+ final DeviceLogFreeze? frozen;
+
+ /// Machines whose own copy of the log is frozen, as their last `group_sync` said.
+ final List<String> frozenPeers;
+}
+
+class DeviceLogRebaseline {
+ const DeviceLogRebaseline(this.head, this.added, this.removed);
+
+ final DevLogHead head;
+ final List<DevLogMember> added;
+ final List<DevLogMember> removed;
+}
+
+class ViewerDeviceLog {
+ ViewerDeviceLog({
+ required this.keys,
+ required this.fetch,
+ required this.append,
+ required this.label,
+ this.onAnnounce,
+ this.onSignedOut,
+ this.onChanged,
+ int Function()? now,
+ Future<void> Function(Duration)? sleep,
+ }) : _now = now ?? (() => DateTime.now().millisecondsSinceEpoch),
+ _sleep = sleep ?? Future.delayed;
+
+ final ViewerKeyStore keys;
+ final DeviceLogFetch fetch;
+ final DeviceLogAppend append;
+
+ /// 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".
+ final void Function(DevLogMember member)? onAnnounce;
+
+ /// This app's own key was removed from the account: it is signed out.
+ final Future<void> Function()? onSignedOut;
+
+ /// The list, or whether it is frozen, changed.
+ final void Function()? onChanged;
+
+ final int Function() _now;
+ final Future<void> Function(Duration) _sleep;
+ final Map<String, bool> _frozenPeers = {};
+ Future<void>? _refreshing;
+ final _random = Random();
+ final Set<String> _removing = {};
+
+ /// 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;
+
+ /// This app's key is gone from the log: sign out, once.
+ Future<void> _signOut() async {
+ if (_signedOut) return;
+ _signedOut = true;
+ await onSignedOut?.call();
+ }
+
+ Future<_File> _read() async => _File.parse(await keys.deviceLog());
+ Future<void> _write(_File f) => keys.writeDeviceLog(f.toJson());
+ Future<String> _selfPub() async => b64e((await keys.identity()).pub);
+
+ /// Read the log and put this app's key into it. Never throws.
+ ///
+ /// [freshSignIn]: the person has just signed in, by hand. A key the log removed is then spent, not
+ /// 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.
+ Future<void> register({bool freshSignIn = false}) async {
+ _signingInAgain = freshSignIn;
+ _signedOut = false;
+ try {
+ await refresh();
+ var identity = await keys.identity();
+ var pub = b64e(identity.pub);
+ final name = _clip(label());
+ for (var attempt = 0; attempt < _appendAttempts; attempt++) {
+ final file = await _read();
+ final state = file.state;
+ if (state == null || file.frozen != null) return;
+ if (state.removed.contains(pub)) {
+ if (!freshSignIn) {
+ await _signOut();
+ return;
+ }
+ await keys.forgetIdentity();
+ await refresh();
+ identity = await keys.identity();
+ pub = b64e(identity.pub);
+ continue;
+ }
+ final mine = state.active[pub];
+ if (mine != null && (mine.label == name || mine.kind != 'viewer')) return;
+ final entry = await signDevLogEntry(
+ nextDevLogEntry(state, op: 'add', pub: pub, kind: 'viewer', machineId: '', label: name, signer: pub, at: _now()),
+ identity,
+ );
+ final answer = await append(entry);
+ if (answer == null) return;
+ if (answer.error == null) {
+ await refresh();
+ return;
+ }
+ if (answer.error != 'STALE_HEAD') return;
+ await refresh();
+ await _sleep(Duration(milliseconds: 200 + _random.nextInt(800) * (attempt + 1)));
+ }
+ } catch (_) {
+ // The next sign-in, resume or push tries again.
+ } finally {
+ _signingInAgain = false;
+ }
+ }
+
+ /// Read and verify whatever the log gained. Concurrent calls share one read. Never throws.
+ Future<void> refresh() => _refreshing ??= _doRefresh().catchError((Object _) {}).whenComplete(() => _refreshing = null);
+
+ Future<void> _doRefresh() async {
+ 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 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;
+ }
+ }
+
+ Future<bool> _accept(List<Object?> entries, bool bootstrap) async {
+ final file = await _read();
+ 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');
+ 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,
+ ));
+ 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();
+ 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.
+ Future<Set<String>> _knownPubs() async {
+ final roster = GroupRoster.parse(await keys.groupRoster());
+ return {
+ for (final p in await keys.peers()) b64e(p.pub),
+ for (final m in roster.members) m.pub,
+ };
+ }
+
+ /// Pin every machine the log adds, and put it in the trust group this app swaps with machines, so
+ /// a machine that predates the log hears of it too. A removal the group made first stands.
+ Future<void> _trust(List<DevLogMember> members) async {
+ final selfPub = await _selfPub();
+ 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 now = _now();
+ final adopt = [
+ for (final m in members)
+ if (m.pub != selfPub && !tombstoned.contains(m.pub)) m,
+ ];
+ final incoming = [
+ for (final m in adopt)
+ ?GroupMember.tryParse({
+ 'pub': m.pub,
+ 'kind': m.kind,
+ 'label': m.label,
+ 'at': min(m.addedAt, now),
+ if (m.machineId.isNotEmpty) 'machineId': m.machineId,
+ }),
+ ];
+ if (incoming.isNotEmpty) {
+ final merged = mergeGroupRoster(stored, GroupRoster(incoming, const []), selfPub);
+ await keys.writeGroupRoster(merged.roster.toJson());
+ }
+ for (final m in adopt) {
+ if (m.kind != 'machine') continue;
+ final current = await keys.peer(m.machineId);
+ if (current != null && b64e(current.pub) == m.pub) continue;
+ await keys.pin(m.machineId, b64d(m.pub), label: m.label);
+ }
+ // A removal the group made before the log existed must not be undone by the log. Not awaited:
+ // this runs inside a read of the log, and a removal reads the log again when it lands — waiting
+ // for it here would wait for this very read to finish.
+ final state = (await _read()).state;
+ if (state != null && state.active[selfPub] != null) {
+ for (final pub in tombstoned) {
+ if (state.active[pub] != null && !_removing.contains(pub)) unawaited(remove(pub));
+ }
+ }
+ }
+
+ Future<void> _drop(DevLogMember m) async {
+ final selfPub = await _selfPub();
+ final stored = GroupRoster.parse(await keys.groupRoster());
+ final merged = mergeGroupRoster(stored, GroupRoster(const [], [GroupTombstone(m.pub, _now())]), selfPub);
+ await keys.writeGroupRoster(merged.roster.toJson());
+ if (m.kind == 'machine') {
+ final current = await keys.peer(m.machineId);
+ if (current != null && b64e(current.pub) == m.pub) await keys.unlink(m.machineId);
+ }
+ }
+
+ /// 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();
+ final state = file.state;
+ if (state == null) return;
+ var changed = false;
+ for (final raw in entries) {
+ final e = DevLogEntry.parse(raw);
+ if (e == null || e.op != 'remove' || state.active[e.signer] == null) continue;
+ final target = state.active[e.pub];
+ if (target == null) continue;
+ if (!await verifySignature(b64d(e.signer), devLogMessage(e), b64d(e.sig))) continue;
+ state.active.remove(e.pub);
+ state.removed.add(e.pub);
+ await _drop(target);
+ changed = true;
+ }
+ if (changed) {
+ await _write(file);
+ onChanged?.call();
+ }
+ }
+
+ Future<void> _freeze(String reason) async {
+ final file = await _read();
+ if (file.frozen != null || file.state == null) return;
+ file.frozen = DeviceLogFreeze(reason, _now(), file.state!.head);
+ await _write(file);
+ onChanged?.call();
+ }
+
+ /// Remove a device from the account, signed by this app. It stops being trusted here at once.
+ /// Null when done, else why not.
+ Future<String?> remove(String pub) async {
+ _removing.add(pub);
+ try {
+ return await _removeOnce(pub);
+ } finally {
+ _removing.remove(pub);
+ }
+ }
+
+ Future<String?> _removeOnce(String pub) async {
+ final identity = await keys.identity();
+ final selfPub = b64e(identity.pub);
+ for (var attempt = 0; attempt < _appendAttempts; attempt++) {
+ final file = await _read();
+ final state = file.state;
+ if (state == null) return 'UNAVAILABLE';
+ final target = state.active[pub];
+ if (target == null) return 'NOT_IN_LOG';
+ if (state.active[selfPub] == null) return 'NOT_ACTIVE';
+ await _drop(target);
+ final entry = await signDevLogEntry(
+ nextDevLogEntry(state, op: 'remove', pub: pub, kind: target.kind, machineId: target.machineId,
+ label: target.label, signer: selfPub, at: _now()),
+ identity,
+ );
+ final answer = await append(entry);
+ if (answer == null) return 'UNAVAILABLE';
+ if (answer.error == null) {
+ await refresh();
+ return null;
+ }
+ if (answer.error != 'STALE_HEAD') return answer.error;
+ await refresh();
+ await _sleep(Duration(milliseconds: 200 + _random.nextInt(800) * (attempt + 1)));
+ }
+ return 'UNAVAILABLE';
+ }
+
+ /// Signing out of this app: its key leaves the account's devices (best effort).
+ Future<void> leave() async {
+ try {
+ await remove(await _selfPub());
+ } catch (_) {}
+ }
+
+ /// What trusting the backend's log again would change; with [confirm], do it.
+ Future<DeviceLogRebaseline?> rebaseline({required bool confirm}) 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;
+ acct = got.acct;
+ head = got.head;
+ entries.addAll(got.entries);
+ if (got.entries.isEmpty || entries.length >= got.head.seq) break;
+ }
+ final DevLogState next;
+ try {
+ next = (await applyDevLogEntries(DevLogState.empty(acct), entries)).state;
+ } on DevLogError {
+ 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);
+ }
+ onChanged?.call();
+ }
+ return DeviceLogRebaseline(next.head, added, removed);
+ }
+
+ /// 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};
+ }
+
+ /// 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 state = file.state;
+ if (state == null || raw is! Map) 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 == '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);
+ unawaited(refresh());
+ }
+ }
+
+ /// The account's devices as this app's log has them.
+ Future<DeviceLogListing> list() async {
+ final file = await _read();
+ 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};
+ return DeviceLogListing(
+ members: [
+ for (final m in members) DeviceLogRow(m, fingerprint: fingerprint(b64d(m.pub)), self: m.pub == selfPub),
+ ],
+ frozen: file.frozen,
+ frozenPeers: [
+ for (final e in _frozenPeers.entries)
+ if (e.value) labels[e.key] ?? fingerprint(b64d(e.key)),
+ ],
+ );
+ }
+}
+
+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_auth.dart b/mobile/lib/viewer/direct_auth.dart
index 30f2e89af..3b79a523b 100644
--- a/mobile/lib/viewer/direct_auth.dart
+++ b/mobile/lib/viewer/direct_auth.dart
@@ -30,10 +30,22 @@ class DirectAuth implements AccessTokenSource {
/// session this device no longer has, and must not touch the one it has now (see [_refresh]).
int _generation = 0;
+ /// Whether a sign-in by hand happened since this was last asked — the device key log reads it to
+ /// tell signing in again after a removal from an app opening under a removed key
+ /// (`device_log_sync.dart` `register`). Asking clears it.
+ bool consumeFreshSignIn() {
+ final fresh = _freshSignIn;
+ _freshSignIn = false;
+ return fresh;
+ }
+
+ bool _freshSignIn = false;
+
Future<void> signIn(
IssuedTokens tokens, {
SessionIssuer issuer = SessionIssuer.sso,
}) {
+ _freshSignIn = true;
_generation++;
return session.saveLogin(
token: tokens.token,
diff --git a/mobile/lib/viewer/direct_link.dart b/mobile/lib/viewer/direct_link.dart
index 7129e1c94..615446664 100644
--- a/mobile/lib/viewer/direct_link.dart
+++ b/mobile/lib/viewer/direct_link.dart
@@ -6,6 +6,7 @@ import '../e2ee/keys.dart';
import 'direct_auth.dart';
import 'direct_auth_api.dart';
import 'code_link.dart';
+import 'device_log_sync.dart';
import 'group_sync.dart';
import 'password_link.dart';
import 'viewer_key_store.dart';
@@ -25,6 +26,10 @@ class DirectLink implements PeerLinkClient {
final AppConfig config;
final RelaySocketFactory socket;
+ /// The account's device key log, once the app has one: its head rides every roster swap, so a
+ /// machine shown a different log than this phone is found out (`device_log_sync.dart`).
+ ViewerDeviceLog? deviceLog;
+
@override
Future<CliLinkConnectResult> connect(
String machineId,
@@ -165,6 +170,7 @@ class DirectLink implements PeerLinkClient {
} catch (_) {
return GroupSyncOutcome.none;
}
+ final log = deviceLog;
return syncTrustGroup(
machineId: machineId,
keys: keys,
@@ -173,6 +179,8 @@ class DirectLink implements PeerLinkClient {
autonomousEnv: config.autonomousEnv,
label: label,
socket: socket,
+ devlog: await log?.gossip(),
+ onDevlog: log?.heard,
);
}
diff --git a/mobile/lib/viewer/group_sync.dart b/mobile/lib/viewer/group_sync.dart
index 3c61bca06..bbab7a8f0 100644
--- a/mobile/lib/viewer/group_sync.dart
+++ b/mobile/lib/viewer/group_sync.dart
@@ -215,6 +215,8 @@ Future<GroupSyncOutcome> syncTrustGroup({
required String label,
RelaySocketFactory socket = defaultRelaySocket,
Duration timeout = const Duration(seconds: 20),
+ Map<String, Object?>? devlog,
+ Future<void> Function(String machinePub, Object? devlog)? onDevlog,
}) async {
WebSocketChannel? channel;
try {
@@ -243,9 +245,12 @@ Future<GroupSyncOutcome> syncTrustGroup({
'requestId': b64e(secureRandomBytes(12)),
'self': self.toJson(),
...local.toJson(),
+ // The device key log's head (device_log_sync.dart): the machine answers with its own.
+ 'devlog': ?devlog,
});
}().timeout(timeout, onTimeout: () => null);
if (reply == null || reply['error'] != null) return GroupSyncOutcome.none;
+ if (reply['devlog'] != null) await onDevlog?.call(b64e(pin.pub), reply['devlog']);
final incoming = GroupRoster.parse(reply);
final theirs = GroupMember.tryParse(reply['self']);
diff --git a/mobile/lib/viewer/viewer_key_store.dart b/mobile/lib/viewer/viewer_key_store.dart
index 1f73732f3..20c54993d 100644
--- a/mobile/lib/viewer/viewer_key_store.dart
+++ b/mobile/lib/viewer/viewer_key_store.dart
@@ -78,6 +78,7 @@ class ViewerKeyStore {
static const _seedKey = 'viewer_e2ee_identity_seed';
static const _peersKey = 'viewer_e2ee_machine_peers';
static const _groupKey = 'viewer_e2ee_group';
+ static const _devLogKey = 'viewer_e2ee_devlog';
/// Minted on first use and kept: every linked machine has pinned it.
Future<E2eeIdentity> identity() => _identity ??= _heldUnlessItFails(
@@ -181,6 +182,29 @@ class ViewerKeyStore {
Future<void> writeGroupRoster(Map<String, Object> roster) =>
_storage.write(_groupKey, jsonEncode(roster));
+ /// This device's verified copy of the account's device key log (`device_log_sync.dart`), as stored
+ /// JSON; null when there is none yet or it cannot be read.
+ Future<Object?> deviceLog() async {
+ final raw = await _storage.read(_devLogKey);
+ if (raw == null) return null;
+ try {
+ return jsonDecode(raw);
+ } on FormatException {
+ return null;
+ }
+ }
+
+ Future<void> writeDeviceLog(Map<String, Object?> log) =>
+ _storage.write(_devLogKey, jsonEncode(log));
+
+ /// 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.
+ 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
/// replaced.
///
diff --git a/mobile/test/notify/agent_announcer_test.dart b/mobile/test/notify/agent_announcer_test.dart
index 0e0a642ba..ac22b8934 100644
--- a/mobile/test/notify/agent_announcer_test.dart
+++ b/mobile/test/notify/agent_announcer_test.dart
@@ -21,6 +21,9 @@ class _RecordingNotices implements SystemNotices {
@override
Future<void> cancel(AgentRef agent) async => cancelled.add(agent);
+
+ @override
+ Future<void> showAccountNotice({required String key, required String title, required String body}) async {}
}
void main() {
diff --git a/mobile/test/notify/local_system_notices_test.dart b/mobile/test/notify/local_system_notices_test.dart
index fed38538e..fd047c6d5 100644
--- a/mobile/test/notify/local_system_notices_test.dart
+++ b/mobile/test/notify/local_system_notices_test.dart
@@ -31,6 +31,18 @@ void main() {
notices = LocalSystemNotices(plugin);
});
+ test('a new device on the account: its own channel, replaced by its own key, opening no agent', () async {
+ await notices.showAccountNotice(key: 'pub-1', title: 'New device on your account', body: 'iPad signed in.');
+ await notices.showAccountNotice(key: 'pub-1', title: 'New device on your account', body: 'iPad signed in.');
+ expect(plugin.shown.map((n) => n.id).toSet(), {accountNoticeIdFor('pub-1')});
+ expect(accountNoticeIdFor('pub-1'), isNot(noticeIdFor(ref)));
+ final shown = plugin.shown.first;
+ expect(shown.title, 'New device on your account');
+ expect(shown.details!.android!.channelId, 'account-device');
+ expect(shown.details!.iOS!.threadIdentifier, 'account-device');
+ expect(decodeAgentPayload(shown.payload), isNull);
+ });
+
test('nothing starts until a notice is first needed', () {
expect(plugin.initialized, 0);
// The app's own, over the real plugin: building it reaches no platform.
diff --git a/mobile/test/viewer/device_log.vectors.json b/mobile/test/viewer/device_log.vectors.json
new file mode 100644
index 000000000..223b62521
--- /dev/null
+++ b/mobile/test/viewer/device_log.vectors.json
@@ -0,0 +1,375 @@
+{
+ "comment": "Generated by cli/scripts/gen-devlog-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4, box2b=5).",
+ "acct": "acct-vectors-1",
+ "seeds": {
+ "box1": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
+ "box2": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=",
+ "browser": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "stranger": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ=",
+ "box2b": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU="
+ },
+ "pubs": {
+ "box1": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "box2": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "browser": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "stranger": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "box2b": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E="
+ },
+ "valid": {
+ "entries": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 1000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "PQ79548gYy1fR00xYYrAqGYQer//uS3fGo1Xwwih7v6Jpw8lLHsM/plOYoenu8qjIWhPTSPlVSghlAt9C6MMCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 2000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "bHi9oSluvJ/RKgTw7RZrPaplcR45FGkVMmnOjm4dQnTzchKsMN6D6WKTNphHLjthUYhcznmjIJDLjplJ5TKsAg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 3000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "Browser · macOS — “Dee”",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "NK0FM6TeU5KyGr78swAvqDRYvHQafuMj/pBBxMANdNdALGrcA3pA+h4WMarQT81Ker2W0ALWvAcufmSkOxjiCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "qNFvpVnzstkVYeTrds5NiQ6EyfyImRIhjndzUjzO/eA=",
+ "at": 4000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1 (renamed)",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "ccsh5GRy/OZkP+l50LN90T+8O1Ca0dcOmdm2pCJlF1ccTNC+ZPwoZ3NujkS2uJORP/xwu9xZ7gSqBhQ3XaWzCg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 5,
+ "prev": "NiCtLf6zNhboU5bHOg8pggpUZxeuey5a0KGQ4lHyehE=",
+ "at": 5000,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "1LAIjj3C77/H5v7LxR1QFYfxTrjJbRFTdk/0nvAmTIOYAoH42xLvqwh3e8bHsvH32GmfNNvARRSGTuXKTkZMBg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 6,
+ "prev": "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "at": 6000,
+ "op": "add",
+ "pub": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "sig": "cwe4qUy9BDLShHXA8IhIMxs/ZbdF/a2Js7IqpQyNBV/FjcCS/eoGDEufpS0+sPPAhDlky2K1vpgwVS0PIakyCw=="
+ }
+ ],
+ "hashes": [
+ "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "qNFvpVnzstkVYeTrds5NiQ6EyfyImRIhjndzUjzO/eA=",
+ "NiCtLf6zNhboU5bHOg8pggpUZxeuey5a0KGQ4lHyehE=",
+ "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "f5WzxT87hry0q9rj895yyaiCax/xP2PRZCCfpGPKDTw="
+ ],
+ "head": {
+ "seq": 6,
+ "hash": "f5WzxT87hry0q9rj895yyaiCax/xP2PRZCCfpGPKDTw="
+ },
+ "active": [
+ "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=",
+ "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w="
+ ],
+ "removed": [
+ "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q="
+ ]
+ },
+ "invalid": [
+ {
+ "name": "tampered label",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "evil",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "udynDrC1h7IK8lrCs+AqPLpTCNeQxD4DlkQP6BOQZD+oNquOndvYqEPmU60wE9JTin8YYVFboZ6jyzxl5YSQAw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "add signed by another key",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "RL5wtkxLhLIkWpUBZ+njRYIh0KqeuYc1pIoEQQ9oAfs2xFa5UwpLJhI4sia2HXI+dovYK+igVD0HnE4QoF3BDA=="
+ },
+ "code": "NOT_SELF_SIGNED"
+ },
+ {
+ "name": "machine id of another active machine",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "imposter",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "KJulD+38Nt9i6HNhMZwVemE3wXIrLOLsMbd1A2BxIC4hke7aKwN6itY04iSRbLqOGlDzOPwi0GUGj0ZrW0DcCQ=="
+ },
+ "code": "MACHINE_TAKEN"
+ },
+ {
+ "name": "removed key comes back",
+ "after": 5,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 6,
+ "prev": "22tYXg7Zejthxmx8p/ArnwtJZYAuiD6VL91MBmtKtAc=",
+ "at": 9000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2 again",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "AyV+EkrCunkAI12uokVnsclD26e2n5ZDIvNqxxoABvxdvgDvSXnXDdJ8EVFFro3FK9ROh0ATNh3FQVoUWa/9CQ=="
+ },
+ "code": "KEY_REMOVED"
+ },
+ {
+ "name": "remove signed by a key not in the log",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "remove",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "xkp6fed+m63wylf9c1Zaz3YXtwPhOgbMzpKqCkXuNo06UfKfPmJx4/BD2OY+Wt+E03hUUrB438ME1gLjzp4VBg=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "remove of a key not in the log",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "remove",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "Vh2WinwrdWHv46djCCkZ+p0QtWlALCHXBIPHgYkSi9Zpys93JPYhaJIJhEcdQYwQuYvEF2IVtxK2um1IaQgJDg=="
+ },
+ "code": "NOT_ACTIVE"
+ },
+ {
+ "name": "wrong prev",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "nPbFpdYE1xqmdxxL8fj77CeBVrosx4N847Zy9gqngg5bBdcyqzMRsHSm/q0OTuW6VEwIzk66/OCMcwuT1HERBA=="
+ },
+ "code": "BROKEN_CHAIN"
+ },
+ {
+ "name": "skipped seq",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "wJqA4rLVUCIewTr/eeeMxSKX2yv9wQOFhqGVws0+1QITAdgkZwGNIWbpBptIlFrcNyh3oRTFMdGWykfeqkTcAA=="
+ },
+ "code": "OUT_OF_ORDER"
+ },
+ {
+ "name": "other account",
+ "after": 2,
+ "entry": {
+ "v": 1,
+ "acct": "acct-other",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "x",
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "sig": "eXH3aVMs0jDDzFg3xehB+Z7G6h2jyvjZcHGm128CIvVwcWDSytwHRAY+g4iXpYkBeJxhksoCOdgpNQds69xMDQ=="
+ },
+ "code": "WRONG_ACCOUNT"
+ },
+ {
+ "name": "machine changes kind",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "c2mJ6r5OoEW7bY0EERqWBt8z37H5ExY59f5KiP6mtRSv5adSQjT5HxzlGXgcILOjLUPIFijE16cGPM++CdJXCg=="
+ },
+ "code": "KIND_CHANGED"
+ },
+ {
+ "name": "re-add with nothing changed",
+ "after": 1,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 9000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "fjF5dBSdSDddFJdLDmYWaleR4RniUf62lI0Fbdb4vTkXp8cXo4rwqAcGncZt5yCHOK2F7pYg56FUbbospfIuAg=="
+ },
+ "code": "NO_CHANGE"
+ },
+ {
+ "name": "viewer with a machine id",
+ "after": 0,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 9000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "b",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "2t+mAiwKKqhImNoq+7HVp7bXdf1UeL7Vd4QOmEiS1fsGG1Ux6+HVKjosKKzX/wzQo9ju84Yd3x12teETgIsjAQ=="
+ },
+ "code": "BAD_ENTRY"
+ },
+ {
+ "name": "control character in label",
+ "after": 0,
+ "entry": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 9000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "a\nb",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "lzDA+QfWL9V5issDES2f9vRw/CX2Tv6dk8nF6ZmwcJ87kyegBoWh1TkUL6RXVS+8vacy9vLJd+keCMwpsCOqAA=="
+ },
+ "code": "BAD_ENTRY"
+ }
+ ]
+}
diff --git a/mobile/test/viewer/device_log_sync_test.dart b/mobile/test/viewer/device_log_sync_test.dart
new file mode 100644
index 000000000..113cea347
--- /dev/null
+++ b/mobile/test/viewer/device_log_sync_test.dart
@@ -0,0 +1,245 @@
+import 'package:flutter_test/flutter_test.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/viewer/device_log.dart';
+import 'package:harness_mobile/viewer/device_log_sync.dart';
+import 'package:harness_mobile/viewer/group_sync.dart';
+import 'package:harness_mobile/viewer/viewer_key_store.dart';
+
+/// The viewer's half of the device key log (`lib/viewer/device_log_sync.dart`), against a backend
+/// that keeps the log honestly — or is told to lie.
+
+class _Memory 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);
+}
+
+const _acct = 'acct-1';
+final _mid2 = 'b' * 32, _mid3 = 'c' * 32;
+
+class _Backend {
+ final entries = <DevLogEntry>[];
+ DevLogState state = DevLogState.empty(_acct);
+ List<DevLogEntry>? lie;
+
+ Future<void> add(E2eeIdentity who, String kind, String machineId, String label) async {
+ final pub = b64e(who.pub);
+ final e = await signDevLogEntry(
+ nextDevLogEntry(state, op: 'add', pub: pub, kind: kind, machineId: machineId, label: label, signer: pub, at: 1000),
+ who,
+ );
+ await _push(e);
+ }
+
+ Future<void> removeBy(String target, E2eeIdentity by) async {
+ final t = state.active[target]!;
+ final e = 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,
+ );
+ await _push(e);
+ }
+
+ Future<void> _push(DevLogEntry e) async {
+ state = (await applyDevLogEntries(state, [e.toJson()])).state;
+ entries.add(e);
+ }
+
+ Future<DeviceLogFetched?> fetch(int since) async {
+ 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()]);
+ }
+
+ 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');
+ }
+ try {
+ await _push(entry);
+ } on DevLogError catch (e) {
+ return (head: null, error: e.code);
+ }
+ return (head: state.head, error: null);
+ }
+}
+
+void main() {
+ late _Backend backend;
+ late ViewerKeyStore keys;
+ late List<DevLogMember> announced;
+ late int signedOut;
+ late E2eeIdentity box2, box3;
+
+ ViewerDeviceLog makeLog() => ViewerDeviceLog(
+ keys: keys,
+ fetch: backend.fetch,
+ append: backend.append,
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onSignedOut: () async => signedOut++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ setUp(() async {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ announced = [];
+ signedOut = 0;
+ box2 = await E2eeIdentity.fromSeed(List.filled(32, 2));
+ box3 = await E2eeIdentity.fromSeed(List.filled(32, 3));
+ });
+
+ test('registers this app and pins every machine already in the log, announcing none', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final me = b64e((await keys.identity()).pub);
+ expect(backend.state.active[me]?.kind, 'viewer');
+ expect(backend.state.active[me]?.label, 'my-phone');
+ expect(b64e((await keys.peer(_mid2))!.pub), b64e(box2.pub));
+ expect(announced, isEmpty);
+ });
+
+ test('a machine added later is pinned and announced once', () async {
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ await log.refresh();
+ expect(await keys.peer(_mid3), isNotNull);
+ expect(announced.map((m) => m.label), ['box3']);
+ // …and the trust group this app swaps with machines names it, for machines that predate the log.
+ final roster = GroupRoster.parse(await keys.groupRoster());
+ expect(roster.members.map((m) => m.pub), contains(b64e(box3.pub)));
+ });
+
+ test('a machine this app had already linked is not news', () async {
+ await keys.pin(_mid3, box3.pub, label: 'box3');
+ final log = makeLog();
+ await log.register();
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await log.refresh();
+ expect(announced, isEmpty);
+ });
+
+ test('a removed machine is unpinned', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ expect(await log.remove(b64e(box2.pub)), isNull);
+ expect(await keys.peer(_mid2), isNull);
+ expect(backend.state.active[b64e(box2.pub)], isNull);
+ });
+
+ test('its own key removed signs it out', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.removeBy(b64e((await keys.identity()).pub), box2);
+ await log.refresh();
+ expect(signedOut, 1);
+ });
+
+ test('signing in again after a removal comes back under a new key, without signing out', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final old = b64e((await keys.identity()).pub);
+ await backend.removeBy(old, box2);
+ // Signed out by the removal before reading the log (a revoked session answers 401 first)…
+ await log.register(freshSignIn: true);
+ final now = b64e((await keys.identity()).pub);
+ expect(now, isNot(old));
+ expect(backend.state.active[now]?.kind, 'viewer');
+ expect(signedOut, 0);
+ });
+
+ test('opening under a removed key still signs out', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await backend.removeBy(b64e((await keys.identity()).pub), box2);
+ await log.register();
+ expect(signedOut, 1);
+ });
+
+ test('freezes on a rewritten log and pins nothing more from it', () 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, 'evil');
+ await forged.add(await E2eeIdentity.fromSeed(List.filled(32, 9)), 'viewer', '', 'x');
+ backend.lie = forged.entries;
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'fork');
+ expect(await keys.peer(_mid3), isNull);
+ });
+
+ test('freezes on a rollback, and trusting again shows the change first', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ backend.lie = backend.entries.sublist(0, 1);
+ await log.refresh();
+ expect((await log.list()).frozen?.reason, 'rollback');
+ backend.lie = null;
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ final preview = await log.rebaseline(confirm: false);
+ expect(preview!.added.map((m) => m.label), ['box3']);
+ expect((await log.list()).frozen, isNotNull);
+ await log.rebaseline(confirm: true);
+ expect((await log.list()).frozen, isNull);
+ expect(await keys.peer(_mid3), isNotNull);
+ });
+
+ test('a machine answering with a different entry at a verified position freezes it', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ final other = _Backend();
+ await other.add(box3, 'machine', _mid3, 'box3');
+ await other.add(box2, 'machine', _mid2, 'box2');
+ await log.heard(b64e(box2.pub), {'head': other.state.head.toJson(), 'frozen': false});
+ expect((await log.list()).frozen?.reason, 'fork');
+ });
+
+ test('says which machines report a frozen log', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ final log = makeLog();
+ await log.register();
+ await log.heard(b64e(box2.pub), {'head': backend.state.head.toJson(), 'frozen': true});
+ expect((await log.list()).frozenPeers, ['box2']);
+ });
+
+ test('a removal the trust group made before the log is written into it, without hanging the read', () async {
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await keys.writeGroupRoster(GroupRoster(const [], [GroupTombstone(b64e(box2.pub), 900)]).toJson());
+ final log = makeLog();
+ await log.register().timeout(const Duration(seconds: 5));
+ for (var i = 0; i < 50 && backend.state.active[b64e(box2.pub)] != null; i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ }
+ expect(backend.state.removed, contains(b64e(box2.pub)));
+ expect(await keys.peer(_mid2), isNull);
+ // …and the log is still readable afterwards.
+ await log.refresh().timeout(const Duration(seconds: 5));
+ });
+
+ test('forgetting the identity mints a new one', () async {
+ final before = b64e((await keys.identity()).pub);
+ await keys.forgetIdentity();
+ expect(b64e((await keys.identity()).pub), isNot(before));
+ });
+}
diff --git a/mobile/test/viewer/device_log_test.dart b/mobile/test/viewer/device_log_test.dart
new file mode 100644
index 000000000..96ef0bd91
--- /dev/null
+++ b/mobile/test/viewer/device_log_test.dart
@@ -0,0 +1,72 @@
+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_log.dart';
+
+/// The Dart port of the device key log, held to the fixture every implementation shares
+/// (cli/scripts/gen-devlog-vectors.ts).
+void main() {
+ final vectors = jsonDecode(File('test/viewer/device_log.vectors.json').readAsStringSync()) as Map<String, dynamic>;
+ final acct = vectors['acct'] as String;
+ final valid = vectors['valid'] as Map<String, dynamic>;
+ final entries = (valid['entries'] as List).cast<Object?>();
+
+ test('derives the fixture keys from their seeds', () async {
+ final seeds = (vectors['seeds'] as Map).cast<String, String>();
+ final pubs = (vectors['pubs'] as Map).cast<String, String>();
+ for (final name in seeds.keys) {
+ final id = await E2eeIdentity.fromSeed(b64d(seeds[name]!));
+ expect(b64e(id.pub), pubs[name]);
+ }
+ });
+
+ test('applies every valid entry to the fixture hashes, head and active set', () async {
+ final applied = await applyDevLogEntries(DevLogState.empty(acct), entries);
+ expect(applied.state.hashes, valid['hashes']);
+ expect(applied.state.head.toJson(), valid['head']);
+ expect(applied.state.active.keys.toList()..sort(), valid['active']);
+ expect(applied.state.removed, valid['removed']);
+ });
+
+ test('re-signs every valid entry to the same signature', () async {
+ final seeds = (vectors['seeds'] as Map).cast<String, String>();
+ final pubs = (vectors['pubs'] as Map).cast<String, String>();
+ final byPub = {for (final n in seeds.keys) pubs[n]!: seeds[n]!};
+ for (final raw in entries) {
+ final e = DevLogEntry.parse(raw)!;
+ final id = await E2eeIdentity.fromSeed(b64d(byPub[e.signer]!));
+ expect((await signDevLogEntry(e.withSig(''), id)).sig, e.sig);
+ }
+ });
+
+ for (final c in (vectors['invalid'] as List).cast<Map<String, dynamic>>()) {
+ test('refuses: ${c['name']} (${c['code']})', () async {
+ final base = (await applyDevLogEntries(DevLogState.empty(acct), entries.sublist(0, c['after'] as int))).state;
+ Object? error;
+ try {
+ await applyDevLogEntries(base, [c['entry']]);
+ } catch (err) {
+ error = err;
+ }
+ expect(error, isA<DevLogError>().having((e) => e.code, 'code', c['code']));
+ });
+ }
+
+ test('round-trips its state through JSON', () async {
+ final s = (await applyDevLogEntries(DevLogState.empty(acct), entries)).state;
+ final back = DevLogState.fromJson(jsonDecode(jsonEncode(s.toJson())))!;
+ expect(back.toJson(), s.toJson());
+ });
+
+ test('tells same, ahead, behind and fork apart', () async {
+ final s = (await applyDevLogEntries(DevLogState.empty(acct), entries.sublist(0, 4))).state;
+ final hashes = (valid['hashes'] as List).cast<String>();
+ expect(compareDevLogHead(s, s.head), 'same');
+ expect(compareDevLogHead(s, DevLogHead(2, hashes[1])), 'ahead');
+ expect(compareDevLogHead(s, DevLogHead(6, hashes[5])), 'behind');
+ expect(compareDevLogHead(s, DevLogHead(3, hashes[1])), 'fork');
+ });
+}