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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: realtime trust-group sync through a signed group board (backend + web)
0xken15afeb858b864d
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 775dd8433..985f54c0f 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -671,6 +671,20 @@ model ExperimentalSettings {/// (routes/zoo.ts): idempotent ops applied in order under `revision`, the draw made here and only/// here (lib/zoo.ts). `state` is validated shape by shape on every read; what does not parse is/// dropped rather than served.+/// The account's trust-group board (lib/groupBoard.ts): member vouches, each signed by an existing+/// member's E2EE identity key. The server keeps and relays them; it cannot mint one, and every device+/// decides for itself which to believe (only vouches by keys it already trusts).+model GroupBoard {+ id String @id @default(auto()) @map("_id") @db.ObjectId+ userId String @unique+ revision Int @default(0)+ entries Json @default("[]")+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@map("group_boards")+}+model Zoo {id String @id @default(auto()) @map("_id") @db.ObjectIduserId String @uniquediff --git a/backend/src/lib/adapterAccountPushes.test.ts b/backend/src/lib/adapterAccountPushes.test.tsindex a02a01488..80d6995d7 100644--- a/backend/src/lib/adapterAccountPushes.test.ts+++ b/backend/src/lib/adapterAccountPushes.test.ts@@ -1,10 +1,10 @@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(), group: vi.fn(), machines: vi.fn(),+ deskUnsub: vi.fn(), zooUnsub: vi.fn(), groupUnsub: vi.fn(), machinesUnsub: vi.fn(),}))-vi.mock('./bus.js', () => ({ subscribeDeskChanged: m.desk, subscribeZooChanged: m.zoo, subscribeDeviceMachineListChanged: m.machines }))+vi.mock('./bus.js', () => ({ subscribeDeskChanged: m.desk, subscribeZooChanged: m.zoo, subscribeGroupChanged: m.group, subscribeDeviceMachineListChanged: m.machines }))import { relayAccountPushes } from './adapterAccountPushes.js'@@ -16,6 +16,7 @@ describe('account pushes on a daemon socket', () => {vi.resetAllMocks()m.desk.mockResolvedValue(m.deskUnsub)m.zoo.mockResolvedValue(m.zooUnsub)+ m.group.mockResolvedValue(m.groupUnsub)m.machines.mockResolvedValue(m.machinesUnsub)})@@ -23,9 +24,17 @@ describe('account pushes on a daemon socket', () => {await relayAccountPushes('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.group).toHaveBeenCalledWith('user-1', expect.any(Function))expect(m.machines).toHaveBeenCalledWith('user-1', expect.any(Function))})+ it('hands the daemon a group change, so it re-reads the board', async () => {+ const send = vi.fn()+ await relayAccountPushes('user-1', send, on)+ m.group.mock.calls[0][1]({ revision: 4 })+ expect(send).toHaveBeenCalledWith({ t: 'down', connId: '', frame: { type: 'group_changed', payload: { revision: 4 } } })+ })+it('hands the daemon a desk change as a connection-less down frame carrying the revision', async () => {const send = vi.fn()await relayAccountPushes('user-1', send, on)@@ -53,6 +62,7 @@ describe('account pushes on a daemon socket', () => {stop()expect(m.deskUnsub).toHaveBeenCalledOnce()expect(m.zooUnsub).toHaveBeenCalledOnce()+ expect(m.groupUnsub).toHaveBeenCalledOnce()expect(m.machinesUnsub).toHaveBeenCalledOnce()})@@ -61,6 +71,7 @@ describe('account pushes on a daemon socket', () => {await expect(relayAccountPushes('user-1', vi.fn(), on)).rejects.toThrow('redis unreachable')expect(m.deskUnsub).toHaveBeenCalledOnce()expect(m.zooUnsub).toHaveBeenCalledOnce()+ expect(m.groupUnsub).toHaveBeenCalledOnce()})it('never listens on the zoo channel while the server has daemons off', async () => {diff --git a/backend/src/lib/adapterAccountPushes.ts b/backend/src/lib/adapterAccountPushes.tsindex 8fc9a28cc..b653f3914 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, subscribeDeviceMachineListChanged, subscribeGroupChanged, subscribeZooChanged } from './bus.js'/*** The pushes a daemon socket carries for its ACCOUNT rather than for its machine: something the@@ -11,6 +11,8 @@ import { subscribeDeskChanged, subscribeDeviceMachineListChanged, subscribeZooCh* - `desk_changed` — the account's tabs.* - `zoo_changed` — the account's daemons and eggs (routes/zoo.ts). Its own frame, so a desk* change never re-fetches the zoo and the other way round.+ * - `group_changed` — the account's trust-group board (routes/groupBoard.ts): the daemon re-reads+ * it and syncs, trusting only vouches signed by a member it already trusts.* - `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`.@@ -32,6 +34,9 @@ export async function relayAccountPushes(userId: string, send: (frame: unknown)send({ t: 'down', connId: '', frame: { type: 'zoo_changed', payload: { revision: msg.revision } } })}))}+ unsubs.push(await subscribeGroupChanged(userId, (msg) => {+ send({ t: 'down', connId: '', frame: { type: 'group_changed', payload: { revision: msg.revision } } })+ }))unsubs.push(await subscribeDeviceMachineListChanged(userId, (msg) => {send({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: msg.reason } } })}))diff --git a/backend/src/lib/backendOnlyFrames.ts b/backend/src/lib/backendOnlyFrames.tsindex 91f6792f5..7c09bbfb4 100644--- a/backend/src/lib/backendOnlyFrames.ts+++ b/backend/src/lib/backendOnlyFrames.ts@@ -6,10 +6,10 @@* them by name. The adapter refuses them too unless they arrive on the backend's own `connId: ''`.** Senders, all backend-side: `lib/adapterWs.ts` (on connect), `services/MachineService.ts`- * (rename, revoke) and `lib/adapterAccountPushes.ts` (desk_changed, zoo_changed, machines_changed —+ * (rename, revoke) and `lib/adapterAccountPushes.ts` (desk_changed, zoo_changed, machines_changed, group_changed —* forged, each one makes every window on that computer re-read from this backend).*/-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', 'group_changed'])/** 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.tsindex b3ff88e48..991553e58 100644--- a/backend/src/lib/bus.ts+++ b/backend/src/lib/bus.ts@@ -684,6 +684,21 @@ export function subscribeDeskChanged(userId: string, cb: (msg: DeskChangedMsg) =return addSub(deskChannel(userId), cb as Cb)}+// Per-USER trust-group invalidation: a member was vouched for or removed on the account's group board+// (routes/groupBoard.ts). Every device of the account re-reads the board and syncs: a hint only — what a+// device believes comes from the signatures on the board, never from this frame.+export interface GroupChangedMsg { revision: number }++const groupChannel = (userId: string): string => `group:${userId}`++export function publishGroupChanged(userId: string, msg: GroupChangedMsg): Promise<number> {+ return safePublish(groupChannel(userId), JSON.stringify(msg))+}++export function subscribeGroupChanged(userId: string, cb: (msg: GroupChangedMsg) => void): Promise<() => void> {+ return addSub(groupChannel(userId), cb as Cb)+}+// Per-USER zoo invalidation: the account's daemons or eggs changed (routes/zoo.ts). The same path as// the desk and a separate channel, so a desk change never re-fetches the zoo and the other way round.export interface ZooChangedMsg { revision: number }diff --git a/backend/src/lib/groupBoard.ts b/backend/src/lib/groupBoard.tsnew file mode 100644index 000000000..6dfb89278--- /dev/null+++ b/backend/src/lib/groupBoard.ts@@ -0,0 +1,138 @@+/**+ * The account's trust-group board: signed statements ("vouches") about who is in the group, kept here+ * so a device can learn a member it has no machine in common with — a browser approved by a phone that+ * had no machine yet, then a machine approved by that same phone.+ *+ * vouch = { subject, signer, sig }+ * subject = { pub, kind: 'machine' | 'viewer', machineId?, label, at } a member+ * | { pub, at, removed: true } a removal+ * sig = ed25519(signer, lvCat('group-vouch-v1', pub, kind | 'removed', machineId | '', label | '', at))+ *+ * The same statement, byte for byte, as the CLI's `lib/e2ee/groupBoard.ts` and the apps'+ * `viewer/group_sync.dart` sign and check.+ *+ * ⚠️ This server does NOT decide trust. It checks only that a signature is well formed and matches+ * its `signer` — so garbage never takes a slot — and every device then believes only vouches signed by+ * a key it already trusts. Holding no member's private key, the server cannot add anyone; it can only+ * withhold or replay what members wrote, which the group's own merge rules (newest wins, a removal at+ * or after an entry beats it) already handle.+ */+import { ed25519 } from '@noble/curves/ed25519.js'++export const MAX_BOARD_ENTRIES = 256+export const MAX_POST_ENTRIES = 32+const MAX_LABEL = 60+const MAX_CLOCK_SKEW_MS = 24 * 60 * 60 * 1000++export interface VouchSubject {+ pub: string+ kind?: 'machine' | 'viewer'+ machineId?: string+ label?: string+ at: number+ removed?: true+}++export interface Vouch {+ subject: VouchSubject+ signer: string+ sig: string+}++/** Standard base64 of exactly [length] bytes, or null. */+function bytesOf(value: unknown, length: number): Uint8Array | null {+ if (typeof value !== 'string' || value.length > 128) return null+ const bytes = Buffer.from(value, 'base64')+ if (bytes.length !== length || bytes.toString('base64') !== value) return null+ return new Uint8Array(bytes)+}++/** core.ts `lvCat`: each part as a 4-byte big-endian length, then its UTF-8 bytes. */+function lvCat(parts: string[]): Uint8Array {+ const encoded = parts.map((p) => Buffer.from(p, 'utf8'))+ const out = Buffer.alloc(encoded.reduce((n, b) => n + 4 + b.length, 0))+ let at = 0+ for (const b of encoded) {+ out.writeUInt32BE(b.length, at)+ b.copy(out, at + 4)+ at += 4 + b.length+ }+ return new Uint8Array(out)+}++/** The bytes a vouch's signature covers. */+export function vouchMessage(subject: VouchSubject): Uint8Array {+ return lvCat([+ 'group-vouch-v1',+ subject.pub,+ subject.removed ? 'removed' : (subject.kind ?? ''),+ subject.machineId ?? '',+ subject.label ?? '',+ String(subject.at),+ ])+}++/** A well-formed vouch whose signature matches its signer, or null. */+export function parseVouch(raw: unknown, now = Date.now()): Vouch | null {+ if (!raw || typeof raw !== 'object') return null+ const { subject, signer, sig } = raw as Record<string, unknown>+ if (!subject || typeof subject !== 'object') return null+ const s = subject as Record<string, unknown>+ if (!bytesOf(s.pub, 32)) return null+ const at = s.at+ if (typeof at !== 'number' || !Number.isSafeInteger(at) || at <= 0 || at > now + MAX_CLOCK_SKEW_MS) return null+ let clean: VouchSubject+ if (s.removed === true) {+ clean = { pub: s.pub as string, at, removed: true }+ } else {+ if (s.kind !== 'machine' && s.kind !== 'viewer') return null+ const label = typeof s.label === 'string' ? s.label : ''+ if (label.length > MAX_LABEL) return null+ const machineId = s.machineId+ if (s.kind === 'machine' && (typeof machineId !== 'string' || !/^[a-f0-9]{32}$/.test(machineId))) return null+ clean = {+ pub: s.pub as string,+ kind: s.kind,+ ...(s.kind === 'machine' ? { machineId: machineId as string } : {}),+ label,+ at,+ }+ }+ const signerKey = bytesOf(signer, 32)+ const signature = bytesOf(sig, 64)+ if (!signerKey || !signature) return null+ try {+ if (!ed25519.verify(signature, vouchMessage(clean), signerKey)) return null+ } catch {+ return null+ }+ return { subject: clean, signer: signer as string, sig: sig as string }+}++/** One statement per signer per member: a signer's newer word about a key (re-added, removed, renamed)+ * replaces its older one — the roster's own rule, newest wins — so repeated approvals do not crowd+ * other members off the capped board. */+const keyOf = (v: Vouch): string => `${v.signer}|${v.subject.pub}`++/** The board after [incoming]: a statement newer than the same signer's last word about that key+ * replaces it, anything else is dropped; newest first, capped. `added` counts what took a place. */+export function mergeBoard(current: Vouch[], incoming: Vouch[]): { entries: Vouch[]; changed: boolean; added: number } {+ const seen = new Map(current.map((v) => [keyOf(v), v]))+ let added = 0+ for (const v of incoming) {+ const key = keyOf(v)+ const had = seen.get(key)+ // Same stamp: the removal wins, as in the roster.+ if (had && (had.subject.at > v.subject.at || (had.subject.at === v.subject.at && (had.subject.removed || !v.subject.removed)))) continue+ seen.set(key, v)+ added+++ }+ const entries = [...seen.values()].sort((a, b) => b.subject.at - a.subject.at).slice(0, MAX_BOARD_ENTRIES)+ return { entries, changed: added > 0, added }+}++/** Stored entries, re-checked on the way out — a row written by an older server is not trusted blind. */+export function parseBoard(raw: unknown): Vouch[] {+ if (!Array.isArray(raw)) return []+ return raw.map((v) => parseVouch(v, Number.MAX_SAFE_INTEGER)).filter((v): v is Vouch => v !== null)+}diff --git a/backend/src/lib/webAccountPushes.test.ts b/backend/src/lib/webAccountPushes.test.tsindex d06d147ca..9c926bc5c 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(), group: vi.fn(), deskUnsub: vi.fn(), zooUnsub: vi.fn(), groupUnsub: vi.fn() }))+vi.mock('./bus.js', () => ({ subscribeDeskChanged: m.desk, subscribeZooChanged: m.zoo, subscribeGroupChanged: m.group }))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.group.mockResolvedValue(m.groupUnsub)})- it('listens on the desk and zoo channels of the account that owns the socket', async () => {+ it('listens on the desk, zoo and group 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.group).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.group.mock.calls[0][1]({ revision: 5 })expect(send.mock.calls).toEqual([[{ type: 'desk_changed', payload: { revision: 7 } }],[{ type: 'zoo_changed', payload: { revision: 3 } }],+ [{ type: 'group_changed', payload: { revision: 5 } }],])})- it('stops listening on both when the socket goes away', async () => {+ it('stops listening on every channel 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.groupUnsub).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('listens on the desk and the group, not the zoo, 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()@@ -54,5 +59,6 @@ describe('account documents on a web or phone socket', () => {expect(send.mock.calls).toEqual([[{ type: 'desk_changed', payload: { revision: 7 } }]])stop()expect(m.deskUnsub).toHaveBeenCalledOnce()+ expect(m.groupUnsub).toHaveBeenCalledOnce()})})diff --git a/backend/src/lib/webAccountPushes.ts b/backend/src/lib/webAccountPushes.tsindex 250e088ec..bdf440299 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, subscribeGroupChanged, subscribeZooChanged } from './bus.js'/*** The account documents a WEB socket hears about — the desk and the zoo — forwarded to the clients@@ -9,6 +9,8 @@ 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.+ * - `group_changed` — the account's trust-group board (routes/groupBoard.ts): a browser or phone+ * re-reads it and trusts only what a member it already trusts signed.** ⚠️ 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.@@ -23,6 +25,7 @@ export async function relayWebDocumentPushes(userId: string, send: (frame: unknotry {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 subscribeGroupChanged(userId, (msg) => { send({ type: 'group_changed', payload: { revision: msg.revision } }) }))} catch (err) {stop()throw errdiff --git a/backend/src/lib/webWs.test.ts b/backend/src/lib/webWs.test.tsindex 10fd9b203..d565961d6 100644--- a/backend/src/lib/webWs.test.ts+++ b/backend/src/lib/webWs.test.ts@@ -14,7 +14,7 @@ describe('frames a web client may never forge', () => {// 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'])+ expect([...BACKEND_ONLY_DOWN_TYPES].sort()).toEqual(['desk_changed', 'group_changed', '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/routes/groupBoard.test.ts b/backend/src/routes/groupBoard.test.tsnew file mode 100644index 000000000..536a60f2f--- /dev/null+++ b/backend/src/routes/groupBoard.test.ts@@ -0,0 +1,124 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'+import { ed25519 } from '@noble/curves/ed25519.js'+import { vouchMessage, parseVouch, mergeBoard, type VouchSubject } from '../lib/groupBoard.js'++// The board in memory; the route and lib/groupBoard.ts run for real.+const fakes = vi.hoisted(() => {+ let row: { userId: string; revision: number; entries: unknown } | null = null+ return {+ reset: () => { row = null },+ row: () => row,+ published: [] as Array<{ userId: string; revision: number }>,+ prisma: {+ groupBoard: {+ findUnique: vi.fn(async () => row),+ updateMany: vi.fn(async ({ where, data }: { where: { revision: number }; data: { revision: number; entries: unknown } }) => {+ if (!row || row.revision !== where.revision) return { count: 0 }+ row = { ...row, ...data }+ return { count: 1 }+ }),+ create: vi.fn(async ({ data }: { data: { userId: string; revision: number; entries: unknown } }) => { row = data; return data }),+ },+ },+ }+})++vi.mock('../lib/prisma.js', () => ({ prisma: fakes.prisma }))+vi.mock('../lib/bus.js', () => ({+ consumeRateLimit: vi.fn(async () => true),+ publishGroupChanged: vi.fn(async (userId: string, msg: { revision: number }) => { fakes.published.push({ userId, ...msg }); return 1 }),+}))++import { groupBoardRoutes } from './groupBoard.js'+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'+import { errorHandler } from '../middlewares/errorHandler.js'++const b64 = (b: Uint8Array): string => Buffer.from(b).toString('base64')+function member() {+ const priv = ed25519.utils.randomSecretKey()+ return { priv, pub: b64(ed25519.getPublicKey(priv)) }+}+function vouch(signer: { priv: Uint8Array; pub: string }, subject: VouchSubject) {+ return { subject, signer: signer.pub, sig: b64(ed25519.sign(vouchMessage(subject), signer.priv)) }+}++const phone = { authorization: 'Bearer phone' }+let app: FastifyInstance+beforeEach(async () => {+ fakes.reset(); fakes.published.length = 0; vi.clearAllMocks()+ app = Fastify()+ app.setErrorHandler(errorHandler)+ registerAuthMiddleware(app, async (token) => {+ if (token !== 'phone') throw Object.assign(new Error('no'), { code: 'INVALID_TOKEN' })+ return { sub: 'u1', email: '[email protected]', role: 'user', autonomousEnv: 'prod' }+ })+ await app.register(groupBoardRoutes)+ await app.ready()+})++describe('a vouch', () => {+ it('is kept only when its signature matches its signer and the statement', () => {+ const p = member(), m = member()+ const good = vouch(p, { pub: m.pub, kind: 'machine', machineId: 'a'.repeat(32), label: 'box', at: 10 })+ expect(parseVouch(good)).not.toBeNull()+ expect(parseVouch({ ...good, subject: { ...good.subject, label: 'other' } })).toBeNull() // the statement changed+ expect(parseVouch({ ...good, signer: member().pub })).toBeNull() // another signer+ expect(parseVouch(vouch(p, { pub: m.pub, kind: 'machine', label: 'x', at: 10 }))).toBeNull() // a machine needs its id+ expect(parseVouch(vouch(p, { pub: m.pub, at: 11, removed: true }))).not.toBeNull()+ })++ it('merges once, newest first', () => {+ const p = member(), a = member(), b = member()+ const va = vouch(p, { pub: a.pub, kind: 'viewer', label: 'a', at: 5 })+ const vb = vouch(p, { pub: b.pub, kind: 'viewer', label: 'b', at: 9 })+ const once = mergeBoard([va], [va, vb])+ expect(once.added).toBe(1)+ expect(once.entries.map((v) => v.subject.pub)).toEqual([b.pub, a.pub])+ expect(mergeBoard(once.entries, [va]).changed).toBe(false)+ })++ it('keeps one word per signer per key: the newest, a removal winning a tie', () => {+ const p = member(), a = member()+ const v5 = vouch(p, { pub: a.pub, kind: 'viewer', label: 'a', at: 5 })+ const v9 = vouch(p, { pub: a.pub, kind: 'viewer', label: 'a2', at: 9 })+ const gone9 = vouch(p, { pub: a.pub, at: 9, removed: true })+ const board = mergeBoard([v5], [v9]).entries+ expect(board).toEqual([v9])+ expect(mergeBoard(board, [v5]).changed).toBe(false)+ expect(mergeBoard(board, [gone9]).entries).toEqual([gone9])+ expect(mergeBoard([gone9], [v9]).changed).toBe(false)+ // Another signer's word about the same key is its own.+ expect(mergeBoard(board, [vouch(member(), { pub: a.pub, kind: 'viewer', label: 'a', at: 1 })]).entries).toHaveLength(2)+ })+})++describe('the board routes', () => {+ it('stores signed vouches, bumps the revision, tells the account, and reads back', async () => {+ const p = member(), web = member()+ const v = vouch(p, { pub: web.pub, kind: 'viewer', label: 'Chrome on macOS', at: Date.now() })+ const posted = await app.inject({ method: 'POST', url: '/api/group/board', headers: phone, payload: { entries: [v] } })+ expect(posted.statusCode).toBe(200)+ expect(posted.json().data).toEqual({ revision: 1, added: 1 })+ expect(fakes.published).toEqual([{ userId: 'u1', revision: 1 }])++ const again = await app.inject({ method: 'POST', url: '/api/group/board', headers: phone, payload: { entries: [v] } })+ expect(again.json().data).toEqual({ revision: 1, added: 0 })+ expect(fakes.published).toHaveLength(1) // nothing new, nobody told++ const read = await app.inject({ method: 'GET', url: '/api/group/board', headers: phone })+ expect(read.json().data).toEqual({ revision: 1, entries: [v] })+ const unchanged = await app.inject({ method: 'GET', url: '/api/group/board?since=1', headers: phone })+ expect(unchanged.json().data).toEqual({ revision: 1 })+ })++ it('refuses a forged or malformed vouch, and an anonymous caller', async () => {+ const p = member(), web = member()+ const v = vouch(p, { pub: web.pub, kind: 'viewer', label: 'x', at: Date.now() })+ const forged = { ...v, subject: { ...v.subject, label: 'y' } }+ expect((await app.inject({ method: 'POST', url: '/api/group/board', headers: phone, payload: { entries: [forged] } })).statusCode).toBe(400)+ expect((await app.inject({ method: 'POST', url: '/api/group/board', headers: phone, payload: { entries: [] } })).statusCode).toBe(400)+ expect((await app.inject({ method: 'GET', url: '/api/group/board' })).statusCode).toBe(401)+ expect(fakes.row()).toBeNull()+ })+})diff --git a/backend/src/routes/groupBoard.ts b/backend/src/routes/groupBoard.tsnew file mode 100644index 000000000..f6940e229--- /dev/null+++ b/backend/src/routes/groupBoard.ts@@ -0,0 +1,75 @@+/**+ * The account's trust-group board (lib/groupBoard.ts for what a vouch is and why the server cannot+ * forge one).+ *+ * GET /api/group/board?since=<revision> → { revision, entries } (entries omitted when unchanged)+ * POST /api/group/board { entries } → { revision, added }+ *+ * Any signed-in client of the account may read and write: a phone or browser (viewer session), a+ * machine (daemon session), or an Autonomous JWT. After a write that added something, every web and+ * adapter socket of the account hears `group_changed` (lib/webAccountPushes.ts,+ * lib/adapterAccountPushes.ts) and re-reads.+ *+ * The desk's write discipline (routes/desk.ts): compare-and-set on the revision, retried from the+ * fresh board — merging is idempotent, so replaying the same entries is the merge.+ */+import type { FastifyInstance } from 'fastify'+import { Prisma } from '@prisma/client'+import { prisma } from '../lib/prisma.js'+import { consumeRateLimit, publishGroupChanged } from '../lib/bus.js'+import { MAX_POST_ENTRIES, mergeBoard, parseBoard, parseVouch, type Vouch } from '../lib/groupBoard.js'+import { sendError, sendSuccess } from '../utils/response.js'++const WRITE_ATTEMPTS = 5+const RATE_WINDOW_SEC = 10 * 60+const POSTS_PER_WINDOW = 60++async function readBoard(userId: string): Promise<{ revision: number; entries: Vouch[] }> {+ const row = await prisma.groupBoard.findUnique({ where: { userId } })+ return row ? { revision: row.revision, entries: parseBoard(row.entries) } : { revision: 0, entries: [] }+}++export async function groupBoardRoutes(app: FastifyInstance): Promise<void> {+ app.get<{ Querystring: { since?: string } }>('/api/group/board', async (req, reply) => {+ // Every device of the account asks this after every `group_changed`, and mostly nothing moved:+ // the revision is compared before any stored signature is checked again.+ const row = await prisma.groupBoard.findUnique({ where: { userId: req.user!.sub }, select: { revision: true } })+ const revision = row?.revision ?? 0+ const since = Number(req.query?.since)+ if (Number.isInteger(since) && since === revision) return sendSuccess(reply, { revision })+ return sendSuccess(reply, await readBoard(req.user!.sub))+ })++ app.post<{ Body: { entries?: unknown } }>('/api/group/board', async (req, reply) => {+ const userId = req.user!.sub+ const raw = req.body?.entries+ if (!Array.isArray(raw) || raw.length === 0 || raw.length > MAX_POST_ENTRIES) {+ return sendError(reply, `entries must be 1–${MAX_POST_ENTRIES} vouches`, 'BAD_REQUEST', 400)+ }+ const incoming = raw.map((v) => parseVouch(v))+ if (incoming.some((v) => v === null)) return sendError(reply, 'a vouch is malformed or its signature does not match', 'BAD_VOUCH', 400)+ if (!(await consumeRateLimit(`groupboard:${userId}`, POSTS_PER_WINDOW, RATE_WINDOW_SEC))) {+ return sendError(reply, 'too many group updates — wait a few minutes', 'RATE_LIMITED', 429)+ }+ for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt++) {+ const current = await readBoard(userId)+ const merged = mergeBoard(current.entries, incoming as Vouch[])+ if (!merged.changed) return sendSuccess(reply, { revision: current.revision, added: 0 })+ const next = current.revision + 1+ const entries = merged.entries as unknown as Prisma.InputJsonValue+ const bumped = await prisma.groupBoard.updateMany({ where: { userId, revision: current.revision }, data: { revision: next, entries } })+ if (bumped.count !== 1) {+ if (current.revision !== 0) continue+ try {+ await prisma.groupBoard.create({ data: { userId, revision: next, entries } })+ } catch (error) {+ if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') continue+ throw error+ }+ }+ void publishGroupChanged(userId, { revision: next })+ return sendSuccess(reply, { revision: next, added: merged.added })+ }+ return sendError(reply, 'The group is changing too quickly; try again.', 'GROUP_BUSY', 409)+ })+}diff --git a/backend/src/server.ts b/backend/src/server.tsindex e399542f0..e5866c2bf 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -14,6 +14,7 @@ import { harnessLinkRoutes } from './routes/harnessLinks.js'import { deskRoutes } from './routes/desk.js'import { tabChannelRoutes } from './routes/tabChannels.js'import { zooRoutes } from './routes/zoo.js'+import { groupBoardRoutes } from './routes/groupBoard.js'import { experimentalSettingsRoutes } from './routes/experimentalSettings.js'import { describeDaemonsSwitch } from './lib/daemonsSwitch.js'import { handleObserverUpgrade } from './lib/observerWs.js'@@ -171,6 +172,7 @@ async function start(): Promise<void> {await app.register(harnessShareRoutes)await app.register(harnessLinkRoutes)await app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)+ await app.register(groupBoardRoutes) // the account's trust-group board: signed member vouches (lib/groupBoard.ts)if (env.HARNESS_CHANNELS) await app.register(tabChannelRoutes)await app.register(experimentalSettingsRoutes, { daemons: DAEMONS })// Availability is separate from opt-in: every account starts off, and its collection is retained.diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dartindex cd18f4dc5..49e3ffe0b 100644--- a/desktop/lib/api/api_client.dart+++ b/desktop/lib/api/api_client.dart@@ -286,6 +286,42 @@ class ApiClient {as String;}+ /// The account's trust-group board since [since] (`GET /api/group/board`): signed member vouches,+ /// which the caller checks itself (`group_sync.dart` `acceptVouches`) — this server cannot mint one.+ /// `entries` null when unchanged since [since]; null overall when it cannot be read.+ Future<({int revision, List<Object?>? entries})?> readGroupBoard({+ int? since,+ }) async {+ try {+ final res = await _dio.get(+ '/api/group/board',+ queryParameters: {'since': ?since},+ );+ final data = unwrapApiResponse(res);+ if (data is! Map || data['revision'] is! int) return null;+ final entries = data['entries'];+ return (+ revision: data['revision'] as int,+ entries: entries is List ? entries : null,+ );+ } catch (_) {+ return null;+ }+ }++ /// Adds vouches this device signed to the account's board; true when the server took them.+ Future<bool> postGroupBoard(List<Map<String, Object>> entries) async {+ if (entries.isEmpty) return true;+ try {+ unwrapApiResponse(+ await _dio.post('/api/group/board', data: {'entries': entries}),+ );+ return true;+ } catch (_) {+ return false;+ }+ }+/// Sign a BROWSER in to this account (its sign-in QR, `k=v`), handing it this device's trust/// group sealed under the QR's pairing code (`viewer/group_sync.dart` `sealHandedRoster`).Future<void> approveBrowserSignIn(diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex bdcb274b8..99a2c9200 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -28,11 +28,15 @@ import '../viewer/group_sync.dart'GroupMember,GroupRoster,GroupSyncOutcome,+ adoptBoard,adoptHandedRoster,admitGroupMember,handoffRoster,+ memberSubject,openHandedRoster,- sealHandedRoster;+ sealHandedRoster,+ signVouch;+import '../viewer/account_events.dart' show AccountEvents;import '../auth/auth_session.dart';import '../auth/peer_link_client.dart';import '../auth/sign_in_client.dart';@@ -766,6 +770,15 @@ class AppNotifier extends ChangeNotifier {// independently, with capped backoff and the same in-flight request as a manual retry.Timer? _machineRecoveryTimer;Timer? _sharingDiscoveryTimer;++ /// Viewer builds: the account's own socket (`viewer/account_events.dart`) — group and machine-list+ /// pushes, whether or not any machine is linked yet. Opened once machines are known; closed on+ /// sign-out.+ AccountEvents? _accountEvents;++ /// The group board's revision last read ([refreshGroup]); null before the first read.+ int? _groupBoardRevision;+ Future<void>? _groupRefresh;bool _sharingDiscoveryBusy = false;bool _sharingDiscoveryAgain = false;int _machineRecoveryAttempts = 0;@@ -3965,6 +3978,9 @@ class AppNotifier extends ChangeNotifier {_sharingDiscoveryTimer?.cancel();_sharingDiscoveryTimer = null;_sharingDiscoveryBusy = false;+ unawaited(_accountEvents?.close());+ _accountEvents = null;+ _groupBoardRevision = null;_sharingDiscoveryAgain = false;_daemonGateFailed = false;_bootStatusMessage = null;@@ -4613,6 +4629,7 @@ class AppNotifier extends ChangeNotifier {return;}if (code != 4404) return;+ final justLost = !machine.needsLink;// 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@@ -4632,6 +4649,9 @@ class AppNotifier extends ChangeNotifier {);notifyListeners();_startLinkRetry(machineId);+ // Its key may be on the group board already — a member vouched for it — or with a group machine.+ // Once, not on every 5 s redial that answers 4404 again.+ if (justLost) unawaited(refreshGroup());}/// The daemon on this computer closed our select with 4403: it serves a different machine id than@@ -5180,7 +5200,10 @@ class AppNotifier extends ChangeNotifier {unawaited(_deskFetch());}unawaited(_rereadMachinesInBackground(pushed: false));+ // A missed `group_changed` is caught here too.+ unawaited(refreshGroup());});+ _startAccountEvents();notifyListeners();}@@ -5544,6 +5567,14 @@ class AppNotifier extends ChangeNotifier {}try {await adoptHandedRoster(keys!, raw);+ // This browser's word for the devices its phone handed over — the phone first — so a device that+ // trusts one of them but shares no machine with this browser can still reach it (the board).+ unawaited(+ _vouch([+ for (final m in GroupRoster.parse(raw).members.take(32))+ memberSubject(m),+ ]),+ );} catch (_) {if (_disposed || !_authWorkCurrent(revision)) return;phoneLink = const PhoneLinkStatus.failed(@@ -5609,6 +5640,136 @@ class AppNotifier extends ChangeNotifier {}}+ /// Viewer builds: open the account's own socket once, so `group_changed` and `machines_changed` arrive+ /// even with no machine linked. The native app's daemon hears them for it.+ void _startAccountEvents() {+ final links = peerLinks;+ if (_accountEvents != null ||+ links is! DirectLink ||+ _paneLayout == null ||+ status != AppStatus.authenticated) {+ return;+ }+ final events = _accountEvents = links.accountEvents((type, payload) {+ if (_disposed) return;+ switch (type) {+ case 'group_changed':+ unawaited(refreshGroup());+ case 'machines_changed':+ unawaited(_rereadMachinesInBackground(pushed: true));+ }+ });+ events.start();+ // What the group settled while this window was closed.+ unawaited(refreshGroup());+ }++ /// Brings this device's trust group up to date — viewer builds only:+ ///+ /// 1. the account's signed board (`GET /api/group/board`), believed only where a member this device+ /// already trusts signed (`group_sync.dart` `adoptBoard`) — how a browser learns a machine it+ /// shares no other machine with;+ /// 2. then a roster swap with a group machine that is online, which passes this device's news on.+ ///+ /// Machines that gained a key connect, and machines the group dropped go back to "Link required"+ /// ([_afterGroupSync]). One refresh at a time; a call during one runs another after it.+ Future<void> refreshGroup() {+ // A push that lands while a refresh is running may carry what that refresh read too early: it+ // runs once more afterwards rather than joining it.+ if (_groupRefresh != null) {+ _groupRefreshAgain = true;+ return _groupRefresh!;+ }+ return _groupRefresh = () async {+ do {+ _groupRefreshAgain = false;+ await _refreshGroup();+ } while (_groupRefreshAgain && !_disposed);+ }().whenComplete(() => _groupRefresh = null);+ }++ bool _groupRefreshAgain = false;++ Future<void> _refreshGroup() async {+ final links = peerLinks;+ final keys = viewer?.keys;+ if (_disposed ||+ links is! DirectLink ||+ keys == null ||+ _paneLayout == null) {+ return;+ }+ final revision = _authRevision;+ try {+ final board = await api.readGroupBoard(since: _groupBoardRevision);+ if (!_authWorkCurrent(revision)) return;+ // Only news is passed on to every machine at once; otherwise one machine, at the usual pace.+ var news = false;+ if (board != null) {+ _groupBoardRevision = board.revision;+ if (board.entries case final entries?) {+ news = true;+ await _afterGroupSync(await adoptBoard(keys, entries));+ }+ }+ final online = [+ for (final id in await _groupMachines())+ if (machineStates[id]?.nodeOnline != false) id,+ ];+ if (online.isNotEmpty && _authWorkCurrent(revision)) {+ await _syncGroup(online.first, spread: news);+ }+ } catch (_) {+ // Background work: the next push, reconnect or safety-net tick tries again.+ }+ }++ /// What a roster change means for the machine list: a machine that now has a key connects, one the+ /// group dropped goes back to "Link required". The same rule as the phone app's.+ Future<void> _afterGroupSync(GroupSyncOutcome outcome) async {+ final keys = viewer?.keys;+ if (keys == null) return;+ var changed = false;+ for (final id in outcome.unpinned) {+ final machine = machineStates[id];+ if (machine == null || machine.needsLink) continue;+ machine.needsLink = true;+ machine.agentLoadStatus = AgentLoadStatus.needsLink;+ await _pool?.closeMachine(id);+ _markSessionsUnreachable(+ machine,+ 'This machine left your group. Link it again to reconnect.',+ );+ _startLinkRetry(id);+ changed = true;+ }+ for (final machine in [...machineStates.values]) {+ if (!machine.needsLink || machine.machine.isShared) continue;+ final id = machine.machine.machineId;+ if (await keys.peer(id) == null) continue;+ machine.needsLink = false;+ machine.agentLoadStatus = AgentLoadStatus.idle;+ _stopLinkRetry(id);+ await _pool?.closeMachine(id);+ _connectMachine(machine);+ changed = true;+ }+ if (changed) notifyListeners();+ }++ /// This device's word for [subjects] on the account's board, so devices that share no machine with+ /// it still hear. Best effort: the relay swap carries the same news where it can.+ Future<void> _vouch(List<Map<String, Object>> subjects) async {+ final keys = viewer?.keys;+ if (keys == null || subjects.isEmpty) return;+ try {+ final identity = await keys.identity();+ await api.postGroupBoard([+ for (final subject in subjects) await signVouch(identity, subject),+ ]);+ } catch (_) {}+ }+final Map<String, DateTime> _groupSyncedAt = {};static const _groupResync = Duration(minutes: 5);@@ -5636,6 +5797,7 @@ class AppNotifier extends ChangeNotifier {machineId,label: label,);+ await _afterGroupSync(outcome);if (!spread && outcome.pinned.isEmpty) return;for (final other in [...machineStates.keys]) {if (other == machineId || machineStates[other]?.nodeOnline == false) {@@ -5643,7 +5805,7 @@ class AppNotifier extends ChangeNotifier {}if (await links.keys.peer(other) == null) continue;_groupSyncedAt[other] = DateTime.now();- await links.syncGroup(other, label: label);+ await _afterGroupSync(await links.syncGroup(other, label: label));}} catch (_) {_groupSyncedAt.remove(machineId);@@ -8011,17 +8173,24 @@ class AppNotifier extends ChangeNotifier {} catch (e) {return (error: '$e', machines: 0, machineId: null);}+ final member = GroupMember(+ pub: pub,+ kind: machine ? 'machine' : 'viewer',+ label: label,+ at: DateTime.now().millisecondsSinceEpoch,+ machineId: machine ? machineId : null,+ );+ // On the account's board too: devices that share no machine with this one learn the new member+ // from it, within seconds (`group_changed`).+ // Awaited (briefly): the approving tab or app is often closed the moment it says done, and a vouch+ // still in flight then would never leave.+ // (A machine the backend named no id for cannot be stated: the board would refuse it.)+ if (!machine || machineId != null) {+ await _vouch([memberSubject(member)])+ .timeout(const Duration(seconds: 5), onTimeout: () {});+ }try {- await admitGroupMember(- keys,- GroupMember(- pub: pub,- kind: machine ? 'machine' : 'viewer',- label: label,- at: DateTime.now().millisecondsSinceEpoch,- machineId: machine ? machineId : null,- ),- );+ await admitGroupMember(keys, member);// A machine is one this device dials: pinned now, by the key the QR vouched for.if (machine && machineId != null) {await keys.pin(machineId, pubBytes, label: label);@@ -10263,6 +10432,17 @@ class AppNotifier extends ChangeNotifier {_startOfflineRetry(machine);} else {_stopOfflineRetry(machineId);+ // A socket dialled while the machine was away (a machine just linked, say, still starting)+ // never finished its handshake: nobody was there to answer it, and nothing will now. Dial it+ // again rather than leave it "connecting" behind a machine that is back.+ if (wasOnline == false &&+ !machine.needsLink &&+ !machine.machine.isShared &&+ !machine.isLocalMachine &&+ machine.connectionStatus != ConnectionStatus.connected) {+ await _pool?.closeMachine(machineId);+ _connectMachine(machine);+ }if (wasOnline == false) {_markSessionsUnreachable(machine,@@ -13448,6 +13628,12 @@ class AppNotifier extends ChangeNotifier {/// What the local CLI closing this machine's socket with [code] does to the/// model — the `WsPool.onLocalFailure` path, without a socket.+ /// What reading [entries] off the account's group board does to the machine list — the middle of+ /// [refreshGroup], without the backend.+ @visibleForTesting+ Future<void> adoptGroupBoardForTest(Object? entries) async =>+ _afterGroupSync(await adoptBoard(viewer!.keys, entries));+@visibleForTestingvoid localFailureForTest(String machineId, int code, String reason) =>_onLocalFailure(machineId, code, reason);@@ -13499,6 +13685,8 @@ class AppNotifier extends ChangeNotifier {_stopAllLinkRetries();_stopAllAgentSyncTimers();_clearAllTurnActivity();+ unawaited(_accountEvents?.close());+ _accountEvents = null;for (final pane in allPanes) {pane.session?.removeListener(notifyListeners);pane.session?.dispose();diff --git a/desktop/lib/viewer/account_events.dart b/desktop/lib/viewer/account_events.dartnew file mode 100644index 000000000..3d24181b7--- /dev/null+++ b/desktop/lib/viewer/account_events.dart@@ -0,0 +1,131 @@+import 'dart:async';+import 'dart:convert';++import 'package:web_socket_channel/web_socket_channel.dart';++import 'password_link.dart' show RelaySocketFactory;++/// The account's own socket: `/api/web-ws` with this device's session and no machine selected — the+/// line the backend's account-wide pushes arrive on (`group_changed`, `machines_changed`), even on a+/// device that has no machine linked yet and so no machine socket to hear them through.+///+/// Every frame here is a HINT to re-read something over REST. It carries nothing trusted: a device+/// believes a group change only from signatures on the board (`group_sync.dart` `acceptVouches`).+///+/// Reconnects with backoff (1 s doubling to 30 s, reset by a socket that stayed up [_stable]) until+/// [close]. A token that cannot be had (signed out) waits the same way. A push sent while the socket+/// was down reached nobody, so every reconnect after the first reports each watched type once — the+/// caller re-reads, and an unchanged revision costs one small GET.+class AccountEvents {+ AccountEvents({+ required this.token,+ required this.uri,+ required this.socket,+ required this.onEvent,+ });++ final Future<String> Function() token;+ final Uri uri;+ final RelaySocketFactory socket;++ /// A frame's type and payload, for the types this socket is for.+ final void Function(String type, Map<String, dynamic> payload) onEvent;++ static const _watched = {'group_changed', 'machines_changed'};+ static const _maxBackoff = Duration(seconds: 30);++ /// An unselected socket never hears `connected` (that answers `machine_select`), so staying up this+ /// long is what proves a dial good.+ static const _stable = Duration(seconds: 30);++ WebSocketChannel? _channel;+ Timer? _retry;+ bool _closed = false;+ bool _started = false;+ int _attempt = 0;+ bool _everOpen = false;+ DateTime? _openedAt;++ void start() {+ if (_started || _closed) return;+ _started = true;+ unawaited(_connect());+ }++ Future<void> _connect() async {+ if (_closed) return;+ final String credential;+ try {+ credential = await token();+ } catch (_) {+ return _later();+ }+ if (_closed) return;+ final WebSocketChannel ch;+ try {+ ch = _channel = socket(uri, [credential]);+ await ch.ready;+ } catch (_) {+ return _later();+ }+ if (_closed) {+ unawaited(ch.sink.close());+ return;+ }+ _openedAt = DateTime.now();+ if (_everOpen) {+ for (final type in _watched) {+ onEvent(type, const {});+ }+ }+ _everOpen = true;+ ch.stream.listen(+ (raw) {+ if (raw is! String) return;+ final Object? frame;+ try {+ frame = jsonDecode(raw);+ } on FormatException {+ return;+ }+ if (frame is! Map) return;+ final type = frame['type'];+ if (type is String && _watched.contains(type)) {+ final payload = frame['payload'];+ onEvent(+ type,+ payload is Map ? Map<String, dynamic>.from(payload) : const {},+ );+ }+ },+ onDone: _later,+ onError: (Object _) => _later(),+ cancelOnError: true,+ );+ }++ void _later() {+ _channel = null;+ final openedAt = _openedAt;+ _openedAt = null;+ if (openedAt != null && DateTime.now().difference(openedAt) >= _stable) {+ _attempt = 0;+ }+ if (_closed || _retry != null) return;+ final wait = Duration(seconds: 1 << (_attempt < 5 ? _attempt : 5));+ _attempt++;+ _retry = Timer(wait > _maxBackoff ? _maxBackoff : wait, () {+ _retry = null;+ unawaited(_connect());+ });+ }++ Future<void> close() async {+ _closed = true;+ _retry?.cancel();+ _retry = null;+ final ch = _channel;+ _channel = null;+ if (ch != null) await ch.sink.close();+ }+}diff --git a/desktop/lib/viewer/direct_link.dart b/desktop/lib/viewer/direct_link.dartindex 42dac1176..ae7da304c 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 'account_events.dart';import 'code_link.dart';import 'group_sync.dart';import 'password_link.dart';@@ -138,6 +139,18 @@ class DirectLink implements PeerLinkClient {}}+ /// The account's own socket (`account_events.dart`): account-wide pushes, whether or not any machine+ /// is linked. Not started; the caller starts and closes it.+ AccountEvents accountEvents(+ void Function(String type, Map<String, dynamic> payload) onEvent,+ ) => AccountEvents(+ token: auth.accessToken,+ uri: Uri.parse('${config.wsBaseUrl}/api/web-ws')+ .replace(queryParameters: {'autonomousEnv': config.autonomousEnv}),+ socket: socket,+ onEvent: onEvent,+ );+/// Swaps trust-group rosters with [machineId] ([syncTrustGroup]): the machines this device learns/// of are pinned — no password for them — and the machine learns this device and whatever it/// linked. [label] is this device's name for itself. Never throws.diff --git a/desktop/lib/viewer/group_sync.dart b/desktop/lib/viewer/group_sync.dartindex 9f70bfb5e..96939d62a 100644--- a/desktop/lib/viewer/group_sync.dart+++ b/desktop/lib/viewer/group_sync.dart@@ -6,6 +6,7 @@ import 'package:web_socket_channel/web_socket_channel.dart';import '../e2ee/bytes.dart';import '../e2ee/envelope.dart';+import '../e2ee/keys.dart' show E2eeIdentity, verifySignature;import '../e2ee/primitives.dart';import '../e2ee/relay_session_crypto.dart';import 'password_link.dart' show RelaySocketFactory, defaultRelaySocket;@@ -492,3 +493,118 @@ Object? openHandedRoster(return null;}}++// ── The account's group board ─────────────────────────────────────────────────────────────────────+//+// Signed statements ("vouches") about who is in the group, kept by the backend so a device can learn a+// member it shares no machine with — a browser approved by a phone that had no machine yet, then a+// machine approved by that phone. The CLI's `lib/e2ee/groupBoard.ts` signs and checks the same bytes+// (one test vector pins both):+//+// sig = ed25519(signer, lvCat('group-vouch-v1', pub, kind | 'removed', machineId | '', label | '', at))+//+// Trust stays on the device: a vouch counts only when its signer is a member this device already+// trusts (or itself), growing to a fixpoint. The server, holding no member's key, cannot add anyone.++/// The bytes a vouch's signature covers.+Uint8List vouchMessage(Map<String, Object?> subject) => lvCat([+ 'group-vouch-v1',+ '${subject['pub']}',+ subject['removed'] == true ? 'removed' : '${subject['kind'] ?? ''}',+ '${subject['machineId'] ?? ''}',+ '${subject['label'] ?? ''}',+ '${subject['at']}',+]);++/// A member as a board statement.+Map<String, Object> memberSubject(GroupMember m) => {+ 'pub': m.pub,+ 'kind': m.kind,+ 'machineId': ?m.machineId,+ 'label': m.label,+ 'at': m.at,+};++/// A vouch about [subject], signed by [identity].+Future<Map<String, Object>> signVouch(+ E2eeIdentity identity,+ Map<String, Object> subject,+) async => {+ 'subject': subject,+ 'signer': b64e(identity.pub),+ 'sig': b64e(await identity.sign(vouchMessage(subject))),+};++/// The part of a board this device believes, as a roster to merge: members and removals signed by a key+/// it already trusts — its roster's members and itself — growing to a fixpoint. A self-vouch is carried+/// for others and never believed on its own; a key the group removed vouches for nobody.+Future<GroupRoster> acceptVouches(+ GroupRoster local,+ String selfPub,+ Object? entries, {+ DateTime? now,+}) async {+ final removedAt = {for (final t in local.removed) t.pub: t.at};+ final trusted = {selfPub, for (final m in local.members) m.pub};+ final pending = <Map<Object?, Object?>>[+ if (entries is List)+ for (final e in entries.take(_maxMembers + _maxTombstones))+ if (e is Map &&+ e['subject'] is Map &&+ e['signer'] is String &&+ e['sig'] is String &&+ (e['signer'] != (e['subject'] as Map)['pub'] ||+ e['signer'] == selfPub))+ e,+ ];+ final members = <GroupMember>[];+ final removed = <GroupTombstone>[];+ final done = <int>{};+ var progressed = true;+ while (progressed) {+ progressed = false;+ for (var i = 0; i < pending.length; i++) {+ final v = pending[i];+ if (done.contains(i) || !trusted.contains(v['signer'])) continue;+ done.add(i);+ final subject = Map<String, Object?>.from(v['subject'] as Map);+ final List<int> signer, sig;+ try {+ signer = b64d(v['signer'] as String);+ sig = b64d(v['sig'] as String);+ } on FormatException {+ continue;+ }+ if (signer.length != 32 || sig.length != 64) continue;+ if (!await verifySignature(signer, vouchMessage(subject), sig)) continue;+ if (subject['removed'] == true) {+ if (GroupTombstone.tryParse(subject, now: now) case final t?) {+ removed.add(t);+ }+ continue;+ }+ final member = GroupMember.tryParse(subject, now: now);+ if (member == null) continue;+ members.add(member);+ final tomb = removedAt[member.pub];+ if (tomb != null && tomb >= member.at) continue;+ if (trusted.add(member.pub)) progressed = true;+ }+ }+ return GroupRoster(members, removed);+}++/// Takes in what this device believes of a board ([acceptVouches]) and pins or drops machines to match.+Future<GroupSyncOutcome> adoptBoard(+ ViewerKeyStore keys,+ Object? entries,+) async {+ final selfPub = b64e((await keys.identity()).pub);+ final merged = await keys.updateGroupRoster((current) async {+ final local = await _seededFrom(keys, current, selfPub);+ final accepted = await acceptVouches(local, selfPub, entries);+ final m = mergeGroupRoster(local, accepted, selfPub);+ return (m.roster.toJson(), m);+ });+ return _apply(keys, merged);+}diff --git a/desktop/test/group_board_state_test.dart b/desktop/test/group_board_state_test.dartnew file mode 100644index 000000000..b614558d3--- /dev/null+++ b/desktop/test/group_board_state_test.dart@@ -0,0 +1,124 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/e2ee/bytes.dart';+import 'package:harness/e2ee/keys.dart' show E2eeIdentity;+import 'package:harness/state/app_state.dart';+import 'package:harness/viewer/group_sync.dart';+import 'package:harness/viewer/viewer_key_store.dart';+import 'package:harness/viewer/viewer_services.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show MemoryStore;++class _Connection extends WsConn {+ _Connection(String id)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: id,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+}++/// web1 was approved by a phone that had no machine; the phone then approved app1. web1 hears of app1+/// only through the account's board — and its row must follow on its own.+void main() {+ final app1 = 'b' * 32;+ late AppNotifier app;+ late ViewerKeyStore keys;+ late E2eeIdentity phone, machine;++ setUp(() async {+ final session = AuthSession(storage: MemoryStore());+ keys = ViewerKeyStore(storage: MemoryStore());+ app = AppNotifier(+ config: AppConfig.dev,+ authSession: session,+ configStore: null,+ viewer: ViewerServices(+ config: AppConfig.dev,+ session: session,+ keys: keys,+ ),+ connectionForTest: _Connection.new,+ );+ phone = await E2eeIdentity.generate();+ machine = await E2eeIdentity.generate();+ await admitGroupMember(+ keys,+ GroupMember(pub: b64e(phone.pub), kind: 'viewer', label: 'phone', at: 5),+ );+ app.machineStates[app1] =+ MachineState(+ Machine(+ machineId: app1,+ authMode: MachineAuthMode.remote,+ name: 'app1',+ ),+ )+ ..nodeOnline = true+ ..needsLink = true+ ..agentLoadStatus = AgentLoadStatus.needsLink;+ });+ tearDown(() => app.dispose());++ test('a machine the phone vouched for connects, no reload', () async {+ var notified = 0;+ app.addListener(() => notified++);+ await app.adoptGroupBoardForTest([+ await signVouch(phone, {+ 'pub': b64e(machine.pub),+ 'kind': 'machine',+ 'machineId': app1,+ 'label': 'app1',+ 'at': 10,+ }),+ ]);+ expect(app.machineStates[app1]!.needsLink, isFalse);+ expect(app.machineStates[app1]!.agentLoadStatus, AgentLoadStatus.idle);+ expect((await keys.peer(app1))!.pub, machine.pub);+ expect(notified, greaterThan(0));+ });++ test('a stranger\'s vouch changes nothing', () async {+ final stranger = await E2eeIdentity.generate();+ await app.adoptGroupBoardForTest([+ await signVouch(stranger, {+ 'pub': b64e(machine.pub),+ 'kind': 'machine',+ 'machineId': app1,+ 'label': 'app1',+ 'at': 10,+ }),+ ]);+ expect(app.machineStates[app1]!.needsLink, isTrue);+ expect(await keys.peer(app1), isNull);+ });++ test('a machine the group removed goes back to "Link required"', () async {+ await app.adoptGroupBoardForTest([+ await signVouch(phone, {+ 'pub': b64e(machine.pub),+ 'kind': 'machine',+ 'machineId': app1,+ 'label': 'app1',+ 'at': 10,+ }),+ ]);+ expect(app.machineStates[app1]!.needsLink, isFalse);+ await app.adoptGroupBoardForTest([+ await signVouch(phone, {+ 'pub': b64e(machine.pub),+ 'at': 20,+ 'removed': true,+ }),+ ]);+ expect(app.machineStates[app1]!.needsLink, isTrue);+ expect(await keys.peer(app1), isNull);+ });+}diff --git a/desktop/test/viewer/group_sync_test.dart b/desktop/test/viewer/group_sync_test.dartindex cc53858c2..f8d149b23 100644--- a/desktop/test/viewer/group_sync_test.dart+++ b/desktop/test/viewer/group_sync_test.dart@@ -188,7 +188,12 @@ void main() {(_) => {'members': [], 'removed': []},beforeReply: () => admitGroupMember(keys,- GroupMember(pub: browserPub, kind: 'viewer', label: 'Chrome on macOS', at: 99),+ GroupMember(+ pub: browserPub,+ kind: 'viewer',+ label: 'Chrome on macOS',+ at: 99,+ ),),);await syncTrustGroup(@@ -329,4 +334,77 @@ void main() {vector,);});++ group('the group board', () {+ test('signs the statement the CLI signs, byte for byte', () async {+ // The same vector as cli/src/lib/e2ee/groupBoard.spec.ts.+ final signer = await E2eeIdentity.fromSeed(+ List.generate(32, (i) => i + 1),+ );+ final v = await signVouch(signer, {+ 'pub': 'ZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoM=',+ 'kind': 'machine',+ 'machineId': 'a' * 32,+ 'label': 'studio',+ 'at': 1700000000000,+ });+ expect(v['signer'], 'ebVWLo/mVPlAeLES6KmLp5AfhTrmlb7X4OORC60ElmQ=');+ expect(+ v['sig'],+ 'vAhKE9/5zgVV7fU9V6NiT8dqPlFjVgI6xRSzAxCCxQh+gsL9hlzJ51ozgyZe2PNOQi8hKfagAWJgQzQxsmM5Dg==',+ );+ });++ test(+ 'a browser the phone approved learns a machine the phone approved later',+ () async {+ final web = ViewerKeyStore(storage: _Memory());+ final phone = await E2eeIdentity.generate();+ final app = await E2eeIdentity.generate();+ final stranger = await E2eeIdentity.generate();+ // What web1 got at its sign-in: the phone, and no machine.+ await admitGroupMember(+ web,+ GroupMember(+ pub: b64e(phone.pub),+ kind: 'viewer',+ label: 'phone',+ at: 5,+ ),+ );+ final board = [+ await signVouch(phone, {+ 'pub': b64e(app.pub),+ 'kind': 'machine',+ 'machineId': 'b' * 32,+ 'label': 'app1',+ 'at': 10,+ }),+ // Nobody web1 trusts: ignored.+ await signVouch(stranger, {+ 'pub': b64e(stranger.pub),+ 'kind': 'machine',+ 'machineId': 'c' * 32,+ 'label': 'evil',+ 'at': 11,+ }),+ ];+ final outcome = await adoptBoard(web, board);+ expect(outcome.pinned, ['b' * 32]);+ expect((await web.peer('b' * 32))!.pub, app.pub);+ expect(await web.peer('c' * 32), isNull);++ // The phone takes it back out: web1 drops it.+ final gone = await adoptBoard(web, [+ await signVouch(phone, {+ 'pub': b64e(app.pub),+ 'at': 20,+ 'removed': true,+ }),+ ]);+ expect(gone.unpinned, ['b' * 32]);+ expect(await web.peer('b' * 32), isNull);+ },+ );+ });}