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
fix(trust): switching accounts keeps each account's trust apart, and the gateway reads the device log again
0xken1582992477a766
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex 25f746ade..a775dcb75 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -455,6 +455,7 @@ describe('harness login --json', () => {'/api/auth/qr/poll': () => ({ status: 'approved', email: '[email protected]' }),'/api/auth/qr/claim': () => ({ token: 'tok_qr', refreshToken: 'r', expiresIn: 3600, email: '[email protected]' }),'/api/auth/qr/cancel': () => ({ cancelled: true }),+ '/api/auth/me': () => ({ user: { id: 'acct_qr' } }),},// Held open so the app's pipe has closed well before the sign-in is done.resolveComputer: () => later(500, { machine: { machineId: 'm_qr' } }),@@ -467,7 +468,8 @@ describe('harness login --json', () => {expect(await login.exit).toBe(0)const session = JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')) as Record<string, unknown>// A sign-in by hand: a sign-in epoch of its own, which the device key log keeps its marks by.- expect(session).toMatchObject({ accessToken: 'tok_qr', method: 'qr', signInEpoch: expect.stringMatching(/^[0-9a-f]{32}@\d+$/) })+ // And the account it was made to, which lets the device key log start over for it at any time.+ expect(session).toMatchObject({ accessToken: 'tok_qr', method: 'qr', signInEpoch: expect.stringMatching(/^[0-9a-f]{32}@\d+$/), signInAcct: 'acct_qr' })expect(calls.map((c) => c.url)).not.toContain('/api/auth/qr/cancel')}, 30_000)@@ -490,11 +492,15 @@ describe('harness login --json', () => {const root = tempRoot()seedSession(root)const gridCalls = recordingGrid(root)- const { base } = await fakeBackend({+ const { base, calls } = await fakeBackend({resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }),+ routes: { '/api/auth/me': () => ({ user: { id: 'acct_other' } }) },})const result = await runAsync(root, ['login', '--json'], base)expect(result.status).toBe(0)+ // Not a sign-in by hand: the account it was made to is not asked again, nor written.+ expect(calls.map((c) => c.url)).not.toContain('/api/auth/me')+ expect(JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8'))).not.toHaveProperty('signInAcct')const lines = result.stdout.trim().split('\n').map((l) => JSON.parse(l))// Harness only: grid is an add-on, signed in the first time a grid feature is used — so the line// says nothing about grid, and not one `grid` command ran, though a `grid` was right there.@@ -554,6 +560,8 @@ describe('harness login --json', () => {await login.exitconst session = JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')) as Record<string, unknown>expect(session.clientId).toBe(kept)+ // `/api/auth/me` is not answered here: the sign-in goes on, with no account recorded.+ expect(session).not.toHaveProperty('signInAcct')}}, 45_000)@@ -564,6 +572,7 @@ describe('harness login --json', () => {authorizeNative: (body) => { capturedRedirectUri = body.redirectUri; return { authorizeUrl: 'https://sso.example.test/authorize?tx=abc', tx: 'tx_abc' } },exchange: () => ({ token: 'tok_new', refreshToken: 'refresh_new', expiresIn: 3600, autonomousEnv: 'prod' }),resolveComputer: () => ({ machine: { machineId: 'm_new' } }),+ routes: { '/api/auth/me': () => ({ user: { id: 'acct_new' } }) },})const gridCalls = recordingGrid(root)@@ -600,6 +609,7 @@ describe('harness login --json', () => {expect(lines[1]).toEqual({ type: 'result', status: 'success', fingerprint: expect.stringMatching(FP) })expect(lines[1].fingerprint).toBe(fingerprintOnDisk(root))expect(existsSync(gridCalls)).toBe(false)+ expect(JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8'))).toMatchObject({ machineId: 'm_new', signInAcct: 'acct_new' })}, 15_000)it('already signed in with no key yet: makes the key and reports its fingerprint', async () => {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex ba88dcfb4..43b80ba01 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -252,6 +252,26 @@ async function resolveComputerMachine(signal?: AbortSignal): Promise<AuthSession}+/**+ * After a sign-in by hand: which account it was made to (`/api/auth/me`, under the token it just got),+ * kept beside its epoch. The device key log then starts over for that account whenever it first reads+ * it — a daemon started more than ten minutes after `harness login` used to freeze on the new account+ * instead, and trusted none of its devices. Merged into the newest file, as `resolveComputerMachine`+ * does, and only while the session is still this sign-in's. Never fails the sign-in: without it the+ * log keeps to the ten-minute window.+ */+async function recordSignInAccount(accessToken: string, signInEpoch: string, autonomousEnv: string): Promise<void> {+ try {+ const me = await requestJson<{ user?: { id?: unknown } }>('GET', '/api/auth/me', undefined, {+ authorization: `Bearer ${accessToken}`, 'x-autonomous-env': autonomousEnv,+ })+ const acct = me?.user?.id+ const latest = readAuthSession()+ if (typeof acct !== 'string' || !acct || latest?.signInEpoch !== signInEpoch) return+ writeAuthSession({ ...latest, signInAcct: acct })+ } catch { /* no account recorded */ }+}+/** This machine's device key code. Signing in is what puts the key into the account, so `create` makes* the identity when it is missing; the read-only commands (`status`, `auth status`) only look, and* show nothing rather than mint a key. Null whenever it cannot be had. */@@ -594,17 +614,20 @@ async function qrSignInCommand(})if (!result.ok) return fail(result.code, result.message)const { tokens } = result+ const signInEpoch = newSignInEpoch()+ const autonomousEnv = tokens.autonomousEnv ?? env.AUTONOMOUS_ENVwriteAuthSession({version: 1,accessToken: tokens.token,...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),...(tokens.expiresIn ? { expiresAt: Date.now() + tokens.expiresIn * 1000 } : {}),- autonomousEnv: tokens.autonomousEnv ?? env.AUTONOMOUS_ENV,+ autonomousEnv,computerId: computerId(),method: 'qr',updatedAt: Date.now(),- signInEpoch: newSignInEpoch(),+ signInEpoch,})+ await recordSignInAccount(tokens.token, signInEpoch, autonomousEnv)try {await resolveComputerMachine()} catch (err) {@@ -693,6 +716,7 @@ async function browserSignIn(throw err}const id = computerId()+ const signInEpoch = newSignInEpoch()const session: AuthSession = {version: 1,accessToken: exchanged.token,@@ -704,9 +728,10 @@ async function browserSignIn(// the clients were split signs every sign-in in as its configured one, and names none....(knownSsoClientId(exchanged.clientId) ? { clientId: knownSsoClientId(exchanged.clientId) } : {}),updatedAt: Date.now(),- signInEpoch: newSignInEpoch(),+ signInEpoch,}writeAuthSession(session)+ await recordSignInAccount(session.accessToken, signInEpoch, session.autonomousEnv)try {await resolveComputerMachine()} catch (err) {diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex baf626e34..8d79df76e 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -1158,8 +1158,8 @@ export interface GatewayStatus {export interface GatewayAccount {/** The machine id the backend gave this sign-in; null signed out. */machineId: string | null- /** Which sign-in by hand this is (lib/authSession.ts `signInOf`), or null. */- signIn: { epoch: string; adopted: boolean; at: number | null } | null+ /** Which sign-in by hand this is, and the account it was made to (lib/authSession.ts `signInOf`), or null. */+ signIn: { epoch: string; adopted: boolean; at: number | null; acct?: string } | null}/** A Wi-Fi device operation refused, with the code the device's local API answers it under. */diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex b6886eee5..b79c855c2 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -779,7 +779,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The relay and its E2EE (gateway/): the backend link, the sessions and the keys, which every remote// client's frames go through, held at the same gate. In its own process by default (core/gatewayLink.ts),// or here (gateway/start.ts); the socket hears it through `fromGateway` and speaks to it in the clear.- const account = (): GatewayAccount => ({ machineId: readAuthSession()?.machineId ?? null, signIn: signInOf(readAuthSession()?.signInEpoch) })+ const account = (s = readAuthSession()): GatewayAccount => ({ machineId: s?.machineId ?? null, signIn: signInOf(s?.signInEpoch, s?.signInAcct) })let serviceLinksRef: ServiceLinks | null = nullconst gatewayLink = outOfProcess.has('gateway') ? createGatewayLink({events: backend.fromGateway,@@ -1140,7 +1140,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// An experiment's process runs once it is on, the devices' once there is one: a request for one off asks for it.onDemand: new Set([...experiments, ...DEVICES_ON_DEMAND]),want: (service) => experimentHooks.want(service),- answer: async (service, query, payload) => deliveries.answer(service, query, payload)+ // The gateway's first: its `backend` reads (the device key log) were refused below as NOT_AN_EXPERIMENT.+ answer: async (service, query, payload) => (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)?? await answerExperimentQuery(coreApi, experiments, service, query, payload)?? await terminalWatch.answer(service, query, payload)?? (service === 'orchestrator' ? orchestratorLink.answer(query, payload) : null)@@ -1152,8 +1153,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {: service === 'devices' ? devicesLink.answer(query, payload): service === 'wifi' ? wifiLink.answer(query, payload): service === 'handoff' ? answerConversationQuery(coreApi, query, payload)- : service === 'recaps' ? recapsLink.answer(query, payload)- : service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : answerAgentQuery(coreApi, query)),+ : service === 'recaps' ? recapsLink.answer(query, payload) : answerAgentQuery(coreApi, query)),// The gateway's own traffic: its remote clients and what they sent, and its comings and goings; and what// the devices tell the core (a turn, a frame for the windows, a dial on the wire); a viewer stream's answers.notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload); else if (service === 'devices') devicesLink.notice(payload); else if (service === 'wifi') wifiLink.notice(payload); else if (service === 'viewers') viewersLink.notice(payload); else if (service === 'recaps') recapsLink.notice(payload) },diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.tsindex bd523789d..ec48a255d 100644--- a/cli/src/gateway/start.ts+++ b/cli/src/gateway/start.ts@@ -23,6 +23,7 @@ import { AutonomousDeviceDirect } from '../lib/autonomous-device/direct.js'import { startDevicePart } from '../lib/autonomous-device/parts.js'import type { AuthSessionManager } from '../lib/authSession.js'import { thisDeviceLabel } from '../lib/daemonState.js'+import { switchAccountTrust } from '../lib/e2ee/accountTrust.js'import { b64d, b64e, fingerprint } from '../lib/e2ee/core.js'import { DeviceLogStore } from '../lib/e2ee/deviceLogStore.js'import { DeviceLogSyncer, type DeviceLogFetched, type DeviceLogTrustOutcome } from '../lib/e2ee/deviceLogSyncer.js'@@ -185,6 +186,7 @@ export function startGateway(host: GatewayHost): StartedGateway {suspended: () => new Set(devLogSyncer?.suspendedKeys() ?? []),// Only a list the backend answered says who is offline; otherwise try every member.reachable: () => reachable,+ ready: () => devLogSyncer?.current() ?? false,log: (line) => console.log(line),})groupSyncer = syncer@@ -211,6 +213,17 @@ export function startGateway(host: GatewayHost): StartedGateway {// Which sign-in by hand this machine is under (minted by `harness login`, never a backend answer —// the machine id is one): the device log can start over only when THIS changes.signIn: () => account.signIn,+ switchAccount: (from, to) => {+ // Run once, whatever it throws: the log goes on to the new account either way, and its devices+ // come back from that log. Run again, a half-done switch would put away what it already restored.+ try { switchAccountTrust(from, to) } catch (err) {+ console.log(`[devlog] could not swap the trust stores to the new account: ${err instanceof Error ? err.message : String(err)}`)+ }+ gateway.e2ee.reloadPaired()+ // Sessions to the old account's machines, and who the group last synced with, are that account's.+ relayPool.close()+ syncer.reset()+ },fetch: async (since) => {const r = await host.backend('GET', `/api/device-keys?since=${since}`)const data = r.status === 200 ? r.body.data as Partial<DeviceLogFetched> | undefined : undefineddiff --git a/cli/src/lib/authSession.spec.ts b/cli/src/lib/authSession.spec.tsindex 4961edee4..74cd24793 100644--- a/cli/src/lib/authSession.spec.ts+++ b/cli/src/lib/authSession.spec.ts@@ -43,14 +43,14 @@ afterAll(async () => {describe('sign-in epoch', () => {it('rides along every rewrite of the session — a refresh and a new machine id', async () => {const epoch = newSignInEpoch()- writeAuthSession({ ...baseSession(), signInEpoch: epoch })+ writeAuthSession({ ...baseSession(), signInEpoch: epoch, signInAcct: 'acct-1' })vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({success: true, data: { token: 'refreshed-access', refreshToken: 'refreshed-refresh', expiresIn: 3600 },}))))const manager = new AuthSessionManager('https://api.example.test')await manager.accessToken()manager.updateMachineId('machine-2')- expect(readAuthSession()).toMatchObject({ accessToken: 'refreshed-access', machineId: 'machine-2', signInEpoch: epoch })+ expect(readAuthSession()).toMatchObject({ accessToken: 'refreshed-access', machineId: 'machine-2', signInEpoch: epoch, signInAcct: 'acct-1' })expect(newSignInEpoch()).not.toBe(epoch)})@@ -74,6 +74,13 @@ describe('sign-in epoch', () => {expect(signInOf(undefined)).toBeNull()expect(signInOf('')).toBeNull()})++ it('says which account a sign-in by hand was made to, never for an adopted one', () => {+ const epoch = newSignInEpoch(1_234)+ expect(signInOf(epoch, 'acct-1')).toEqual({ epoch, adopted: false, at: 1_234, acct: 'acct-1' })+ expect(signInOf(`${ADOPTED_SIGN_IN}${epoch}`, 'acct-1')).toEqual({ epoch: `${ADOPTED_SIGN_IN}${epoch}`, adopted: true, at: 1_234 })+ expect(signInOf(epoch, '')).toEqual({ epoch, adopted: false, at: 1_234 })+ })})it('reads a legacy session without interpreting optional metadata or rewriting the sign-in', async () => {diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.tsindex 06fa4ef3f..b5ff47893 100644--- a/cli/src/lib/authSession.ts+++ b/cli/src/lib/authSession.ts@@ -21,6 +21,9 @@ export interface AuthSession {/** Which sign-in by hand this session is: minted here when the person signs in, never anything the* backend sends — the device key log keeps its marks per sign-in (deviceLogSyncer `signIn`). */signInEpoch?: string+ /** The account that sign-in by hand was made to (`/api/auth/me`'s user id, the device key log's `acct`),+ * asked right after it: the log may then start over for that account any time, not only in 10 minutes. */+ signInAcct?: string}/**@@ -70,6 +73,7 @@ function parse(raw: string): AuthSession | null {...(knownSsoClientId(value.clientId) ? { clientId: knownSsoClientId(value.clientId) } : {}),updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,...(typeof value.signInEpoch === 'string' && value.signInEpoch ? { signInEpoch: value.signInEpoch } : {}),+ ...(typeof value.signInAcct === 'string' && value.signInAcct ? { signInAcct: value.signInAcct } : {}),}} catch { return null }}@@ -97,11 +101,13 @@ export async function ensureSignInEpoch(): Promise<string | null> {}/** A `signInEpoch` as the device key log reads it (deviceLogSyncer `signIn`): whether it was adopted,- * and when it was made — null when it does not say (one from before the time was recorded). */-export function signInOf(epoch: string | undefined | null): { epoch: string; adopted: boolean; at: number | null } | null {+ * when it was made — null when it does not say (one from before the time was recorded) — and the+ * account it was made to (`signInAcct`), never for an adopted one: nobody saw that sign-in made. */+export function signInOf(epoch: string | undefined | null, acct?: string | null): { epoch: string; adopted: boolean; at: number | null; acct?: string } | null {if (!epoch) return nullconst at = /@(\d{1,15})$/.exec(epoch)- return { epoch, adopted: epoch.startsWith(ADOPTED_SIGN_IN), at: at ? Number(at[1]) : null }+ const adopted = epoch.startsWith(ADOPTED_SIGN_IN)+ return { epoch, adopted, at: at ? Number(at[1]) : null, ...(acct && !adopted ? { acct } : {}) }}export function readAuthSession(): AuthSession | null {diff --git a/cli/src/lib/e2ee/accountTrust.spec.ts b/cli/src/lib/e2ee/accountTrust.spec.tsnew file mode 100644index 000000000..6f4e7a99e--- /dev/null+++ b/cli/src/lib/e2ee/accountTrust.spec.ts@@ -0,0 +1,78 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { describe, expect, it } from 'vitest'+import { stashTrust, switchAccountTrust, unstashTrust } from './accountTrust.js'++const A = '65f0a1b2c3d4e5f6a7b8c9d0', B = '65f0a1b2c3d4e5f6a7b8c9d1'+const web = (pub: string) => ({ identityPub: pub, label: pub, pairedAt: 1, role: 'web' })+const device = { identityPub: 'dev', label: 'wifi', pairedAt: 1, role: 'device' }++function e2e(): string {+ const dir = mkdtempSync(join(tmpdir(), 'account-trust-'))+ writeFileSync(join(dir, 'identity.json'), '{"pub":"me"}')+ return dir+}+const write = (dir: string, name: string, data: unknown): void => writeFileSync(join(dir, name), JSON.stringify(data))+const read = (dir: string, name: string): unknown => existsSync(join(dir, name)) ? JSON.parse(readFileSync(join(dir, name), 'utf-8')) : undefined++describe('trust stores kept per account', () => {+ it('puts away one account\'s stores and brings back the other\'s, keeping the Wi-Fi device and the identity', () => {+ const dir = e2e()+ write(dir, 'paired.json', [web('a-web'), device])+ write(dir, 'group.json', { members: ['a'], removed: [] })+ write(dir, 'group-blocked.json', ['a-blocked'])+ write(dir, 'machinePeers.json', [{ machineId: 'ma', pub: 'a-box' }])++ switchAccountTrust(A, B, dir)+ expect(read(dir, 'paired.json')).toEqual([device])+ for (const name of ['group.json', 'group-blocked.json', 'machinePeers.json']) expect(read(dir, name)).toBeUndefined()+ expect(read(join(dir, 'accounts', A), 'paired.json')).toEqual([web('a-web')])+ expect(read(join(dir, 'accounts', A), 'group.json')).toEqual({ members: ['a'], removed: [] })++ // B makes its own, then A comes back as it was.+ write(dir, 'paired.json', [device, web('b-web')])+ write(dir, 'group.json', { members: ['b'], removed: [] })+ switchAccountTrust(B, A, dir)+ expect(read(dir, 'paired.json')).toEqual([device, web('a-web')])+ expect(read(dir, 'group.json')).toEqual({ members: ['a'], removed: [] })+ expect(read(dir, 'group-blocked.json')).toEqual(['a-blocked'])+ expect(read(dir, 'machinePeers.json')).toEqual([{ machineId: 'ma', pub: 'a-box' }])+ expect(read(join(dir, 'accounts', B), 'paired.json')).toEqual([web('b-web')])+ expect(read(join(dir, 'accounts', A), 'paired.json')).toBeUndefined()+ expect(read(dir, 'identity.json')).toEqual({ pub: 'me' })+ })++ it('a stash cut short after its copy keeps the keys in both places, and a second run finishes it', () => {+ const dir = e2e()+ // The copy was written, the live file not yet cut.+ mkdirSync(join(dir, 'accounts', A), { recursive: true })+ write(join(dir, 'accounts', A), 'paired.json', [web('a-web')])+ write(dir, 'paired.json', [web('a-web'), device])+ stashTrust(A, dir)+ expect(read(dir, 'paired.json')).toEqual([device])+ expect(read(join(dir, 'accounts', A), 'paired.json')).toEqual([web('a-web')])+ // Run again with nothing of A's left live: its copy stays as it is.+ stashTrust(A, dir)+ expect(read(join(dir, 'accounts', A), 'paired.json')).toEqual([web('a-web')])+ })++ it('an account never kept starts empty', () => {+ const dir = e2e()+ write(dir, 'paired.json', [device])+ unstashTrust(B, dir)+ expect(read(dir, 'paired.json')).toEqual([device])+ expect(read(dir, 'group.json')).toBeUndefined()+ })++ it('refuses an account id that is not one, before anything moves', () => {+ const dir = e2e()+ write(dir, 'paired.json', [web('a-web')])+ for (const bad of ['../x', '', 'a/b', 'x'.repeat(65)]) {+ expect(() => switchAccountTrust(A, bad, dir)).toThrow(/not an account id/)+ expect(() => switchAccountTrust(bad, A, dir)).toThrow(/not an account id/)+ }+ expect(read(dir, 'paired.json')).toEqual([web('a-web')])+ expect(existsSync(join(dir, 'accounts', A))).toBe(false)+ })+})diff --git a/cli/src/lib/e2ee/accountTrust.ts b/cli/src/lib/e2ee/accountTrust.tsnew file mode 100644index 000000000..e9bb92ee8--- /dev/null+++ b/cli/src/lib/e2ee/accountTrust.ts@@ -0,0 +1,82 @@+/**+ * What this machine trusts, kept per account: when it moves from one account's device log to another's+ * (deviceLogSyncer `switchAccount`), the trust stores of the account it leaves go to+ * ${ADAPTER_DATA_DIR}/e2e/accounts/<acct>/ and the ones it kept for the account it joins come back.+ * Before this, signing out of A and in to B left A's browsers paired here, A's roster went out to B's+ * machines over `group_sync`, and A's keys counted as "already trusted" in B's log, so none of them was+ * ever shown as a new device.+ *+ * The Wi-Fi device's pairings (`role: 'device'` in paired.json) stay: the device belongs to this+ * computer, not to an account. identity.json is never touched.+ *+ * Every step is a rename, or a write of the copy before the original is cut: a crash part way leaves a+ * key in both places, never in neither.+ *+ * ponytail: no journal. A switch that dies between `stashTrust` and `unstashTrust` and is run again+ * stashes what was already restored under the account it leaves. The caller runs the switch once and+ * goes on whatever it throws, and each account's log brings its devices back on its own; a journal+ * (accounts/.switching) is the upgrade if that ever matters.+ */+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'+import { join } from 'path'+import { env } from '../../config/env.js'++/** The stores moved whole: the trust group's roster and blocks, and the machines this one dials. */+const WHOLE = ['group.json', 'group-blocked.json', 'machinePeers.json']+const PAIRED = 'paired.json'+/** An account id is a path segment here. The backend's are Mongo ObjectIds; anything else is refused. */+const ACCT = /^[A-Za-z0-9_-]{1,64}$/++type Paired = { identityPub?: unknown; role?: unknown }++const defaultDir = (): string => join(env.ADAPTER_DATA_DIR, 'e2e')++function accountDir(dir: string, acct: string): string {+ if (!ACCT.test(acct)) throw new Error(`not an account id: ${JSON.stringify(acct.slice(0, 80))}`)+ return join(dir, 'accounts', acct)+}++function readList(file: string): Paired[] | null {+ try {+ const raw = JSON.parse(readFileSync(file, 'utf-8')) as unknown+ return Array.isArray(raw) ? raw as Paired[] : null+ } catch { return null }+}++function writeAtomic(file: string, data: unknown): void {+ const temp = `${file}.${process.pid}.tmp`+ writeFileSync(temp, JSON.stringify(data, null, 2), { mode: 0o600 })+ renameSync(temp, file)+}++/** Put away what `acct` trusts here; the live stores are left holding only the Wi-Fi device's pairings. */+export function stashTrust(acct: string, dir = defaultDir()): void {+ const kept = accountDir(dir, acct)+ mkdirSync(kept, { recursive: true, mode: 0o700 })+ for (const name of WHOLE) if (existsSync(join(dir, name))) renameSync(join(dir, name), join(kept, name))+ const live = readList(join(dir, PAIRED))+ const accounts = live?.filter((p) => p.role !== 'device') ?? []+ // Nothing of the account's left live: an earlier stash cut it already, and its copy stays as it is.+ if (!live || !accounts.length) return+ writeAtomic(join(kept, PAIRED), accounts)+ writeAtomic(join(dir, PAIRED), live.filter((p) => p.role === 'device'))+}++/** Bring back what `acct` trusted when this machine left it; nothing kept means it starts empty. */+export function unstashTrust(acct: string, dir = defaultDir()): void {+ const kept = accountDir(dir, acct)+ for (const name of WHOLE) if (existsSync(join(kept, name))) renameSync(join(kept, name), join(dir, name))+ const back = readList(join(kept, PAIRED))+ if (!back) return+ const devices = (readList(join(dir, PAIRED)) ?? []).filter((p) => p.role === 'device')+ const pubs = new Set(devices.map((p) => p.identityPub))+ writeAtomic(join(dir, PAIRED), [...devices, ...back.filter((p) => !pubs.has(p.identityPub))])+ rmSync(join(kept, PAIRED), { force: true })+}++/** Leave `from`'s trust for `to`'s. Both ids are checked before anything moves. */+export function switchAccountTrust(from: string, to: string, dir = defaultDir()): void {+ accountDir(dir, to)+ stashTrust(from, dir)+ unstashTrust(to, dir)+}diff --git a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts b/cli/src/lib/e2ee/deviceLogSyncer.spec.tsindex ad53e79d8..edde7c41f 100644--- a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts+++ b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts@@ -69,7 +69,10 @@ class FakeBackend {/** `signIn`: the sign-in's epoch (one starting ADOPTED_SIGN_IN is adopted), made at `signInAt` (the* clock's 5_000 by default — just now). */-function setup(opts: { known?: string[]; tombstoned?: string[]; blocked?: string[]; store?: DeviceLogStore; backend?: FakeBackend; signIn?: () => string | null; signInAt?: number | null; isTrusted?: (pub: string) => boolean } = {}) {+function setup(opts: {+ known?: string[]; tombstoned?: string[]; blocked?: string[]; store?: DeviceLogStore; backend?: FakeBackend; signIn?: () => string | null; signInAt?: number | null+ isTrusted?: (pub: string) => boolean; signInAcct?: () => string | null; switchAccount?: (from: string, to: string) => void+} = {}) {const backend = opts.backend ?? new FakeBackend()const store = opts.store ?? new DeviceLogStore(join(mkdtempSync(join(tmpdir(), 'devlog-')), 'devlog.json'))const calls = {@@ -84,8 +87,10 @@ function setup(opts: { known?: string[]; tombstoned?: string[]; blocked?: stringidentity: () => me,signIn: () => {const epoch = opts.signIn?.() ?? null- return epoch ? { epoch, adopted: epoch.startsWith(ADOPTED_SIGN_IN), at: opts.signInAt === undefined ? 5_000 : opts.signInAt } : null+ const acct = opts.signInAcct?.() ?? null+ return epoch ? { epoch, adopted: epoch.startsWith(ADOPTED_SIGN_IN), at: opts.signInAt === undefined ? 5_000 : opts.signInAt, ...(acct ? { acct } : {}) } : null},+ ...(opts.switchAccount ? { switchAccount: opts.switchAccount } : {}),self: () => ({ machineId: MID_ME, label: 'my-mac' }),fetch: backend.fetch,append: backend.append,@@ -1533,6 +1538,127 @@ describe('DeviceLogSyncer — departed keys, sign-ins and kept accounts', () =>})})+ describe('a sign-in by hand to the account the backend names starts the log over at any time', () => {+ const OLD = 5_000 - 11 * 60_000+ /** Signed in by hand to ACCT long ago (box2 on the log); then to `acct` (recorded as `named`), with+ * the backend now serving `acct-2`. */+ const signedInAgain = async (named: string | null, more: Parameters<typeof setup>[0] = {}) => {+ const who = { user: 'u1', acct: ACCT as string | null }+ const s = setup({ signIn: () => who.user, signInAcct: () => who.acct, signInAt: OLD, ...more })+ s.backend.add(box2, 'machine', MID2, 'box2')+ await s.syncer.register()+ who.user = 'u2'+ who.acct = named+ s.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)+ await s.syncer.refresh()+ return { ...s, who }+ }++ it('long after it was made, when it was made to that account', async () => {+ const s = await signedInAgain('acct-2')+ expect(s.store.read()).toMatchObject({ state: { acct: 'acct-2' }, frozen: null, owner: 'u2' })+ })++ it('made to another account than the backend names, long ago: only freezes', async () => {+ const s = await signedInAgain('acct-3')+ expect(s.store.read()).toMatchObject({ state: { acct: ACCT }, frozen: { reason: 'invalid' } })+ })++ it('made to another account than the backend names, even just now: only freezes', async () => {+ // The account the sign-in was made to is known: a different one named minutes later is the+ // backend's word against it, which the window must not let through.+ const s = await signedInAgain('acct-3', { signInAt: 5_000 - 60_000 })+ expect(s.store.read()).toMatchObject({ state: { acct: ACCT }, frozen: { reason: 'invalid' } })+ })++ it('the account is not taken from a sign-in that is not new here', async () => {+ const who = { acct: ACCT }+ const s = setup({ signIn: () => 'u1', signInAcct: () => who.acct, signInAt: OLD })+ await s.syncer.register()+ who.acct = 'acct-2'+ s.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)+ await s.syncer.refresh()+ expect(s.store.read()).toMatchObject({ state: { acct: ACCT }, frozen: { reason: 'invalid' } })+ })++ it('swaps the trust stores before the new log is written: what it already trusted is the new account\'s', async () => {+ const seen: Array<{ from: string; to: string; live: string | undefined; archived: boolean }> = []+ let t!: ReturnType<typeof setup>+ const switchAccount = vi.fn((from: string, to: string) => {+ seen.push({ from, to, live: t.store.read().state?.acct, archived: t.store.archivedFile(from) !== null })+ // What the stores hold once swapped: the new account's own (nothing of box2).+ t.trusted.splice(0, t.trusted.length, phone.pub)+ })+ const who = { user: 'u1', acct: ACCT }+ t = setup({ signIn: () => who.user, signInAcct: () => who.acct, signInAt: OLD, switchAccount })+ t.backend.add(box2, 'machine', MID2, 'box2')+ await t.syncer.register()+ t.trusted.push(box2.pub)+ expect(switchAccount).not.toHaveBeenCalled() // the first read keeps what was trusted before the log+ who.user = 'u2'+ who.acct = 'acct-2'+ const other = FakeBackend.of('acct-2')+ t.backend.fetch.mockImplementation(other.fetch)+ await t.syncer.refresh()+ expect(seen).toEqual([{ from: ACCT, to: 'acct-2', live: ACCT, archived: false }])+ expect(t.store.read()).toMatchObject({ state: { acct: 'acct-2' }, preLog: [phone.pub] })+ // And back: the kept log comes back, and so do its stores.+ who.user = 'u3'+ who.acct = ACCT+ t.backend.fetch.mockImplementation(async (since) => ({ acct: ACCT, head: t.backend.state.head, entries: t.backend.entries.filter((e) => e.seq > since) }))+ await t.syncer.refresh()+ expect(switchAccount).toHaveBeenLastCalledWith('acct-2', ACCT)+ expect(t.store.read().state?.acct).toBe(ACCT)+ })++ it('a review of another account\'s list swaps them too', async () => {+ const switchAccount = vi.fn()+ const s = await signedInAgain(null, { switchAccount })+ expect(s.store.read().frozen?.reason).toBe('invalid')+ expect(switchAccount).not.toHaveBeenCalled()+ await s.syncer.rebaseline(false)+ expect(switchAccount).not.toHaveBeenCalled()+ await s.syncer.rebaseline(true)+ expect(switchAccount).toHaveBeenCalledWith(ACCT, 'acct-2')+ expect(s.store.read()).toMatchObject({ state: { acct: 'acct-2' }, frozen: null })+ })++ it('the trust group waits until the log is this sign-in\'s and not frozen on another account', async () => {+ const fresh = setup({ signIn: () => 'u1' })+ expect(fresh.syncer.current()).toBe(true) // nothing read yet: no account to carry over+ const who = { user: 'u1', acct: ACCT as string | null }+ const s = setup({ signIn: () => who.user, signInAcct: () => who.acct, signInAt: OLD })+ await s.syncer.register()+ expect(s.syncer.current()).toBe(true)+ who.user = 'u2'+ expect(s.syncer.current()).toBe(false)+ who.acct = 'acct-3'+ s.backend.fetch.mockImplementation(FakeBackend.of('acct-2').fetch)+ await s.syncer.refresh()+ expect(s.store.read().frozen?.reason).toBe('invalid')+ expect(s.syncer.current()).toBe(false)+ })+ })++ describe('gossip names its account', () => {+ it('says it, and a peer of another account is not heard: nothing frozen, no tail taken', async () => {+ const s = setup()+ s.backend.add(box2, 'machine', MID2, 'box2')+ await s.syncer.register()+ expect(s.syncer.gossip()).toMatchObject({ acct: ACCT })+ const other = FakeBackend.of('acct-2')+ other.add(evil, 'viewer', '', 'evil')+ other.add(phone, 'viewer', '', 'phone') // as long as this log, and different: a fork, were it this account's+ const head = s.store.read().state!.head+ expect(s.syncer.heard(evil.pub, { acct: 'acct-2', head: other.state.head, hashes: hashesOf(other.state), tail: other.entries, frozen: true })).toBeUndefined()+ expect(s.store.read()).toMatchObject({ frozen: null, state: { head } })+ expect(s.syncer.list().frozenPeers).toEqual([])+ // The same log, under this account's name (or none, from an older peer), is a fork.+ expect(s.syncer.heard(evil.pub, { acct: ACCT, head: other.state.head, hashes: hashesOf(other.state) })).toBeDefined()+ expect(s.store.read().frozen?.reason).toBe('fork')+ })+ })+describe('a suspension kept in another account\'s log shows, and lifts, in this one', () => {/** Signed in to ACCT, where a fork suspended evil; then signed in by hand to acct-2, whose log has evil. */const moved = async () => {diff --git a/cli/src/lib/e2ee/deviceLogSyncer.ts b/cli/src/lib/e2ee/deviceLogSyncer.tsindex 456e15816..694c40abb 100644--- a/cli/src/lib/e2ee/deviceLogSyncer.ts+++ b/cli/src/lib/e2ee/deviceLogSyncer.ts@@ -40,6 +40,10 @@ export interface DevLogSignIn {adopted: boolean/** When it was made (ms); null when not known — then it never starts the log over either. */at: number | null+ /** The account it was made to, as the backend named it right after (authSession `signInAcct`); absent+ * when that could not be asked (then only DEVLOG_RESET_WINDOW_MS opens the door), never for an+ * adopted one. */+ acct?: string | null}/** How long after a sign-in by hand a read of another account may start the log over: past it, with@@ -53,15 +57,19 @@ export interface DeviceLogSyncerDeps {/** How this machine describes itself in the log; no machineId = not signed in, nothing to register. */self: () => { machineId: string | null; label: string }/** Which sign-in by hand this machine is under; null when not known. The log of another account is- * started (or a kept one restored) only when this changed AND the backend's account differs AND it- * was made less than DEVLOG_RESET_WINDOW_MS ago — never for an adopted one. Otherwise a different- * account id from the backend freezes the log. While the file is not this sign-in's yet (no read of- * it so far), what peers gossip is not taken either. */+ * started (or a kept one restored) only when this changed AND the backend's account differs AND it is+ * the account that sign-in was made to, or it was made less than DEVLOG_RESET_WINDOW_MS ago — never+ * for an adopted one. Otherwise a different account id from the backend freezes the log. While the+ * file is not this sign-in's yet (no read of it so far), what peers gossip is not taken either. */signIn: () => DevLogSignIn | null/** The log from `since`; null when the backend has none to give (an older backend, or unreachable). */fetch: (since: number) => Promise<DeviceLogFetched | null>/** Append one signed entry; null when the backend could not be reached. */append: (entry: DevLogEntry) => Promise<DeviceLogAppendAnswer | null>+ /** This machine is moving from one account's log to another's (a sign-in by hand, or a review of the+ * other account's list): put away what `from` trusted here and bring back what `to` did. Called before+ * the new log is written, so what it snapshots as already trusted (`trustedNow`) is `to`'s. */+ switchAccount?: (from: string, to: string) => void/** 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). */@@ -309,6 +317,14 @@ export class DeviceLogSyncer {return !local.adopted && local.at !== null && Math.abs(this.now() - local.at) <= DEVLOG_RESET_WINDOW_MS}+ /** Whether the trust group may swap rosters now: the log is this sign-in's (or none was read yet) and+ * not frozen on an account it was not signed in to. Before that the roster here may still be the+ * account this machine just left, and handing it out would carry its devices into the new one. */+ current(): boolean {+ const file = this.deps.store.read()+ return !file.state || (this.ownsFile(file) && file.frozen?.reason !== 'invalid')+ }+/** Whether the file is the log of the sign-in this machine is under (or that cannot be told). Until a* read of it under a new sign-in, it may be another account's: what a peer says is not judged* against it — a peer of the new account would read as a fork of the old one. */@@ -479,10 +495,10 @@ export class DeviceLogSyncer {if (now) {const signedInAgain = local !== null && latest.owner !== local.epochif (now.acct !== got.acct) {- // Another account only right after a sign-in by hand here. Otherwise it is the backend saying- // so — and starting over would clear every mark a fork put on the list, the real log then- // adopted whole.- if (!signedInAgain || !this.mayStartOver(local)) {+ // Another account only after a sign-in by hand here: the account it was made to, whenever; with+ // none recorded, any one right after it. Otherwise it is the backend saying so — and starting+ // over would clear every mark a fork put on the list, the real log then adopted whole.+ if (!signedInAgain || (local.acct ? local.acct !== got.acct : !this.mayStartOver(local))) {this.freeze('invalid')return}@@ -493,7 +509,11 @@ export class DeviceLogSyncer {}}if (reset) {- if (now) this.deps.store.archive(latest)+ if (now) {+ // What the account left behind trusted goes with its log, and comes back with it.+ this.deps.switchAccount?.(now.acct, got.acct)+ this.deps.store.archive(latest)+ }// Back to an account this machine was signed in to before: its log as verified then, and every// mark on it (frozen, suspended, pending), go on from where they were.const kept = this.deps.store.restore(got.acct, (k) => this.carrySuspensions({ ...k, ...(local ? { owner: local.epoch } : {}) }))@@ -804,7 +824,10 @@ export class DeviceLogSyncer {// The reviewed list is another account's: the one this machine leaves is kept, as on a sign-in// (and what a fork suspended in it stays suspended here) — and a kept one of the reviewed account// goes on from where it was.- if (file.state && !same) this.deps.store.archive(file)+ if (file.state && !same) {+ this.deps.switchAccount?.(file.state.acct, next.acct)+ this.deps.store.archive(file)+ }const { joining: _j, ...rest } = baseconst reviewed: DevLogFile = this.carrySuspensions({...rest,@@ -838,7 +861,9 @@ export class DeviceLogSyncer {if (!file.state || !this.ownsFile(file)) return undefined// The newest hashes let a peer that finds the logs forked say where they split.const hashes = file.state.hashes.slice(-GOSSIP_HASHES).map((hash, i, all) => ({ seq: file.state!.head.seq - (all.length - 1 - i), hash }))- return { head: file.state.head, frozen: file.frozen !== null, hashes }+ // The account rides along: a device still signed in to the one this machine left must not have its+ // log taken for a fork of this one.+ return { acct: file.state.acct, head: file.state.head, frozen: file.frozen !== null, hashes }}/**@@ -853,7 +878,10 @@ export class DeviceLogSyncer {if (!this.ownsFile(file)) return undefinedconst mine = this.gossip()if (!state || !raw || typeof raw !== 'object') return mine- const p = raw as { head?: unknown; frozen?: unknown; tail?: unknown }+ const p = raw as { acct?: unknown; head?: unknown; frozen?: unknown; tail?: unknown }+ // Another account's log says nothing about this one. A peer from before the account rode along+ // sends none, and is judged as before.+ if (p.acct !== undefined && p.acct !== state.acct) return undefinedthis.frozenPeers.set(peerPub, p.frozen === true)const head = p.head as { seq?: unknown; hash?: unknown } | undefinedif (!head || typeof head.seq !== 'number' || !Number.isSafeInteger(head.seq) || head.seq < 0 || typeof head.hash !== 'string') return minediff --git a/cli/src/lib/e2ee/groupSyncer.spec.ts b/cli/src/lib/e2ee/groupSyncer.spec.tsindex 488b532ff..d46812dbd 100644--- a/cli/src/lib/e2ee/groupSyncer.spec.ts+++ b/cli/src/lib/e2ee/groupSyncer.spec.ts@@ -36,6 +36,8 @@ interface Node {trusted: Map<string, { kind?: string; machineId?: string }>syncer: InstanceType<typeof S.GroupSyncer>online: boolean+ /** What `ready` answers: the device key log is this sign-in's. */+ ready: booleandroppedSessions: string[]}@@ -61,6 +63,7 @@ function fleet(): { add: (name: string, machine?: boolean) => Node; link: (joinepeers: new MemPeers(),trusted: new Map(),online: true,+ ready: true,droppedSessions: [],} as unknown as Nodenode.syncer = new S.GroupSyncer({@@ -80,6 +83,7 @@ function fleet(): { add: (name: string, machine?: boolean) => Node; link: (joinereturn { type: 'group_sync_result', payload: target.syncer.handle(node.pub, frame.payload as Record<string, unknown>) }},dropSessions: (machineId) => { node.droppedSessions.push(machineId) },+ ready: () => node.ready,now: () => ++clock,})nodes.push(node)@@ -189,6 +193,30 @@ describe('GroupSyncer', () => {for (const n of f.nodes) n.syncer.stop()})+ it('while the device key log is not this sign-in\'s, no roster is swapped either way', async () => {+ vi.useFakeTimers()+ const f = fleet()+ const [a, b] = [f.add('a'), f.add('b')]+ f.link(a, b)+ const stranger = { pub: C.b64e(C.newIdentity().pub), kind: 'viewer', label: 'old account', at: 5 }+ b.ready = false+ // Answered with nothing, and nothing taken in.+ const reply = b.syncer.handle(a.pub, { self: { pub: a.pub, kind: 'machine', label: 'a', at: S.SELF_STAMP, machineId: a.machineId }, members: [stranger], removed: [] })+ expect(reply).toEqual({ members: [], removed: [], digest: G.rosterDigest({ members: [], removed: [] }) })+ expect(b.syncer.roster().members.some((m) => m.pub === stranger.pub)).toBe(false)+ // Nor sent: no dial at all.+ b.ready = true+ a.ready = false+ const handle = vi.spyOn(b.syncer, 'handle')+ await a.syncer.syncAll()+ expect(await a.syncer.syncWith(b.machineId!)).toBe(false)+ expect(handle).not.toHaveBeenCalled()+ a.ready = true+ expect(await a.syncer.syncWith(b.machineId!)).toBe(true)+ expect(handle).toHaveBeenCalledTimes(1)+ for (const n of f.nodes) n.syncer.stop()+ })+it('a peer may describe only itself: a self entry under another key is ignored', () => {const f = fleet()const [a, b] = [f.add('a'), f.add('b')]diff --git a/cli/src/lib/e2ee/groupSyncer.ts b/cli/src/lib/e2ee/groupSyncer.tsindex bcb58e3a9..42bff8809 100644--- a/cli/src/lib/e2ee/groupSyncer.ts+++ b/cli/src/lib/e2ee/groupSyncer.ts@@ -58,6 +58,11 @@ export interface GroupSyncerDeps {suspended?: () => ReadonlySet<string>/** Machines worth dialing now; null = unknown, try every member. */reachable?: () => Set<string> | null+ /** Whether the roster here is the account's this machine is signed in to (deviceLogSyncer `current`).+ * While not, nothing is swapped: a daemon started after a switch of accounts read the new account's+ * log only after its first rounds, and handed the roster of the account it left to the new one's+ * machines. */+ ready?: () => booleannow?: () => numberlog?: (line: string) => void}@@ -69,6 +74,8 @@ export class GroupSyncer {private fanOutTimer: ReturnType<typeof setTimeout> | null = nullprivate periodic: ReturnType<typeof setInterval> | null = nullprivate retryRound = 0+ /** Bumped when the account changes: an exchange started before is not merged into the new roster. */+ private generation = 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@@ -98,6 +105,14 @@ export class GroupSyncer {roster(): Roster { return this.deps.store.read() }+ /** The trust stores were swapped for another account's (accountTrust.ts): who was synced, and what is+ * on its way, belong to the one left. */+ reset(): void {+ this.generation+++ this.lastSynced.clear()+ this.inFlight.clear()+ }+/** A device just linked to or from this machine over the remote password: it joins the group, and the* rest of the group hears of it. */linked(peer: LinkedPeer): void {@@ -184,6 +199,10 @@ export class GroupSyncer {/** Responder side of `group_sync`, for a sealed request from the session identity `peerPub`. */handle(peerPub: string, payload: Record<string, unknown>): Record<string, unknown> {+ if (this.deps.ready?.() === false) {+ const none: Roster = { members: [], removed: [] }+ return { ...none, digest: rosterDigest(none) }+ }const now = this.now()const incoming = parseRoster(payload, now)const self = parseMember(payload.self, now)@@ -211,6 +230,7 @@ export class GroupSyncer {/** Every reachable machine member (and every machine pinned outside the roster), one at a time. */async syncAll(): Promise<void> {+ if (this.deps.ready?.() === false) { this.retryLater(); return }// Put back any pin the relay dropped. A member can hear of another before that one hears of it,// and its first dial is then refused — remoteRelay.ts unlinks a peer that answers e2e_denied. The// roster still says they belong together, so they are re-pinned and tried again on this round.@@ -229,6 +249,10 @@ export class GroupSyncer {const members = new Set(this.deps.store.read().members.map((m) => m.machineId))const missed = due.some((machineId, i) => !answered[i] && members.has(machineId))if (!missed) { this.retryRound = 0; return }+ this.retryLater()+ }++ private retryLater(): void {const delay = RETRY_MS[this.retryRound]if (delay === undefined) return // the periodic round takes overthis.retryRound++@@ -237,7 +261,8 @@ export class GroupSyncer {private async exchange(machineId: string): Promise<boolean> {const pin = this.deps.peers.get(machineId)- if (!pin) return false+ if (!pin || this.deps.ready?.() === false) return false+ const generation = this.generationconst local = this.deps.store.read()const devlog = this.devlog?.gossip()const reply = await this.deps.request(machineId, {@@ -247,7 +272,7 @@ export class GroupSyncer {...(devlog ? { devlog } : {}),},}, SYNC_TIMEOUT_MS).catch(() => null)- if (!reply) return false+ if (!reply || generation !== this.generation) return falsethis.lastSynced.set(machineId, this.now())const payload = (reply.payload ?? {}) as Record<string, unknown>if (typeof payload.error === 'string') return falsediff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.tsindex c918b4a5a..99f50d8b3 100644--- a/cli/src/lib/e2ee/manager.test.ts+++ b/cli/src/lib/e2ee/manager.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'-import { mkdtempSync, readFileSync, rmSync } from 'fs'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'import { tmpdir } from 'os'import { join } from 'path'@@ -525,6 +525,27 @@ describe('E2eeManager revoke', () => {expect(h.mgr.hasSession('z2')).toBe(false)})+ it('reloadPaired: a key another account\'s stores left out loses its session; the rest keep theirs, re-keyed', async () => {+ const h = machine()+ const gone = await fullPair(h, 'k1')+ const kept = await fullPair(h, 'k2')+ await fullPair(h, 'kd', 'device')+ // What accountTrust.ts leaves on disk: the account's browsers put away, the Wi-Fi device kept.+ const file = join(process.env.ADAPTER_DATA_DIR as string, 'e2e', 'paired.json')+ const pairs = JSON.parse(readFileSync(file, 'utf-8')) as Array<{ identityPub: string }>+ writeFileSync(file, JSON.stringify(pairs.filter((p) => p.identityPub !== C.b64e(gone.identity.pub))))+ h.mgr.reloadPaired()+ expect((h.lastFor('k1', 'e2e_denied')!.payload as Record<string, unknown>).reason).toBe('revoked')+ expect(h.mgr.hasSession('k1')).toBe(false)+ expect(h.mgr.hasSession('k2')).toBe(true)+ expect(h.mgr.hasSession('kd')).toBe(true)+ expect(h.mgr.listPaired().map((p) => p.role).sort()).toEqual(['device', 'web'])+ kept.onRekey(h.lastFor('k2', 'e2e_rekey')!)+ const env = (h.mgr.wrapUp({ type: 'text_delta', dbSessionId: 's', payload: { content: 'b' } }).payload as import('./core.js').WrappedPayload).__e2e+ expect(C.unwrapPayload(kept.session!.groupKey, env, 'text_delta', 's')).toEqual({ content: 'b' })+ expect(C.unwrapPayload(gone.session!.groupKey, env, 'text_delta', 's')).toBeNull()+ })+it('revoke NOT_FOUND for an unknown selector', async () => {const h = machine()await fullPair(h, 'q1')diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.tsindex af2735dc1..762f4d23c 100644--- a/cli/src/lib/e2ee/manager.ts+++ b/cli/src/lib/e2ee/manager.ts@@ -204,6 +204,16 @@ export class E2eeManager {return true}pairedPeers(): ReturnType<E2eeStore['list']> { return this.store.list() }+ /** paired.json changed under this manager (accountTrust.ts moved another account's keys in): read it+ * again, and close every session of a key no longer paired, as an unpair would — a browser of the+ * account this machine left must not keep its session, nor the group key. */+ reloadPaired(): void {+ const before = this.store.list().map((p) => p.identityPub)+ this.store.reloadPaired()+ const gone = before.filter((pub) => !this.store.isPaired(pub))+ for (const pub of gone) this.denyAndDropSessionsFor(pub)+ if (gone.length) this.rotateGroupKey()+ }hasSession(connId: string): boolean { return this.sessions.has(connId) }sessionIdentity(connId: string): string | null { return this.sessions.get(connId)?.webIdentityPub ?? null }sessionRole(connId: string): C.PairRole | null { return this.sessions.get(connId)?.role ?? null }diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.tsindex effbdec54..99fca5e2b 100644--- a/cli/src/lib/e2ee/store.ts+++ b/cli/src/lib/e2ee/store.ts@@ -103,12 +103,7 @@ export class E2eeStore {this.identity = id}}- try {- const arr = JSON.parse(readFileSync(PAIRED_FILE, 'utf-8')) as Array<PairedClient & { role?: PairRole }>- for (const p of arr) {- if (p?.identityPub) this.paired.set(p.identityPub, { ...p, role: p.role === 'device' ? 'device' : 'web' })- }- } catch { /* none yet */ }+ this.reloadPaired()try {const raw = JSON.parse(readFileSync(REMOTE_PASSWORD_FILE, 'utf-8')) as Partial<RemotePasswordRecord>if (raw?.v === 1 && typeof raw.stretched === 'string' && typeof raw.setAt === 'number') {@@ -125,6 +120,17 @@ export class E2eeStore {return this.identity}+ /** Read paired.json again, as it is on disk now (accountTrust.ts swaps it when the account changes). */+ reloadPaired(): void {+ this.paired.clear()+ try {+ const arr = JSON.parse(readFileSync(PAIRED_FILE, 'utf-8')) as Array<PairedClient & { role?: PairRole }>+ for (const p of arr) {+ if (p?.identityPub) this.paired.set(p.identityPub, { ...p, role: p.role === 'device' ? 'device' : 'web' })+ }+ } catch { /* none yet */ }+ }+getIdentity(): Identity {return this.identity ?? this.init()}diff --git a/cli/src/loginForceRace.spec.ts b/cli/src/loginForceRace.spec.tsindex f4809cbd1..12b1f1dea 100644--- a/cli/src/loginForceRace.spec.ts+++ b/cli/src/loginForceRace.spec.ts@@ -180,6 +180,9 @@ describe('login --force beside a start that lands mid-sign-in', () => {return { data: { machine: { machineId: 'm_new' } } }}return { status: 503, error: 'no daemon in this test' }+ case '/api/auth/me':+ // Asked under the token the sign-in just got: the account the new session was made to.+ return req.headers.authorization === 'Bearer tok_new' ? { data: { user: { id: 'acct_new' } } } : { data: { user: { id: 'acct_old' } } }default:return { status: 404, error: 'not stubbed' }}@@ -213,6 +216,6 @@ describe('login --force beside a start that lands mid-sign-in', () => {.map((line) => JSON.parse(line) as { type: string }).filter((line) => line.type === 'result')expect(results).toEqual([expect.objectContaining({ type: 'result', status: 'success' })])expect(JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')))- .toMatchObject({ accessToken: 'tok_new', machineId: 'm_new', signInEpoch: expect.stringMatching(/^[0-9a-f]{32}@\d+$/) })+ .toMatchObject({ accessToken: 'tok_new', machineId: 'm_new', signInEpoch: expect.stringMatching(/^[0-9a-f]{32}@\d+$/), signInAcct: 'acct_new' })}, 30_000)})diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex bbcce3be8..9ba53ce78 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -4788,6 +4788,8 @@ class AppNotifier extends ChangeNotifier {}if (me != null) {currentUser = CurrentUserProfile.fromMe(me);+ // A sign-in by hand: the device log keeps which account it was made to.+ if (currentUser!.id case final id?) unawaited(_deviceLog?.signedInAs(id));notifyListeners();}} catch (error) {@@ -5043,6 +5045,7 @@ class AppNotifier extends ChangeNotifier {_sharingDiscoveryTimer = null;_deafMachineListTimer?.cancel();_deafMachineListTimer = null;+ _groupSyncedAt.clear();_sharingDiscoveryBusy = false;_sharingDiscoveryAgain = false;_daemonGateFailed = false;@@ -7334,6 +7337,9 @@ class AppNotifier extends ChangeNotifier {final now = DateTime.now();final last = _groupSyncedAt[machineId];if (!spread && last != null && now.difference(last) < _groupResync) return;+ // Not stamped while the device log is still the last account's (DirectLink.syncGroup skips it+ // then): stamped, a machine reached right after an account switch went five minutes unsynced.+ if (await _deviceLog?.ownsLog() == false) return;_groupSyncedAt[machineId] = now;// Fire-and-forget from the connection handler: a state file that is locked for a moment must not// surface as an unhandled error. The next session retries.diff --git a/desktop/lib/viewer/device_log_sync.dart b/desktop/lib/viewer/device_log_sync.dartindex ca1d23bc6..f36eadd9f 100644--- a/desktop/lib/viewer/device_log_sync.dart+++ b/desktop/lib/viewer/device_log_sync.dart@@ -386,6 +386,9 @@ class ViewerDeviceLog {/// The write of the sign-in id [beginSignIn] minted; [register] waits for it.Future<void>? _epochSaving;+ /// The sign-in by hand [beginSignIn] minted in this run, until [signedInAs] names its account.+ String? _awaitingAcct;+/// This app's key is gone from the log: sign out, once.Future<void> _signOut() async {if (_signedOut) return;@@ -509,10 +512,12 @@ class ViewerDeviceLog {// for the read that comes first ([_doRefresh] ends it), or until [register] takes over._signingInAgain = fresh;_signInRound++;+ _awaitingAcct = null;if (!fresh) return;final previous = _epoch;final minted = _mintEpoch();_epoch = minted;+ _awaitingAcct = minted;_epochSaving = keys.writeSignInEpoch(minted).then((_) {},onError: (Object _) {@@ -522,6 +527,23 @@ class ViewerDeviceLog {);}+ /// Who the person just signed in as, by hand: the profile's user id (`/api/auth/me`), which is what+ /// the log names its account by. Kept beside the sign-in id, so the first read of that account+ /// starts the list over whenever it comes ([_mayStartOver]). Only for the sign-in by hand+ /// [beginSignIn] minted in this run — a stored session (the app opening) records nothing. Never+ /// throws.+ Future<void> signedInAs(String acct) async {+ final epoch = _awaitingAcct;+ if (epoch == null || acct.isEmpty) return;+ _awaitingAcct = null;+ try {+ await _epochSaving;+ if (_epoch == epoch) await keys.writeSignInAcct(epoch, acct);+ } catch (_) {+ // Not recorded: the sign-in falls back to the short window.+ }+ }+/// Read and verify whatever the log gained. Concurrent calls share one read. Never throws.Future<void> refresh() => _refreshing ??= _doRefresh().catchError((Object _) {}).whenComplete(() => _refreshing = null);@@ -558,16 +580,35 @@ class ViewerDeviceLog {'${[for (var i = 0; i < 16; i++) _secure.nextInt(256).toRadixString(16).padLeft(2, '0')].join()}@${_now()}';static final _secure = Random.secure();- /// Whether [local] — a sign-in by hand the file is not yet the log of — may start it over for another- /// account: never an adopted one, and only shortly after it was made. A backend that holds the log- /// back after a sign-in must not keep that door open, to name another account days later.- bool _mayStartOver(String local) {+ /// Whether [local] — a sign-in by hand the file is not yet the log of — may start it over for [acct]:+ /// never an adopted one; the account the profile named for it ([signedInAs]) whenever its first read+ /// comes, and no other; with none named, any only shortly after it was made. A backend that holds the+ /// log back after a sign-in must not keep that door open, to name another account days later.+ Future<bool> _mayStartOver(String local, String acct) async {if (local.startsWith(_adoptedSignIn)) return false;+ try {+ final named = await keys.signInAcct(local);+ if (named != null) return named == acct;+ } catch (_) {+ // Unreadable: the window alone decides.+ }final made = RegExp(r'@(\d{1,15})$').firstMatch(local);if (made == null) return false;return (_now() - int.parse(made.group(1)!)).abs() <= _resetWindowMs;}+ /// Whether the log this app holds is the one of the sign-in it is under — false while it may still be+ /// the account just left, before the first read under a new sign-in. No log yet is nobody's: true.+ /// Never throws (false when the file cannot be read).+ Future<bool> ownsLog() async {+ try {+ final file = await _read();+ return file.state == null || await _ownsFile(file);+ } catch (_) {+ return false;+ }+ }+/// Whether [file] is the log of the sign-in this app is under (or that cannot be told). Until a read/// of it under a new sign-in it may be the account just left: what a machine gossips is not judged/// against it — a machine of the new account would read as a fork of the old one.@@ -608,28 +649,39 @@ class ViewerDeviceLog {}}- /// Keep [file] — the log of an account this app is leaving — to restore if it comes back. Under the lock.- Future<void> _archiveIn(_File file) async {+ /// Keep [file] — the log of an account this app is leaving — to restore if it comes back, with what+ /// this app trusted under it ([trust]: [ViewerKeyStore.trustSnapshot]). [keep]: the account about+ /// to be restored, never the one dropped to make room — it was, when it was the oldest kept, and+ /// coming back to it then started its list over. Under the lock.+ Future<void> _archiveIn(_File file, {Map<String, Object?>? trust, String? keep}) async {final acct = file.state?.acct;if (acct == null) return;final all = await _archived()..remove(acct);- all[acct] = file.toJson();- while (all.length > _archivedKept) {- all.remove(all.keys.first);+ all[acct] = {...file.toJson(), 'trust': ?trust};+ while (all.length > _archivedKept + (all.containsKey(keep) ? 1 : 0)) {+ all.remove(all.keys.firstWhere((k) => k != keep));}await keys.writeDeviceLogArchive(all);}/// The kept log of [acct], made the live file (this sign-in's: [owner]) and only then taken out of/// the archive — a crash in between leaves it in both, never in neither. Null when there is none.- /// Under the lock.- Future<_File?> _restoreIn(String acct, String? owner) async {- final kept = _File.parse((await _archived())[acct]);+ /// With [swapTrust] (another account's log was live), what this app trusted under [acct] is trusted+ /// again — and nothing of the account left. Under the lock.+ Future<_File?> _restoreIn(String acct, String? owner, {required bool swapTrust}) async {+ final raw = (await _archived())[acct];+ final kept = _File.parse(raw);if (kept.state?.acct != acct) return null;kept.owner = owner ?? kept.owner;await _carrySuspensionsIn(kept);await _write(kept);+ if (swapTrust) {+ final trust = _trustOf(raw);+ await keys.writeTrust(trust ?? const {});+ // Kept by a build that did not keep trust with it: what the log names is trusted again.+ if (trust == null && kept.frozen == null) await _trust(kept.state!.active.values.toList());+ }final all = await _archived()..remove(acct);await keys.writeDeviceLogArchive(all);@@ -654,6 +706,10 @@ class ViewerDeviceLog {..pending = {...file.pending, ...carried}.toList();}+ /// What this app trusted under a kept log ([_archiveIn]); null in one kept before that existed.+ static Map<Object?, Object?>? _trustOf(Object? kept) =>+ kept is Map && kept['trust'] is Map ? kept['trust'] as Map<Object?, Object?> : null;+/// A suspension lifted here holds for every kept account too: none of them keeps [pubs] out. Under/// the lock.Future<void> _unsuspendArchivedIn(Iterable<String> pubs) async {@@ -664,7 +720,7 @@ class ViewerDeviceLog {final f = _File.parse(e.value);if (!f.suspended.any(lift.contains)) continue;f.suspended = [for (final k in f.suspended) if (!lift.contains(k)) k];- all[e.key] = f.toJson();+ all[e.key] = {...f.toJson(), 'trust': ?_trustOf(e.value)};changed = true;}if (changed) await keys.writeDeviceLogArchive(all);@@ -815,7 +871,7 @@ class ViewerDeviceLog {// Another account only after a sign-in by hand here. Otherwise it is the backend saying so// — and starting over would clear every mark a fork put on the list, the real log then// adopted whole.- if (local == null || !signedInAgain || !_mayStartOver(local)) {+ if (local == null || !signedInAgain || !await _mayStartOver(local, got.acct)) {await _freezeIn(file, 'invalid', effects);return false;}@@ -827,10 +883,17 @@ class ViewerDeviceLog {}}if (reset) {- if (file.state != null) await _archiveIn(file);+ // Another account's log was live: it is kept with what this app trusted under it, none of+ // which this account's machines are told of or trusted by. A first read keeps the pins: they+ // are links made before the log existed.+ final leaving = file.state != null;+ if (leaving) {+ await _archiveIn(file, trust: await keys.trustSnapshot(), keep: got.acct);+ _frozenPeers.clear();+ }// Back to an account this app was signed in to before: its log as verified then, and every// mark on it (frozen, suspended, pending), go on from where they were.- final kept = await _restoreIn(got.acct, local);+ final kept = await _restoreIn(got.acct, local, swapTrust: leaving);if (kept != null) {bootstrap = (kept.state?.head.seq ?? 0) == 0;return true;@@ -838,7 +901,9 @@ class ViewerDeviceLog {// First read, or signed in to another account here: that account's log starts from nothing.// `joinedSeq` starts at 0 and follows the head of each page this app VERIFIES ([_acceptIn]):// never the head the backend merely claims, or it could park it far ahead and have every key- // it forges below that adopted without a word. `preLog` is what was trusted already.+ // it forges below that adopted without a word. `preLog` is what was trusted already — under+ // this account, so nothing when another one's log was live.+ if (leaving) await keys.writeTrust(const {});file = _File(DevLogState.empty(got.acct),[],@@ -1228,7 +1293,12 @@ class ViewerDeviceLog {// live file, or — for another account — the one kept when this app left it (its marks go on), or// else nothing (every key on it is new here). Never against the account being left.final kept = same ? null : await _archivedFileIn(next.acct);- final base = same ? file : kept ?? _File(null, [], null, 0, joinedSeq: 0, preLog: [...file.preLog]);+ // Moving from another account's live log: what this app trusted under each goes with it.+ final switching = file.state != null && !same;+ final keptTrust = kept == null ? null : _trustOf((await _archived())[next.acct]);+ final base = same+ ? file+ : kept ?? _File(null, [], null, 0, joinedSeq: 0, preLog: switching ? [] : [...file.preLog]);final before = base.state?.active ?? const <String, DevLogMember>{};final added = [for (final m in next.active.values) if (before[m.pub] == null) m];final removed = [for (final m in before.values) if (next.active[m.pub] == null) m];@@ -1250,7 +1320,10 @@ class ViewerDeviceLog {// The reviewed list is another account's: the one this app leaves is kept, as on a sign-in (and// what a fork suspended in it stays suspended here) — and a kept one of the reviewed account// goes on from where it was.- if (file.state != null && !same) await _archiveIn(file);+ if (switching) {+ await _archiveIn(file, trust: await keys.trustSnapshot());+ _frozenPeers.clear();+ }base..state = next..recent = parsed@@ -1272,6 +1345,7 @@ class ViewerDeviceLog {await _carrySuspensionsIn(base);// Live first, then out of the archive: a crash in between leaves it in both, never in neither.await _write(base);+ if (switching) await keys.writeTrust(keptTrust ?? const {});if (kept != null) {final all = await _archived();if (all.remove(next.acct) != null) await keys.writeDeviceLogArchive(all);@@ -1298,6 +1372,7 @@ class ViewerDeviceLog {// The newest hashes let a peer that finds the logs forked say where they split.final from = max(0, state.hashes.length - _gossipHashes);return {+ 'acct': state.acct,'head': state.head.toJson(),'frozen': file.frozen != null,'hashes': [@@ -1315,6 +1390,9 @@ class ViewerDeviceLog {// A sign-in waiting for its first read: the file may be the account left behind, and a machine of// the new one would freeze it as a fork. Nothing is judged until the log is this sign-in's.if (!await _ownsFile(file)) return;+ // Another account's log (a machine still signed in to it): nothing in it says anything about this+ // one. A machine too old to say which account is heard as before.+ if (raw['acct'] != null && raw['acct'] != state.acct) return;_frozenPeers[machinePub] = raw['frozen'] == true;final theirs = DevLogHead.fromJson(raw['head']);if (theirs == null) return;diff --git a/desktop/lib/viewer/direct_link.dart b/desktop/lib/viewer/direct_link.dartindex 92983ca5e..5c6b432e0 100644--- a/desktop/lib/viewer/direct_link.dart+++ b/desktop/lib/viewer/direct_link.dart@@ -77,13 +77,16 @@ class DirectLink implements PeerLinkClient {String machineId, {required String label,}) async {+ final log = deviceLog;+ // Until the log is this sign-in's, the pins and the roster may still be the account just left's:+ // none of it goes to this account's machines, and nothing they say is taken in beside it.+ if (log != null && !await log.ownsLog()) return GroupSyncOutcome.none;final String token;try {token = await auth.accessToken();} catch (_) {return GroupSyncOutcome.none;}- final log = deviceLog;return syncTrustGroup(machineId: machineId,keys: keys,diff --git a/desktop/lib/viewer/viewer_key_store.dart b/desktop/lib/viewer/viewer_key_store.dartindex ff42aa699..0ba550107 100644--- a/desktop/lib/viewer/viewer_key_store.dart+++ b/desktop/lib/viewer/viewer_key_store.dart@@ -66,6 +66,7 @@ class ViewerKeyStore {static const _devLogKey = 'viewer_e2ee_devlog';static const _devLogArchiveKey = 'viewer_e2ee_devlog_archive';static const _signInKey = 'viewer_e2ee_sign_in';+ static const _signInAcctKey = 'viewer_e2ee_sign_in_acct';/// Minted on first use and kept: every linked machine has pinned it.Future<E2eeIdentity> identity() => _identity ??= _loadOrMintIdentity();@@ -180,6 +181,41 @@ class ViewerKeyStore {Future<void> writeSignInEpoch(String epoch) =>_storage.write(_signInKey, epoch);+ /// The account the sign-in by hand [epoch] was made to, as the profile said right after it; null+ /// when none was recorded for that sign-in (one recorded for an earlier sign-in never answers).+ Future<String?> signInAcct(String epoch) async {+ final raw = await _storage.read(_signInAcctKey);+ if (raw == null) return null;+ try {+ final decoded = jsonDecode(raw);+ if (decoded is Map && decoded['epoch'] == epoch && decoded['acct'] is String) {+ return decoded['acct'] as String;+ }+ } on FormatException {+ // Unreadable: none recorded.+ }+ return null;+ }++ Future<void> writeSignInAcct(String epoch, String acct) =>+ _storage.write(_signInAcctKey, jsonEncode({'epoch': epoch, 'acct': acct}));++ /// What this device trusts — its pins and its trust group — as stored: kept with an account's+ /// device key log when this device signs in to another one ([writeTrust] puts it back).+ Future<Map<String, Object?>> trustSnapshot() async => {+ 'peers': await _storage.read(_peersKey),+ 'group': await _storage.read(_groupKey),+ };++ /// Trust exactly what [snapshot] ([trustSnapshot]) holds; an empty one trusts nothing.+ Future<void> writeTrust(Map<Object?, Object?> snapshot) async {+ await _storage.synchronized('viewer_peers', () => _put(_peersKey, snapshot['peers']));+ await _put(_groupKey, snapshot['group']);+ }++ Future<void> _put(String key, Object? value) =>+ value is String ? _storage.write(key, value) : _storage.delete(key);+/// 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. The log as this device/// verified it stays, with every mark on it: signing in again to the same account goes on from there.diff --git a/desktop/test/e2ee/encrypted_down_types_test.dart b/desktop/test/e2ee/encrypted_down_types_test.dartindex 8d3b396ec..d94353db5 100644--- a/desktop/test/e2ee/encrypted_down_types_test.dart+++ b/desktop/test/e2ee/encrypted_down_types_test.dart@@ -51,6 +51,8 @@ void main() {machineRequests = {...namesIn(frames, 'MACHINE_REQUESTS = new Set(['),...namesIn(relay, 'OWNER_COMMAND_TYPES = new Set(['),+ // ...which spread the route commands in from their own set.+ ...namesIn(relay, 'ROUTE_COMMAND_TYPES: ReadonlySet<string> = new Set(['),};unwrapped = {...core,@@ -59,7 +61,7 @@ void main() {...namesIn(relay, 'PAIR_REQUESTS = new Set(['),...namesIn(cli('sharing/protocol.ts'), 'SHARE_REQUEST_TYPES = new Set(['),...namesIn(cli('teams/wire.ts'), 'TEAM_REQUEST_TYPES = new Set(['),- ...namesIn(cli('lib/viewerWire.ts'), 'VIEWER_DOWN_TYPES = new Set(['),+ ...namesIn(cli('lib/viewerFrames.ts'), 'VIEWER_DOWN_TYPES = new Set(['),};});diff --git a/desktop/test/viewer/device_log_sync_test.dart b/desktop/test/viewer/device_log_sync_test.dartindex 1764ea3a4..b23646cce 100644--- a/desktop/test/viewer/device_log_sync_test.dart+++ b/desktop/test/viewer/device_log_sync_test.dart@@ -1,11 +1,16 @@import 'dart:async';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.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/direct_auth.dart';+import 'package:harness/viewer/direct_auth_api.dart';+import 'package:harness/viewer/direct_link.dart';import 'package:harness/viewer/group_sync.dart';import 'package:harness/viewer/viewer_key_store.dart';@@ -101,6 +106,18 @@ class _LostSignIn extends _Memory {}}+/// A sign-in that counts how often a token is asked for, and has none.+class _Auth extends DirectAuth {+ _Auth() : super(session: AuthSession(storage: _Memory()), api: DirectAuthApi(config: AppConfig.dev));+ int asked = 0;++ @override+ Future<String> accessToken({bool force = false, String? failedToken}) async {+ asked++;+ throw StateError('signed out');+ }+}+/// Lets whatever is runnable run (crypto included), for at most [ms].Future<void> _settle(Future<void> f, [int ms = 300]) =>Future.any([f, Future<void>.delayed(Duration(milliseconds: ms))]);@@ -1218,6 +1235,24 @@ void main() {expect((await keys.deviceLogArchive()).keys, ['acct-b0', 'acct-b1', 'acct-b2', 'acct-b3']);});+ test('the oldest kept account is not the one dropped when it is the one being come back to', () async {+ var current = backend;+ final log = at(() => current);+ await backend.add(box2, 'machine', _mid2, 'box2');+ await log.register(freshSignIn: true);+ for (var i = 0; i < 4; i++) {+ current = _Backend('acct-b$i');+ await log.register(freshSignIn: true);+ }+ // Four kept, the first account the oldest of them: back to it, it is restored, not started over.+ expect((await keys.deviceLogArchive()).keys.first, _acct);+ current = backend;+ await log.register(freshSignIn: true);+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect(await keys.peer(_mid2), isNotNull, reason: 'what it trusted comes back with it');+ expect((await keys.deviceLogArchive()).keys, ['acct-b0', 'acct-b1', 'acct-b2', 'acct-b3']);+ });+test('a session from before sign-in ids takes the list over but never starts it over', () async {var current = backend;final log = at(() => current);@@ -1522,8 +1557,9 @@ void main() {const now = 30 * 60 * 1000;/// Signed in on [backend] (box3 new there), then the sign-in [epoch] (not yet the list's), whose- /// first read — at [now] — is of another account.- Future<void> later(String epoch) async {+ /// first read — at [now] — is of another account. [acct]: the account the profile named for+ /// the sign-in [acctEpoch] (by default [epoch]).+ Future<void> later(String epoch, {String? acct, String? acctEpoch}) async {var current = backend;final log = at(() => current);await backend.add(box2, 'machine', _mid2, 'box2');@@ -1532,6 +1568,7 @@ void main() {await backend.add(box3, 'machine', _mid3, 'box3');await log.refresh();await keys.writeSignInEpoch(epoch);+ if (acct != null) await keys.writeSignInAcct(acctEpoch ?? epoch, acct);final restarted = at(() => current, now: now);current = _Backend('acct-2');await restarted.refresh();@@ -1556,6 +1593,131 @@ void main() {expect(((await file())['state'] as Map)['acct'], 'acct-2');expect((await keys.deviceLogArchive()).keys, [_acct]);});++ test('one made long ago to the account the profile named starts it over', () async {+ await later('${'f' * 32}@${now - 11 * 60 * 1000}', acct: 'acct-2');+ expect(((await file())['state'] as Map)['acct'], 'acct-2');+ expect((await file())['frozen'], isNull);+ expect((await keys.deviceLogArchive()).keys, [_acct]);+ });++ test('one made long ago to another account than the one served only freezes', () async {+ await later('${'f' * 32}@${now - 11 * 60 * 1000}', acct: 'acct-3');+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect((await file())['frozen'], containsPair('reason', 'invalid'));+ expect(await keys.deviceLogArchive(), isEmpty);+ });++ test('one made just now to another account than the one served only freezes', () async {+ // The profile named this sign-in's account: a different one minutes later is the backend's word+ // against it, which the window must not let through.+ await later('${'f' * 32}@${now - 60 * 1000}', acct: 'acct-3');+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect((await file())['frozen'], containsPair('reason', 'invalid'));+ });++ test('the account an earlier sign-in was made to says nothing about this one', () async {+ await later('${'f' * 32}@${now - 11 * 60 * 1000}', acct: 'acct-2', acctEpoch: '${'e' * 32}@1');+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect((await file())['frozen'], containsPair('reason', 'invalid'));+ });+ });++ group('what this app trusts is kept per account', () {+ final midD = 'd' * 32, midPw = 'e' * 32;+ late E2eeIdentity boxD;+ setUp(() async => boxD = await E2eeIdentity.fromSeed(List.filled(32, 4)));++ Future<Set<String>> rosterPubs() async =>+ {for (final m in GroupRoster.parse(await keys.groupRoster()).members) m.pub};++ /// box3 linked by password before the log existed, box2 on the first account's log; then signed+ /// in by hand to acct-2, whose log has boxD.+ Future<(ViewerDeviceLog, _Backend)> switched() async {+ var current = backend;+ final log = at(() => current);+ await keys.pin(midPw, box3.pub, label: 'pw');+ await backend.add(box2, 'machine', _mid2, 'box2');+ await log.register(freshSignIn: true);+ // A first read keeps the links made before the log.+ expect(await keys.peer(midPw), isNotNull);+ expect((await file())['preLog'], [b64e(box3.pub)]);+ final b = _Backend('acct-2');+ await b.add(boxD, 'machine', midD, 'boxD');+ current = b;+ await log.register(freshSignIn: true);+ expect(((await file())['state'] as Map)['acct'], 'acct-2');+ return (log, b);+ }++ test('another account trusts none of the first one\'s machines; back to it, they are trusted again', () async {+ final (log, b) = await switched();+ expect(await keys.peer(_mid2), isNull);+ expect(await keys.peer(midPw), isNull);+ expect(await keys.peer(midD), isNotNull);+ expect(await rosterPubs(), {b64e(boxD.pub)});+ expect(((await keys.deviceLogArchive())[_acct] as Map)['trust'], isA<Map>());+ // What the first account trusted is not "already known" here: on this log it is news.+ expect((await file())['preLog'], isEmpty);+ await b.add(box2, 'machine', _mid2, 'box2');+ await log.refresh();+ expect(announced.map((m) => m.label), ['box2']);+ await at(() => backend).register(freshSignIn: true);+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect(await keys.peer(_mid2), isNotNull);+ expect(await keys.peer(midPw), isNotNull);+ expect(await keys.peer(midD), isNull);+ expect(await rosterPubs(), isNot(contains(b64e(boxD.pub))));+ });++ test('a kept list from before trust was kept with it trusts what its log names again', () async {+ await switched();+ final all = await keys.deviceLogArchive();+ await keys.writeDeviceLogArchive({_acct: {...(all[_acct] as Map).cast<String, Object?>()}..remove('trust')});+ await at(() => backend).register(freshSignIn: true);+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect(await keys.peer(_mid2), isNotNull);+ expect(await keys.peer(midD), isNull);+ });++ test('…unless it is frozen: nothing is trusted from it', () async {+ await switched();+ final all = await keys.deviceLogArchive();+ final kept = {...(all[_acct] as Map).cast<String, Object?>()}..remove('trust');+ kept['frozen'] = {'reason': 'fork', 'at': 1, 'lastGoodHead': backend.state.head.toJson()};+ await keys.writeDeviceLogArchive({_acct: kept});+ await at(() => backend).register(freshSignIn: true);+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect(await keys.peer(_mid2), isNull);+ expect(await keys.peer(midD), isNull);+ });++ test('"It\'s mine" lifting a kept list\'s suspension keeps what that list trusted', () async {+ final (log, _) = await switched();+ final pub = b64e(boxD.pub);+ final all = await keys.deviceLogArchive();+ await keys.writeDeviceLogArchive({_acct: {...(all[_acct] as Map).cast<String, Object?>(), 'suspended': [pub]}});+ await keys.writeDeviceLog({...(await file()).cast<String, Object?>(), 'suspended': [pub]});+ await log.dismiss(pub: pub);+ final kept = (await keys.deviceLogArchive())[_acct] as Map;+ expect(kept['suspended'], isNull);+ expect(kept['trust'], isA<Map>());+ await at(() => backend).register(freshSignIn: true);+ expect(await keys.peer(midPw), isNotNull);+ });++ test('the group is not swapped while the log may still be the account left', () async {+ final (log, _) = await switched();+ final auth = _Auth();+ final link = DirectLink(keys: keys, auth: auth, config: AppConfig.dev)..deviceLog = log;+ expect(await log.ownsLog(), isTrue);+ await link.syncGroup(_mid2, label: 'my-phone');+ expect(auth.asked, 1); // goes on to the swap+ log.beginSignIn(fresh: true);+ expect(await log.ownsLog(), isFalse);+ expect(await link.syncGroup(_mid2, label: 'my-phone'), same(GroupSyncOutcome.none));+ expect(auth.asked, 1);+ });});test('a restore that fails half way has the kept list live first: its marks are never lost', () async {@@ -1595,6 +1757,24 @@ void main() {expect((await file())['frozen'], containsPair('reason', 'fork'));});+ test('gossip names its account; a machine gossiping another account\'s log is not heard', () async {+ final log = at(() => backend);+ await backend.add(box2, 'machine', _mid2, 'box2');+ await log.register(freshSignIn: true);+ expect((await log.gossip())?['acct'], _acct);+ final other = _Backend('acct-2');+ await other.add(evil, 'viewer', '', 'evil');+ await other.add(phone, 'viewer', '', 'phone');+ final hashes = [for (var i = 0; i < other.state.hashes.length; i++) {'seq': i + 1, 'hash': other.state.hashes[i]}];+ final theirs = {'head': other.state.head.toJson(), 'frozen': true, 'hashes': hashes};+ await log.heard(b64e(box2.pub), {...theirs, 'acct': 'acct-2'});+ expect((await file())['frozen'], isNull);+ expect((await log.list()).frozenPeers, isEmpty);+ // A machine too old to say which account: heard as before.+ await log.heard(b64e(box2.pub), theirs);+ expect((await file())['frozen'], containsPair('reason', 'fork'));+ });+group('beginSignIn', () {test('a read before register already judges by the new sign-in, and register mints nothing more', () async {var current = backend;@@ -1640,6 +1820,22 @@ void main() {expect(await keys.signInEpoch(), before);});+ test('the account a sign-in by hand was made to is kept with it; a stored session keeps none', () async {+ final log = makeLog();+ log.beginSignIn(fresh: true);+ await log.signedInAs('acct-2');+ final epoch = (await keys.signInEpoch())!;+ expect(await keys.signInAcct(epoch), 'acct-2');+ await log.signedInAs('acct-3'); // once, for the sign-in it was made for+ expect(await keys.signInAcct(epoch), 'acct-2');+ final restarted = makeLog()..beginSignIn(fresh: false);+ await restarted.signedInAs('acct-3');+ expect(await keys.signInAcct(epoch), 'acct-2');+ log.beginSignIn(fresh: true);+ await log.register();+ expect(await keys.signInAcct((await keys.signInEpoch())!), isNull);+ });+test('this app\'s old key removed, read before register: no sign-out', () async {final log = at(() => backend);await backend.add(box2, 'machine', _mid2, 'box2');@@ -1727,6 +1923,7 @@ void main() {test('a review of another account\'s list after a sign-in keeps the one it leaves', () async {await backend.add(box2, 'machine', _mid2, 'box2');await makeLog().register();+ await keys.pin('e' * 32, box3.pub, label: 'pw');final f = Map<String, Object?>.from(await file());f['state'] = {...(f['state'] as Map).cast<String, Object?>(), 'acct': 'old'};f['suspended'] = ['k'];@@ -1738,6 +1935,11 @@ void main() {expect(((await file())['state'] as Map)['acct'], _acct);expect((await file())['owner'], 'f' * 32);expect((await keys.deviceLogArchive()).keys, ['old']);+ // What was trusted under the account left goes with it; this one trusts what its list names.+ expect(((await keys.deviceLogArchive())['old'] as Map)['trust'], isA<Map>());+ expect(await keys.peer('e' * 32), isNull);+ expect(await keys.peer(_mid2), isNotNull);+ expect((await file())['preLog'], isEmpty);});group('another account\'s list under the sign-in the live list belongs to', () {@@ -1942,11 +2144,14 @@ void main() {final f = Map<String, Object?>.from(await file())..['suspended'] = [b64e(evil.pub)];await keys.writeDeviceLog(f);await keys.unlink(_mid3); // as the suspension does+ await keys.pin('e' * 32, phone.pub, label: 'pw');final b = _Backend('acct-2');await b.add(k5, 'viewer', '', 'k5');current = b;await log.register(freshSignIn: true);expect(((await file())['state'] as Map)['acct'], 'acct-2');+ expect(await keys.peer(_mid2), isNull);+ expect(await keys.peer('e' * 32), isNull);current = backend; // no sign-in: the backend says the first accountawait log.refresh();expect(((await file())['state'] as Map)['acct'], 'acct-2');@@ -1987,6 +2192,8 @@ void main() {expect(pubs(f['departed']), [b64e(k7.pub)]);expect(announced, isEmpty);expect(await keys.peer(_mid3), isNull);+ expect(await keys.peer(_mid2), isNotNull);+ expect(await keys.peer('e' * 32), isNotNull);final row = (await log.list()).members.firstWhere((r) => r.member.pub == b64e(evil.pub));expect([row.suspended, row.pending], [true, true]);expect((await keys.deviceLogArchive()).keys, isNot(contains(_acct)));diff --git a/mobile/lib/phone/welcome/unlock_computer.dart b/mobile/lib/phone/welcome/unlock_computer.dartindex 52b515352..6e8b8fcb1 100644--- a/mobile/lib/phone/welcome/unlock_computer.dart+++ b/mobile/lib/phone/welcome/unlock_computer.dart@@ -6,6 +6,8 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/state/app_state.dart';+import '../devices_page.dart';+import '../phone_navigation.dart' show phoneRoute;import '../tty.dart';import '../tty_controls.dart';import 'scan_to_connect.dart';@@ -174,6 +176,40 @@ class _UnlockComputerState extends State<UnlockComputer> {'On $name, open Harness ▸ Add Phone…, then scan the QR code.',style: tty.style(size: TtySize.row, color: tty.faint),),+ // This phone's copy of the device list is frozen, so it pins no computer from it: a review is+ // the other way in, beside the code and the password.+ ListenableBuilder(+ listenable: widget.notifier,+ builder: (context, _) => !widget.notifier.deviceListNeedsReview+ ? const SizedBox.shrink()+ : Padding(+ padding: const EdgeInsets.only(top: 12),+ child: Row(+ children: [+ Expanded(+ child: Text(+ 'Your device list needs a review.',+ style: tty.style(+ size: TtySize.meta,+ color: tty.yellow,+ ),+ ),+ ),+ TtyTextButton(+ key: const ValueKey('device-list-review'),+ label: 'Your devices',+ onPressed: () => unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => DevicesPage(notifier: widget.notifier),+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),const SizedBox(height: 18),TtyPrimaryButton(key: const ValueKey('unlock-scan'),diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex e45826ef7..d3b19426f 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -1320,6 +1320,9 @@ class AppNotifier extends ChangeNotifier {// landed first (a push, a reconnect) would judge a just-signed-in phone by the old sign-in's// file, and the log has to know the sign-in is fresh before anything waits._registerDeviceLog(revision);+ // With no machine connected nothing is pushed to this phone: the machine list is read again now+ // and then until one is ([_rereadMachinesWhileDeaf]).+ _startDeafPoll();// Signed in. Display-name/avatar metadata is independent of machine// discovery and must not delay work.unawaited(_loadProfile());@@ -1365,6 +1368,10 @@ class AppNotifier extends ChangeNotifier {}if (me != null) {currentUser = CurrentUserProfile.fromMe(me);+ // A sign-in by hand: the device log keeps which account it was made to.+ if (currentUser?.id case final id?) {+ unawaited(_deviceLog?.signedInAs(id));+ }notifyListeners();}} catch (error) {@@ -1390,6 +1397,7 @@ class AppNotifier extends ChangeNotifier {// The code was scanned into the session that just ended — see [logout].pendingPairing = null;_clearDeviceNotices();+ _stopAccountTimers();_desk.reset();zoo.reset();unawaited(_pool?.closeAll());@@ -1502,6 +1510,7 @@ class AppNotifier extends ChangeNotifier {unawaited(cliLogin.logout());_stopAllOfflineRetries();_stopAllAgentSyncTimers();+ _stopAccountTimers();// Tiles go, the saved layout stays: signing out and back in is the same// person at the same desk, and the file is only read once machines exist.await _closeAllPanes(persist: false);@@ -1555,14 +1564,48 @@ class AppNotifier extends ChangeNotifier {departedDevices.clear();deviceRemovals.clear();_failedDismissals.clear();+ _deviceListFrozen = false;+ }++ /// What an account leaving takes with it: the refusals being settled, the machine list re-read+ /// while deaf, and when each machine last swapped trust groups (the next account's swap is its own).+ void _stopAccountTimers() {+ _forgetAllTrustSettles();+ _stopDeafPoll();+ _groupSyncedAt.clear();}void _onLocalFailure(String machineId, int code, String reason) {final machine = machineStates[machineId];if (machine == null || code != 4404) return;+ // A refusal for want of trust is usually only early: this phone's key not yet in the account's+ // device log, or the machine not yet in this phone's copy of it — a computer signed in after the+ // phone was. That is settled first ([_settleTrust]), while the machine keeps showing as+ // connecting; only a refusal that outlasts it asks for a password. Not for a machine a scanned+ // code waits for: its pairing screen is the way in, at once.+ if (_deviceLog != null &&+ (reason == 'NO_PEER_LINK' || reason == 'E2E_DENIED') &&+ pendingPairing?.machineId != machineId) {+ if ((_trustRounds[machineId] ?? 0) < _trustSettleRounds) {+ if (_trustSettling.add(machineId)) {+ unawaited(_settleTrust(machineId, reason));+ }+ return;+ }+ if (!machine.needsLink) {+ appLog.info(+ 'link',+ '${_shortId(machineId)} still refused ($reason) after the device list was checked',+ );+ }+ }// 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());+ _markNeedsLink(machine);+ }++ void _markNeedsLink(MachineState machine) {// 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 +1625,130 @@ class AppNotifier extends ChangeNotifier {notifyListeners();}+ // -- a refusal for want of trust ([_onLocalFailure]) ---------------------------------------------++ /// How many refusals of each machine were settled since it last connected, and the ones under way —+ /// each with what ends its wait early (a pin landing: [_redialNewlyTrusted]).+ final Map<String, int> _trustRounds = {};+ final Set<String> _trustSettling = {};+ final Map<String, Completer<void>> _trustWakes = {};+ static const _trustSettleRounds = 2;++ /// How long one settling round waits for the machine's key to land before dialling again: two+ /// rounds, about fifteen seconds, before a password is asked for.+ @visibleForTesting+ Duration trustSettleRound = const Duration(milliseconds: 7500);++ /// How long a machine that denied this phone's key gets to read the account's log again (its CLI+ /// does on a hello from a key it does not know) before the first hello is said again.+ @visibleForTesting+ Duration trustDeniedWait = const Duration(seconds: 1);++ /// Hears every [_redial], for a test with no pool to dial through.+ @visibleForTesting+ void Function(String machineId)? onRedialForTest;++ static String _shortId(String id) => id.length > 8 ? id.substring(0, 8) : id;++ /// One round of settling [machineId]'s refusal ([reason]: `NO_PEER_LINK`, no key here for it, or+ /// `E2E_DENIED`, the machine does not know this phone's): put this phone into the account's device+ /// log and read it, then dial again — at once when the machine's key just landed, after a moment for+ /// a machine that has to read the log itself. A frozen log can settle nothing: the password it is.+ Future<void> _settleTrust(String machineId, String reason) async {+ final log = _deviceLog;+ if (log == null) return;+ final revision = _authRevision;+ final round = _trustRounds[machineId] = (_trustRounds[machineId] ?? 0) + 1;+ final wake = _trustWakes[machineId] = Completer<void>();+ final short = _shortId(machineId);+ bool current() =>+ !_disposed &&+ _authWorkCurrent(revision) &&+ identical(_trustWakes[machineId], wake) &&+ machineStates.containsKey(machineId);+ final started = Stopwatch()..start();+ try {+ final registration = await log.ensureRegistered().timeout(+ trustSettleRound,+ onTimeout: () => DeviceLogRegistration.missing,+ );+ if (!current()) return;+ if (registration == DeviceLogRegistration.frozen) {+ appLog.info('link', '$short refused ($reason): the device list is frozen');+ // The machine's password form says so (deviceListNeedsReview), from the listing.+ unawaited(_syncPendingDevices());+ _trustRounds[machineId] = _trustSettleRounds;+ _endTrustSettle(machineId);+ final machine = machineStates[machineId]!+ ..connectionStatus = ConnectionStatus.disconnected;+ _markNeedsLink(machine);+ return;+ }+ if (registration == DeviceLogRegistration.registered) {+ appLog.info('link', '$short refused ($reason): this phone joined the device list');+ }+ final pinned = await _holdsMachineKey(machineId);+ if (!current()) return;+ if (reason == 'E2E_DENIED' || !pinned) {+ final rest = trustSettleRound - started.elapsed;+ final wait = reason == 'E2E_DENIED' && round == 1+ ? trustDeniedWait+ : rest.isNegative+ ? Duration.zero+ : rest;+ await Future.any([Future<void>.delayed(wait), wake.future]);+ if (!current()) return;+ }+ final now = pinned || await _holdsMachineKey(machineId);+ if (!current()) return;+ appLog.info(+ 'link',+ '$short refused ($reason): ${now ? 'pinned' : 'no key yet'}, dialling again (round $round)',+ );+ _endTrustSettle(machineId);+ _redial(machineId);+ } finally {+ // However the round ended, a machine no longer being settled can be settled again.+ if (identical(_trustWakes[machineId], wake)) _endTrustSettle(machineId);+ }+ }++ void _endTrustSettle(String machineId) {+ _trustSettling.remove(machineId);+ final wake = _trustWakes.remove(machineId);+ if (wake != null && !wake.isCompleted) wake.complete();+ }++ /// [machineId] connected, or the account is left: its refusals start counting again.+ void _forgetTrustSettle(String machineId) {+ _trustRounds.remove(machineId);+ _endTrustSettle(machineId);+ }++ void _forgetAllTrustSettles() {+ for (final machineId in [..._trustRounds.keys, ..._trustSettling]) {+ _forgetTrustSettle(machineId);+ }+ }++ Future<bool> _holdsMachineKey(String machineId) async {+ try {+ return await viewer.keys.peer(machineId) != null;+ } catch (_) {+ return false;+ }+ }++ /// Dial [machineId] again from scratch: a refused connection is closed for good, so it is closed+ /// and replaced.+ void _redial(String machineId) {+ final machine = machineStates[machineId];+ if (machine == null) return;+ onRedialForTest?.call(machineId);+ unawaited(_pool?.closeMachine(machineId));+ _connectMachine(machine);+ }+/// The token a viewer's relay socket dials with.Future<String> _socketToken(bool force, String? failedToken) =>// Only a session that is gone for good may sign the person out — see@@ -1619,10 +1786,17 @@ class AppNotifier extends ChangeNotifier {void _onConnectionStatus(String machineId, ConnectionStatus nextStatus) {final machine = machineStates[machineId];if (machine == null) return;- machine.connectionStatus = nextStatus;+ // A refusal being settled against the device log ([_settleTrust]) is still connecting.+ final settling =+ nextStatus == ConnectionStatus.disconnected &&+ _trustSettling.contains(machineId);+ machine.connectionStatus = settling+ ? ConnectionStatus.connecting+ : nextStatus;if (nextStatus == ConnectionStatus.connected) {_refreshDeviceLogAfterReconnect();machine.needsLink = false;+ _forgetTrustSettle(machineId);// A relay socket reports `connected` only after the machine's welcome// proved the link (`WsConn._markReady`), so a code held to pair this// machine has nothing left to do. Kept, it would be spent the next time@@ -1657,7 +1831,7 @@ class AppNotifier extends ChangeNotifier {// request still report. Read as offline, every return to the app flashed "Offline" and// threw the pager away. The streams on it are dead all the same: told so, and put back once// the socket is.- if (!machine.needsLink) {+ if (!machine.needsLink && !settling) {_markSessionsUnreachable(machine, 'Connection lost. Reconnecting…');}}@@ -2109,6 +2283,17 @@ class AppNotifier extends ChangeNotifier {ViewerDeviceLog? get deviceLog => _deviceLog;+ /// This phone's copy of the device log is frozen, so it pins no machine from it until someone+ /// reviews the list (Your devices). A machine asking for its password says so.+ bool get deviceListNeedsReview => _deviceListFrozen;+ bool _deviceListFrozen = false;++ @visibleForTesting+ set deviceListNeedsReviewForTest(bool frozen) {+ _deviceListFrozen = frozen;+ notifyListeners();+ }+/// Devices this phone dismissed whose write to the log failed: the banner must not bring them back/// on the next read of `pending`. Gone with the sign-in, or when the key is announced afresh.final Set<String> _failedDismissals = {};@@ -2203,6 +2388,9 @@ class AppNotifier extends ChangeNotifier {return;}if (_disposed || gen != _pendingSyncGen || status != AppStatus.authenticated) return;+ final frozen = listing.frozen != null;+ final frozenChanged = frozen != _deviceListFrozen;+ _deviceListFrozen = frozen;final pending = listing.pending.toSet();_suspendedNew..clear()@@ -2224,7 +2412,7 @@ class AppNotifier extends ChangeNotifier {final same = listEquals([for (final m in next) m.pub], [for (final m in newDevices) m.pub]);final sameDeparted =listEquals([for (final d in nextDeparted) d.pub], [for (final d in departedDevices) d.pub]);- if (same && sameDeparted) return;+ if (same && sameDeparted && !frozenChanged) return;newDevices..clear()..addAll(next);@@ -2234,11 +2422,18 @@ class AppNotifier extends ChangeNotifier {notifyListeners();}- /// A machine waiting for its password that the device key log now vouches for: dial it again.+ /// A machine waiting on trust — being settled ([_settleTrust]), or asking for its password — that the+ /// device key log now vouches for: dial it again, at once.Future<void> _redialNewlyTrusted() async {for (final state in [...machineStates.values]) {+ final machineId = state.machine.machineId;+ if (!state.needsLink && !_trustSettling.contains(machineId)) continue;+ if (!await _holdsMachineKey(machineId)) continue;+ if (_trustWakes[machineId] case final wake? when !wake.isCompleted) {+ wake.complete();+ continue;+ }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);@@ -2257,14 +2452,15 @@ class AppNotifier extends ChangeNotifier {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.+ /// read the log again — and put this phone's key into it if the boot's register could not — 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());+ unawaited(log.ensureRegistered());}/// The devices list was opened: every device announced so far has been seen — the banner's, and@@ -2392,6 +2588,9 @@ class AppNotifier extends ChangeNotifier {final now = DateTime.now();final last = _groupSyncedAt[machineId];if (!spread && last != null && now.difference(last) < _groupResync) return;+ // Not stamped while the device log is still the last account's (DirectLink.syncGroup skips it+ // then): stamped, a machine reached right after an account switch went five minutes unsynced.+ if (await _deviceLog?.ownsLog() == false) return;_groupSyncedAt[machineId] = now;// Fire-and-forget from the connection handler: a state file that is locked for a moment must not// surface as an unhandled error. The next session retries.@@ -2529,6 +2728,7 @@ class AppNotifier extends ChangeNotifier {if (!visible.contains(selectedMachineId)) {selectedMachineId = machines.first.machineId;}+ final dial = <MachineState>[];for (final machine in machines) {final state = machineStates[machine.machineId]!;// ⚠️ **A machine the account says is down is not dialled, and this is the@@ -2567,27 +2767,67 @@ class AppNotifier extends ChangeNotifier {StartupTrace.mark('skipped offline machine ${machine.machineId}');continue;}- _connectMachine(state);- // ⚠️ **Only ask a machine that is already answering.** `_connectMachine`- // starts a dial; it does not finish one. Asking here regardless meant- // `waitUntilReady` sat on a handshake that had not happened yet, spending- // the inventory budget on the connection rather than on the request — and- // on a first launch it spent ALL of it, which then read as the machine- // having gone offline and triggered a `forceReconnect()` that threw the- // working socket away and started over.- //- // A machine that is not ready yet loses nothing: `_onConnectionStatus`- // calls this the moment its handshake completes, with `force: true`, which- // is the path every reconnect in the app already takes.- //- // Read off the POOL rather than through `_conn`, which would build a- // connection as a side effect of being asked about one — for a machine- // `_connectMachine` had just declined to dial, that would be this method- // quietly undoing its own decision.- if (_connectionReady(machine.machineId)) {- unawaited(_loadMachineData(state));+ dial.add(state);+ }+ unawaited(_connectAfterDeviceLog(dial, load: true));+ }++ /// Dial [states]: at once a machine this phone holds a key for, one already asking for its password+ /// and one a scanned code waits for. A machine with no key here may only be missing from this+ /// phone's copy of the device log — a computer signed in after the phone was — so the log is read+ /// first, briefly, rather than dialling a refusal. [load]: ask a machine that already answers for+ /// its data ([_dialAndLoad]).+ Future<void> _connectAfterDeviceLog(+ List<MachineState> states, {+ required bool load,+ }) async {+ final revision = _authRevision;+ bool current(MachineState state) =>+ _authWorkCurrent(revision) &&+ identical(machineStates[state.machine.machineId], state);+ final waiting = <MachineState>[];+ for (final state in states) {+ final machineId = state.machine.machineId;+ if (state.needsLink ||+ pendingPairing?.machineId == machineId ||+ await _holdsMachineKey(machineId)) {+ if (current(state)) _dialAndLoad(state, load: load);+ } else {+ waiting.add(state);}}+ if (waiting.isEmpty) return;+ await _deviceLog?.refresh().timeout(+ const Duration(seconds: 5),+ onTimeout: () {},+ );+ for (final state in waiting) {+ if (current(state)) _dialAndLoad(state, load: load);+ }+ }++ void _dialAndLoad(MachineState state, {required bool load}) {+ _connectMachine(state);+ if (!load) return;+ // ⚠️ **Only ask a machine that is already answering.** `_connectMachine`+ // starts a dial; it does not finish one. Asking here regardless meant+ // `waitUntilReady` sat on a handshake that had not happened yet, spending+ // the inventory budget on the connection rather than on the request — and+ // on a first launch it spent ALL of it, which then read as the machine+ // having gone offline and triggered a `forceReconnect()` that threw the+ // working socket away and started over.+ //+ // A machine that is not ready yet loses nothing: `_onConnectionStatus`+ // calls this the moment its handshake completes, with `force: true`, which+ // is the path every reconnect in the app already takes.+ //+ // Read off the POOL rather than through `_conn`, which would build a+ // connection as a side effect of being asked about one — for a machine+ // `_connectMachine` had just declined to dial, that would be this method+ // quietly undoing its own decision.+ if (_connectionReady(state.machine.machineId)) {+ unawaited(_loadMachineData(state));+ }}/// A user-triggered reload is in flight.@@ -2793,6 +3033,7 @@ class AppNotifier extends ChangeNotifier {var warmed = 0;var warmedAgents = 0;final warmMachines = <Machine>[];+ final warmStates = <MachineState>[];for (final entry in cached) {final machine = entry.machine;// A viewer reaches every machine through the relay; a cached entry that@@ -2862,12 +3103,14 @@ class AppNotifier extends ChangeNotifier {// from the cache are already on screen meanwhile. The warm start's job is// to have the socket ALREADY OPEN when that happens, which is where its// second and a half comes from; the request itself was never the part- // worth racing.- _connectMachine(state);+ // worth racing. A machine with no key here reads the device log first+ // ([_connectAfterDeviceLog]).+ warmStates.add(state);warmMachines.add(machine);warmed++;}if (warmed == 0) return;+ unawaited(_connectAfterDeviceLog(warmStates, load: false));// ⚠️ Published to `machines` as well, because every screen indexes agents// through THAT list (`agentIndex`, `filterableMachines`) rather than through// `machineStates` — without this the warm start would have opened the@@ -5717,6 +5960,12 @@ class AppNotifier extends ChangeNotifier {// Arrives once per machine socket, like desk_changed; concurrent reads share one.unawaited(_deviceLog?.refresh());return;+ case 'machines_changed':+ // The account's machine list changed somewhere: a machine created, renamed or deleted. The+ // payload is only a reason; the list itself is read again (once per machine socket it+ // arrives on: concurrent reads share one).+ _rereadMachines();+ 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@@ -6059,8 +6308,15 @@ 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());+ if (status == AppStatus.authenticated) {+ // The device key log too: a `device_keys_changed` sent while the phone was away reached nobody+ // — and this phone's key goes into it if the boot could not put it there.+ unawaited(_deviceLog?.ensureRegistered());+ // And the machine list, when no machine is connected to push one: the person most likely just+ // went to their computer to sign it in.+ _rereadMachinesWhileDeaf();+ _startDeafPoll();+ }// 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());@@ -6069,7 +6325,53 @@ class AppNotifier extends ChangeNotifier {/// The app went into a pocket: stop the reads that only make sense in front/// of somebody. The sockets are left to the OS, which suspends them anyway —/// [handleAppResumed] is what puts both back.- void handleAppPaused() => _desk.pause();+ void handleAppPaused() {+ _desk.pause();+ _stopDeafPoll();+ }++ /// How often a phone with no machine connected reads the machine list again. Every push+ /// (`machines_changed`, `device_keys_changed`) reaches the phone over a machine's socket; with none+ /// connected — the person signed in on the phone first and is now running `harness login` on their+ /// computer — nothing tells it that computer joined.+ @visibleForTesting+ Duration deafMachineListInterval = const Duration(seconds: 20);++ Timer? _deafMachineListTimer;+ Future<void>? _machineReread;++ void _startDeafPoll() {+ if (_disposed || status != AppStatus.authenticated) return;+ _deafMachineListTimer ??= Timer.periodic(+ deafMachineListInterval,+ (_) => _rereadMachinesWhileDeaf(),+ );+ }++ void _stopDeafPoll() {+ _deafMachineListTimer?.cancel();+ _deafMachineListTimer = null;+ }++ /// A phone that hears nothing reads the machine list again: the computer the person is signing in on+ /// right now appears, and the dial that follows reads the device log for its key first.+ void _rereadMachinesWhileDeaf() {+ if (_disposed || status != AppStatus.authenticated) return;+ if (machineStates.values.any(+ (m) => m.connectionStatus == ConnectionStatus.connected,+ )) {+ return;+ }+ _rereadMachines();+ }++ /// Read the machine list again because something other than the person asked; reads under way are+ /// shared, and a failure is left to the next one.+ void _rereadMachines() {+ _machineReread ??= refreshMachines()+ .catchError((Object _) {})+ .whenComplete(() => _machineReread = null);+ }/// What the local CLI closing this machine's socket with [code] does to the/// model — the `WsPool.onLocalFailure` path, without a socket.@@ -6094,6 +6396,7 @@ class AppNotifier extends ChangeNotifier {_channelControllers.clear();_disposed = true;_closedHistory.clear();+ _stopAccountTimers();_stopAllOfflineRetries();_stopAllAgentSyncTimers();_clearAllTurnActivity();diff --git a/mobile/lib/viewer/device_log_sync.dart b/mobile/lib/viewer/device_log_sync.dartindex 9248b9c1a..f36eadd9f 100644--- a/mobile/lib/viewer/device_log_sync.dart+++ b/mobile/lib/viewer/device_log_sync.dart@@ -309,6 +309,10 @@ class DeviceLogRebaseline {final bool otherAccount;}+/// What [ViewerDeviceLog.ensureRegistered] found: this app's key already in the log, put there just now,+/// kept out by a frozen log, or still missing (no log to read, the backend down, a refusal).+enum DeviceLogRegistration { active, registered, frozen, missing }+class ViewerDeviceLog {ViewerDeviceLog({required this.keys,@@ -362,6 +366,10 @@ class ViewerDeviceLog {/// Set while [register] runs.bool _registering = false;+ /// The [register] under way, which [ensureRegistered] lets finish before it judges.+ Future<void>? _registerRun;+ Future<DeviceLogRegistration>? _ensuring;+/// Moves on with each [beginSignIn]: a read that began after one, outside [register], ends what it/// set — a sign-in by hand that never registers must not keep this app's own removal from signing/// it out for good.@@ -378,6 +386,9 @@ class ViewerDeviceLog {/// The write of the sign-in id [beginSignIn] minted; [register] waits for it.Future<void>? _epochSaving;+ /// The sign-in by hand [beginSignIn] minted in this run, until [signedInAs] names its account.+ String? _awaitingAcct;+/// This app's key is gone from the log: sign out, once.Future<void> _signOut() async {if (_signedOut) return;@@ -399,7 +410,15 @@ class ViewerDeviceLog {/// A sign-in by hand is also what lets this app's copy of the log move to another account (keeping/// the one it leaves, to restore if it comes back) — for a short while after it ([_resetWindowMs])./// Its id is minted by [beginSignIn], which [register] calls itself when it was not called before.- Future<void> register({bool freshSignIn = false}) async {+ Future<void> register({bool freshSignIn = false}) {+ final run = _register(freshSignIn: freshSignIn);+ _registerRun = run;+ return run.whenComplete(() {+ if (identical(_registerRun, run)) _registerRun = null;+ });+ }++ Future<void> _register({required bool freshSignIn}) async {if (freshSignIn && !_freshPending) beginSignIn(fresh: true);final fresh = _freshPending;_freshPending = false;@@ -444,13 +463,43 @@ class ViewerDeviceLog {await _sleep(Duration(milliseconds: 200 + _random.nextInt(800) * (attempt + 1)));}} catch (_) {- // The next sign-in, resume or push tries again.+ // [ensureRegistered] tries again: a machine refusing this app, a socket back, the app in front.} finally {_signingInAgain = false;_registering = false;}}+ /// Put this app's key into the log when it is not there yet. [register] can end without it — no log+ /// to read, the backend down, five lost races, a refusal — and then no machine will trust this app,+ /// so this is asked again whenever that matters: a machine refusing this app, a socket coming back,+ /// the app in front again. A frozen log is left as it is: only a review unfreezes it. Concurrent+ /// calls share one run. Never throws.+ Future<DeviceLogRegistration> ensureRegistered() =>+ _ensuring ??= _ensureRegistered().whenComplete(() => _ensuring = null);++ Future<DeviceLogRegistration> _ensureRegistered() async {+ try {+ // A register already under way (the boot's) decides first: a second one beside it would race it.+ await _registerRun;+ await refresh();+ if (await _registration() case final known?) return known;+ await register();+ return await _registration() == DeviceLogRegistration.active+ ? DeviceLogRegistration.registered+ : DeviceLogRegistration.missing;+ } catch (_) {+ return DeviceLogRegistration.missing;+ }+ }++ /// Where this app's key stands in the file: null when it is not there and nothing keeps it out.+ Future<DeviceLogRegistration?> _registration() async {+ final file = await _read();+ if (file.state?.active.containsKey(await _selfPub()) ?? false) return DeviceLogRegistration.active;+ return file.frozen != null ? DeviceLogRegistration.frozen : null;+ }+/// The app knows who is signed in — call it synchronously, before anything that reads the log (a/// restored pane, a machine list, a connection) can start, then [register]. [fresh]: the person/// signed in by hand just now (`DirectAuth.consumeFreshSignIn()`); its id is minted here, so a read@@ -463,10 +512,12 @@ class ViewerDeviceLog {// for the read that comes first ([_doRefresh] ends it), or until [register] takes over._signingInAgain = fresh;_signInRound++;+ _awaitingAcct = null;if (!fresh) return;final previous = _epoch;final minted = _mintEpoch();_epoch = minted;+ _awaitingAcct = minted;_epochSaving = keys.writeSignInEpoch(minted).then((_) {},onError: (Object _) {@@ -476,6 +527,23 @@ class ViewerDeviceLog {);}+ /// Who the person just signed in as, by hand: the profile's user id (`/api/auth/me`), which is what+ /// the log names its account by. Kept beside the sign-in id, so the first read of that account+ /// starts the list over whenever it comes ([_mayStartOver]). Only for the sign-in by hand+ /// [beginSignIn] minted in this run — a stored session (the app opening) records nothing. Never+ /// throws.+ Future<void> signedInAs(String acct) async {+ final epoch = _awaitingAcct;+ if (epoch == null || acct.isEmpty) return;+ _awaitingAcct = null;+ try {+ await _epochSaving;+ if (_epoch == epoch) await keys.writeSignInAcct(epoch, acct);+ } catch (_) {+ // Not recorded: the sign-in falls back to the short window.+ }+ }+/// Read and verify whatever the log gained. Concurrent calls share one read. Never throws.Future<void> refresh() => _refreshing ??= _doRefresh().catchError((Object _) {}).whenComplete(() => _refreshing = null);@@ -512,16 +580,35 @@ class ViewerDeviceLog {'${[for (var i = 0; i < 16; i++) _secure.nextInt(256).toRadixString(16).padLeft(2, '0')].join()}@${_now()}';static final _secure = Random.secure();- /// Whether [local] — a sign-in by hand the file is not yet the log of — may start it over for another- /// account: never an adopted one, and only shortly after it was made. A backend that holds the log- /// back after a sign-in must not keep that door open, to name another account days later.- bool _mayStartOver(String local) {+ /// Whether [local] — a sign-in by hand the file is not yet the log of — may start it over for [acct]:+ /// never an adopted one; the account the profile named for it ([signedInAs]) whenever its first read+ /// comes, and no other; with none named, any only shortly after it was made. A backend that holds the+ /// log back after a sign-in must not keep that door open, to name another account days later.+ Future<bool> _mayStartOver(String local, String acct) async {if (local.startsWith(_adoptedSignIn)) return false;+ try {+ final named = await keys.signInAcct(local);+ if (named != null) return named == acct;+ } catch (_) {+ // Unreadable: the window alone decides.+ }final made = RegExp(r'@(\d{1,15})$').firstMatch(local);if (made == null) return false;return (_now() - int.parse(made.group(1)!)).abs() <= _resetWindowMs;}+ /// Whether the log this app holds is the one of the sign-in it is under — false while it may still be+ /// the account just left, before the first read under a new sign-in. No log yet is nobody's: true.+ /// Never throws (false when the file cannot be read).+ Future<bool> ownsLog() async {+ try {+ final file = await _read();+ return file.state == null || await _ownsFile(file);+ } catch (_) {+ return false;+ }+ }+/// Whether [file] is the log of the sign-in this app is under (or that cannot be told). Until a read/// of it under a new sign-in it may be the account just left: what a machine gossips is not judged/// against it — a machine of the new account would read as a fork of the old one.@@ -562,28 +649,39 @@ class ViewerDeviceLog {}}- /// Keep [file] — the log of an account this app is leaving — to restore if it comes back. Under the lock.- Future<void> _archiveIn(_File file) async {+ /// Keep [file] — the log of an account this app is leaving — to restore if it comes back, with what+ /// this app trusted under it ([trust]: [ViewerKeyStore.trustSnapshot]). [keep]: the account about+ /// to be restored, never the one dropped to make room — it was, when it was the oldest kept, and+ /// coming back to it then started its list over. Under the lock.+ Future<void> _archiveIn(_File file, {Map<String, Object?>? trust, String? keep}) async {final acct = file.state?.acct;if (acct == null) return;final all = await _archived()..remove(acct);- all[acct] = file.toJson();- while (all.length > _archivedKept) {- all.remove(all.keys.first);+ all[acct] = {...file.toJson(), 'trust': ?trust};+ while (all.length > _archivedKept + (all.containsKey(keep) ? 1 : 0)) {+ all.remove(all.keys.firstWhere((k) => k != keep));}await keys.writeDeviceLogArchive(all);}/// The kept log of [acct], made the live file (this sign-in's: [owner]) and only then taken out of/// the archive — a crash in between leaves it in both, never in neither. Null when there is none.- /// Under the lock.- Future<_File?> _restoreIn(String acct, String? owner) async {- final kept = _File.parse((await _archived())[acct]);+ /// With [swapTrust] (another account's log was live), what this app trusted under [acct] is trusted+ /// again — and nothing of the account left. Under the lock.+ Future<_File?> _restoreIn(String acct, String? owner, {required bool swapTrust}) async {+ final raw = (await _archived())[acct];+ final kept = _File.parse(raw);if (kept.state?.acct != acct) return null;kept.owner = owner ?? kept.owner;await _carrySuspensionsIn(kept);await _write(kept);+ if (swapTrust) {+ final trust = _trustOf(raw);+ await keys.writeTrust(trust ?? const {});+ // Kept by a build that did not keep trust with it: what the log names is trusted again.+ if (trust == null && kept.frozen == null) await _trust(kept.state!.active.values.toList());+ }final all = await _archived()..remove(acct);await keys.writeDeviceLogArchive(all);@@ -608,6 +706,10 @@ class ViewerDeviceLog {..pending = {...file.pending, ...carried}.toList();}+ /// What this app trusted under a kept log ([_archiveIn]); null in one kept before that existed.+ static Map<Object?, Object?>? _trustOf(Object? kept) =>+ kept is Map && kept['trust'] is Map ? kept['trust'] as Map<Object?, Object?> : null;+/// A suspension lifted here holds for every kept account too: none of them keeps [pubs] out. Under/// the lock.Future<void> _unsuspendArchivedIn(Iterable<String> pubs) async {@@ -618,7 +720,7 @@ class ViewerDeviceLog {final f = _File.parse(e.value);if (!f.suspended.any(lift.contains)) continue;f.suspended = [for (final k in f.suspended) if (!lift.contains(k)) k];- all[e.key] = f.toJson();+ all[e.key] = {...f.toJson(), 'trust': ?_trustOf(e.value)};changed = true;}if (changed) await keys.writeDeviceLogArchive(all);@@ -769,7 +871,7 @@ class ViewerDeviceLog {// Another account only after a sign-in by hand here. Otherwise it is the backend saying so// — and starting over would clear every mark a fork put on the list, the real log then// adopted whole.- if (local == null || !signedInAgain || !_mayStartOver(local)) {+ if (local == null || !signedInAgain || !await _mayStartOver(local, got.acct)) {await _freezeIn(file, 'invalid', effects);return false;}@@ -781,10 +883,17 @@ class ViewerDeviceLog {}}if (reset) {- if (file.state != null) await _archiveIn(file);+ // Another account's log was live: it is kept with what this app trusted under it, none of+ // which this account's machines are told of or trusted by. A first read keeps the pins: they+ // are links made before the log existed.+ final leaving = file.state != null;+ if (leaving) {+ await _archiveIn(file, trust: await keys.trustSnapshot(), keep: got.acct);+ _frozenPeers.clear();+ }// Back to an account this app was signed in to before: its log as verified then, and every// mark on it (frozen, suspended, pending), go on from where they were.- final kept = await _restoreIn(got.acct, local);+ final kept = await _restoreIn(got.acct, local, swapTrust: leaving);if (kept != null) {bootstrap = (kept.state?.head.seq ?? 0) == 0;return true;@@ -792,7 +901,9 @@ class ViewerDeviceLog {// First read, or signed in to another account here: that account's log starts from nothing.// `joinedSeq` starts at 0 and follows the head of each page this app VERIFIES ([_acceptIn]):// never the head the backend merely claims, or it could park it far ahead and have every key- // it forges below that adopted without a word. `preLog` is what was trusted already.+ // it forges below that adopted without a word. `preLog` is what was trusted already — under+ // this account, so nothing when another one's log was live.+ if (leaving) await keys.writeTrust(const {});file = _File(DevLogState.empty(got.acct),[],@@ -1182,7 +1293,12 @@ class ViewerDeviceLog {// live file, or — for another account — the one kept when this app left it (its marks go on), or// else nothing (every key on it is new here). Never against the account being left.final kept = same ? null : await _archivedFileIn(next.acct);- final base = same ? file : kept ?? _File(null, [], null, 0, joinedSeq: 0, preLog: [...file.preLog]);+ // Moving from another account's live log: what this app trusted under each goes with it.+ final switching = file.state != null && !same;+ final keptTrust = kept == null ? null : _trustOf((await _archived())[next.acct]);+ final base = same+ ? file+ : kept ?? _File(null, [], null, 0, joinedSeq: 0, preLog: switching ? [] : [...file.preLog]);final before = base.state?.active ?? const <String, DevLogMember>{};final added = [for (final m in next.active.values) if (before[m.pub] == null) m];final removed = [for (final m in before.values) if (next.active[m.pub] == null) m];@@ -1204,7 +1320,10 @@ class ViewerDeviceLog {// The reviewed list is another account's: the one this app leaves is kept, as on a sign-in (and// what a fork suspended in it stays suspended here) — and a kept one of the reviewed account// goes on from where it was.- if (file.state != null && !same) await _archiveIn(file);+ if (switching) {+ await _archiveIn(file, trust: await keys.trustSnapshot());+ _frozenPeers.clear();+ }base..state = next..recent = parsed@@ -1226,6 +1345,7 @@ class ViewerDeviceLog {await _carrySuspensionsIn(base);// Live first, then out of the archive: a crash in between leaves it in both, never in neither.await _write(base);+ if (switching) await keys.writeTrust(keptTrust ?? const {});if (kept != null) {final all = await _archived();if (all.remove(next.acct) != null) await keys.writeDeviceLogArchive(all);@@ -1252,6 +1372,7 @@ class ViewerDeviceLog {// The newest hashes let a peer that finds the logs forked say where they split.final from = max(0, state.hashes.length - _gossipHashes);return {+ 'acct': state.acct,'head': state.head.toJson(),'frozen': file.frozen != null,'hashes': [@@ -1269,6 +1390,9 @@ class ViewerDeviceLog {// A sign-in waiting for its first read: the file may be the account left behind, and a machine of// the new one would freeze it as a fork. Nothing is judged until the log is this sign-in's.if (!await _ownsFile(file)) return;+ // Another account's log (a machine still signed in to it): nothing in it says anything about this+ // one. A machine too old to say which account is heard as before.+ if (raw['acct'] != null && raw['acct'] != state.acct) return;_frozenPeers[machinePub] = raw['frozen'] == true;final theirs = DevLogHead.fromJson(raw['head']);if (theirs == null) return;diff --git a/mobile/lib/viewer/direct_link.dart b/mobile/lib/viewer/direct_link.dartindex 755d827dd..fe5187375 100644--- a/mobile/lib/viewer/direct_link.dart+++ b/mobile/lib/viewer/direct_link.dart@@ -164,13 +164,16 @@ class DirectLink implements PeerLinkClient {String machineId, {required String label,}) async {+ final log = deviceLog;+ // Until the log is this sign-in's, the pins and the roster may still be the account just left's:+ // none of it goes to this account's machines, and nothing they say is taken in beside it.+ if (log != null && !await log.ownsLog()) return GroupSyncOutcome.none;final String token;try {token = await auth.accessToken();} catch (_) {return GroupSyncOutcome.none;}- final log = deviceLog;return syncTrustGroup(machineId: machineId,keys: keys,diff --git a/mobile/lib/viewer/viewer_key_store.dart b/mobile/lib/viewer/viewer_key_store.dartindex 604a1879a..b2a0b3fab 100644--- a/mobile/lib/viewer/viewer_key_store.dart+++ b/mobile/lib/viewer/viewer_key_store.dart@@ -81,6 +81,7 @@ class ViewerKeyStore {static const _devLogKey = 'viewer_e2ee_devlog';static const _devLogArchiveKey = 'viewer_e2ee_devlog_archive';static const _signInKey = 'viewer_e2ee_sign_in';+ static const _signInAcctKey = 'viewer_e2ee_sign_in_acct';/// Minted on first use and kept: every linked machine has pinned it.Future<E2eeIdentity> identity() => _identity ??= _heldUnlessItFails(@@ -222,6 +223,51 @@ class ViewerKeyStore {Future<void> writeSignInEpoch(String epoch) =>_storage.write(_signInKey, epoch);+ /// The account the sign-in by hand [epoch] was made to, as the profile said right after it; null+ /// when none was recorded for that sign-in (one recorded for an earlier sign-in never answers).+ Future<String?> signInAcct(String epoch) async {+ final raw = await _storage.read(_signInAcctKey);+ if (raw == null) return null;+ try {+ final decoded = jsonDecode(raw);+ if (decoded is Map &&+ decoded['epoch'] == epoch &&+ decoded['acct'] is String) {+ return decoded['acct'] as String;+ }+ } on FormatException {+ // Unreadable: none recorded.+ }+ return null;+ }++ Future<void> writeSignInAcct(String epoch, String acct) => _storage.write(+ _signInAcctKey,+ jsonEncode({'epoch': epoch, 'acct': acct}),+ );++ /// What this device trusts — its pins and its trust group — as stored: kept with an account's+ /// device key log when this device signs in to another one ([writeTrust] puts it back).+ Future<Map<String, Object?>> trustSnapshot() async => {+ 'peers': await _storage.read(_peersKey),+ 'group': await _storage.read(_groupKey),+ };++ /// Trust exactly what [snapshot] ([trustSnapshot]) holds; an empty one trusts nothing. The held+ /// pins ([_peers]) are let go of on both sides of the write, so none is believed from before it.+ Future<void> writeTrust(Map<Object?, Object?> snapshot) async {+ _peers = null;+ try {+ await _put(_peersKey, snapshot['peers']);+ } finally {+ _peers = null;+ }+ await _put(_groupKey, snapshot['group']);+ }++ Future<void> _put(String key, Object? value) =>+ value is String ? _storage.write(key, value) : _storage.delete(key);+/// 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. The log as this device/// verified it stays, with every mark on it: signing in again to the same account goes on from there.diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dartindex 170f34789..d96ffa6f1 100644--- a/mobile/lib/ws/ws_conn.dart+++ b/mobile/lib/ws/ws_conn.dart@@ -542,6 +542,10 @@ class WsConn {/// three — only a link can — so this stops and says so the way the CLI's own relay does, with/// 4404.void _refusePeer(String reason) {+ appLog.info(+ 'ws',+ 'refused ${machineId.length > 8 ? machineId.substring(0, 8) : machineId}: $reason',+ );_closing = true;_ready = false;_disposePlugin();diff --git a/mobile/test/app_state_pairing_test.dart b/mobile/test/app_state_pairing_test.dartindex 323a4e1d2..6ab05f180 100644--- a/mobile/test/app_state_pairing_test.dart+++ b/mobile/test/app_state_pairing_test.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/auth/cli_link.dart';import 'package:harness_mobile/core/models.dart';@@ -10,13 +12,28 @@ import 'viewer_app_fixture.dart';/// Linking a phone to a machine: by its password, by the code an "Add phone" QR/// carries, and taking the link away again.void main() {+ /// [machineId] refuses this phone for want of a link, and goes on refusing after the device list+ /// was checked (two short rounds, each dial refused again): it wants its password.+ Future<void> refuse(ViewerRig rig, String machineId) async {+ rig.app+ ..trustSettleRound = Duration.zero+ ..onRedialForTest = (id) => scheduleMicrotask(+ () => rig.app.localFailureForTest(id, 4404, 'NO_PEER_LINK'),+ );+ rig.app.localFailureForTest(machineId, 4404, 'NO_PEER_LINK');+ for (var i = 0; i < 200 && !rig.app.stateOf(machineId)!.needsLink; i++) {+ await Future<void>.delayed(const Duration(milliseconds: 5));+ }+ expect(rig.app.stateOf(machineId)!.needsLink, isTrue);+ }+/// Signed in to an account with one machine, `m`, that wants its password.Future<ViewerRig> lockedMachine() async {final rig = viewerApp();rig.api.onMachines = () async => [remoteMachine('m')];await rig.app.bootstrap();await settle();- rig.app.localFailureForTest('m', 4404, 'NO_PEER_LINK');+ await refuse(rig, 'm');return rig;}@@ -70,8 +87,8 @@ void main() {rig.api.onMachines = () async => [remoteMachine('m'), remoteMachine('n')];await rig.app.bootstrap();await settle();- rig.app.localFailureForTest('m', 4404, 'NO_PEER_LINK');- rig.app.localFailureForTest('n', 4404, 'NO_PEER_LINK');+ await refuse(rig, 'm');+ await refuse(rig, 'n');rig.links.connectResult = const CliLinkConnectResult(linkedMachineId: 'n',);@@ -182,6 +199,8 @@ void main() {rig.app.localFailureForTest('m', 4404, 'NO_PEER_LINK');expect(rig.app.pendingPairing, (machineId: 'm', code: 'K7QM'));+ // Not settled against the device list first: the pairing screen is the way in, at once.+ expect(rig.app.stateOf('m')!.needsLink, isTrue);},);});@@ -247,9 +266,9 @@ void main() {rig.api.onMachines = () async => [remoteMachine('m')];await rig.app.bootstrap();await settle();+ await refuse(rig, 'm');final asked = rig.conn('m').requests.length;- rig.app.localFailureForTest('m', 4404, 'NO_PEER_LINK');await Future<void>.delayed(AppNotifier.offlineRetryInterval + const Duration(milliseconds: 200),);diff --git a/mobile/test/encrypted_down_types_test.dart b/mobile/test/encrypted_down_types_test.dartindex 6d073b1eb..a7aa0606c 100644--- a/mobile/test/encrypted_down_types_test.dart+++ b/mobile/test/encrypted_down_types_test.dart@@ -51,8 +51,16 @@ void main() {'ENCRYPTED_DOWN_TYPES = new Set<string>([',);final frames = cli('lib/e2ee/applicationFrames.ts');- machineRequests = namesIn(frames, 'MACHINE_REQUESTS = new Set([');- pairRequests = namesIn(frames, 'PAIR_REQUESTS = new Set([');+ final relay = cli('lib/relayFrames.ts');+ // `MACHINE_REQUESTS` also spreads the owner commands in; those are read where they are declared,+ // as are the pair frames.+ machineRequests = {+ ...namesIn(frames, 'MACHINE_REQUESTS = new Set(['),+ ...namesIn(relay, 'OWNER_COMMAND_TYPES = new Set(['),+ // ...which spread the route commands in from their own set.+ ...namesIn(relay, 'ROUTE_COMMAND_TYPES: ReadonlySet<string> = new Set(['),+ };+ pairRequests = namesIn(relay, 'PAIR_REQUESTS = new Set([');unwrapped = {...pairRequests,...core,@@ -60,7 +68,7 @@ void main() {...namesIn(frames, 'FLEET_REQUESTS = new Set(['),...namesIn(cli('sharing/protocol.ts'), 'SHARE_REQUEST_TYPES = new Set(['),...namesIn(cli('teams/wire.ts'), 'TEAM_REQUEST_TYPES = new Set(['),- ...namesIn(cli('lib/viewerWire.ts'), 'VIEWER_DOWN_TYPES = new Set(['),+ ...namesIn(cli('lib/viewerFrames.ts'), 'VIEWER_DOWN_TYPES = new Set(['),};});diff --git a/mobile/test/state/device_pending_sync_test.dart b/mobile/test/state/device_pending_sync_test.dartindex 45a776439..2c45d9462 100644--- a/mobile/test/state/device_pending_sync_test.dart+++ b/mobile/test/state/device_pending_sync_test.dart@@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/auth/auth_session.dart';import 'package:harness_mobile/core/config.dart';import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/core/models.dart';import 'package:harness_mobile/e2ee/bytes.dart';import 'package:harness_mobile/e2ee/keys.dart';import 'package:harness_mobile/notify/system_notices.dart';@@ -101,7 +102,11 @@ class _Backend {],);+ /// Every append is refused while set: this phone never gets into the log.+ bool refuseAppends = false;+Future<DeviceLogAppendAnswer?> append(DevLogEntry entry) async {+ if (refuseAppends) return (head: null, error: 'FORBIDDEN');if (entry.seq != state.head.seq + 1 || entry.prev != state.head.hash) {return (head: state.head, error: 'STALE_HEAD');}@@ -943,6 +948,19 @@ void main() {},);+ test('a sign-in by hand keeps the profile\'s account beside its id; a stored session does not', () async {+ final (first, _) = await launch(fresh: true, profileId: _acct);+ expect(jsonDecode(disk.values['viewer_e2ee_sign_in_acct']!), {+ 'epoch': disk.values['viewer_e2ee_sign_in'],+ 'acct': _acct,+ });+ first.dispose();+ apps.remove(first);+ disk.values.remove('viewer_e2ee_sign_in_acct');+ await launch(profileId: _acct);+ expect(disk.values['viewer_e2ee_sign_in_acct'], isNull);+ });+test('a sign-in by hand mints the log\'s own id, not the profile\'s',() async {@@ -991,4 +1009,200 @@ void main() {);});});++ // A phone signed in first, then `harness login` on a computer: the machine is new to this phone's+ // copy of the log (or the phone to the machine's), and the refusal says nothing more than "early".+ // It is settled — the phone joins the log, reads it, dials again — before a password is asked for.+ group('a machine that refuses this phone for want of trust', () {+ Future<AppNotifier> withMachine() async {+ final (app, _) = await launch();+ (app.api as _Api).onMachines = () async => [remoteMachine(_mid2)];+ await app.refreshMachines();+ await settle();+ return app;+ }++ Future<void> until(bool Function() done) async {+ for (var i = 0; i < 500 && !done(); i++) {+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }+ }++ /// The phone's own key store, whose pins it holds in memory.+ ViewerKeyStore keysOf(AppNotifier app) => app.viewer.keys;++ test(+ 'the log names it: pinned and dialled again, no password asked',+ () async {+ final app = await withMachine();+ final keys = keysOf(app);+ await backend.add(box2, 'machine', _mid2, 'box2');+ expect(+ await keys.peer(_mid2),+ isNull,+ reason: 'the phone has not read the log since',+ );+ final redialled = <String>[];+ app.onRedialForTest = redialled.add;++ app.localFailureForTest(_mid2, 4404, 'NO_PEER_LINK');+ expect(+ app.stateOf(_mid2)!.needsLink,+ isFalse,+ reason: 'still connecting while it is settled',+ );+ app.connectionStatusForTest(_mid2, ConnectionStatus.disconnected);+ expect(+ app.stateOf(_mid2)!.connectionStatus,+ ConnectionStatus.connecting,+ );+ await until(() => redialled.isNotEmpty);++ expect(redialled, [_mid2]);+ expect(app.stateOf(_mid2)!.needsLink, isFalse);+ expect(await keys.peer(_mid2), isNotNull);+ },+ );++ test(+ 'a key that lands while it is settled ends the wait at once',+ () async {+ final app = await withMachine()+ ..trustSettleRound = const Duration(seconds: 30);+ final redialled = <String>[];+ app.onRedialForTest = redialled.add;+ app.localFailureForTest(_mid2, 4404, 'NO_PEER_LINK');+ await settle();+ await backend.add(box2, 'machine', _mid2, 'box2');+ await app.deviceLog!.refresh(); // a `device_keys_changed`+ await until(() => redialled.isNotEmpty);+ expect(redialled, [_mid2]);+ expect(app.stateOf(_mid2)!.needsLink, isFalse);+ },+ );++ test('denied once, then let in: never asks for a password', () async {+ final app = await withMachine()+ ..trustDeniedWait = const Duration(milliseconds: 10);+ await keysOf(app).pin(_mid2, box2.pub, label: 'box2');+ final redialled = <String>[];+ app.onRedialForTest = redialled.add;++ app.localFailureForTest(_mid2, 4404, 'E2E_DENIED');+ await until(() => redialled.isNotEmpty);+ await settle();++ expect(redialled, [_mid2]);+ expect(app.stateOf(_mid2)!.needsLink, isFalse);+ expect(+ app.stateOf(_mid2)!.agentLoadStatus,+ isNot(AgentLoadStatus.needsLink),+ );+ });++ test('still refused after the grace: the password it is', () async {+ final app = await withMachine()+ ..trustSettleRound = const Duration(milliseconds: 20);+ var redials = 0;+ // Each dial again is refused again: nothing names this machine.+ app.onRedialForTest = (id) {+ redials++;+ scheduleMicrotask(+ () => app.localFailureForTest(id, 4404, 'NO_PEER_LINK'),+ );+ };++ app.localFailureForTest(_mid2, 4404, 'NO_PEER_LINK');+ await until(() => app.stateOf(_mid2)!.needsLink);++ expect(app.stateOf(_mid2)!.needsLink, isTrue);+ expect(app.stateOf(_mid2)!.agentLoadStatus, AgentLoadStatus.needsLink);+ expect(redials, 2, reason: 'two rounds, then the password');+ expect(app.deviceListNeedsReview, isFalse);+ });++ test('a frozen log settles nothing: the password at once, and the list asks for a review', () async {+ backend.refuseAppends =+ true; // this phone is not in it, and cannot get in while it is frozen+ final app = await withMachine();+ final keys = keysOf(app);+ final file = Map<String, Object?>.from(await keys.deviceLog() as Map);+ file['frozen'] = {+ 'reason': 'fork',+ 'at': 1,+ 'lastGoodHead': backend.state.head.toJson(),+ };+ await keys.writeDeviceLog(file);+ final redialled = <String>[];+ app.onRedialForTest = redialled.add;++ app.localFailureForTest(_mid2, 4404, 'NO_PEER_LINK');+ await until(+ () => app.stateOf(_mid2)!.needsLink && app.deviceListNeedsReview,+ );++ expect(app.stateOf(_mid2)!.needsLink, isTrue);+ expect(app.deviceListNeedsReview, isTrue);+ expect(redialled, isEmpty);++ await app.logout();+ expect(+ app.deviceListNeedsReview,+ isFalse,+ reason: 'the next sign-in may be another account',+ );+ });+ });++ group('a phone that hears no machine', () {+ test('reads the machine list again on its own, and on coming back, until a machine connects', () async {+ final (app, _) = await launch();+ final api = app.api as _Api;+ api.onMachines = () async => [remoteMachine(_mid2)];+ app.handleAppPaused();+ app.deafMachineListInterval = const Duration(milliseconds: 40);++ // Back in front (the person was signing in their computer): asked at once, then now and then.+ var before = api.machineFetches;+ app.handleAppResumed();+ await settle();+ expect(api.machineFetches, greaterThan(before));+ before = api.machineFetches;+ await Future<void>.delayed(const Duration(milliseconds: 130));+ await settle();+ expect(api.machineFetches, greaterThan(before));++ // In a pocket: not asked at all.+ app.handleAppPaused();+ await settle();+ before = api.machineFetches;+ await Future<void>.delayed(const Duration(milliseconds: 130));+ expect(api.machineFetches, before);++ // A machine connected: its pushes say what changes.+ app.handleAppResumed();+ await settle();+ app.connectionStatusForTest(_mid2, ConnectionStatus.connected);+ await settle();+ before = api.machineFetches;+ await Future<void>.delayed(const Duration(milliseconds: 130));+ await settle();+ expect(api.machineFetches, before);+ });++ test('a `machines_changed` push reads the list again', () async {+ final (app, _) = await launch();+ final api = app.api as _Api;+ api.onMachines = () async => [remoteMachine(_mid2)];+ await app.refreshMachines();+ await settle();+ final before = api.machineFetches;+ await app.handleMachineEventForTest(_mid2, {+ 'type': 'machines_changed',+ 'payload': {'reason': 'created'},+ });+ await settle();+ expect(api.machineFetches, before + 1);+ });+ });}diff --git a/mobile/test/unlock_by_scan_test.dart b/mobile/test/unlock_by_scan_test.dartindex 675434ba4..4e9abfee1 100644--- a/mobile/test/unlock_by_scan_test.dart+++ b/mobile/test/unlock_by_scan_test.dart@@ -154,4 +154,21 @@ void main() {);},);++ testWidgets(+ 'a frozen device list says so beside the password, with the way to review it',+ (tester) async {+ final (app, _) = await pump(tester, _Links(const CliLinkConnectResult()));+ expect(find.text('Your device list needs a review.'), findsNothing);++ app.deviceListNeedsReviewForTest = true;+ await tester.pump();+ expect(find.text('Your device list needs a review.'), findsOneWidget);+ expect(find.byKey(const ValueKey('device-list-review')), findsOneWidget);+ expect(+ find.byKey(const Key('remote-password-connect-field')),+ findsOneWidget,+ );+ },+ );}diff --git a/mobile/test/viewer/device_log_sync_test.dart b/mobile/test/viewer/device_log_sync_test.dartindex 3217a5649..dbfaa7f29 100644--- a/mobile/test/viewer/device_log_sync_test.dart+++ b/mobile/test/viewer/device_log_sync_test.dart@@ -321,6 +321,45 @@ void main() {expect((await log.list()).frozen?.reason, 'fork');});+ group('ensureRegistered', () {+ test('a boot that could not register is made good once the backend answers', () async {+ await backend.add(box2, 'machine', _mid2, 'box2');+ final log = makeLog();+ backend.offline = true;+ await log.register();+ final me = b64e((await keys.identity()).pub);+ expect(backend.state.active[me], isNull, reason: 'no log to read, nothing appended');++ backend.offline = false;+ expect(await log.ensureRegistered(), DeviceLogRegistration.registered);+ expect(backend.state.active[me]?.kind, 'viewer');+ expect(await keys.peer(_mid2), isNotNull, reason: 'the read that came with it pinned the machine');+ });++ test('already in the log: reads it and appends nothing', () async {+ final log = makeLog();+ await log.register();+ final entries = backend.entries.length;+ await backend.add(box2, 'machine', _mid2, 'box2');+ expect(await log.ensureRegistered(), DeviceLogRegistration.active);+ expect(backend.entries.length, entries + 1);+ expect(await keys.peer(_mid2), isNotNull);+ });++ test('a frozen log is left as it is', () async {+ await backend.add(box2, 'machine', _mid2, 'box2');+ await backend.add(box3, 'machine', _mid3, 'box3');+ final log = makeLog();+ await log.refresh();+ backend.lie = backend.entries.sublist(0, 1);+ await log.refresh();+ expect((await log.list()).frozen, isNotNull);+ final entries = backend.entries.length;+ expect(await log.ensureRegistered(), DeviceLogRegistration.frozen);+ expect(backend.entries.length, entries);+ });+ });+test('says which machines report a frozen log', () async {await backend.add(box2, 'machine', _mid2, 'box2');final log = makeLog();@@ -598,6 +637,17 @@ void main() {final g = (await log.gossip())!;expect((g['hashes']! as List).length, 2);expect((g['hashes']! as List).last, {'seq': 2, 'hash': backend.state.head.hash});+ expect(g['acct'], _acct);+ });++ test('a machine gossiping another account\'s log is not heard: no freeze, no tail', () async {+ final (log, other) = await forkedSetup();+ await log.heard(b64e(box2.pub), {...gossipOf(other.state), 'acct': 'acct-2', 'frozen': true});+ expect((await log.list()).frozen, isNull);+ expect((await log.list()).frozenPeers, isEmpty);+ // The same gossip saying no account is judged as before.+ await log.heard(b64e(box2.pub), gossipOf(other.state));+ expect((await log.list()).frozen?.reason, 'fork');});});@@ -1179,6 +1229,78 @@ void main() {expect((await keys.deviceLogArchive()).keys, ['acct-b0', 'acct-b1', 'acct-b2', 'acct-b3']);});+ test('the oldest kept account is not the one dropped when it is the one being come back to', () async {+ var current = backend;+ final log = at(() => current);+ await backend.add(box2, 'machine', _mid2, 'box2');+ await log.register(freshSignIn: true);+ for (var i = 0; i < 4; i++) {+ current = _Backend('acct-b$i');+ await log.register(freshSignIn: true);+ }+ // Four kept, the first account the oldest of them: back to it, it is restored, not started over.+ expect((await keys.deviceLogArchive()).keys.first, _acct);+ current = backend;+ await log.register(freshSignIn: true);+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect(await keys.peer(_mid2), isNotNull, reason: 'what it trusted comes back with it');+ expect((await keys.deviceLogArchive()).keys, ['acct-b0', 'acct-b1', 'acct-b2', 'acct-b3']);+ });++ group('what this app trusts is the account\'s', () {+ final linked = 'p' * 32;++ /// Signed in by hand to the first account (box2 on its log, and a machine linked by password),+ /// then to acct-2 (evil's machine on its log).+ Future<ViewerDeviceLog> switched() async {+ var current = backend;+ final log = at(() => current);+ await keys.pin(linked, box3.pub, label: 'linked');+ await backend.add(box2, 'machine', _mid2, 'box2');+ await log.register(freshSignIn: true);+ expect(await keys.peer(linked), isNotNull, reason: 'the first read keeps what was pinned before');+ expect((await file())['preLog'], contains(b64e(box3.pub)));+ final other = _Backend('acct-2');+ await other.add(evil, 'machine', _mid3, 'evil');+ current = other;+ await log.register(freshSignIn: true);+ expect(((await file())['state'] as Map)['acct'], 'acct-2');+ current = backend;+ return log;+ }++ test('the account left is not trusted under another, nor known to it', () async {+ await switched();+ expect(await keys.peer(_mid2), isNull);+ expect(await keys.peer(linked), isNull);+ expect(b64e((await keys.peer(_mid3))!.pub), b64e(evil.pub));+ expect(await rosterPubs(), isNot(contains(b64e(box2.pub))));+ expect((await file())['preLog'], isEmpty);+ });++ test('and comes back with it, without what the other account trusted', () async {+ final log = await switched();+ await log.register(freshSignIn: true);+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect(await keys.peer(_mid2), isNotNull);+ expect(await keys.peer(linked), isNotNull);+ expect(await keys.peer(_mid3), isNull);+ expect(await rosterPubs(), isNot(contains(b64e(evil.pub))));+ expect((await keys.deviceLogArchive())['acct-2'], containsPair('trust', isNotNull));+ });++ test('a list kept before trust was: what its log names comes back', () async {+ final log = await switched();+ final all = await keys.deviceLogArchive();+ all[_acct] = {...(all[_acct] as Map).cast<String, Object?>()}..remove('trust');+ await keys.writeDeviceLogArchive(all);+ await log.register(freshSignIn: true);+ expect(await keys.peer(_mid2), isNotNull);+ expect(await keys.peer(linked), isNull);+ expect(await keys.peer(_mid3), isNull);+ });+ });+test('a session from before sign-in ids takes the list over but never starts it over', () async {var current = backend;final log = at(() => current);@@ -1484,7 +1606,7 @@ void main() {/// Signed in on [backend] (box3 new there), then the sign-in [epoch] (not yet the list's), whose/// first read — at [now] — is of another account.- Future<void> later(String epoch) async {+ Future<void> later(String epoch, {String? acct}) async {var current = backend;final log = at(() => current);await backend.add(box2, 'machine', _mid2, 'box2');@@ -1493,6 +1615,7 @@ void main() {await backend.add(box3, 'machine', _mid3, 'box3');await log.refresh();await keys.writeSignInEpoch(epoch);+ if (acct != null) await keys.writeSignInAcct(epoch, acct);final restarted = at(() => current, now: now);current = _Backend('acct-2');await restarted.refresh();@@ -1512,11 +1635,32 @@ void main() {expect((await file())['frozen'], containsPair('reason', 'invalid'));});+ test('one made long ago to the very account read starts it over', () async {+ await later('${'f' * 32}@${now - 11 * 60 * 1000}', acct: 'acct-2');+ expect(((await file())['state'] as Map)['acct'], 'acct-2');+ expect((await file())['frozen'], isNull);+ expect((await keys.deviceLogArchive()).keys, [_acct]);+ });++ test('one made long ago to another account than the one read only freezes', () async {+ await later('${'f' * 32}@${now - 11 * 60 * 1000}', acct: 'acct-3');+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect((await file())['frozen'], containsPair('reason', 'invalid'));+ });+test('one made just now starts it over', () async {await later('${'f' * 32}@${now - 9 * 60 * 1000}');expect(((await file())['state'] as Map)['acct'], 'acct-2');expect((await keys.deviceLogArchive()).keys, [_acct]);});++ test('one made just now to another account than the one read only freezes', () async {+ // The profile named this sign-in's account: a different one minutes later is the backend's word+ // against it, which the window must not let through.+ await later('${'f' * 32}@${now - 60 * 1000}', acct: 'acct-3');+ expect(((await file())['state'] as Map)['acct'], _acct);+ expect((await file())['frozen'], containsPair('reason', 'invalid'));+ });});test('a restore that fails half way has the kept list live first: its marks are never lost', () async {@@ -1557,6 +1701,36 @@ void main() {});group('beginSignIn', () {+ test('the account of a sign-in by hand is kept beside it, once, and goes with the next one', () async {+ final log = at(() => backend);+ Future<String?> acct() async => keys.signInAcct((await keys.signInEpoch()) ?? '');+ await log.register();+ log.beginSignIn(fresh: false);+ await log.signedInAs(_acct); // a stored session: nothing+ expect(await acct(), isNull);+ log.beginSignIn(fresh: true);+ await log.signedInAs(_acct);+ expect(await acct(), _acct);+ await log.signedInAs('acct-2');+ expect(await acct(), _acct);+ log.beginSignIn(fresh: true);+ await log.register();+ expect(await acct(), isNull);+ });++ test('the log is owned once the new sign-in read it (or before there is one)', () async {+ var current = backend;+ final log = at(() => current);+ expect(await log.ownsLog(), isTrue);+ await log.register(freshSignIn: true);+ expect(await log.ownsLog(), isTrue);+ current = _Backend('acct-2');+ log.beginSignIn(fresh: true);+ expect(await log.ownsLog(), isFalse, reason: 'still the account left');+ await log.register();+ expect(await log.ownsLog(), isTrue);+ });+test('a read before register already judges by the new sign-in, and register mints nothing more', () async {var current = backend;final log = at(() => current);@@ -1649,6 +1823,8 @@ void main() {await log.dismiss(pub: b64e(evil.pub));expect(await log.suspendedPubs(), isNot(contains(b64e(evil.pub))));expect(b64e((await keys.peer(_mid3))!.pub), b64e(evil.pub));+ // What the kept account trusted stays kept with it.+ expect((await keys.deviceLogArchive())[_acct], containsPair('trust', isNotNull));});test('a review does not lift it (it never showed it as suspended): only "It\'s mine" does', () async {@@ -1693,12 +1869,17 @@ void main() {f['suspended'] = ['k'];await keys.writeDeviceLog(f);await keys.writeSignInEpoch('f' * 32); // signed in again, long ago: the list is not its yet+ await keys.pin('p' * 32, box3.pub); // linked under the old accountfinal log = makeLog();final r = await log.rebaseline(confirm: true);expect(r!.otherAccount, isFalse);expect(((await file())['state'] as Map)['acct'], _acct);expect((await file())['owner'], 'f' * 32);expect((await keys.deviceLogArchive()).keys, ['old']);+ // What the old account trusted went with it; the reviewed list is trusted.+ expect(await keys.peer('p' * 32), isNull);+ expect(await keys.peer(_mid2), isNotNull);+ expect(((await keys.deviceLogArchive())['old'] as Map)['trust'], isNotNull);});group('another account\'s list under the sign-in the live list belongs to', () {diff --git a/mobile/test/viewer/viewer_key_store_test.dart b/mobile/test/viewer/viewer_key_store_test.dartindex d7826d72b..778ce3b4f 100644--- a/mobile/test/viewer/viewer_key_store_test.dart+++ b/mobile/test/viewer/viewer_key_store_test.dart@@ -177,4 +177,49 @@ void main() {});});});++ group('what one account trusts', () {+ test('a snapshot put back is the pins and the trust group it was taken of — never the held pins', () async {+ final storage = _FlakyStore();+ final store = ViewerKeyStore(storage: storage);+ await store.pin('a', List.filled(32, 1), label: 'A');+ await store.writeGroupRoster({'members': [], 'removed': []});+ final snapshot = await store.trustSnapshot();++ await store.writeTrust(const {});+ expect(+ await store.peers(),+ isEmpty,+ reason: 'the held list is replaced, not read stale',+ );+ expect(await store.groupRoster(), isNull);++ await store.pin('b', List.filled(32, 2));+ await store.writeTrust(snapshot);+ expect([for (final p in await store.peers()) p.machineId], ['a']);+ final reads = storage.reads;+ expect((await store.peer('a'))!.label, 'A');+ expect(storage.reads, reads, reason: 'read once, then held again');+ expect(await store.groupRoster(), {'members': [], 'removed': []});+ // And on disk, for the next launch.+ expect(+ [+ for (final p in await ViewerKeyStore(storage: storage).peers())+ p.machineId,+ ],+ ['a'],+ );+ });++ test(+ 'the account of a sign-in by hand answers for that sign-in only',+ () async {+ final store = ViewerKeyStore(storage: MemoryKeyValueStore());+ expect(await store.signInAcct('e1'), isNull);+ await store.writeSignInAcct('e1', 'acct-1');+ expect(await store.signInAcct('e1'), 'acct-1');+ expect(await store.signInAcct('e2'), isNull);+ },+ );+ });}