Skip to content

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

Confirm a new device once, on any trusted device (#1196)

Dee61ba12536b5d
diff --git a/SECURITY.md b/SECURITY.md
index 94411323b..114183e9a 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -23,9 +23,15 @@ directory.
identity key to the account's device key log, and the account's other devices trust it end to end
with no password. So anyone who can sign in as you — or whoever runs the backend — can add a device.
This is deliberate, and it is not prevented, only made visible: every device announces each key added
-after it joined ("New device: X") and keeps it marked New until you look, says who removed a device,
-and the device list shows every one with a Remove and the full add/remove history. Devices check the
-log against what they already verified and compare it among themselves, so the backend cannot rewrite
+after it joined ("New device: X") and keeps it marked New until you confirm it on one of your trusted
+devices (It's mine) or review it on each, says who removed a device, and the device list shows every one
+with a Remove and the full add/remove history. A confirmation is a signed acknowledgement kept beside
+the log, never in it; each device checks it against its own verified log and counts it only from a
+device it already trusts (not one that is itself new there), so the backend cannot forge one, and it
+never makes a device trusted or lifts a suspension — it only clears the New mark. One device's It's
+mine then speaks for all of them: confirm only a device you recognise. The one-time "New device: X"
+notice still comes on every device. Devices check the log against what they already verified and
+compare it among themselves, so the backend cannot rewrite
or roll back that history, hide a key from one device, or move a device to another account's list
without a fresh sign-in there: the list freezes instead, and keys added after a detected split are
not trusted until someone reviews it. Stopping the backend from adding a device in the first place is
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 954490642..26a50aebc 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -879,6 +879,30 @@ model DeviceKeyLogState {
@@map("device_key_log_state")
}
+/// A device's signed "It's mine" for another key on the account's device key log (lib/deviceAckCore.ts):
+/// once one trusted device confirms a new one, the account's other devices stop showing it as New.
+/// Kept beside `device_key_log` and never in its chain — an op the chain does not know would make every
+/// older client freeze the whole log — so a client that predates it never sees one.
+///
+/// `ack` is the JSON the device sent, kept verbatim; its signature covers a binary encoding of its
+/// fields, and every device checks it against its own verified log, never this table's word. The unique
+/// `(userId, pub, signer)` makes appending idempotent: one acknowledgement per key per signer.
+model DeviceKeyAck {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ userId String
+ /// The acknowledged key, and the seq of the log entry that added it.
+ pub String
+ addSeq Int
+ /// The key that acknowledged it (and signed `ack`).
+ signer String
+ ack String
+ createdAt DateTime @default(now())
+
+ @@unique([userId, pub, signer])
+ @@index([userId, addSeq])
+ @@map("device_key_acks")
+}
+
/// Public/private link metadata only. The owner daemon keeps the final policy and encrypted discussion.
model HarnessLink {
id String @id @map("_id")
diff --git a/backend/src/lib/deviceAck.vectors.json b/backend/src/lib/deviceAck.vectors.json
new file mode 100644
index 000000000..838e0d1a2
--- /dev/null
+++ b/backend/src/lib/deviceAck.vectors.json
@@ -0,0 +1,271 @@
+{
+ "comment": "Generated by cli/scripts/gen-devack-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4). `message` is the hex of devAckMessage(valid[0]).",
+ "acct": "acct-vectors-1",
+ "seeds": {
+ "box1": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
+ "box2": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=",
+ "browser": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "stranger": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ="
+ },
+ "pubs": {
+ "box1": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "box2": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "browser": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "stranger": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw="
+ },
+ "log": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 1000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "PQ79548gYy1fR00xYYrAqGYQer//uS3fGo1Xwwih7v6Jpw8lLHsM/plOYoenu8qjIWhPTSPlVSghlAt9C6MMCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 2000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "bHi9oSluvJ/RKgTw7RZrPaplcR45FGkVMmnOjm4dQnTzchKsMN6D6WKTNphHLjthUYhcznmjIJDLjplJ5TKsAg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 3000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "browser",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "vYm6LtYV1vK3yQR7Sp1/EPFoiFTOyM+7zhsnDUCXZUDeYJ1e9SL7m3xjEGdgo3x9Fd6DPwM51bkDwz9JstSpCQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "vMPGnQgYDO21pqy7wyaTJJGLaHpCdXDVAIkJrfJ7KUA=",
+ "at": 4000,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "gYDuihZziynx5hm1/FB2kZUKs+qZzVT1CZ4MbtjCSdKJEYM/736O4oKgFCnzg6RdHlGLcqUTRhkq3xZ3sqxuCA=="
+ }
+ ],
+ "message": "000000116861726e6573732d64657661636b2d763100000001310000000e616363742d766563746f72732d3100000020ed4928c628d1c2c6eae90338905995612959273a5c63f93636c14614ac8737d10000000133000000208a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c0000000435303030",
+ "valid": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "addSeq": 1,
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "at": 6000,
+ "sig": "Tvs71LrL6KUWDTzt8vqopLsIubbiEF+Q+wHMjPNappC+jCvHUXvOuUwnPHAIovDQGhCnOybac7StvvHFm0k1Bg=="
+ }
+ ],
+ "invalid": [
+ {
+ "name": "tampered time",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5001,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "signed under the device log tag",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "UiDLPvPt03A2Am5iDEakR3ilJc/OC1cfF2jhL7n3a+4UJN+pFFENwJPRTWodgahPRyw9SeyB0LOue6L4FzFQDw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "signed by another key than the signer",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "eqjcnHjAWOjrRa1aGALmlEzLhVZR1QkzxNsCxV+l/8/wlbK+NoHtTnR/+tlhxXmhCMdrTVuZSS4Q0HZESphFDw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "a key acknowledging itself",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "at": 5000,
+ "sig": "Cmg55AVm78H0Uvm25ugS1dX8QncK0jVBztdkmP2mMfY/2Ze+NaBSWCkX35MXiAO5JjdGwT7oNIdjN0egnm26BA=="
+ },
+ "code": "SELF_ACK"
+ },
+ {
+ "name": "signer not in the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "at": 5000,
+ "sig": "MGKqHpl4Oe701BsU7aWlmsgOUDnJ7WqOQjbWmBvGiPqM26/5MPuT8fHqHTgMqfbzC2U0K5YBKlKqbK1hwjl1Bw=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "signer removed from the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "at": 5000,
+ "sig": "y2HnM3LiMr69YaXjuNNsWNE0iLwQ3ZfzFzyLYck9SPbOa6Orz3lPI/32MzN0UCC4Ng/EQySy5XYFZAeLbQf0AA=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "wrong add entry",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 2,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "3dCkpuz6Tu5XEmvFIGnFQaiLin+Ninldkrmvp6K/a9g1EqEJ4uTds8dMdtqZKjsAIZpMEKKQUGbrL3wWeBOBCg=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "key removed from the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "addSeq": 2,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "/GLyfKMRBF4JXwbg07KnkIB1wHMnZHkwIs4+utnxwJrobNkI9kaf0GdcBewxkt9F0MJ5MvWqWpwuQGraVpo9BA=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "key never in the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "U+ud4hDLUP1a4uAJY8+oPqBCho6vndu3AflTI7NhfUYcIukAH65jtjM3WArUDhO3iM8+GG9XYvBz66o+Pf8kDw=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "another account",
+ "ack": {
+ "v": 1,
+ "acct": "acct-other",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "cTBr1vv9/MOr3txBo0ZoPG7RK+YvqsxfNGyCG1bv5djsBaIAOHh9JeW0PEse15pstinySS5fZfcscgMhmbJEBg=="
+ },
+ "code": "WRONG_ACCOUNT"
+ },
+ {
+ "name": "unknown version",
+ "ack": {
+ "v": 2,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "add entry zero",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 0,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "848QPR9kk82i9U1SGs7xcG7cZDAq8M6a7erc9FFGQk9QQui8X/HoCMzdmydlVxy4jvGHvNGepQ41htILwCvvDw=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "key of the wrong length",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "not an object",
+ "ack": "ack",
+ "code": "BAD_ACK"
+ }
+ ]
+}
diff --git a/backend/src/lib/deviceAckCore.test.ts b/backend/src/lib/deviceAckCore.test.ts
new file mode 100644
index 000000000..c1a8c1830
--- /dev/null
+++ b/backend/src/lib/deviceAckCore.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { ed25519 } from '@noble/curves/ed25519.js'
+import { checkDevAck, devAckMessage, signDevAck } from './deviceAckCore.js'
+import { applyDevLogEntries, emptyDevLogState } from './deviceLogCore.js'
+
+// The same fixture the CLI and both Dart ports are held to (cli/scripts/gen-devack-vectors.ts).
+const vectors = JSON.parse(readFileSync(join(import.meta.dirname, 'deviceAck.vectors.json'), 'utf-8'))
+const b64d = (s: string): Uint8Array => new Uint8Array(Buffer.from(s, 'base64'))
+
+describe('device acknowledgement core against the shared vectors', () => {
+ const state = applyDevLogEntries(emptyDevLogState(vectors.acct), vectors.log).state
+ const seeds = vectors.seeds as Record<string, string>
+ const byPub = new Map(Object.entries(vectors.pubs as Record<string, string>).map(([name, pub]) => [pub, b64d(seeds[name])]))
+
+ it('encodes, signs and accepts every valid acknowledgement as the fixture does', () => {
+ expect(Buffer.from(devAckMessage(vectors.valid[0])).toString('hex')).toBe(vectors.message)
+ for (const a of vectors.valid) {
+ const { sig, ...unsigned } = a
+ expect(Buffer.from(ed25519.getPublicKey(byPub.get(a.signer)!)).toString('base64')).toBe(a.signer)
+ expect(signDevAck(unsigned, byPub.get(a.signer)!).sig).toBe(sig)
+ expect(checkDevAck(state, a)).toEqual({ ok: true, ack: a })
+ }
+ })
+
+ for (const c of vectors.invalid as Array<{ name: string; ack: unknown; code: string }>) {
+ it(`refuses: ${c.name} (${c.code})`, () => {
+ expect(checkDevAck(state, c.ack)).toEqual({ ok: false, code: c.code })
+ })
+ }
+})
diff --git a/backend/src/lib/deviceAckCore.ts b/backend/src/lib/deviceAckCore.ts
new file mode 100644
index 000000000..6991c2197
--- /dev/null
+++ b/backend/src/lib/deviceAckCore.ts
@@ -0,0 +1,128 @@
+/**
+ * "It's mine", said once for the whole account: a device's signed acknowledgement that another device
+ * on the account's device key log is the person's own, kept beside the log and never in it (an op the
+ * log does not know would make every older client freeze it as invalid). The backend checks one before
+ * it keeps it, so a device never has to throw a bad one away — but no device takes the backend's word
+ * for it: each checks the signature and its signer against its own verified log.
+ *
+ * ⚠ A copy of cli/src/lib/e2ee/deviceAck.ts, identical below the imports (noble v2 import paths here;
+ * cli/src/lib/e2ee/deviceAck.spec.ts compares them). Also ported to Dart
+ * (desktop/lib/viewer/device_ack.dart, mobile/lib/viewer/device_ack.dart). All of them are held to
+ * deviceAck.vectors.json; change the format in every copy together.
+ */
+import { ed25519 } from '@noble/curves/ed25519.js'
+import type { DevLogState } from './deviceLogCore.js'
+
+export const DEVACK_VERSION = 1
+/** The domain tag that heads every signed acknowledgement. Never the device log's (`harness-devlog-v1`). */
+export const DEVACK_TAG = 'harness-devack-v1'
+
+export interface DevAck {
+ v: number
+ /** The account (backend User id) whose log names both keys. */
+ acct: string
+ /** base64 Ed25519 key of the device being acknowledged. */
+ pub: string
+ /** seq of the log entry that added `pub`: an acknowledgement is of that one entry, never of the key in
+ * general (a key cannot come back after a remove, but naming the entry keeps it exact). */
+ addSeq: number
+ /** base64 Ed25519 key of the device that acknowledges it, and signs it. */
+ signer: string
+ /** Milliseconds since the epoch, as the signer's clock read it. Shown, never trusted for anything. */
+ at: number
+ sig: string
+}
+
+export type UnsignedDevAck = Omit<DevAck, 'sig'>
+
+/** Why `checkDevAck` refused an acknowledgement. */
+export type DevAckRefusal =
+ | 'BAD_ACK'
+ | 'WRONG_ACCOUNT'
+ | 'BAD_SIGNATURE'
+ | 'SELF_ACK'
+ | 'SIGNER_NOT_ACTIVE'
+ | 'NOT_ADDED_THERE'
+
+const HAS_BUFFER = typeof Buffer !== 'undefined'
+
+function b64e(u: Uint8Array): string {
+ if (HAS_BUFFER) return Buffer.from(u).toString('base64')
+ let s = ''
+ for (let i = 0; i < u.length; i++) s += String.fromCharCode(u[i])
+ return btoa(s)
+}
+function b64d(s: string): Uint8Array {
+ if (HAS_BUFFER) return new Uint8Array(Buffer.from(s, 'base64'))
+ const bin = atob(s)
+ const u = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i)
+ return u
+}
+/** base64 of exactly [n] bytes, in its one canonical spelling; false otherwise. */
+function isBytes(s: unknown, n: number): s is string {
+ if (typeof s !== 'string' || s.length > 128) return false
+ try {
+ const u = b64d(s)
+ return u.length === n && b64e(u) === s
+ } catch { return false }
+}
+function lvCat(...parts: Array<Uint8Array | string>): Uint8Array {
+ const chunks: Uint8Array[] = []
+ let total = 0
+ for (const p of parts) {
+ const b = typeof p === 'string' ? new TextEncoder().encode(p) : p
+ const len = new Uint8Array(4)
+ new DataView(len.buffer).setUint32(0, b.length, false)
+ chunks.push(len, b)
+ total += 4 + b.length
+ }
+ const out = new Uint8Array(total)
+ let off = 0
+ for (const c of chunks) { out.set(c, off); off += c.length }
+ return out
+}
+
+/** The bytes a signature covers. Numbers are written in decimal, so every language agrees. */
+export function devAckMessage(a: UnsignedDevAck): Uint8Array {
+ return lvCat(DEVACK_TAG, String(a.v), a.acct, b64d(a.pub), String(a.addSeq), b64d(a.signer), String(a.at))
+}
+
+export function signDevAck(a: UnsignedDevAck, priv: Uint8Array): DevAck {
+ return { ...a, sig: b64e(ed25519.sign(devAckMessage(a), priv)) }
+}
+
+/** Every field present, of its type and within bounds; null when anything is off. */
+export function parseDevAck(raw: unknown): DevAck | null {
+ if (!raw || typeof raw !== 'object') return null
+ const { v, acct, pub, addSeq, signer, at, sig } = raw as Record<string, unknown>
+ if (v !== DEVACK_VERSION) return null
+ if (typeof acct !== 'string' || !acct || acct.length > 128) return null
+ if (!isBytes(pub, 32) || !isBytes(signer, 32) || !isBytes(sig, 64)) return null
+ if (!Number.isSafeInteger(addSeq) || (addSeq as number) < 1) return null
+ if (!Number.isSafeInteger(at) || (at as number) <= 0) return null
+ return { v, acct, pub, addSeq: addSeq as number, signer, at: at as number, sig }
+}
+
+/** Whether [a]'s signature is its signer's, over its fields. */
+export function verifyDevAckSignature(a: DevAck): boolean {
+ try { return ed25519.verify(b64d(a.sig), devAckMessage(a), b64d(a.signer)) } catch { return false }
+}
+
+/**
+ * Check [raw] against [state], a device key log as verified by whoever is asking: well formed, of this
+ * account, signed by its signer, not the key vouching for itself, the signer active on the log, and
+ * `pub` active on it and added at `addSeq`. What it does NOT judge is each device's own: whether the
+ * signer is itself new, suspended or gone there, or whether `pub` is suspended there.
+ */
+export function checkDevAck(state: DevLogState, raw: unknown): { ok: true; ack: DevAck } | { ok: false; code: DevAckRefusal } {
+ const ack = parseDevAck(raw)
+ if (!ack) return { ok: false, code: 'BAD_ACK' }
+ if (ack.acct !== state.acct) return { ok: false, code: 'WRONG_ACCOUNT' }
+ if (!verifyDevAckSignature(ack)) return { ok: false, code: 'BAD_SIGNATURE' }
+ // A key saying it is its own owner's says nothing: whoever added it would sign that too.
+ if (ack.signer === ack.pub) return { ok: false, code: 'SELF_ACK' }
+ if (!state.active[ack.signer]) return { ok: false, code: 'SIGNER_NOT_ACTIVE' }
+ if (state.active[ack.pub]?.seq !== ack.addSeq) return { ok: false, code: 'NOT_ADDED_THERE' }
+ return { ok: true, ack }
+}
diff --git a/backend/src/lib/deviceKeyLog.test.ts b/backend/src/lib/deviceKeyLog.test.ts
index dadee3782..28eb0f694 100644
--- a/backend/src/lib/deviceKeyLog.test.ts
+++ b/backend/src/lib/deviceKeyLog.test.ts
@@ -12,6 +12,8 @@ const m = vi.hoisted(() => ({
publishChanged: vi.fn(), publishDown: vi.fn(), revoke: vi.fn(),
seen: {} as Record<string, Record<string, string>>,
hsetCalls: 0,
+ acks: [] as Array<{ userId: string; pub: string; addSeq: number; signer: string; ack: string; createdAt: number }>,
+ failAck: null as unknown,
}))
vi.mock('./prisma.js', () => ({
prisma: {
@@ -41,6 +43,18 @@ vi.mock('./prisma.js', () => ({
m.snaps.set(data.userId, structuredClone(data)); return data
}),
},
+ deviceKeyAck: {
+ create: vi.fn(async ({ data }: { data: { userId: string; pub: string; addSeq: number; signer: string; ack: string } }) => {
+ if (m.failAck) { const err = m.failAck; m.failAck = null; throw err }
+ if (m.acks.some(a => a.userId === data.userId && a.pub === data.pub && a.signer === data.signer)) {
+ throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' })
+ }
+ m.acks.push({ ...data, createdAt: m.acks.length }); return data
+ }),
+ findMany: vi.fn(async ({ where, take }: { where: { userId: string; addSeq: { gt: number } }; take: number }) =>
+ m.acks.filter(a => a.userId === where.userId && a.addSeq > where.addSeq.gt)
+ .sort((a, b) => a.addSeq - b.addSeq || a.createdAt - b.createdAt).slice(0, take)),
+ },
harnessSession: { updateMany: m.revoke },
},
}))
@@ -61,7 +75,8 @@ vi.mock('./bus.js', () => ({
hgetall: async (key: string) => m.seen[key] ?? {},
},
}))
-import { appendDeviceKey, deviceKeysSeen, readDeviceKeyLog, touchDeviceKey } from './deviceKeyLog.js'
+import { appendDeviceAck, appendDeviceKey, deviceKeysSeen, readDeviceAcks, readDeviceKeyLog, touchDeviceKey } from './deviceKeyLog.js'
+import { signDevAck, type DevAck } from './deviceAckCore.js'
import { emptyDevLogState, nextDevLogEntry, signDevLogEntry, applyDevLogEntries, DEVLOG_MAX_ACTIVE, type DevLogState } from './deviceLogCore.js'
import { prisma } from './prisma.js'
@@ -311,3 +326,75 @@ describe('when a key was last seen', () => {
expect(await deviceKeysSeen('user-seen-3')).toEqual({ seen: {}, since: null })
})
})
+
+describe('acknowledgements ("It\'s mine", once for the account)', () => {
+ const stranger = key(4)
+ beforeEach(async () => {
+ m.rows.length = 0
+ m.snaps.clear()
+ m.acks.length = 0
+ m.failAck = null
+ vi.clearAllMocks()
+ m.publishChanged.mockResolvedValue(1)
+ m.publishDown.mockResolvedValue(1)
+ // box1 (seq 1), phone (seq 2), box2 (seq 3), then box2 removed by box1 (seq 4).
+ await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })
+ await appendDeviceKey(USER, await addEntry(phone, 'viewer', '', 'phone'), { kind: 'viewer' })
+ await appendDeviceKey(USER, await addEntry(box2, 'machine', MID2, 'box2'), { kind: 'machine', machineId: MID2 })
+ await appendDeviceKey(USER, await removeEntry(box2.pub, box1), { kind: 'machine', machineId: MID1 })
+ m.publishChanged.mockClear()
+ })
+ const ack = (by: { priv: Uint8Array; pub: string }, of: string, addSeq: number, extra: Partial<DevAck> = {}): DevAck =>
+ signDevAck({ v: 1, acct: USER, pub: of, addSeq, signer: by.pub, at: 9_000, ...extra }, by.priv)
+
+ it('keeps one a key active on the log signed for a key the log added there, and tells every device', async () => {
+ const a = ack(box1, phone.pub, 2)
+ expect(await appendDeviceAck(USER, a)).toEqual({ ok: true, created: true })
+ expect(m.acks).toHaveLength(1)
+ // The log's head did not move: the push is only "read again".
+ expect(m.publishChanged).toHaveBeenCalledWith(USER, (await readDeviceKeyLog(USER, 0)).head)
+ expect(await readDeviceAcks(USER, 0)).toEqual({ acks: [a] })
+ })
+
+ it('takes the same signer saying it again as done, and keeps the first', async () => {
+ const first = ack(box1, phone.pub, 2)
+ await appendDeviceAck(USER, first)
+ m.publishChanged.mockClear()
+ expect(await appendDeviceAck(USER, ack(box1, phone.pub, 2, { at: 10_000 }))).toEqual({ ok: true, created: false })
+ expect(m.publishChanged).not.toHaveBeenCalled()
+ expect((await readDeviceAcks(USER, 0)).acks).toEqual([first])
+ })
+
+ it('refuses a bad signature, an unknown or removed signer, a key vouching for itself, the wrong entry and another account', async () => {
+ const cases: Array<[unknown, string]> = [
+ [{ ...ack(box1, phone.pub, 2), at: 9_001 }, 'BAD_SIGNATURE'],
+ [ack(stranger, phone.pub, 2), 'SIGNER_NOT_ACTIVE'],
+ [ack(box2, phone.pub, 2), 'SIGNER_NOT_ACTIVE'],
+ [ack(phone, phone.pub, 2), 'SELF_ACK'],
+ [ack(box1, phone.pub, 3), 'NOT_ADDED_THERE'],
+ [ack(box1, box2.pub, 3), 'NOT_ADDED_THERE'],
+ [ack(box1, phone.pub, 2, { acct: 'someone-else' }), 'WRONG_ACCOUNT'],
+ [{ v: 1 }, 'BAD_ACK'],
+ ]
+ for (const [raw, code] of cases) expect(await appendDeviceAck(USER, raw), code).toEqual({ ok: false, status: 400, code })
+ expect(m.acks).toHaveLength(0)
+ expect(m.publishChanged).not.toHaveBeenCalled()
+ })
+
+ it('lets a failure to store it through, rather than calling it kept', async () => {
+ m.failAck = new Error('mongo down')
+ await expect(appendDeviceAck(USER, ack(box1, phone.pub, 2))).rejects.toThrow('mongo down')
+ expect(m.publishChanged).not.toHaveBeenCalled()
+ })
+
+ it('reads only the keys added after an entry, oldest key first', async () => {
+ const forPhone = ack(box1, phone.pub, 2)
+ const forBox1 = ack(phone, box1.pub, 1)
+ await appendDeviceAck(USER, forPhone)
+ await appendDeviceAck(USER, forBox1)
+ expect((await readDeviceAcks(USER, 0)).acks).toEqual([forBox1, forPhone])
+ expect((await readDeviceAcks(USER, 1)).acks).toEqual([forPhone])
+ expect((await readDeviceAcks(USER, 2)).acks).toEqual([])
+ expect((await readDeviceAcks('someone-else', 0)).acks).toEqual([])
+ })
+})
diff --git a/backend/src/lib/deviceKeyLog.ts b/backend/src/lib/deviceKeyLog.ts
index d39ab910e..814aca256 100644
--- a/backend/src/lib/deviceKeyLog.ts
+++ b/backend/src/lib/deviceKeyLog.ts
@@ -7,6 +7,7 @@ import {
applyDevLogEntries, DevLogError, emptyDevLogState, parseDevLogEntry,
type DevLogEntry, type DevLogHead, type DevLogState,
} from './deviceLogCore.js'
+import { checkDevAck } from './deviceAckCore.js'
/**
* The account's device key log, as the backend keeps it (the format and every rule are
@@ -175,6 +176,47 @@ export async function appendDeviceKey(userId: string, raw: unknown, channel: Dev
return { ok: true, head }
}
+// ── "It's mine", once for the account ─────────────────────────────────────────────────────────────
+// A device that confirms a new one signs an acknowledgement (lib/deviceAckCore.ts), and the account's
+// other devices stop showing that key as New. Kept beside the log, never in its chain, so an older
+// client never sees one. Checked here against the log as it stands — a bad one is refused rather than
+// kept for every device to throw away — but no device takes this side's word for it: each checks the
+// signature and the signer against its own verified log, and its own marks on both keys.
+
+/** The acknowledgements one read returns. Each key has at most one per signer, and a device asks only
+ * from just below the oldest key it still shows as New, so a page holds what any real account has. */
+const ACK_PAGE = 500
+
+export type DeviceAckAppendResult = { ok: true; created: boolean } | { ok: false; status: 400; code: string }
+
+export async function appendDeviceAck(userId: string, raw: unknown): Promise<DeviceAckAppendResult> {
+ const { state } = await currentState(userId)
+ const checked = checkDevAck(state, raw)
+ if (!checked.ok) return { ok: false, status: 400, code: checked.code }
+ const { ack } = checked
+ try {
+ await prisma.deviceKeyAck.create({ data: { userId, pub: ack.pub, addSeq: ack.addSeq, signer: ack.signer, ack: JSON.stringify(ack) } })
+ } catch (err) {
+ // This signer already said so for this key: the first one stands, and saying it again is no error
+ // (a device that retries, or two of its windows).
+ if (isUniqueViolation(err)) return { ok: true, created: false }
+ throw err
+ }
+ // The head did not move; the push only tells every device to read again, which reads acknowledgements.
+ await publishDeviceKeysChanged(userId, state.head).catch(() => { /* best effort: devices also re-read on their own */ })
+ touchDeviceKey(userId, ack.signer)
+ logger.info('device key acknowledged', { userId, addSeq: ack.addSeq })
+ return { ok: true, created: true }
+}
+
+/** The acknowledgements of keys added after entry [since], oldest key first, as the devices sent them. */
+export async function readDeviceAcks(userId: string, since: number): Promise<{ acks: unknown[] }> {
+ const rows = await prisma.deviceKeyAck.findMany({
+ where: { userId, addSeq: { gt: since } }, orderBy: [{ addSeq: 'asc' }, { createdAt: 'asc' }], take: ACK_PAGE,
+ })
+ return { acks: rows.map(r => JSON.parse(r.ack) as unknown) }
+}
+
/**
* A removed key is banned from the log for good, which is what keeps it out. Signing the device out is
* on top of that, where the backend can: a machine is told to drop its sign-in (the same frame a deleted
diff --git a/backend/src/routes/deviceKeys.test.ts b/backend/src/routes/deviceKeys.test.ts
index e56a7e5fd..c912af206 100644
--- a/backend/src/routes/deviceKeys.test.ts
+++ b/backend/src/routes/deviceKeys.test.ts
@@ -1,7 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Fastify, { type FastifyInstance } from 'fastify'
-const m = vi.hoisted(() => ({ auth: vi.fn(), read: vi.fn(), append: vi.fn(), seen: vi.fn(), touch: vi.fn() }))
-vi.mock('../lib/deviceKeyLog.js', () => ({ readDeviceKeyLog: m.read, appendDeviceKey: m.append, deviceKeysSeen: m.seen, touchDeviceKey: m.touch }))
+const m = vi.hoisted(() => ({ auth: vi.fn(), read: vi.fn(), append: vi.fn(), seen: vi.fn(), touch: vi.fn(), readAcks: vi.fn(), appendAck: vi.fn() }))
+vi.mock('../lib/deviceKeyLog.js', () => ({
+ readDeviceKeyLog: m.read, appendDeviceKey: m.append, deviceKeysSeen: m.seen, touchDeviceKey: m.touch,
+ readDeviceAcks: m.readAcks, appendDeviceAck: m.appendAck,
+}))
vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: m.auth }))
import { deviceKeyRoutes } from './deviceKeys.js'
import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
@@ -102,4 +105,57 @@ describe('device key routes', () => {
expect(r.statusCode).toBe(400)
expect(m.append).not.toHaveBeenCalled()
})
+
+ describe('acknowledgements', () => {
+ it('needs a sign-in', async () => {
+ expect((await app.inject({ method: 'GET', url: '/api/device-keys/acks' })).statusCode).toBe(401)
+ expect((await app.inject({ method: 'POST', url: '/api/device-keys/acks', payload: { ack: {} } })).statusCode).toBe(401)
+ expect(m.appendAck).not.toHaveBeenCalled()
+ })
+
+ it('reads the caller\'s from an entry, uncached', async () => {
+ m.readAcks.mockResolvedValue({ acks: [{ v: 1 }] })
+ const r = await app.inject({ method: 'GET', url: '/api/device-keys/acks?since=4', headers: auth })
+ expect(r.statusCode).toBe(200)
+ expect(r.headers['cache-control']).toBe('no-store')
+ expect(r.json().data).toEqual({ acks: [{ v: 1 }] })
+ expect(m.readAcks).toHaveBeenCalledWith('user-1', 4)
+ await app.inject({ method: 'GET', url: '/api/device-keys/acks', headers: auth })
+ expect(m.readAcks).toHaveBeenLastCalledWith('user-1', 0)
+ expect((await app.inject({ method: 'GET', url: '/api/device-keys/acks?since=-1', headers: auth })).statusCode).toBe(400)
+ })
+
+ it('keeps one for the caller\'s account, and says whether it was new', async () => {
+ m.appendAck.mockResolvedValue({ ok: true, created: false })
+ const r = await app.inject({ method: 'POST', url: '/api/device-keys/acks', headers: auth, payload: { ack: { v: 1 } } })
+ expect(r.statusCode).toBe(200)
+ expect(r.json().data).toEqual({ created: false })
+ expect(m.appendAck).toHaveBeenCalledWith('user-1', { v: 1 })
+ })
+
+ it('passes a refusal through with its code', async () => {
+ m.appendAck.mockResolvedValue({ ok: false, status: 400, code: 'SIGNER_NOT_ACTIVE' })
+ const r = await app.inject({ method: 'POST', url: '/api/device-keys/acks', headers: auth, payload: { ack: {} } })
+ expect(r.statusCode).toBe(400)
+ expect(r.json().error.code).toBe('SIGNER_NOT_ACTIVE')
+ })
+
+ it('refuses a body without an acknowledgement, or with anything beside it', async () => {
+ for (const payload of [{ other: 1 }, { ack: {}, extra: 1 }, { ack: 'x' }]) {
+ expect((await app.inject({ method: 'POST', url: '/api/device-keys/acks', headers: auth, payload })).statusCode).toBe(400)
+ }
+ expect(m.appendAck).not.toHaveBeenCalled()
+ })
+
+ it('limits how often one account acknowledges, apart from its appends to the log', async () => {
+ m.auth.mockResolvedValue({ ...user, sub: 'user-acking' })
+ m.appendAck.mockResolvedValue({ ok: true, created: true })
+ m.append.mockResolvedValue({ ok: true, head })
+ const codes: number[] = []
+ for (let i = 0; i < 21; i++) codes.push((await app.inject({ method: 'POST', url: '/api/device-keys/acks', headers: auth, payload: { ack: {} } })).statusCode)
+ expect(codes.slice(0, 20).every((c) => c === 200)).toBe(true)
+ expect(codes[20]).toBe(429)
+ expect((await app.inject({ method: 'POST', url: '/api/device-keys', headers: auth, payload: { entry: {} } })).statusCode).toBe(200)
+ })
+ })
})
diff --git a/backend/src/routes/deviceKeys.ts b/backend/src/routes/deviceKeys.ts
index d1487ee3d..ed5e4a837 100644
--- a/backend/src/routes/deviceKeys.ts
+++ b/backend/src/routes/deviceKeys.ts
@@ -1,6 +1,6 @@
import type { FastifyInstance } from 'fastify'
import { z } from 'zod'
-import { appendDeviceKey, deviceKeysSeen, readDeviceKeyLog, touchDeviceKey } from '../lib/deviceKeyLog.js'
+import { appendDeviceAck, appendDeviceKey, deviceKeysSeen, readDeviceAcks, readDeviceKeyLog, touchDeviceKey } from '../lib/deviceKeyLog.js'
import { validateBody, validateQuery } from '../middlewares/validation.js'
import { sendError, sendSuccess } from '../utils/response.js'
@@ -15,22 +15,32 @@ const query = z.object({
/** Appends per account per minute, per process — a viewer appends its key once per sign-in and a
* removal when someone asks. Generous for that; a loop cannot rebuild the log on every request. */
const APPENDS_PER_MINUTE = 20
-const appendWindows = new Map<string, { start: number; count: number }>()
-function allowAppend(userId: string, now = Date.now()): boolean {
- const w = appendWindows.get(userId)
- if (!w || now - w.start >= 60_000) {
- if (appendWindows.size >= 10_000) appendWindows.clear()
- appendWindows.set(userId, { start: now, count: 1 })
- return true
+/** At most [perMinute] calls per account per minute, per process. */
+function limiter(perMinute: number): (userId: string, now?: number) => boolean {
+ const windows = new Map<string, { start: number; count: number }>()
+ return (userId, now = Date.now()) => {
+ const w = windows.get(userId)
+ if (!w || now - w.start >= 60_000) {
+ if (windows.size >= 10_000) windows.clear()
+ windows.set(userId, { start: now, count: 1 })
+ return true
+ }
+ return ++w.count <= perMinute
}
- return ++w.count <= APPENDS_PER_MINUTE
}
+const allowAppend = limiter(APPENDS_PER_MINUTE)
+// An acknowledgement is one "It's mine" a person pressed, on one device: the same budget, kept apart so
+// confirming devices never costs the log its appends. Each one replays the log to check it.
+const allowAck = limiter(APPENDS_PER_MINUTE)
const body = z.object({ entry: z.record(z.string(), z.unknown()) }).strict()
+const acksQuery = z.object({ since: z.coerce.number().int().min(0).default(0) })
+const ackBody = z.object({ ack: z.record(z.string(), z.unknown()) }).strict()
/**
* The account's device key log (lib/deviceKeyLog.ts), for the viewer apps: read it from a head, append a
* viewer's own key or a viewer-signed removal. Machines append over their adapter socket instead
- * (`devlog_append`), which is what ties an entry to the machine that sent it.
+ * (`devlog_append`), which is what ties an entry to the machine that sent it. Beside the log, for every
+ * device: the acknowledgements ("It's mine") of keys on it.
*
* A Harness session (a phone signed in by a QR) may append: that phone is one of the account's devices.
*/
@@ -64,4 +74,23 @@ export async function deviceKeyRoutes(app: FastifyInstance): Promise<void> {
}
sendError(reply, 'This entry was refused.', result.code, result.status)
})
+
+ // "It's mine", once for the account (lib/deviceAckCore.ts): a device's signed acknowledgement that a key
+ // on the log is the person's own, so the other devices stop showing it as New. Its own route beside the
+ // log, never an entry in it: a client that predates it never asks, never sees one, and keeps working
+ // as before. A device asks from just below the oldest key it still shows as New (`since`, an entry seq).
+ app.get<{ Querystring: z.infer<typeof acksQuery> }>('/api/device-keys/acks', { preHandler: validateQuery(acksQuery) }, async (req, reply) => {
+ reply.header('Cache-Control', 'no-store')
+ sendSuccess(reply, await readDeviceAcks(req.user!.sub, req.query.since))
+ })
+
+ // Machines and apps alike: an acknowledgement's authority is its signature by a key active on the log,
+ // which every device checks itself, so the channel it came over adds nothing.
+ app.post<{ Body: z.infer<typeof ackBody> }>('/api/device-keys/acks', { preHandler: validateBody(ackBody) }, async (req, reply) => {
+ const user = req.user!
+ if (!allowAck(user.sub)) return sendError(reply, 'Too many changes to your devices. Try again in a minute.', 'RATE_LIMITED', 429)
+ const result = await appendDeviceAck(user.sub, req.body.ack)
+ if (result.ok) return sendSuccess(reply, { created: result.created })
+ sendError(reply, 'This acknowledgement was refused.', result.code, result.status)
+ })
}
diff --git a/cli/e2e/deviceAck.e2e.ts b/cli/e2e/deviceAck.e2e.ts
new file mode 100644
index 000000000..b17c4a9e5
--- /dev/null
+++ b/cli/e2e/deviceAck.e2e.ts
@@ -0,0 +1,113 @@
+/**
+ * "It's mine" said once, for the whole account: two real daemons signed in to one fake backend that keeps
+ * the account's device key log (harness/fakeBackend.ts `enableDeviceLog`). A phone joins; the person
+ * confirms it on machine A (`harness devices dismiss <fp>` posts `confirm`), and machine B — which read
+ * the acknowledgement A signed, and checked it against its own copy of the log — stops showing it as new,
+ * and says where it was confirmed. A device that is itself new on a machine cannot vouch there until the
+ * person confirms it; and a backend from before acknowledgements leaves every machine as it was.
+ */
+import { afterEach, describe, expect, it } from 'vitest'
+import { b64e, newIdentity, type Identity } from '../src/lib/e2ee/core.js'
+import { nextDevLogEntry, signDevLogEntry } from '../src/lib/e2ee/deviceLog.js'
+import { until, type IsolatedDaemon } from './harness/daemon.js'
+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'
+import { signedInDaemon, writeE2ee } from './harness/fleet.js'
+
+type Listing = { pending?: string[]; members: Array<{ pub: string; label: string; confirmed?: { by: string; label: string } }> }
+
+const local = { 'x-adapter-local': '1', 'content-type': 'application/json' }
+const devices = async (daemon: IsolatedDaemon): Promise<Listing> =>
+ (await fetch(`http://127.0.0.1:${daemon.port}/api/devices`, { headers: local })).json() as Promise<Listing>
+const dismiss = async (daemon: IsolatedDaemon, body: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }> => {
+ const res = await fetch(`http://127.0.0.1:${daemon.port}/api/devices/dismiss`, { method: 'POST', headers: local, body: JSON.stringify(body) })
+ return { status: res.status, body: await res.json() as Record<string, unknown> }
+}
+const pendingOn = async (daemon: IsolatedDaemon): Promise<string[]> => (await devices(daemon)).pending ?? []
+
+let backend: FakeBackend | null = null
+const daemons: IsolatedDaemon[] = []
+afterEach(async () => {
+ await Promise.allSettled(daemons.splice(0).map((d) => d.close()))
+ await backend?.close()
+ backend = null
+})
+
+/** A machine of the account, started, with its own identity. */
+async function machine(b: FakeBackend, name: string, n: number): Promise<{ daemon: IsolatedDaemon; pub: string }> {
+ const identity: Identity = newIdentity()
+ const spec: FakeMachine = { machineId: String(n).repeat(32), computerId: `e2e-computer-0000-0000-00000000000${n}`, name, token: `e2e-token-${name}` }
+ b.addMachine(spec)
+ const daemon = await signedInDaemon(b, spec)
+ daemons.push(daemon)
+ await writeE2ee(daemon, { 'identity.json': { priv: b64e(identity.priv), pub: b64e(identity.pub) } })
+ await daemon.start()
+ return { daemon, pub: b64e(identity.pub) }
+}
+
+/** A phone of the account signing in: its key added to the log, as its `POST /api/device-keys` does. */
+function phoneJoins(b: FakeBackend, label: string): string {
+ const id = newIdentity()
+ const pub = b64e(id.pub)
+ const entry = signDevLogEntry(nextDevLogEntry(b.deviceLog!.state, { op: 'add', pub, kind: 'viewer', machineId: '', label, signer: pub }, Date.now()), id.priv)
+ expect(b.appendDeviceEntry(entry)).toHaveProperty('head')
+ return pub
+}
+
+describe('"It\'s mine" on one machine is the account\'s', () => {
+ it('confirmed on A, a new phone stops being new on B; a device new on A vouches there only once confirmed', async () => {
+ const b = backend = await FakeBackend.start()
+ b.enableDeviceLog()
+ // A first, then B: on A, B is new; on B, A was already on the account.
+ const a = await machine(b, 'machine-a', 1)
+ await until('A on the account\'s log', () => !!b.deviceLog!.state.active[a.pub], 60_000)
+ const m = await machine(b, 'machine-b', 2)
+ await until('B on the account\'s log', () => !!b.deviceLog!.state.active[m.pub], 60_000)
+ await until('A to read B as new', async () => (await pendingOn(a.daemon)).includes(m.pub), 30_000)
+ expect(await pendingOn(m.daemon)).not.toContain(a.pub)
+
+ const phone = phoneJoins(b, 'phone')
+ await until('both to read the phone as new', async () => (await pendingOn(a.daemon)).includes(phone) && (await pendingOn(m.daemon)).includes(phone), 30_000)
+
+ // "It's mine" on A: marked there, and shared.
+ const confirmed = await dismiss(a.daemon, { pub: phone, confirm: true })
+ expect(confirmed).toEqual({ status: 200, body: { ok: true, shared: true } })
+ expect(await pendingOn(a.daemon)).not.toContain(phone)
+ await until('B to stop showing the phone as new', async () => !(await pendingOn(m.daemon)).includes(phone), 30_000)
+ const onB = await devices(m.daemon)
+ const labelOfA = onB.members.find((x) => x.pub === a.pub)!.label
+ expect(onB.members.find((x) => x.pub === phone)?.confirmed).toEqual(expect.objectContaining({ by: a.pub, label: labelOfA }))
+
+ // B vouches for a tablet: on A, B is itself new — it does not count there, until the person says B is theirs.
+ const tablet = phoneJoins(b, 'tablet')
+ await until('both to read the tablet as new', async () => (await pendingOn(a.daemon)).includes(tablet) && (await pendingOn(m.daemon)).includes(tablet), 30_000)
+ const mark = b.seen.length
+ expect((await dismiss(m.daemon, { pubs: [tablet], confirm: true })).body.shared).toBe(true)
+ expect(b.deviceLog!.acks).toHaveLength(2)
+ // A has read it (the backend's push; B, with nothing new left, asks for none), and kept the tablet
+ // new: B is not a device A trusts to vouch yet.
+ await until('A to read the acknowledgements again', () => b.seen.slice(mark).some((s) => s.startsWith('GET /api/device-keys/acks')), 10_000)
+ await new Promise((done) => setTimeout(done, 1_000))
+ expect(await pendingOn(a.daemon)).toContain(tablet)
+ // "It's mine" for B on A: now B's word counts there, and the tablet goes too.
+ expect((await dismiss(a.daemon, { pub: m.pub, confirm: true })).body.shared).toBe(true)
+ await until('A to stop showing the tablet as new', async () => !(await pendingOn(a.daemon)).includes(tablet), 30_000)
+ })
+
+ it('a backend from before acknowledgements changes nothing: each machine keeps its own', async () => {
+ const b = backend = await FakeBackend.start()
+ b.enableDeviceLog()
+ b.deviceAcks = false
+ const a = await machine(b, 'machine-a', 1)
+ await until('A on the account\'s log', () => !!b.deviceLog!.state.active[a.pub], 60_000)
+ const m = await machine(b, 'machine-b', 2)
+ await until('B on the account\'s log', () => !!b.deviceLog!.state.active[m.pub], 60_000)
+ const phone = phoneJoins(b, 'phone')
+ await until('both to read the phone as new', async () => (await pendingOn(a.daemon)).includes(phone) && (await pendingOn(m.daemon)).includes(phone), 30_000)
+ expect(await dismiss(a.daemon, { pub: phone, confirm: true })).toEqual({ status: 200, body: { ok: true, shared: false } })
+ expect(await pendingOn(a.daemon)).not.toContain(phone)
+ // Something else moves the log: B reads it again, and still shows the phone as new.
+ phoneJoins(b, 'tablet')
+ await until('B to read the tablet', async () => (await pendingOn(m.daemon)).length === 2, 30_000)
+ expect(await pendingOn(m.daemon)).toContain(phone)
+ })
+})
diff --git a/cli/e2e/harness/fakeBackend.ts b/cli/e2e/harness/fakeBackend.ts
index add20d03a..a95b8d34e 100644
--- a/cli/e2e/harness/fakeBackend.ts
+++ b/cli/e2e/harness/fakeBackend.ts
@@ -26,6 +26,13 @@
* invitation, answered 200; what a node sends to one of Share's observers (`observer:` connections) is
* kept in `targeted`, so a test can open what Share sealed for it.
*
+ * - The account's device key log, once a test turns it on (`enableDeviceLog`), as the real backend keeps
+ * it (backend lib/deviceKeyLog.ts): `GET /api/device-keys?since=`, a machine's `devlog_append` over its
+ * own socket (its own key only), and `device_keys_changed` to every node after each change. Beside it,
+ * the acknowledgements ("It's mine", lib/e2ee/deviceAck.ts): `GET`/`POST /api/device-keys/acks`,
+ * checked as the real one checks them — or, with `deviceAcks` off, a backend from before them (404).
+ * Off, every one of these is a 404, as before.
+ *
* Everything else is answered 404. Requests are recorded in `seen`, so a test can say what was asked.
*
* And it can misbehave, as a relay under stress does: every socket dropped at once, down for a while,
@@ -38,6 +45,11 @@ import { createServer, type IncomingMessage, type Server } from 'node:http'
import type { Duplex } from 'node:stream'
import { WebSocket, WebSocketServer, type RawData } from 'ws'
import { decodeTerminalHop, encodeTerminalHop, parseTerminalBinaryEnvelope, TerminalHopDirection } from '../../src/lib/terminalBinary.js'
+import { checkDevAck } from '../../src/lib/e2ee/deviceAck.js'
+import { applyDevLogEntries, DevLogError, emptyDevLogState, type DevLogEntry, type DevLogHead, type DevLogState } from '../../src/lib/e2ee/deviceLog.js'
+
+/** The account every machine and phone of a fake backend belongs to, as its device key log names it. */
+export const FAKE_ACCOUNT = 'e2e-user'
export interface FakeMachine {
machineId: string
@@ -92,6 +104,10 @@ export class FakeBackend {
readonly deviceSent: Frame[] = []
/** What a node sent to a connection that is neither a device's nor a web client's (Share's observers), by id. */
readonly targeted = new Map<string, Frame[]>()
+ /** The account's device key log and the acknowledgements beside it; null until `enableDeviceLog`. */
+ deviceLog: { entries: DevLogEntry[]; state: DevLogState; acks: unknown[] } | null = null
+ /** Off: a backend from before acknowledgements — their routes answer 404. */
+ deviceAcks = true
private constructor(private readonly server: Server, readonly port: number) {}
@@ -120,6 +136,7 @@ export class FakeBackend {
res.end(json({ success: true, data: {} }))
return
}
+ if (backend.deviceLog && backend.deviceKeysRoute(req, res)) return
res.statusCode = 404
res.end(json({ success: false, error: { code: 'NOT_FOUND', message: 'not on the fake backend' } }))
})
@@ -157,6 +174,81 @@ export class FakeBackend {
this.userTokens.add(token)
}
+ // ── the device key log ──────────────────────────────────────────────────────────────────────
+
+ /** Serve the account's device key log (and its acknowledgements) from now on, starting empty. */
+ enableDeviceLog(): void {
+ this.deviceLog = { entries: [], state: emptyDevLogState(FAKE_ACCOUNT), acks: [] }
+ }
+
+ /** Append one signed entry as the real backend does — refused when it does not continue the log or
+ * breaks a rule — and tell every node. What a phone's `POST /api/device-keys` does, for a test. */
+ appendDeviceEntry(entry: DevLogEntry): { head: DevLogHead } | { error: string; head?: DevLogHead } {
+ const log = this.deviceLog
+ if (!log) return { error: 'NOT_FOUND' }
+ if (entry.seq !== log.state.head.seq + 1 || entry.prev !== log.state.head.hash) return { error: 'STALE_HEAD', head: log.state.head }
+ try {
+ log.state = applyDevLogEntries(log.state, [entry]).state
+ } catch (err) {
+ return { error: err instanceof DevLogError ? err.code : 'BAD_ENTRY' }
+ }
+ log.entries.push(entry)
+ this.deviceKeysChanged()
+ return { head: log.state.head }
+ }
+
+ /** `device_keys_changed` to every node: read the log (and its acknowledgements) again. */
+ private deviceKeysChanged(): void {
+ const head = this.deviceLog?.state.head
+ for (const machineId of this.nodes.keys()) this.sendNode(machineId, '', { type: 'device_keys_changed', payload: { ...head } })
+ }
+
+ /** The device key log's routes; false when the request is not one of them. */
+ private deviceKeysRoute(req: IncomingMessage, res: import('node:http').ServerResponse): boolean {
+ const log = this.deviceLog!
+ const url = new URL(req.url ?? '/', this.httpUrl)
+ const since = Number(url.searchParams.get('since') ?? 0) || 0
+ if (req.method === 'GET' && url.pathname === '/api/device-keys') {
+ res.end(json({ success: true, data: { acct: FAKE_ACCOUNT, head: log.state.head, entries: log.entries.filter((e) => e.seq > since) } }))
+ return true
+ }
+ if (url.pathname !== '/api/device-keys/acks' || !this.deviceAcks) return false
+ if (req.method === 'GET') {
+ const acks = log.acks.filter((a) => (a as { addSeq: number }).addSeq > since)
+ res.end(json({ success: true, data: { acks } }))
+ return true
+ }
+ if (req.method !== 'POST') return false
+ const chunks: Buffer[] = []
+ req.on('data', (c: Buffer) => chunks.push(c))
+ req.on('end', () => {
+ let ack: unknown
+ try { ack = (JSON.parse(Buffer.concat(chunks).toString()) as { ack?: unknown }).ack } catch { ack = null }
+ // Checked as the real backend checks it (backend lib/deviceKeyLog.ts appendDeviceAck).
+ const checked = checkDevAck(log.state, ack)
+ if (!checked.ok) {
+ res.statusCode = 400
+ res.end(json({ success: false, error: { code: checked.code } }))
+ return
+ }
+ const fresh = !log.acks.some((a) => (a as { pub: string }).pub === checked.ack.pub && (a as { signer: string }).signer === checked.ack.signer)
+ if (fresh) log.acks.push(checked.ack)
+ res.end(json({ success: true, data: { created: fresh } }))
+ if (fresh) this.deviceKeysChanged()
+ })
+ return true
+ }
+
+ /** A machine's own append to the log, over its socket: only about itself, as the real backend allows. */
+ private devlogAppend(machineId: string, payload: Record<string, unknown> | undefined): void {
+ const requestId = typeof payload?.requestId === 'string' ? payload.requestId : ''
+ const entry = payload?.entry as DevLogEntry | undefined
+ const signer = entry && this.deviceLog?.state.active[entry.signer]
+ const own = !!entry && (entry.op === 'add' ? entry.kind === 'machine' && entry.machineId === machineId : signer?.kind === 'machine' && signer.machineId === machineId)
+ const answer = !entry ? { error: 'BAD_ENTRY' } : !own ? { error: 'WRONG_CHANNEL' } : this.appendDeviceEntry(entry)
+ this.sendNode(machineId, '', { type: 'devlog_append_result', payload: { requestId, ...answer } })
+ }
+
/** The web clients bound to a machine now, by connection id. */
webConnections(machineId: string): string[] {
return [...this.webClients].filter((client) => client.machineId === machineId && client.ws.readyState === WebSocket.OPEN).map((client) => client.connId)
@@ -297,6 +389,8 @@ export class FakeBackend {
let envelope: { t?: string; targetConnId?: string; commanderEligible?: boolean; webEligible?: boolean; frame?: Frame }
try { envelope = JSON.parse(raw.toString()) } catch { return }
if (envelope.t !== 'up' || !envelope.frame) return
+ // The backend's own business, answered to this machine alone: never relayed.
+ if (envelope.frame.type === 'devlog_append' && this.deviceLog) { this.devlogAppend(machineId, envelope.frame.payload); return }
const tagged = { ...envelope.frame, machineId }
if (envelope.targetConnId) {
const owner = this.connOwners.get(envelope.targetConnId)
diff --git a/cli/e2e/harness/fleet.ts b/cli/e2e/harness/fleet.ts
index dbd8b9116..333d909f9 100644
--- a/cli/e2e/harness/fleet.ts
+++ b/cli/e2e/harness/fleet.ts
@@ -86,7 +86,7 @@ export async function writeE2ee(daemon: IsolatedDaemon, files: Record<string, un
}
/** A daemon for one machine of the account, signed in to the fake backend and nothing else. */
-async function signedInDaemon(backend: FakeBackend, spec: FakeMachine, env: Record<string, string> = {}, scriptPath?: string): Promise<IsolatedDaemon> {
+export async function signedInDaemon(backend: FakeBackend, spec: FakeMachine, env: Record<string, string> = {}, scriptPath?: string): Promise<IsolatedDaemon> {
const daemon = await IsolatedDaemon.create({ ...(scriptPath ? { scriptPath } : {}), env: { ...remoteSettings(backend), ADAPTER_COMPUTER_ID: spec.computerId, ...env } })
// The daemon inherits the runner's environment, where a registry or a proxy may be named. None of
// them is anywhere a fleet daemon may go.
diff --git a/cli/scripts/gen-devack-vectors.ts b/cli/scripts/gen-devack-vectors.ts
new file mode 100644
index 000000000..1d7313297
--- /dev/null
+++ b/cli/scripts/gen-devack-vectors.ts
@@ -0,0 +1,87 @@
+/**
+ * Regenerates src/lib/e2ee/deviceAck.vectors.json — the fixture every implementation of the device
+ * acknowledgement (deviceAck.ts: CLI, backend, desktop and mobile Dart) is held to. Deterministic: fixed
+ * seeds, Ed25519 signs deterministically. Run: `npx tsx scripts/gen-devack-vectors.ts`, then copy the
+ * file to backend/src/lib/ and to desktop/test/viewer/ and mobile/test/viewer/.
+ */
+import { writeFileSync } from 'fs'
+import { join } from 'path'
+import { ed25519 } from '@noble/curves/ed25519'
+import { lvCat } from '../src/lib/e2ee/core.js'
+import { checkDevAck, devAckMessage, signDevAck, type DevAck, type UnsignedDevAck } from '../src/lib/e2ee/deviceAck.js'
+import { applyDevLogEntries, emptyDevLogState, nextDevLogEntry, signDevLogEntry, type DevLogEntry, type DevLogState } from '../src/lib/e2ee/deviceLog.js'
+
+const b64 = (u: Uint8Array): string => Buffer.from(u).toString('base64')
+const seed = (n: number): Uint8Array => new Uint8Array(32).fill(n)
+const keys = { box1: seed(1), box2: seed(2), browser: seed(3), stranger: seed(4) }
+type Name = keyof typeof keys
+const pub = (k: Name): string => b64(ed25519.getPublicKey(keys[k]))
+const acct = 'acct-vectors-1'
+const MID1 = 'a'.repeat(32)
+const MID2 = 'b'.repeat(32)
+
+// The log the acknowledgements are checked against: two machines and a browser, then box2 removed.
+let state: DevLogState = emptyDevLogState(acct)
+const log: DevLogEntry[] = []
+function add(k: Name, kind: 'machine' | 'viewer', machineId: string, label: string, at: number): void {
+ const e = signDevLogEntry(nextDevLogEntry(state, { op: 'add', pub: pub(k), kind, machineId, label, signer: pub(k) }, at), keys[k])
+ state = applyDevLogEntries(state, [e]).state
+ log.push(e)
+}
+add('box1', 'machine', MID1, 'box1', 1_000)
+add('box2', 'machine', MID2, 'box2', 2_000)
+add('browser', 'viewer', '', 'browser', 3_000)
+{
+ const m = state.active[pub('box2')]
+ const e = signDevLogEntry(nextDevLogEntry(state, { op: 'remove', pub: m.pub, kind: m.kind, machineId: m.machineId, label: m.label, signer: pub('box1') }, 4_000), keys.box1)
+ state = applyDevLogEntries(state, [e]).state
+ log.push(e)
+}
+
+const unsigned = (by: Name, of: Name, addSeq: number, at = 5_000, account = acct): UnsignedDevAck =>
+ ({ v: 1, acct: account, pub: pub(of), addSeq, signer: pub(by), at })
+const ack = (by: Name, of: Name, addSeq: number, at?: number, account?: string): DevAck => signDevAck(unsigned(by, of, addSeq, at, account), keys[by])
+
+const valid = [ack('box1', 'browser', 3), ack('browser', 'box1', 1, 6_000)]
+for (const a of valid) if (!checkDevAck(state, a).ok) throw new Error('a valid acknowledgement was refused')
+
+/** Each invalid case must be refused with `code`. */
+const invalid: Array<{ name: string; ack: unknown; code: string }> = []
+function bad(name: string, raw: unknown, code: string): void {
+ const r = checkDevAck(state, raw)
+ if (r.ok || r.code !== code) throw new Error(`${name}: expected ${code}, got ${r.ok ? 'ok' : r.code}`)
+ invalid.push({ name, ack: raw, code })
+}
+bad('tampered time', { ...ack('box1', 'browser', 3), at: 5_001 }, 'BAD_SIGNATURE')
+// The same fields signed under the device log's tag: a signature is only ever good for the one kind of
+// record it was made for.
+{
+ const u = unsigned('box1', 'browser', 3)
+ const wrongTag = lvCat('harness-devlog-v1', String(u.v), u.acct, Buffer.from(u.pub, 'base64'), String(u.addSeq), Buffer.from(u.signer, 'base64'), String(u.at))
+ bad('signed under the device log tag', { ...u, sig: b64(ed25519.sign(wrongTag, keys.box1)) }, 'BAD_SIGNATURE')
+}
+bad('signed by another key than the signer', { ...unsigned('box1', 'browser', 3), sig: b64(ed25519.sign(devAckMessage(unsigned('box1', 'browser', 3)), keys.stranger)) }, 'BAD_SIGNATURE')
+bad('a key acknowledging itself', ack('browser', 'browser', 3), 'SELF_ACK')
+bad('signer not in the log', ack('stranger', 'browser', 3), 'SIGNER_NOT_ACTIVE')
+bad('signer removed from the log', ack('box2', 'browser', 3), 'SIGNER_NOT_ACTIVE')
+bad('wrong add entry', ack('box1', 'browser', 2), 'NOT_ADDED_THERE')
+bad('key removed from the log', ack('box1', 'box2', 2), 'NOT_ADDED_THERE')
+bad('key never in the log', ack('box1', 'stranger', 3), 'NOT_ADDED_THERE')
+bad('another account', ack('box1', 'browser', 3, 5_000, 'acct-other'), 'WRONG_ACCOUNT')
+bad('unknown version', { ...ack('box1', 'browser', 3), v: 2 }, 'BAD_ACK')
+bad('add entry zero', ack('box1', 'browser', 0), 'BAD_ACK')
+bad('key of the wrong length', { ...ack('box1', 'browser', 3), pub: b64(new Uint8Array(31)) }, 'BAD_ACK')
+bad('not an object', 'ack', 'BAD_ACK')
+
+const out = {
+ comment: 'Generated by cli/scripts/gen-devack-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4). `message` is the hex of devAckMessage(valid[0]).',
+ acct,
+ seeds: Object.fromEntries(Object.entries(keys).map(([k, v]) => [k, b64(v)])),
+ pubs: Object.fromEntries(Object.keys(keys).map((k) => [k, pub(k as Name)])),
+ log,
+ message: Buffer.from(devAckMessage(valid[0])).toString('hex'),
+ valid,
+ invalid,
+}
+writeFileSync(join(import.meta.dirname, '../src/lib/e2ee/deviceAck.vectors.json'), JSON.stringify(out, null, 2) + '\n')
+console.log(`wrote ${valid.length} valid acknowledgements, ${invalid.length} invalid cases`)
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 4890ce12d..46ebdb69f 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -200,7 +200,8 @@ every future connect, until you change or clear it:
first 4+ characters); a # or a shorter start asks first, --yes skips it
harness devices history every device added to or removed from the account, newest first, as this
machine verified it (--json for the rows)
- harness devices dismiss [<#|fp>] mark every new device as seen, or just that one
+ harness devices dismiss [<#|fp>] mark every new device as seen here, or say one is yours — your
+ other devices then stop showing it as new too
harness devices rebaseline the device list froze (the backend served one that does not match what
this machine verified): show what changed, --yes to trust it again
(both \`remote-password set\` and \`link connect\` prompt for the password interactively, or read one
@@ -2182,10 +2183,15 @@ async function devicesCommand(sub: string | undefined, arg: string | undefined,
const listed = out.members.some((m) => norm(m.fingerprint).startsWith(key))
target = gone.length === 1 && !listed ? gone[0] : resolve(arg, out.members).row
}
- const { status } = await call('POST', '/api/devices/dismiss', target ? { pub: target.pub } : {})
+ // One device named is "It's mine" for it: the account's other devices are told too, and stop showing
+ // it as new. Every device at once is only "seen here" — nobody vouched for each one.
+ const { status, json: out } = await call('POST', '/api/devices/dismiss', target ? { pub: target.pub, confirm: true } : {})
needsNewerDaemon(status)
if (status !== 200) { console.error(`\n ✗ Could not mark ${target ? 'it' : 'them'} as seen (is this machine signed in?).\n`); process.exit(1) }
- console.log(target ? `\n ✓ Marked ${target.label || '(no name)'} as seen.\n` : '\n ✓ Marked every device as seen.\n')
+ const name = target?.label || '(no name)'
+ console.log(!target ? '\n ✓ Marked every device as seen.\n'
+ : out.shared === true ? `\n ✓ Marked ${name} as yours, here and on your other devices.\n`
+ : `\n ✓ Marked ${name} as seen.\n`)
process.exit(0)
}
if (sub === 'rebaseline') {
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 31ca69add..1feec8abd 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -1236,7 +1236,8 @@ export interface GatewayOps {
devicesList(): Promise<HttpAnswer>
devicesRemove(pub: string): Promise<HttpAnswer>
devicesHistory(): Promise<HttpAnswer>
- devicesDismiss(body: { pub?: string; pubs?: string[]; baseline?: boolean }): Promise<HttpAnswer>
+ /** `confirm`: "It's mine" for the one key named, shared with the account's other devices. */
+ devicesDismiss(body: { pub?: string; pubs?: string[]; baseline?: boolean; confirm?: boolean }): Promise<HttpAnswer>
devicesRebaseline(confirm: boolean, head?: { seq: number; hash: string }): Promise<HttpAnswer>
/** The Wi-Fi device's direct links: discovered devices, pairing one, and its pairings. A refusal is an
* answer (`{ refused }`), as the device's local API words it. */
diff --git a/cli/src/devicesCommand.spec.ts b/cli/src/devicesCommand.spec.ts
index 3305de38b..ae04948e9 100644
--- a/cli/src/devicesCommand.spec.ts
+++ b/cli/src/devicesCommand.spec.ts
@@ -14,6 +14,8 @@ const dirs: string[] = []
let rebaseConflict = false
/** The daemon answers OTHER_ACCOUNT: on the preview, or only on the confirm. */
let rebaseOther: 'no' | 'preview' | 'confirm' = 'no'
+/** Whether the fake daemon says an "It's mine" reached the account's other devices. */
+let dismissShared = false
const servers: Server[] = []
afterEach(async () => {
@@ -55,8 +57,9 @@ function fakeDaemon(lastSeen: Record<string, number> = { 'pub-old': now - 3 * DA
at: new Date(2026, 9, 1, 14, 5).getTime(), thisDevice: false, afterJoin: true, pending: true, active: true, whileFrozen: false,
}] }))
} else if (newRoutes && req.method === 'POST' && req.url === '/api/devices/dismiss') {
- dismissed.push(JSON.parse(raw))
- res.end(JSON.stringify({ ok: true }))
+ const body = JSON.parse(raw) as { confirm?: boolean }
+ dismissed.push(body)
+ res.end(JSON.stringify({ ok: true, ...(body.confirm ? { shared: dismissShared } : {}) }))
} else if (newRoutes && req.method === 'POST' && req.url === '/api/devices/rebaseline') {
const body = JSON.parse(raw) as { confirm?: boolean; head?: unknown }
rebased.push(body)
@@ -417,9 +420,15 @@ describe('harness devices', () => {
const d = await fakeDaemon(undefined, undefined, {}, true)
const all = await run(d.port, ['dismiss'])
expect(all.stdout).toContain('Marked every device as seen.')
+ // One device named is "It's mine" for it; every device at once is only seen here.
const one = await run(d.port, ['dismiss', '3'])
expect(one.stdout).toContain('Marked phone as seen.')
- expect(d.dismissed).toEqual([{}, { pub: 'pub-new' }])
+ expect(d.dismissed).toEqual([{}, { pub: 'pub-new', confirm: true }])
+ dismissShared = true
+ try {
+ const shared = await run(d.port, ['dismiss', '3'])
+ expect(shared.stdout).toContain('Marked phone as yours, here and on your other devices.')
+ } finally { dismissShared = false }
}, 30_000)
it('lists a key that joined and left before you looked, and dismisses it by its key code', async () => {
@@ -430,7 +439,7 @@ describe('harness devices', () => {
expect(list.stdout).toContain('⚠ Chrome joined and left before you looked — mark it seen: harness devices dismiss 7777·6666·5555·4444')
const one = await run(d.port, ['dismiss', '7777·6666'])
expect(one.stdout).toContain('Marked Chrome as seen.')
- expect(d.dismissed).toEqual([{ pub: 'pub-gone' }])
+ expect(d.dismissed).toEqual([{ pub: 'pub-gone', confirm: true }])
}, 30_000)
it('list flags only what the daemon says is pending, and shows the conflict and suspended lines', async () => {
diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.ts
index fa896bd49..9064c6223 100644
--- a/cli/src/gateway/start.ts
+++ b/cli/src/gateway/start.ts
@@ -69,6 +69,13 @@ export interface StartedGateway {
* hello every few seconds, or a relay replaying one, reads the log once, not each time. */
const UNKNOWN_HELLO_EVERY_MS = 10_000
+/** How long a read of the log waits for the acknowledgements ("It's mine" said on another device): it is
+ * part of every read while a key is new here, and a hello from a key not paired here waits on a read
+ * (`trustFromLog`), so a backend slow to answer them must not hold that up for long. */
+const ACK_READ_TIMEOUT_MS = 5_000
+/** How long "It's mine" waits for the backend to keep it; the person's own dismissal is already saved. */
+const ACK_POST_TIMEOUT_MS = 10_000
+
/** What `trustFromLog` found, as the log line says it. */
const TRUST_OUTCOME: Record<DeviceLogTrustOutcome, string> = {
trusted: 'trusted: it is on the account\'s device list',
@@ -253,6 +260,20 @@ export function startGateway(host: GatewayHost): StartedGateway {
|| !Number.isSafeInteger(head.seq) || head.seq < 0 || typeof head.hash !== 'string') return null
return { acct: data.acct, head: { seq: head.seq, hash: head.hash }, entries: data.entries }
},
+ // "It's mine", once for the account (deviceAck.ts): beside the log, over REST like its reads. Not over
+ // this machine's socket like an append: an acknowledgement's authority is its signature by a key
+ // active on the log, which every device checks itself, so the channel ties nothing to it.
+ fetchAcks: async (since) => {
+ // A short deadline: the read of the log that asked waits on it (ACK_READ_TIMEOUT_MS).
+ const r = await accountHttp.backend('GET', `/api/device-keys/acks?since=${since}`, undefined, ACK_READ_TIMEOUT_MS)
+ const acks = r.status === 200 ? (r.body.data as { acks?: unknown } | undefined)?.acks : undefined
+ return Array.isArray(acks) ? acks : null
+ },
+ postAck: async (ack) => {
+ const r = await accountHttp.backend('POST', '/api/device-keys/acks', { ack }, ACK_POST_TIMEOUT_MS)
+ if (r.status !== 200 && r.status !== 404) console.log(`[devlog] the backend did not keep "It's mine" (${r.status}: ${String((r.body.error as { code?: unknown } | undefined)?.code ?? '')})`)
+ return r.status === 200
+ },
append: async (entry) => {
const p = await gateway.appendDeviceLog(entry as unknown as Record<string, unknown>)
if (!p) return null
@@ -422,7 +443,11 @@ export function startGateway(host: GatewayHost): StartedGateway {
return { status, body: { error: r.error, ...(r.detail ? { detail: r.detail } : {}) } }
},
devicesHistory: async () => ({ status: 200, body: { ...(await devlog.history()) } }),
- devicesDismiss: async (body) => { devlog.dismiss(body); return { status: 200, body: { ok: true } } },
+ // `shared`: an "It's mine" (`confirm`) reached the backend for the account's other devices.
+ devicesDismiss: async (body) => {
+ const shared = await devlog.dismiss(body)
+ return { status: 200, body: { ok: true, ...(body.confirm ? { shared } : {}) } }
+ },
devicesRebaseline: async (confirm, head) => {
const r = await devlog.rebaseline(confirm, head)
if (r && 'error' in r) return { status: 409, body: { error: r.error } }
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index e3e482479..04a6acd84 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -747,6 +747,11 @@ describe('the device history and dismiss endpoints', () => {
expect((await post(JSON.stringify({ pubs: 'a' }))).status).toBe(400)
expect((await post(JSON.stringify({ pubs: ['a', 5] }))).status).toBe(400)
expect((await post(JSON.stringify({ pubs: Array.from({ length: 257 }, (_, i) => `k${i}`) }))).status).toBe(400)
+ // "It's mine": only a literal true asks for the other devices to be told.
+ expect((await post(JSON.stringify({ pubs: ['a'], confirm: true }))).status).toBe(200)
+ expect(onDevicesDismiss).toHaveBeenLastCalledWith({ pubs: ['a'], confirm: true })
+ expect((await post(JSON.stringify({ pub: 'k', confirm: 'yes' }))).status).toBe(200)
+ expect(onDevicesDismiss).toHaveBeenLastCalledWith({ pub: 'k' })
})
it('rebaseline passes the previewed head on, and refuses a malformed one', async () => {
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index fa60d2703..5402e048e 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -947,7 +947,7 @@ export function startHookServer(
if (req.method === 'POST' && url === '/api/devices/dismiss') {
if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
if (!handlers.onDevicesDismiss) { json(503, { error: 'UNAVAILABLE' }); return }
- let body: { pub?: unknown; pubs?: unknown; baseline?: unknown }
+ let body: { pub?: unknown; pubs?: unknown; baseline?: unknown; confirm?: unknown }
try { body = JSON.parse(await readBody(req)) as typeof body } catch { json(400, { error: 'bad json' }); return }
if (!body || typeof body !== 'object') { json(400, { error: 'bad json' }); return }
if (body.pub !== undefined && (typeof body.pub !== 'string' || !body.pub)) { json(400, { error: 'MISSING_PUB' }); return }
@@ -958,6 +958,8 @@ export function startHookServer(
...(typeof body.pub === 'string' ? { pub: body.pub } : {}),
...(Array.isArray(body.pubs) ? { pubs: body.pubs as string[] } : {}),
...(body.baseline === true ? { baseline: true } : {}),
+ // "It's mine" for one device: the account's other devices are told too (deviceLogSyncer `dismiss`).
+ ...(body.confirm === true ? { confirm: true } : {}),
}); json(out.status, out.body); return
}
diff --git a/cli/src/lib/e2ee/deviceAck.spec.ts b/cli/src/lib/e2ee/deviceAck.spec.ts
new file mode 100644
index 000000000..16ca20887
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceAck.spec.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { ed25519 } from '@noble/curves/ed25519'
+import vectors from './deviceAck.vectors.json' with { type: 'json' }
+import { checkDevAck, devAckMessage, parseDevAck, signDevAck, verifyDevAckSignature, type DevAck } from './deviceAck.js'
+import { applyDevLogEntries, emptyDevLogState } from './deviceLog.js'
+
+const b64d = (s: string): Uint8Array => new Uint8Array(Buffer.from(s, 'base64'))
+const read = (rel: string): Buffer => readFileSync(fileURLToPath(new URL(rel, import.meta.url)))
+/** A source file from its first line after the imports: what every copy must share. */
+const belowImports = (src: string): string => {
+ const lines = src.split('\n')
+ let last = -1
+ lines.forEach((l, i) => { if (l.startsWith('import ')) last = i })
+ return lines.slice(last + 1).join('\n')
+}
+
+describe('device acknowledgement vectors', () => {
+ const state = applyDevLogEntries(emptyDevLogState(vectors.acct), vectors.log).state
+ const seeds = vectors.seeds as Record<string, string>
+ const byPub = new Map(Object.entries(vectors.pubs).map(([name, pub]) => [pub, b64d(seeds[name])]))
+
+ it('every other copy of the fixture is byte-identical to this one', () => {
+ const here = read('./deviceAck.vectors.json')
+ for (const copy of ['../../../../backend/src/lib/deviceAck.vectors.json', '../../../../desktop/test/viewer/deviceAck.vectors.json', '../../../../mobile/test/viewer/deviceAck.vectors.json']) {
+ expect(read(copy).equals(here), `${copy} differs: run scripts/gen-devack-vectors.ts and copy it`).toBe(true)
+ }
+ })
+
+ it('the backend copy of the module is this one, below the imports', () => {
+ const backend = read('../../../../backend/src/lib/deviceAckCore.ts').toString()
+ expect(belowImports(backend)).toBe(belowImports(read('./deviceAck.ts').toString()))
+ })
+
+ it('derives the fixture keys from their seeds', () => {
+ for (const [name, seed] of Object.entries(seeds)) {
+ expect(Buffer.from(ed25519.getPublicKey(b64d(seed))).toString('base64')).toBe((vectors.pubs as Record<string, string>)[name])
+ }
+ })
+
+ it('encodes the first acknowledgement to the fixture bytes', () => {
+ expect(Buffer.from(devAckMessage(vectors.valid[0])).toString('hex')).toBe(vectors.message)
+ })
+
+ it('re-signs every valid acknowledgement to the same signature, and accepts it', () => {
+ for (const a of vectors.valid) {
+ const { sig, ...unsigned } = a
+ expect(signDevAck(unsigned, byPub.get(a.signer)!).sig).toBe(sig)
+ expect(checkDevAck(state, a)).toEqual({ ok: true, ack: a })
+ }
+ })
+
+ for (const c of vectors.invalid) {
+ it(`refuses: ${c.name} (${c.code})`, () => {
+ expect(checkDevAck(state, c.ack)).toEqual({ ok: false, code: c.code })
+ })
+ }
+})
+
+describe('parseDevAck', () => {
+ const good = vectors.valid[0] as DevAck
+
+ it('takes exactly the fields it signs', () => {
+ expect(parseDevAck({ ...good, extra: 1 })).toEqual(good)
+ })
+
+ it('refuses each field out of bounds', () => {
+ for (const bad of [
+ null, 7, { ...good, acct: '' }, { ...good, acct: 'x'.repeat(129) }, { ...good, acct: 5 },
+ { ...good, signer: 'not base64!' }, { ...good, sig: Buffer.alloc(63).toString('base64') },
+ // Base64 that decodes but is not in its one canonical spelling.
+ { ...good, pub: `${good.pub.slice(0, -2)}x=` }, { ...good, pub: 'A'.repeat(200) },
+ { ...good, addSeq: 1.5 }, { ...good, addSeq: '3' }, { ...good, at: 0 }, { ...good, at: Number.MAX_SAFE_INTEGER + 1 },
+ ]) expect(parseDevAck(bad)).toBeNull()
+ })
+
+ it('a signature that does not decode is no signature', () => {
+ expect(verifyDevAckSignature({ ...good, sig: Buffer.alloc(64, 0xff).toString('base64') })).toBe(false)
+ })
+})
diff --git a/cli/src/lib/e2ee/deviceAck.ts b/cli/src/lib/e2ee/deviceAck.ts
new file mode 100644
index 000000000..1338fe013
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceAck.ts
@@ -0,0 +1,140 @@
+/**
+ * "It's mine", said once for the whole account: a device's signed acknowledgement that another device
+ * on the account's device key log (deviceLog.ts) is the person's own. Without it every device kept a new
+ * key marked New until someone looked at it THERE; with it, one trusted device confirming the new one is
+ * enough for the others to stop asking.
+ *
+ * Kept OUTSIDE the hash chain on purpose. An op the log does not know makes every older client freeze
+ * the whole log as invalid, so the chain keeps its two ops (`add`, `remove`) and acknowledgements ride
+ * beside it: an older client never sees one, and behaves exactly as before.
+ *
+ * An acknowledgement never adds trust. It only takes a key that is already trusted (it is active on the
+ * log) off the "New" list. And no device takes the backend's word for one: each checks the signature
+ * itself, against its own verified log, with `checkDevAck` — plus its own marks (the signer must not be
+ * new, suspended or gone there; a suspended key stays suspended, which only the person lifts, on that
+ * device).
+ *
+ * Pure: no I/O. The signature covers a length-prefixed binary encoding of the fields in a fixed order,
+ * headed by its OWN domain tag (`harness-devack-v1`), so a signature made for a log entry can never be
+ * passed off as an acknowledgement or the other way round. JSON is only the wire format.
+ *
+ * ⚠ Ported to Dart (desktop/lib/viewer/device_ack.dart, mobile/lib/viewer/device_ack.dart) and copied
+ * into the backend (backend/src/lib/deviceAckCore.ts, identical below the imports). All of them are held
+ * to deviceAck.vectors.json (cli/scripts/gen-devack-vectors.ts); change the format in every copy together.
+ */
+import { ed25519 } from '@noble/curves/ed25519'
+import type { DevLogState } from './deviceLog.js'
+
+export const DEVACK_VERSION = 1
+/** The domain tag that heads every signed acknowledgement. Never the device log's (`harness-devlog-v1`). */
+export const DEVACK_TAG = 'harness-devack-v1'
+
+export interface DevAck {
+ v: number
+ /** The account (backend User id) whose log names both keys. */
+ acct: string
+ /** base64 Ed25519 key of the device being acknowledged. */
+ pub: string
+ /** seq of the log entry that added `pub`: an acknowledgement is of that one entry, never of the key in
+ * general (a key cannot come back after a remove, but naming the entry keeps it exact). */
+ addSeq: number
+ /** base64 Ed25519 key of the device that acknowledges it, and signs it. */
+ signer: string
+ /** Milliseconds since the epoch, as the signer's clock read it. Shown, never trusted for anything. */
+ at: number
+ sig: string
+}
+
+export type UnsignedDevAck = Omit<DevAck, 'sig'>
+
+/** Why `checkDevAck` refused an acknowledgement. */
+export type DevAckRefusal =
+ | 'BAD_ACK'
+ | 'WRONG_ACCOUNT'
+ | 'BAD_SIGNATURE'
+ | 'SELF_ACK'
+ | 'SIGNER_NOT_ACTIVE'
+ | 'NOT_ADDED_THERE'
+
+const HAS_BUFFER = typeof Buffer !== 'undefined'
+
+function b64e(u: Uint8Array): string {
+ if (HAS_BUFFER) return Buffer.from(u).toString('base64')
+ let s = ''
+ for (let i = 0; i < u.length; i++) s += String.fromCharCode(u[i])
+ return btoa(s)
+}
+function b64d(s: string): Uint8Array {
+ if (HAS_BUFFER) return new Uint8Array(Buffer.from(s, 'base64'))
+ const bin = atob(s)
+ const u = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i)
+ return u
+}
+/** base64 of exactly [n] bytes, in its one canonical spelling; false otherwise. */
+function isBytes(s: unknown, n: number): s is string {
+ if (typeof s !== 'string' || s.length > 128) return false
+ try {
+ const u = b64d(s)
+ return u.length === n && b64e(u) === s
+ } catch { return false }
+}
+function lvCat(...parts: Array<Uint8Array | string>): Uint8Array {
+ const chunks: Uint8Array[] = []
+ let total = 0
+ for (const p of parts) {
+ const b = typeof p === 'string' ? new TextEncoder().encode(p) : p
+ const len = new Uint8Array(4)
+ new DataView(len.buffer).setUint32(0, b.length, false)
+ chunks.push(len, b)
+ total += 4 + b.length
+ }
+ const out = new Uint8Array(total)
+ let off = 0
+ for (const c of chunks) { out.set(c, off); off += c.length }
+ return out
+}
+
+/** The bytes a signature covers. Numbers are written in decimal, so every language agrees. */
+export function devAckMessage(a: UnsignedDevAck): Uint8Array {
+ return lvCat(DEVACK_TAG, String(a.v), a.acct, b64d(a.pub), String(a.addSeq), b64d(a.signer), String(a.at))
+}
+
+export function signDevAck(a: UnsignedDevAck, priv: Uint8Array): DevAck {
+ return { ...a, sig: b64e(ed25519.sign(devAckMessage(a), priv)) }
+}
+
+/** Every field present, of its type and within bounds; null when anything is off. */
+export function parseDevAck(raw: unknown): DevAck | null {
+ if (!raw || typeof raw !== 'object') return null
+ const { v, acct, pub, addSeq, signer, at, sig } = raw as Record<string, unknown>
+ if (v !== DEVACK_VERSION) return null
+ if (typeof acct !== 'string' || !acct || acct.length > 128) return null
+ if (!isBytes(pub, 32) || !isBytes(signer, 32) || !isBytes(sig, 64)) return null
+ if (!Number.isSafeInteger(addSeq) || (addSeq as number) < 1) return null
+ if (!Number.isSafeInteger(at) || (at as number) <= 0) return null
+ return { v, acct, pub, addSeq: addSeq as number, signer, at: at as number, sig }
+}
+
+/** Whether [a]'s signature is its signer's, over its fields. */
+export function verifyDevAckSignature(a: DevAck): boolean {
+ try { return ed25519.verify(b64d(a.sig), devAckMessage(a), b64d(a.signer)) } catch { return false }
+}
+
+/**
+ * Check [raw] against [state], a device key log as verified by whoever is asking: well formed, of this
+ * account, signed by its signer, not the key vouching for itself, the signer active on the log, and
+ * `pub` active on it and added at `addSeq`. What it does NOT judge is each device's own: whether the
+ * signer is itself new, suspended or gone there, or whether `pub` is suspended there.
+ */
+export function checkDevAck(state: DevLogState, raw: unknown): { ok: true; ack: DevAck } | { ok: false; code: DevAckRefusal } {
+ const ack = parseDevAck(raw)
+ if (!ack) return { ok: false, code: 'BAD_ACK' }
+ if (ack.acct !== state.acct) return { ok: false, code: 'WRONG_ACCOUNT' }
+ if (!verifyDevAckSignature(ack)) return { ok: false, code: 'BAD_SIGNATURE' }
+ // A key saying it is its own owner's says nothing: whoever added it would sign that too.
+ if (ack.signer === ack.pub) return { ok: false, code: 'SELF_ACK' }
+ if (!state.active[ack.signer]) return { ok: false, code: 'SIGNER_NOT_ACTIVE' }
+ if (state.active[ack.pub]?.seq !== ack.addSeq) return { ok: false, code: 'NOT_ADDED_THERE' }
+ return { ok: true, ack }
+}
diff --git a/cli/src/lib/e2ee/deviceAck.vectors.json b/cli/src/lib/e2ee/deviceAck.vectors.json
new file mode 100644
index 000000000..838e0d1a2
--- /dev/null
+++ b/cli/src/lib/e2ee/deviceAck.vectors.json
@@ -0,0 +1,271 @@
+{
+ "comment": "Generated by cli/scripts/gen-devack-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4). `message` is the hex of devAckMessage(valid[0]).",
+ "acct": "acct-vectors-1",
+ "seeds": {
+ "box1": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
+ "box2": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=",
+ "browser": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "stranger": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ="
+ },
+ "pubs": {
+ "box1": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "box2": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "browser": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "stranger": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw="
+ },
+ "log": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 1000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "PQ79548gYy1fR00xYYrAqGYQer//uS3fGo1Xwwih7v6Jpw8lLHsM/plOYoenu8qjIWhPTSPlVSghlAt9C6MMCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 2000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "bHi9oSluvJ/RKgTw7RZrPaplcR45FGkVMmnOjm4dQnTzchKsMN6D6WKTNphHLjthUYhcznmjIJDLjplJ5TKsAg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 3000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "browser",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "vYm6LtYV1vK3yQR7Sp1/EPFoiFTOyM+7zhsnDUCXZUDeYJ1e9SL7m3xjEGdgo3x9Fd6DPwM51bkDwz9JstSpCQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "vMPGnQgYDO21pqy7wyaTJJGLaHpCdXDVAIkJrfJ7KUA=",
+ "at": 4000,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "gYDuihZziynx5hm1/FB2kZUKs+qZzVT1CZ4MbtjCSdKJEYM/736O4oKgFCnzg6RdHlGLcqUTRhkq3xZ3sqxuCA=="
+ }
+ ],
+ "message": "000000116861726e6573732d64657661636b2d763100000001310000000e616363742d766563746f72732d3100000020ed4928c628d1c2c6eae90338905995612959273a5c63f93636c14614ac8737d10000000133000000208a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c0000000435303030",
+ "valid": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "addSeq": 1,
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "at": 6000,
+ "sig": "Tvs71LrL6KUWDTzt8vqopLsIubbiEF+Q+wHMjPNappC+jCvHUXvOuUwnPHAIovDQGhCnOybac7StvvHFm0k1Bg=="
+ }
+ ],
+ "invalid": [
+ {
+ "name": "tampered time",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5001,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "signed under the device log tag",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "UiDLPvPt03A2Am5iDEakR3ilJc/OC1cfF2jhL7n3a+4UJN+pFFENwJPRTWodgahPRyw9SeyB0LOue6L4FzFQDw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "signed by another key than the signer",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "eqjcnHjAWOjrRa1aGALmlEzLhVZR1QkzxNsCxV+l/8/wlbK+NoHtTnR/+tlhxXmhCMdrTVuZSS4Q0HZESphFDw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "a key acknowledging itself",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "at": 5000,
+ "sig": "Cmg55AVm78H0Uvm25ugS1dX8QncK0jVBztdkmP2mMfY/2Ze+NaBSWCkX35MXiAO5JjdGwT7oNIdjN0egnm26BA=="
+ },
+ "code": "SELF_ACK"
+ },
+ {
+ "name": "signer not in the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "at": 5000,
+ "sig": "MGKqHpl4Oe701BsU7aWlmsgOUDnJ7WqOQjbWmBvGiPqM26/5MPuT8fHqHTgMqfbzC2U0K5YBKlKqbK1hwjl1Bw=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "signer removed from the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "at": 5000,
+ "sig": "y2HnM3LiMr69YaXjuNNsWNE0iLwQ3ZfzFzyLYck9SPbOa6Orz3lPI/32MzN0UCC4Ng/EQySy5XYFZAeLbQf0AA=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "wrong add entry",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 2,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "3dCkpuz6Tu5XEmvFIGnFQaiLin+Ninldkrmvp6K/a9g1EqEJ4uTds8dMdtqZKjsAIZpMEKKQUGbrL3wWeBOBCg=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "key removed from the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "addSeq": 2,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "/GLyfKMRBF4JXwbg07KnkIB1wHMnZHkwIs4+utnxwJrobNkI9kaf0GdcBewxkt9F0MJ5MvWqWpwuQGraVpo9BA=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "key never in the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "U+ud4hDLUP1a4uAJY8+oPqBCho6vndu3AflTI7NhfUYcIukAH65jtjM3WArUDhO3iM8+GG9XYvBz66o+Pf8kDw=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "another account",
+ "ack": {
+ "v": 1,
+ "acct": "acct-other",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "cTBr1vv9/MOr3txBo0ZoPG7RK+YvqsxfNGyCG1bv5djsBaIAOHh9JeW0PEse15pstinySS5fZfcscgMhmbJEBg=="
+ },
+ "code": "WRONG_ACCOUNT"
+ },
+ {
+ "name": "unknown version",
+ "ack": {
+ "v": 2,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "add entry zero",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 0,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "848QPR9kk82i9U1SGs7xcG7cZDAq8M6a7erc9FFGQk9QQui8X/HoCMzdmydlVxy4jvGHvNGepQ41htILwCvvDw=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "key of the wrong length",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "not an object",
+ "ack": "ack",
+ "code": "BAD_ACK"
+ }
+ ]
+}
diff --git a/cli/src/lib/e2ee/deviceDisplay.spec.ts b/cli/src/lib/e2ee/deviceDisplay.spec.ts
index 0b893a32f..4b6d4d333 100644
--- a/cli/src/lib/e2ee/deviceDisplay.spec.ts
+++ b/cli/src/lib/e2ee/deviceDisplay.spec.ts
@@ -172,6 +172,12 @@ describe('formatDeviceDetail', () => {
expect(text).toContain(`Not yours? harness devices remove ${FP_OLD}`)
expect(text).not.toContain('This is this machine.')
})
+ it('says on which device a key was confirmed, and nothing for one that was not', () => {
+ const app = listing().members[2]
+ expect(formatDeviceDetail({ ...app, confirmed: { by: 'B', label: 'studio-mac', at: NOW } }, undefined, NOW).join('\n')).toContain('confirmed on studio-mac')
+ expect(formatDeviceDetail({ ...app, confirmed: { by: 'B', label: '', at: NOW } }, undefined, NOW).join('\n')).toContain('confirmed on another device')
+ expect(formatDeviceDetail(app, undefined, NOW).join('\n')).not.toContain('confirmed')
+ })
it('shows an app without a machine row, and unknown activity', () => {
const app = listing().members[2]
const text = formatDeviceDetail(app, undefined, NOW).join('\n')
diff --git a/cli/src/lib/e2ee/deviceDisplay.ts b/cli/src/lib/e2ee/deviceDisplay.ts
index f02af80d9..8568888fb 100644
--- a/cli/src/lib/e2ee/deviceDisplay.ts
+++ b/cli/src/lib/e2ee/deviceDisplay.ts
@@ -10,7 +10,7 @@ import type { DevLogHistoryRow } from './deviceHistory.js'
/** The fields of a listing row this module reads. `seq` (log position) and `firstSeen` (when this
* machine first applied the add) are the two a device cannot choose for itself; both optional so a
* daemon that predates them still lists, just without `new`. */
-export type DeviceRow = Pick<DeviceLogListing['members'][number], 'pub' | 'label' | 'machineId' | 'addedAt' | 'fingerprint' | 'self'> & {
+export type DeviceRow = Pick<DeviceLogListing['members'][number], 'pub' | 'label' | 'machineId' | 'addedAt' | 'fingerprint' | 'self' | 'confirmed'> & {
kind: string
seq?: number
firstSeen?: number
@@ -229,6 +229,9 @@ export function formatDeviceDetail(row: DeviceRow, lastSeen: number | undefined,
lines.push(` added ${fullDateTime(row.addedAt)} (${relativeAgo(row.addedAt, now)})`)
lines.push(` last active ${lastSeen === undefined ? 'unknown' : `${relativeAgo(lastSeen, now)} (${fullDateTime(lastSeen)})`}`)
if (row.kind === 'machine') lines.push(` machine ${row.machineId.slice(0, 8)}`)
+ // Another of the person's devices said "It's mine" for it while it was new here: where, not when it
+ // was looked at here — this machine never showed it as new for long.
+ if (row.confirmed) lines.push(` confirmed on ${row.confirmed.label || 'another device'}`)
lines.push(` key code ${row.fingerprint}`, '')
lines.push(` ${COMPARE_HINT}`, '')
lines.push(row.self ? ' This is this machine.' : ` Not yours? harness devices remove ${row.fingerprint}`, '')
diff --git a/cli/src/lib/e2ee/deviceLogStore.spec.ts b/cli/src/lib/e2ee/deviceLogStore.spec.ts
index 7974ca291..c243aac90 100644
--- a/cli/src/lib/e2ee/deviceLogStore.spec.ts
+++ b/cli/src/lib/e2ee/deviceLogStore.spec.ts
@@ -142,6 +142,20 @@ describe('DeviceLogStore — writes and the archive of other accounts', () => {
expect(store.read().departed?.map((x) => x.pub)).toEqual(['k1'])
})
+ it('keeps which device confirmed a key, and drops unreadable marks rather than failing the read', () => {
+ const path = file()
+ const store = new DeviceLogStore(path)
+ const mark = { by: 'B', label: 'box2', at: 7 }
+ store.write(of('a', { confirmed: { k1: mark } }))
+ expect(store.read().confirmed).toEqual({ k1: mark })
+ writeFileSync(path, JSON.stringify({ ...of('a'), confirmed: { k1: mark, k2: { by: 'B' }, k3: null, k4: { ...mark, at: '7' } } }))
+ expect(store.read().confirmed).toEqual({ k1: mark })
+ for (const junk of [['k1'], 'k1', null]) {
+ writeFileSync(path, JSON.stringify({ ...of('a'), confirmed: junk }))
+ expect(store.read().confirmed).toBeUndefined()
+ }
+ })
+
it('never restores a kept file under an account it is not for', () => {
const path = file()
const store = new DeviceLogStore(path)
diff --git a/cli/src/lib/e2ee/deviceLogStore.ts b/cli/src/lib/e2ee/deviceLogStore.ts
index a584bb3ca..9aa497e7e 100644
--- a/cli/src/lib/e2ee/deviceLogStore.ts
+++ b/cli/src/lib/e2ee/deviceLogStore.ts
@@ -60,6 +60,14 @@ export interface DevLogDeparted {
/** How many departed keys are kept; the oldest goes first. */
export const DEVLOG_DEPARTED = 32
+/** Another of the person's trusted devices said "It's mine" for a key that was new here (deviceAck.ts),
+ * so it is not New here any more: which device, what it was called then, and when this machine read it. */
+export interface DevLogConfirmed {
+ by: string
+ label: string
+ at: number
+}
+
export interface DevLogFile {
state: DevLogState | null
recent: DevLogEntry[]
@@ -97,6 +105,9 @@ export interface DevLogFile {
joining?: boolean
/** New keys removed before anyone looked (oldest first, at most DEVLOG_DEPARTED). */
departed?: DevLogDeparted[]
+ /** New keys another trusted device confirmed, by pub: "Confirmed on <label>" where a banner would have
+ * been. Only ever the reason a key left `pending`; it trusts nothing. */
+ confirmed?: Record<string, DevLogConfirmed>
}
const empty = (): DevLogFile => ({ state: null, recent: [], frozen: null, notifiedUpTo: 0 })
@@ -120,6 +131,18 @@ const isDeparted = (v: unknown): v is DevLogDeparted => {
&& typeof d.selfRemoved === 'boolean'
}
+const isConfirmed = (v: unknown): v is DevLogConfirmed => {
+ if (!v || typeof v !== 'object') return false
+ const c = v as Record<string, unknown>
+ return typeof c.by === 'string' && typeof c.label === 'string' && typeof c.at === 'number'
+}
+
+/** The confirmed marks of a stored file, each one checked; anything else is dropped. */
+function parseConfirmed(raw: unknown): { confirmed?: Record<string, DevLogConfirmed> } {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
+ return { confirmed: Object.fromEntries(Object.entries(raw as Record<string, unknown>).filter((e): e is [string, DevLogConfirmed] => isConfirmed(e[1]))) }
+}
+
/** How many other accounts' files are kept (devlog.archive.json); the oldest goes first. */
export const DEVLOG_ARCHIVED = 4
@@ -147,6 +170,7 @@ function parseFile(value: unknown): DevLogFile {
...(raw.joining === true ? { joining: true } : {}),
...(isConflict(raw.conflict) ? { conflict: raw.conflict } : {}),
...(Array.isArray(raw.departed) ? { departed: raw.departed.filter(isDeparted) } : {}),
+ ...parseConfirmed(raw.confirmed),
}
}
diff --git a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts
index c959b736f..cd5b1bff9 100644
--- a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts
+++ b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts
@@ -8,6 +8,7 @@ import {
type DevLogEntry, type DevLogState,
} from './deviceLog.js'
import { DeviceLogStore } from './deviceLogStore.js'
+import { checkDevAck, signDevAck, type DevAck } from './deviceAck.js'
import { DeviceLogSyncer, devLogDivergence, type DeviceKeysSeen, type DeviceLogAppendAnswer, type DeviceLogFetched, type DeviceLogRebaseline } from './deviceLogSyncer.js'
import { ADOPTED_SIGN_IN } from '../authSession.js'
import { b64d, fingerprint } from './core.js'
@@ -66,6 +67,25 @@ class FakeBackend {
try { this.push(entry) } catch (err) { return { error: err instanceof DevLogError ? err.code : 'X' } }
return { head: this.state.head }
})
+
+ /** The acknowledgements it keeps — served as they are, checked or not: a backend that lies keeps
+ * anything. `acksRoute` false: a backend from before them (null, as a 404 reads). */
+ acks: unknown[] = []
+ acksRoute = true
+ fetchAcks = vi.fn(async (since: number): Promise<unknown[] | null> => {
+ if (this.offline || !this.acksRoute) return null
+ return this.acks.filter((a) => typeof (a as { addSeq?: unknown }).addSeq !== 'number' || (a as { addSeq: number }).addSeq > since)
+ })
+ postAck = vi.fn(async (ack: DevAck): Promise<boolean> => {
+ if (this.offline || !this.acksRoute) return false
+ this.acks.push(ack)
+ return true
+ })
+
+ /** A signed acknowledgement of `of` (added at `addSeq`, or where the log added it) by `by`. */
+ ack(by: { priv: Uint8Array; pub: string }, of: string, addSeq = this.state.active[of]?.seq ?? 1, acct = this.acct): DevAck {
+ return signDevAck({ v: 1, acct, pub: of, addSeq, signer: by.pub, at: 7_000 }, by.priv)
+ }
}
/** `signIn`: the sign-in's epoch (one starting ADOPTED_SIGN_IN is adopted), made at `signInAt` (the
@@ -74,6 +94,8 @@ 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
now?: () => number; seen?: () => Promise<DeviceKeysSeen | null>; log?: (line: string) => void
+ /** Wire the backend's acknowledgements ("It's mine" shared): read and posted. */
+ acks?: boolean
} = {}) {
const backend = opts.backend ?? new FakeBackend()
const store = opts.store ?? new DeviceLogStore(join(mkdtempSync(join(tmpdir(), 'devlog-')), 'devlog.json'))
@@ -96,6 +118,7 @@ function setup(opts: {
self: () => ({ machineId: MID_ME, label: 'my-mac' }),
fetch: backend.fetch,
append: backend.append,
+ ...(opts.acks ? { fetchAcks: backend.fetchAcks, postAck: backend.postAck } : {}),
adopt: calls.adopt,
drop: (pub) => { tombstoned.delete(pub); calls.drop(pub) },
trustedNow: () => [...trusted],
@@ -2244,3 +2267,278 @@ describe('DeviceLogSyncer.sweepStale', () => {
expect(t.backend.append).toHaveBeenCalledTimes(2) // register + the refused removal
})
})
+
+describe('DeviceLogSyncer — "It\'s mine", once for the account', () => {
+ const later = key(5)
+ /** box2 was on the account before this machine joined (trusted, never new); phone joined after (new). */
+ async function joined(opts: Parameters<typeof setup>[0] = {}) {
+ const t = setup({ acks: true, ...opts })
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ expect(t.store.read().pending).toEqual([phone.pub])
+ t.calls.announce.mockClear()
+ t.calls.changed.mockClear()
+ t.backend.fetchAcks.mockClear()
+ return t
+ }
+
+ it('a trusted older device\'s "It\'s mine" takes the new key off the list here, and says on which', async () => {
+ const lines: string[] = []
+ const t = await joined({ log: (l) => lines.push(l) })
+ t.backend.acks.push(t.backend.ack(box2, phone.pub))
+ await t.syncer.refresh()
+ expect(t.store.read().pending).toEqual([])
+ expect(t.syncer.list().members.find((m) => m.pub === phone.pub)).toMatchObject({ pending: false, confirmed: { by: box2.pub, label: 'box2', at: 5_000 } })
+ expect(t.syncer.list().members.find((m) => m.pub === box2.pub)?.confirmed).toBeUndefined()
+ expect(t.calls.changed).toHaveBeenCalled()
+ expect(lines.some((l) => l.includes('confirmed as yours on box2'))).toBe(true)
+ // It stays trusted as it was: an acknowledgement adds no trust and takes none away.
+ expect(t.calls.drop).not.toHaveBeenCalledWith(phone.pub)
+ })
+
+ it('asks from just below the oldest key new here, and not at all while nothing is new', async () => {
+ const t = await joined()
+ await t.syncer.refresh()
+ expect(t.backend.fetchAcks).toHaveBeenCalledWith(t.backend.state.active[phone.pub].seq - 1)
+ t.syncer.dismiss({ pub: phone.pub })
+ t.backend.fetchAcks.mockClear()
+ await t.syncer.refresh()
+ expect(t.backend.fetchAcks).not.toHaveBeenCalled()
+ })
+
+ it('a device confirmed while this machine was away is announced once, as every new key is, then taken off the list', async () => {
+ const t = setup({ acks: true })
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ t.backend.add(later, 'viewer', '', 'later')
+ t.backend.acks.push(t.backend.ack(box2, phone.pub))
+ await t.syncer.refresh()
+ // The one-time "New device" never waits on, or is skipped for, anyone's word.
+ expect(t.calls.announce.mock.calls.map(([m]) => m.pub)).toEqual([phone.pub, later.pub])
+ expect(t.store.read().pending).toEqual([later.pub])
+ await t.syncer.refresh()
+ expect(t.calls.announce).toHaveBeenCalledTimes(2)
+ })
+
+ it('stays as before when the acknowledgements cannot be read, or the read fails', async () => {
+ for (const fail of ['no route', 'throws'] as const) {
+ const lines: string[] = []
+ const t = setup({ acks: true, log: (l) => lines.push(l) })
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ if (fail === 'no route') t.backend.acksRoute = false
+ else t.backend.fetchAcks.mockRejectedValueOnce(new Error('down'))
+ t.backend.add(phone, 'viewer', '', 'phone')
+ t.backend.acks.push(t.backend.ack(box2, phone.pub))
+ await t.syncer.refresh()
+ expect(t.calls.announce, fail).toHaveBeenCalledWith(expect.objectContaining({ pub: phone.pub }))
+ expect(t.store.read().pending, fail).toEqual([phone.pub])
+ if (fail === 'throws') expect(lines.some((l) => l.includes('could not read which devices were confirmed: down'))).toBe(true)
+ }
+ })
+
+ describe('what is ignored', () => {
+ it('a key vouching for itself, a bad signature, the wrong entry, another account, or this machine\'s own', async () => {
+ const t = await joined()
+ const good = t.backend.ack(box2, phone.pub)
+ t.backend.acks.push(
+ t.backend.ack(phone, phone.pub),
+ { ...good, at: good.at + 1 },
+ t.backend.ack(box2, phone.pub, t.backend.state.active[phone.pub].seq - 1),
+ t.backend.ack(box2, phone.pub, undefined, 'acct-2'),
+ t.backend.ack(me, phone.pub),
+ { junk: true },
+ )
+ await t.syncer.refresh()
+ expect(t.store.read().pending).toEqual([phone.pub])
+ expect(t.store.read().confirmed).toBeUndefined()
+ expect(t.calls.changed).not.toHaveBeenCalled()
+ })
+
+ it('a signer that is itself new here: two new devices must not vouch for each other', async () => {
+ const t = await joined()
+ t.backend.add(later, 'viewer', '', 'later')
+ await t.syncer.refresh()
+ t.backend.acks.push(t.backend.ack(later, phone.pub), t.backend.ack(phone, later.pub))
+ await t.syncer.refresh()
+ expect(t.store.read().pending).toEqual([phone.pub, later.pub])
+ })
+
+ it('a signer that is gone (removed, or joined and left before anyone looked)', async () => {
+ const t = await joined()
+ t.backend.add(later, 'viewer', '', 'later')
+ await t.syncer.refresh()
+ const fromLater = t.backend.ack(later, phone.pub)
+ const fromBox2 = t.backend.ack(box2, phone.pub)
+ t.backend.removeBy(later.pub, later)
+ t.backend.removeBy(box2.pub, me)
+ t.backend.acks.push(fromLater, fromBox2)
+ await t.syncer.refresh()
+ expect(t.store.read().departed?.map((d) => d.pub)).toEqual([later.pub])
+ expect(t.store.read().pending).toEqual([phone.pub])
+ })
+
+ it('a signer suspended here, unpaired here, or tombstoned here', async () => {
+ for (const how of ['suspended', 'blocked', 'tombstoned'] as const) {
+ const t = await joined(how === 'blocked' ? { blocked: [box2.pub] } : how === 'tombstoned' ? { tombstoned: [box2.pub] } : {})
+ if (how === 'suspended') t.store.write({ ...t.store.read(), suspended: [box2.pub] })
+ t.backend.acks.push(t.backend.ack(box2, phone.pub))
+ await t.syncer.refresh()
+ expect(t.store.read().pending, how).toEqual([phone.pub])
+ }
+ })
+
+ it('never lifts a suspension: a key a fork suspended here stays new and suspended', async () => {
+ const t = await joined()
+ t.store.write({ ...t.store.read(), suspended: [phone.pub] })
+ t.backend.acks.push(t.backend.ack(box2, phone.pub))
+ await t.syncer.refresh()
+ expect(t.backend.fetchAcks).not.toHaveBeenCalled()
+ expect(t.store.read()).toMatchObject({ pending: [phone.pub], suspended: [phone.pub] })
+ expect(t.calls.resume).not.toHaveBeenCalled()
+ })
+
+ it('nothing at all while the log is frozen here', async () => {
+ const t = await joined()
+ t.store.write({ ...t.store.read(), frozen: { reason: 'fork', at: 1, lastGoodHead: t.backend.state.head } })
+ t.backend.acks.push(t.backend.ack(box2, phone.pub))
+ await t.syncer.refresh()
+ expect(t.backend.fetchAcks).not.toHaveBeenCalled()
+ expect(t.store.read().pending).toEqual([phone.pub])
+ })
+
+ it('a key looked at here while the acknowledgements were on their way is left as the person left it', async () => {
+ const t = await joined()
+ t.backend.acks.push(t.backend.ack(box2, phone.pub))
+ t.backend.fetchAcks.mockImplementationOnce(async () => { t.syncer.dismiss({ pub: phone.pub }); return t.backend.acks })
+ await t.syncer.refresh()
+ expect(t.store.read().confirmed).toBeUndefined()
+ expect(t.calls.changed).toHaveBeenCalledOnce() // the dismissal's own
+ })
+ })
+
+ it('the mark goes with the key: a confirmed key removed later leaves none behind', async () => {
+ const t = await joined()
+ t.backend.acks.push(t.backend.ack(box2, phone.pub))
+ await t.syncer.refresh()
+ expect(t.store.read().confirmed?.[phone.pub]).toBeDefined()
+ t.backend.removeBy(phone.pub, me)
+ await t.syncer.refresh()
+ expect(t.store.read().confirmed).toBeUndefined()
+ // Confirmed, not new: its removal is not a "joined and left before you looked".
+ expect(t.store.read().departed ?? []).toEqual([])
+ })
+
+ describe('"It\'s mine" here is shared', () => {
+ it('for the one device the person pressed it for, signed by this machine for the entry that added it', async () => {
+ for (const opts of [{ pub: phone.pub }, { pubs: [phone.pub] }]) {
+ const t = await joined()
+ expect(await t.syncer.dismiss({ ...opts, confirm: true })).toBe(true)
+ expect(t.store.read().pending).toEqual([])
+ expect(t.backend.acks).toHaveLength(1)
+ expect(t.backend.acks[0]).toMatchObject({ signer: me.pub, pub: phone.pub, addSeq: t.backend.state.active[phone.pub].seq, acct: ACCT })
+ // What every other device checks it against: the same log.
+ expect(checkDevAck(t.backend.state, t.backend.acks[0]).ok).toBe(true)
+ }
+ })
+
+ it('never for a list looked at, every device at once, the baseline, or without "It\'s mine"', async () => {
+ const t = await joined()
+ t.backend.add(later, 'viewer', '', 'later')
+ await t.syncer.refresh()
+ expect(await t.syncer.dismiss({ pubs: [phone.pub, later.pub], confirm: true })).toBe(false)
+ const u = await joined()
+ expect(await u.syncer.dismiss({ pub: phone.pub })).toBe(false)
+ expect(await u.syncer.dismiss({ confirm: true })).toBe(false)
+ expect(await u.syncer.dismiss({ baseline: true, confirm: true })).toBe(false)
+ expect(t.backend.postAck).not.toHaveBeenCalled()
+ expect(u.backend.postAck).not.toHaveBeenCalled()
+ })
+
+ it('never for a key that was not new here, or this machine\'s own', async () => {
+ const t = await joined()
+ expect(await t.syncer.dismiss({ pub: box2.pub, confirm: true })).toBe(false)
+ expect(await t.syncer.dismiss({ pub: me.pub, confirm: true })).toBe(false)
+ t.syncer.dismiss({ pub: phone.pub })
+ expect(await t.syncer.dismiss({ pub: phone.pub, confirm: true })).toBe(false)
+ expect(t.backend.postAck).not.toHaveBeenCalled()
+ })
+
+ it('for a suspended key only when "It\'s mine" lifted the suspension here', async () => {
+ const t = await joined()
+ t.store.write({ ...t.store.read(), suspended: [phone.pub] })
+ expect(await t.syncer.dismiss({ pubs: [phone.pub], confirm: true })).toBe(false)
+ expect(t.store.read().suspended).toEqual([phone.pub])
+ expect(await t.syncer.dismiss({ pub: phone.pub, confirm: true })).toBe(true)
+ expect(t.store.read().suspended).toEqual([])
+ })
+
+ it('not from a frozen log, or one this machine is not on — the key is marked seen here all the same', async () => {
+ const t = await joined()
+ t.store.write({ ...t.store.read(), frozen: { reason: 'fork', at: 1, lastGoodHead: t.backend.state.head } })
+ expect(await t.syncer.dismiss({ pub: phone.pub, confirm: true })).toBe(false)
+ expect(t.store.read().pending).toEqual([])
+ const u = await joined()
+ const file = u.store.read()
+ const { [me.pub]: _gone, ...others } = file.state!.active
+ u.store.write({ ...file, state: { ...file.state!, active: others } })
+ expect(await u.syncer.dismiss({ pub: phone.pub, confirm: true })).toBe(false)
+ expect(t.backend.postAck).not.toHaveBeenCalled()
+ expect(u.backend.postAck).not.toHaveBeenCalled()
+ })
+
+ it('a backend that does not take it (or predates it) leaves the dismissal here, and says so', async () => {
+ const lines: string[] = []
+ const t = await joined({ log: (l) => lines.push(l) })
+ t.backend.acksRoute = false
+ expect(await t.syncer.dismiss({ pub: phone.pub, confirm: true })).toBe(false)
+ expect(t.store.read().pending).toEqual([])
+ expect(lines.some((l) => l.includes('could not tell your other devices'))).toBe(true)
+ const u = await joined({ log: (l) => lines.push(l) })
+ u.backend.postAck.mockRejectedValueOnce(new Error('boom'))
+ expect(await u.syncer.dismiss({ pub: phone.pub, confirm: true })).toBe(false)
+ expect(lines.some((l) => l.includes('boom'))).toBe(true)
+ })
+
+ it('a machine with nothing to share it with keeps "It\'s mine" here', async () => {
+ const t = setup()
+ t.backend.add(box2, 'machine', MID2, 'box2')
+ await t.syncer.register()
+ t.backend.add(phone, 'viewer', '', 'phone')
+ await t.syncer.refresh()
+ expect(await t.syncer.dismiss({ pub: phone.pub, confirm: true })).toBe(false)
+ expect(t.store.read().pending).toEqual([])
+ })
+
+ it('reaches the other machine: its banner goes, and says where it was confirmed', async () => {
+ // Two machines of one account, each with its own copy of the log, against one backend.
+ const backend = new FakeBackend()
+ backend.add(box2, 'machine', MID2, 'box2')
+ const here = setup({ acks: true, backend })
+ await here.syncer.register()
+ backend.add(phone, 'viewer', '', 'phone')
+ await here.syncer.refresh()
+ const there = new DeviceLogSyncer({
+ store: new DeviceLogStore(join(mkdtempSync(join(tmpdir(), 'devlog-')), 'devlog.json')),
+ identity: () => box2, signIn: () => null, self: () => ({ machineId: MID2, label: 'box2' }),
+ fetch: backend.fetch, append: backend.append, fetchAcks: backend.fetchAcks, postAck: backend.postAck,
+ adopt: () => {}, drop: () => {}, trustedNow: () => [], tombstoned: () => false, blocked: () => false,
+ announce: () => {}, signedOut: () => {}, now: () => 6_000, sleep: async () => {},
+ })
+ // box2 read the log before phone joined: phone is new there too.
+ const real = backend.fetch.getMockImplementation()!
+ backend.fetch.mockImplementationOnce(async () => ({ acct: ACCT, head: backend.state.hashes.length ? { seq: 2, hash: backend.state.hashes[1] } : backend.state.head, entries: backend.entries.slice(0, 2) }))
+ await there.refresh()
+ backend.fetch.mockImplementation(real)
+ await there.refresh()
+ expect(there.list().pending).toEqual([phone.pub])
+ expect(await here.syncer.dismiss({ pubs: [phone.pub], confirm: true })).toBe(true)
+ await there.refresh()
+ expect(there.list().pending).toEqual([])
+ expect(there.list().members.find((m) => m.pub === phone.pub)?.confirmed).toEqual({ by: me.pub, label: 'my-mac', at: 6_000 })
+ })
+ })
+})
diff --git a/cli/src/lib/e2ee/deviceLogSyncer.ts b/cli/src/lib/e2ee/deviceLogSyncer.ts
index f9c64fb0e..913c76515 100644
--- a/cli/src/lib/e2ee/deviceLogSyncer.ts
+++ b/cli/src/lib/e2ee/deviceLogSyncer.ts
@@ -16,13 +16,18 @@
* account (or by the backend itself) is seen. Decided from the log alone, never from what the trust
* group already holds: a roster that outran the log must not hide it.
* - history: what the log says about every add and remove, as this machine verified it.
+ * - confirm: "It's mine" here (`dismiss` with `confirm`) is signed and shared beside the log
+ * (deviceAck.ts), and one another trusted device shared takes a key off `pending` here — so the person
+ * confirms a new device once, on any of their devices, not on every one.
*/
import {
applyDevLogEntries, compareDevLogHead, DevLogError, devLogHash, devLogMessage, emptyDevLogState, nextDevLogEntry,
parseDevLogEntry, signDevLogEntry, type DevLogEntry, type DevLogHead, type DevLogMember, type DevLogState,
} from './deviceLog.js'
+import { checkDevAck, DEVACK_VERSION, signDevAck, type DevAck } from './deviceAck.js'
import {
- DEVLOG_DEPARTED, DEVLOG_RECENT, type DevLogConflict, type DevLogDeparted, type DevLogFile, type DevLogFreeze, type DeviceLogStore,
+ DEVLOG_DEPARTED, DEVLOG_RECENT, type DevLogConfirmed, type DevLogConflict, type DevLogDeparted, type DevLogFile, type DevLogFreeze,
+ type DeviceLogStore,
} from './deviceLogStore.js'
import { devLogHistory, type DevLogHistoryRow } from './deviceHistory.js'
import { b64d, fingerprint, verify } from './core.js'
@@ -66,6 +71,13 @@ export interface DeviceLogSyncerDeps {
fetch: (since: number) => Promise<DeviceLogFetched | null>
/** Append one signed entry; null when the backend could not be reached. */
append: (entry: DevLogEntry) => Promise<DeviceLogAppendAnswer | null>
+ /** The acknowledgements ("It's mine", deviceAck.ts) of keys added after entry `since`, as the backend
+ * keeps them — unchecked: every one is judged here. null when there are none to read (a backend from
+ * before them answers 404, which is null too). Absent: none are ever read. */
+ fetchAcks?: (since: number) => Promise<unknown[] | null>
+ /** Keep one acknowledgement this machine signed; false when the backend did not take it. Absent: none
+ * is shared, and "It's mine" here stays here. */
+ postAck?: (ack: DevAck) => Promise<boolean>
/** 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. */
@@ -110,7 +122,8 @@ export interface DeviceLogListing {
head: DevLogHead | null
frozen: DevLogFreeze | null
self: string
- members: Array<DevLogMember & { fingerprint: string; self: boolean; firstSeen?: number; pending: boolean; suspended: boolean }>
+ /** `confirmed`: another trusted device said "It's mine" for it while it was new here — which, and when. */
+ members: Array<DevLogMember & { fingerprint: string; self: boolean; firstSeen?: number; pending: boolean; suspended: boolean; confirmed?: DevLogConfirmed }>
/** Machines whose own copy of the log is frozen, as their last `group_sync` said. */
frozenPeers: string[]
/** Keys that joined after this machine did and nobody has marked as seen. */
@@ -481,6 +494,10 @@ export class DeviceLogSyncer {
this.endJoin()
}
this.reconcile()
+ // After the entries, so a key added and confirmed while this machine was away is first announced, as
+ // every new key is — the one-time "New device: X" never waits on, or is skipped for, anyone's word —
+ // and only then taken off the list.
+ await this.applyAcks()
}
/**
@@ -604,6 +621,80 @@ export class DeviceLogSyncer {
return uniq(keys ?? []).filter((k) => state.active[k] !== undefined)
}
+ /** The confirmed marks of keys still active, as a file field (none when there are none). */
+ private keptConfirmed(marks: Record<string, DevLogConfirmed> | undefined, state: DevLogState): { confirmed?: Record<string, DevLogConfirmed> } {
+ const kept = Object.entries(marks ?? {}).filter(([k]) => state.active[k] !== undefined)
+ return kept.length ? { confirmed: Object.fromEntries(kept) } : {}
+ }
+
+ /**
+ * Take off `pending` every key another of the person's trusted devices said "It's mine" for
+ * (deviceAck.ts), and remember which device did ("Confirmed on <label>").
+ *
+ * The backend's word counts for nothing: each acknowledgement must check out against the log as THIS
+ * machine verified it (signature, a signer active on it, the key added at the entry it names), and
+ * against this machine's own marks. The key must still be new here and not suspended — an
+ * acknowledgement never lifts a suspension; only the person does, on this machine, with "It's mine" on
+ * that very device. The signer must be a device this machine trusts: not new here itself (two new
+ * devices must not vouch for each other), not suspended, not removed (a departed key is not active),
+ * not unpaired or tombstoned here, and not this machine (its own "It's mine" already took the key off).
+ * Nothing is read while the log is frozen or not yet this sign-in's. Never throws.
+ */
+ private async applyAcks(): Promise<void> {
+ const fetchAcks = this.deps.fetchAcks
+ if (!fetchAcks) return
+ try {
+ const candidates = this.ackable(this.deps.store.read())
+ // Nothing new here: nothing to ask (and no request at all, on every read, for most of a device's life).
+ if (!candidates.length) return
+ const raw = await fetchAcks(Math.min(...candidates.map((m) => m.seq)) - 1)
+ if (!raw?.length) return
+ // Judged against the file as it is NOW: the log may have moved, or a key been looked at, meanwhile.
+ const file = this.deps.store.read()
+ const state = file.state
+ const open = new Set(this.ackable(file).map((m) => m.pub))
+ if (!state || !open.size) return
+ const selfPub = this.deps.identity().pub
+ const pending = new Set(file.pending ?? [])
+ const suspended = new Set(this.suspendedKeys())
+ const confirmed: Record<string, DevLogConfirmed> = {}
+ for (const r of raw) {
+ const checked = checkDevAck(state, r)
+ if (!checked.ok) continue
+ const { ack } = checked
+ if (!open.has(ack.pub) || confirmed[ack.pub]) continue
+ if (ack.signer === selfPub || pending.has(ack.signer) || suspended.has(ack.signer)
+ || this.deps.blocked(ack.signer) || this.deps.tombstoned(ack.signer)) continue
+ confirmed[ack.pub] = { by: ack.signer, label: state.active[ack.signer].label, at: this.now() }
+ }
+ const pubs = Object.keys(confirmed)
+ if (!pubs.length) return
+ this.deps.store.write({
+ ...file,
+ pending: (file.pending ?? []).filter((k) => !confirmed[k]),
+ ...this.keptConfirmed({ ...file.confirmed, ...confirmed }, state),
+ })
+ for (const pub of pubs) {
+ const c = confirmed[pub]
+ this.deps.log?.(`[devlog] ${state.active[pub].label || '(no name)'} (${fp(pub)}) was confirmed as yours on ${c.label || 'another device'} (${fp(c.by)}): no longer new here`)
+ }
+ this.deps.changed?.()
+ } catch (err) {
+ // The list stays as it was; the next read asks again.
+ this.deps.log?.(`[devlog] could not read which devices were confirmed: ${err instanceof Error ? err.message : String(err)}`)
+ }
+ }
+
+ /** The keys an acknowledgement could take off `pending` in `file`: new here, still active, not
+ * suspended, not this machine — and none at all from a log that is frozen or not this sign-in's. */
+ private ackable(file: DevLogFile): DevLogMember[] {
+ const state = file.state
+ if (!state || file.frozen || !this.ownsFile(file)) return []
+ const selfPub = this.deps.identity().pub
+ const suspended = new Set(this.suspendedKeys())
+ return uniq(file.pending ?? []).map((k) => state.active[k]).filter((m): m is DevLogMember => !!m && m.pub !== selfPub && !suspended.has(m.pub))
+ }
+
/** The notice for a `remove` that took `gone` out, or null when there is nothing to say: this
* machine's own removal, this machine's own key, or a removal from before it joined. `known` says
* what each key was called, and what kind it was, BEFORE this removal — the remove entry's own label
@@ -673,7 +764,7 @@ export class DeviceLogSyncer {
const conflictOver = !!file.conflict && (!!applied.state.active[selfPub] || !applied.state.active[file.conflict.pub])
// A key taken into the "already on your account" list after that list was acknowledged: show it.
const unseen = joining && file.baselineSeen !== false && applied.added.some((m) => m.pub !== selfPub)
- const { conflict: _c, ...rest } = file
+ const { conflict: _c, confirmed: _k, ...rest } = file
this.deps.store.write(this.carrySuspensions({
...rest,
...(unseen ? { baselineSeen: false } : {}),
@@ -688,6 +779,7 @@ export class DeviceLogSyncer {
announced: this.prune([...announced, ...toAnnounce.map((m) => m.pub)], applied.state),
suspended: this.prune(file.suspended, applied.state),
...this.withDeparted(file.departed, departed),
+ ...this.keptConfirmed(file.confirmed, applied.state),
}))
this.trustState(applied.state, bootstrap ? Object.values(applied.state.active) : [...applied.added, ...applied.relabeled])
for (const m of applied.removed) this.deps.drop(m.pub)
@@ -1049,8 +1141,24 @@ export class DeviceLogSyncer {
* when it is only part of a list that was looked at; `pub` — "It's mine" on that very device — is the
* person vouching for it, and lifts its suspension here (and in every kept account's log). A key that
* joined and left before anyone looked (`departed`) is cleared the same way: named, or every one.
+ *
+ * `confirm` — "It's mine", pressed for ONE device (`pub`, or `pubs` naming only it) — also tells the
+ * account's other devices, with an acknowledgement this machine signs (deviceAck.ts): they stop showing
+ * it as New too. Never for a list that was only looked at, every device at once, or the baseline: only
+ * an explicit "It's mine" vouches. Marking it seen here is done before this returns; the promise says
+ * whether the other devices were told (false: the backend did not take it, or there was nothing to tell).
*/
- dismiss(opts: { pub?: string; pubs?: string[]; baseline?: boolean } = {}): void {
+ dismiss(opts: { pub?: string; pubs?: string[]; baseline?: boolean; confirm?: boolean } = {}): Promise<boolean> {
+ const one = opts.pub ?? (opts.pubs?.length === 1 ? opts.pubs[0] : undefined)
+ const wasNew = one !== undefined && (this.marks().pending ?? []).includes(one)
+ this.markSeen(opts)
+ // Only a key that was new here, and that this machine trusts now: one a fork suspended here (and
+ // "It's mine" did not lift) is not this machine's to vouch for.
+ if (!opts.confirm || opts.baseline || one === undefined || !wasNew || this.suspendedKeys().includes(one)) return Promise.resolve(false)
+ return this.shareAck(one)
+ }
+
+ private markSeen(opts: { pub?: string; pubs?: string[]; baseline?: boolean }): void {
const file = this.marks()
if (!file.state) return
const suspended = file.suspended ?? []
@@ -1077,6 +1185,29 @@ export class DeviceLogSyncer {
this.deps.changed?.()
}
+ /** Sign "It's mine" for `pub` and hand it to the backend for the account's other devices. Only from a
+ * log this machine verified, is on, and that is not frozen (a frozen list is not one to vouch from),
+ * about a key on it that is not this machine. Never throws. */
+ private async shareAck(pub: string): Promise<boolean> {
+ const post = this.deps.postAck
+ if (!post) return false
+ try {
+ const file = this.deps.store.read()
+ const state = file.state
+ const { pub: selfPub, priv } = this.deps.identity()
+ if (!state || file.frozen || !this.ownsFile(file) || pub === selfPub || !state.active[selfPub]) return false
+ const member = state.active[pub]
+ if (!member) return false
+ const ack = signDevAck({ v: DEVACK_VERSION, acct: state.acct, pub, addSeq: member.seq, signer: selfPub, at: this.now() }, priv)
+ const kept = await post(ack)
+ if (!kept) this.deps.log?.(`[devlog] could not tell your other devices that ${member.label || '(no name)'} (${fp(pub)}) is yours: they still show it as new`)
+ return kept
+ } catch (err) {
+ this.deps.log?.(`[devlog] could not share "It's mine": ${err instanceof Error ? err.message : String(err)}`)
+ return false
+ }
+ }
+
/**
* Every add and remove in the log, newest first, as this machine verified it: the entries come from
* the backend but each must hash to what this machine already verified, or the log freezes. Offline,
@@ -1152,7 +1283,11 @@ export class DeviceLogSyncer {
const suspended = file.suspended ?? []
const members = Object.values(file.state?.active ?? {})
.sort((a, b) => a.seq - b.seq)
- .map((m) => ({ ...m, fingerprint: fp(m.pub), self: m.pub === selfPub, pending: pending.includes(m.pub), suspended: suspended.includes(m.pub) }))
+ .map((m) => {
+ const row = { ...m, fingerprint: fp(m.pub), self: m.pub === selfPub, pending: pending.includes(m.pub), suspended: suspended.includes(m.pub) }
+ const confirmed = file.confirmed?.[m.pub]
+ return confirmed ? { ...row, confirmed } : row
+ })
const labels = new Map(members.map((m) => [m.pub, m.label]))
const frozenPeers = [...this.frozenPeers].filter(([, frozen]) => frozen).map(([pub]) => labels.get(pub) ?? fp(pub))
// Each row carries when this machine first applied it (never the entry's self-chosen `at`).
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 594665de3..89f391489 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -7,6 +7,7 @@ import '../core/config.dart';
import '../core/models.dart';
import '../core/test_run.dart';
import '../logging/http_log.dart';
+import '../viewer/device_ack.dart';
import '../viewer/device_log.dart';
import '../viewer/device_log_sync.dart' show DeviceLogAppendAnswer, DeviceLogFetched;
import '../ws/local_daemon_transport.dart';
@@ -310,6 +311,37 @@ class ApiClient {
}
}
+ /// `GET /api/device-keys/acks?since=` — the acknowledgements ("It's mine" said on another device,
+ /// `viewer/device_ack.dart`) of keys added after entry [since], unchecked: the device log judges each.
+ /// Null when there are none to read (a backend from before them, signed out, or unreachable). A short
+ /// deadline: while it runs, the read of the log that asked holds back its "New device" notices.
+ Future<List<Object?>?> deviceAcks(int since) async {
+ try {
+ final res = await _dio.get(
+ '/api/device-keys/acks',
+ queryParameters: {'since': since},
+ options: Options(receiveTimeout: const Duration(seconds: 5)),
+ );
+ if (res.statusCode != 200) return null;
+ final data = unwrapApiResponse(res);
+ final acks = data is Map ? data['acks'] : null;
+ return acks is List ? acks.cast<Object?>() : null;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// `POST /api/device-keys/acks` — share this app's "It's mine" for a device with the account's other
+ /// devices. False when the backend did not keep it (or predates it).
+ Future<bool> postDeviceAck(DevAck ack) async {
+ try {
+ final res = await _dio.post('/api/device-keys/acks', data: {'ack': ack.toJson()});
+ return res.statusCode == 200;
+ } catch (_) {
+ return false;
+ }
+ }
+
/// `GET /api/device-keys/seen` — when each key last opened a session, `{pub: ms}`; empty when it
/// cannot be read. A hint for offering to remove apps not used in a long while.
Future<Map<String, int>> deviceKeysSeen() async {
@@ -374,12 +406,14 @@ class ApiClient {
/// `POST /api/devices/dismiss` — new devices marked as seen: [pub] one, neither argument every
/// one, [pubs] exactly those (what the person was shown), [baseline] the "Already on your account"
- /// list. False when the daemon predates the route (an old one answers a `pubs` body with an error).
- Future<bool> daemonDismissDevices({String? pub, List<String>? pubs, bool baseline = false}) async {
+ /// list. [confirm]: "It's mine" for the one device named — the daemon shares it with the account's
+ /// other devices (one that predates it ignores the field and only marks it seen). False when the
+ /// daemon predates the route (an old one answers a `pubs` body with an error).
+ Future<bool> daemonDismissDevices({String? pub, List<String>? pubs, bool baseline = false, bool confirm = false}) async {
try {
final res = await _dio.post(
'/api/devices/dismiss',
- data: {'pub': ?pub, 'pubs': ?pubs, if (baseline) 'baseline': true},
+ data: {'pub': ?pub, 'pubs': ?pubs, if (baseline) 'baseline': true, if (confirm) 'confirm': true},
options: Options(headers: {'x-adapter-local': '1'}),
);
return res.statusCode == 200;
diff --git a/desktop/lib/settings/sections/account_device_detail.dart b/desktop/lib/settings/sections/account_device_detail.dart
index 9bb9d05fb..ada0360de 100644
--- a/desktop/lib/settings/sections/account_device_detail.dart
+++ b/desktop/lib/settings/sections/account_device_detail.dart
@@ -235,6 +235,14 @@ class _AccountDeviceDetailState extends State<_AccountDeviceDetail> {
machineId.length < 8 ? machineId.length : 8,
),
),
+ // Another of the person's devices said "It's mine" for it while it was new here: where
+ // the banner would have been, the list says where it was settled.
+ if (device?.confirmedOn case final on?)
+ _Fact(
+ 'Confirmed',
+ 'on ${on.trim().isEmpty ? 'another device' : on.trim()}',
+ key: const Key('device-detail-confirmed'),
+ ),
const SizedBox(height: 14),
if (fp.isNotEmpty) ...[
FingerprintText(
@@ -302,7 +310,7 @@ class _AccountDeviceDetailState extends State<_AccountDeviceDetail> {
}
class _Fact extends StatelessWidget {
- const _Fact(this.label, this.value);
+ const _Fact(this.label, this.value, {super.key});
final String label, value;
diff --git a/desktop/lib/state/account_devices.dart b/desktop/lib/state/account_devices.dart
index 9245a46e6..e743c6624 100644
--- a/desktop/lib/state/account_devices.dart
+++ b/desktop/lib/state/account_devices.dart
@@ -20,6 +20,7 @@ class AccountDevice {
this.seq,
this.pending = false,
this.suspended = false,
+ this.confirmedOn,
});
final String pub;
@@ -46,11 +47,16 @@ class AccountDevice {
/// Not trusted here after a fork, until the list is reviewed.
final bool suspended;
+ /// What the device that said "It's mine" for it was called, when another of the person's devices
+ /// confirmed it while it was new here ('' when it had no name); null when none did.
+ final String? confirmedOn;
+
bool get isMachine => kind == 'machine';
AccountDevice withLastSeen(DateTime? at) => AccountDevice(
pub: pub, label: label, kind: kind, machineId: machineId, addedAt: addedAt,
fingerprint: fingerprint, self: self, lastSeen: at, seq: seq, pending: pending, suspended: suspended,
+ confirmedOn: confirmedOn,
);
static AccountDevice? fromDaemon(Object? raw) {
@@ -58,19 +64,22 @@ class AccountDevice {
final pub = raw['pub'], label = raw['label'], kind = raw['kind'], machineId = raw['machineId'];
final addedAt = raw['addedAt'], fp = raw['fingerprint'], self = raw['self'];
if (pub is! String || label is! String || kind is! String || addedAt is! int || fp is! String) return null;
+ final confirmed = raw['confirmed'];
return AccountDevice(
pub: pub, label: label, kind: kind, machineId: machineId is String ? machineId : '',
addedAt: DateTime.fromMillisecondsSinceEpoch(addedAt), fingerprint: fp, self: self == true,
seq: raw['seq'] is int ? raw['seq'] as int : null,
pending: raw['pending'] == true,
suspended: raw['suspended'] == true,
+ // A daemon that predates "It's mine" for the account sends none.
+ confirmedOn: confirmed is Map && confirmed['label'] is String ? confirmed['label'] as String : null,
);
}
static AccountDevice fromRow(DeviceLogRow row) => AccountDevice(
pub: row.member.pub, label: row.member.label, kind: row.member.kind, machineId: row.member.machineId,
addedAt: DateTime.fromMillisecondsSinceEpoch(row.member.addedAt), fingerprint: row.fingerprint, self: row.self,
- seq: row.member.seq, pending: row.pending, suspended: row.suspended,
+ seq: row.member.seq, pending: row.pending, suspended: row.suspended, confirmedOn: row.confirmed?.label,
);
}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 63e985be1..f018ae7fd 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -7734,6 +7734,9 @@ class AppNotifier extends ChangeNotifier {
),
),
append: (entry) => api.appendDeviceKey(entry),
+ // "It's mine", once for the account: read what other devices confirmed, share what this one does.
+ fetchAcks: (since) => api.deviceAcks(since),
+ postAck: (ack) => api.postDeviceAck(ack),
label: _deviceLabel,
onAnnounce: (m) => _whenSignedIn(() {
// A key the person has already dismissed (while this waited) is not news any more.
@@ -7984,11 +7987,13 @@ class AppNotifier extends ChangeNotifier {
/// Persists "seen" for [pub] (one), every device (neither) or the baseline panel, in whichever copy
/// of the log this end keeps. Only when that cannot be — a daemon that predates it — does it stay
- /// in memory ([_dismissedDevices]).
+ /// in memory ([_dismissedDevices]). [confirm]: the person pressed "It's mine" for that one device, so
+ /// the account's other devices are told too and stop showing it as new.
Future<void> _persistSeen({
String? pub,
List<String>? pubs,
bool baseline = false,
+ bool confirm = false,
}) async {
// Which dismissals this write settles; the baseline panel's "Got it" settles none of them.
void settled() {
@@ -8003,7 +8008,7 @@ class AppNotifier extends ChangeNotifier {
if (baseline) {
await log.seeBaseline();
} else {
- await log.dismiss(pub: pub, pubs: pubs);
+ await log.dismiss(pub: pub, pubs: pubs, confirm: confirm);
}
settled();
return;
@@ -8012,6 +8017,7 @@ class AppNotifier extends ChangeNotifier {
pub: pub,
pubs: pubs,
baseline: baseline,
+ confirm: confirm,
)) {
settled();
}
@@ -8061,7 +8067,8 @@ class AppNotifier extends ChangeNotifier {
///
/// [pub] alone (the device's own page, where a suspension is shown) also lifts a suspension on it;
/// the banner's "It's mine" does not — it dismisses through [pubs], which leaves a fork's
- /// suspension in place.
+ /// suspension in place. Either way it is "It's mine" for this one device: the account's other
+ /// devices are told, and stop showing it as new (opening the list, [seenNewDevices], tells nobody).
void dismissNewDevice(String pub, {bool liftSuspension = false}) {
newDevices.removeWhere((d) => d.pub == pub);
// A key that joined and left before anyone looked: a "New device" for it is a stale replay, and its
@@ -8075,7 +8082,9 @@ class AppNotifier extends ChangeNotifier {
_pendingSyncGeneration++;
notifyListeners();
unawaited(
- liftSuspension ? _persistSeen(pub: pub) : _persistSeen(pubs: [pub]),
+ liftSuspension
+ ? _persistSeen(pub: pub, confirm: true)
+ : _persistSeen(pubs: [pub], confirm: true),
);
}
diff --git a/desktop/lib/viewer/device_ack.dart b/desktop/lib/viewer/device_ack.dart
new file mode 100644
index 000000000..307754768
--- /dev/null
+++ b/desktop/lib/viewer/device_ack.dart
@@ -0,0 +1,113 @@
+import 'dart:typed_data';
+
+import '../e2ee/bytes.dart';
+import '../e2ee/keys.dart';
+import 'device_log.dart';
+
+/// "It's mine", said once for the whole account: a device's signed acknowledgement that another device
+/// on the account's device key log is the person's own (cli/src/lib/e2ee/deviceAck.ts, ported). One
+/// trusted device confirming a new one is enough for the others to stop showing it as New.
+///
+/// Kept OUTSIDE the hash chain: an op the log does not know would make every older client freeze the
+/// whole log as invalid. An acknowledgement never adds trust — it only takes a key the log already
+/// leaves active off the "New" list — and this app never takes the backend's word for one: [checkDevAck]
+/// verifies it against this app's own verified log, and [ViewerDeviceLog] adds its own marks (the signer
+/// must not be new, suspended or gone here; a suspended key stays suspended).
+///
+/// Pure: no I/O. The signature covers [devAckMessage] — the fields length-prefixed in a fixed order,
+/// headed by its own domain tag, never the device log's — never JSON. ⚠️ Held, with the CLI, the
+/// backend and the other app's copy (desktop/ and mobile/lib/viewer/device_ack.dart, byte-identical), to
+/// `test/viewer/deviceAck.vectors.json`: change the format in every copy together.
+
+const devAckVersion = 1;
+const devAckTag = 'harness-devack-v1';
+const _maxSafe = 9007199254740991;
+
+class DevAck {
+ const DevAck({
+ required this.v,
+ required this.acct,
+ required this.pub,
+ required this.addSeq,
+ required this.signer,
+ required this.at,
+ this.sig = '',
+ });
+
+ final int v;
+ final String acct;
+
+ /// The device being acknowledged.
+ final String pub;
+
+ /// The seq of the log entry that added [pub].
+ final int addSeq;
+
+ /// The device that acknowledges it, and signs it.
+ final String signer;
+
+ /// When, as the signer's clock read it. Shown, never trusted for anything.
+ final int at;
+ final String sig;
+
+ DevAck withSig(String sig) =>
+ DevAck(v: v, acct: acct, pub: pub, addSeq: addSeq, signer: signer, at: at, sig: sig);
+
+ Map<String, Object?> toJson() =>
+ {'v': v, 'acct': acct, 'pub': pub, 'addSeq': addSeq, 'signer': signer, 'at': at, 'sig': sig};
+
+ /// deviceAck.ts `parseDevAck`: every field present, of its type and within bounds.
+ static DevAck? parse(Object? raw) {
+ if (raw is! Map) return null;
+ final v = raw['v'], acct = raw['acct'], pub = raw['pub'], addSeq = raw['addSeq'];
+ final signer = raw['signer'], at = raw['at'], sig = raw['sig'];
+ if (v != devAckVersion) return null;
+ if (acct is! String || acct.isEmpty || acct.length > 128) return null;
+ if (!_isBytes(pub, 32) || !_isBytes(signer, 32) || !_isBytes(sig, 64)) return null;
+ if (addSeq is! int || addSeq < 1 || addSeq > _maxSafe) return null;
+ if (at is! int || at <= 0 || at > _maxSafe) return null;
+ return DevAck(
+ v: v as int, acct: acct, pub: pub as String, addSeq: addSeq, signer: signer as String, at: at,
+ sig: sig as String,
+ );
+ }
+}
+
+/// base64 of exactly [n] bytes, in its one canonical spelling.
+bool _isBytes(Object? s, int n) {
+ if (s is! String || s.length > 128) return false;
+ try {
+ final u = b64d(s);
+ return u.length == n && b64e(u) == s;
+ } catch (_) {
+ return false;
+ }
+}
+
+/// The bytes a signature covers.
+Uint8List devAckMessage(DevAck a) => lvCat([
+ devAckTag, '${a.v}', a.acct, b64d(a.pub), '${a.addSeq}', b64d(a.signer), '${a.at}',
+]);
+
+Future<DevAck> signDevAck(DevAck unsigned, E2eeIdentity identity) async =>
+ unsigned.withSig(b64e(await identity.sign(devAckMessage(unsigned))));
+
+/// What [checkDevAck] made of an acknowledgement: [ack] when it holds, else [code] says why not.
+typedef DevAckCheck = ({DevAck? ack, String? code});
+
+/// deviceAck.ts `checkDevAck`: well formed, of [state]'s account, signed by its signer, not a key
+/// vouching for itself, the signer active on [state], and the key active on it and added at `addSeq`.
+/// Whether the signer is new, suspended or gone here is the caller's to judge.
+Future<DevAckCheck> checkDevAck(DevLogState state, Object? raw) async {
+ final ack = DevAck.parse(raw);
+ if (ack == null) return (ack: null, code: 'BAD_ACK');
+ if (ack.acct != state.acct) return (ack: null, code: 'WRONG_ACCOUNT');
+ if (!await verifySignature(b64d(ack.signer), devAckMessage(ack), b64d(ack.sig))) {
+ return (ack: null, code: 'BAD_SIGNATURE');
+ }
+ // A key saying it is its own owner's says nothing: whoever added it would sign that too.
+ if (ack.signer == ack.pub) return (ack: null, code: 'SELF_ACK');
+ if (state.active[ack.signer] == null) return (ack: null, code: 'SIGNER_NOT_ACTIVE');
+ if (state.active[ack.pub]?.seq != ack.addSeq) return (ack: null, code: 'NOT_ADDED_THERE');
+ return (ack: ack, code: null);
+}
diff --git a/desktop/lib/viewer/device_log_sync.dart b/desktop/lib/viewer/device_log_sync.dart
index c9452dcde..fe2264e1c 100644
--- a/desktop/lib/viewer/device_log_sync.dart
+++ b/desktop/lib/viewer/device_log_sync.dart
@@ -3,6 +3,7 @@ import 'dart:math';
import '../e2ee/bytes.dart';
import '../e2ee/keys.dart';
+import 'device_ack.dart';
import 'device_history.dart';
import 'device_log.dart';
import 'group_sync.dart';
@@ -19,6 +20,9 @@ export 'device_history.dart'
/// log or rolls it back FREEZES it here: nothing more is pinned from it until someone reviews what
/// changed ([rebaseline]). A key added after this app joined the log is announced ("New device: X") and
/// stays pending until it is marked seen; what the log says is never read against what the roster holds.
+/// "It's mine" here ([dismiss] with `confirm`) is signed and shared beside the log (device_ack.dart), and
+/// one another trusted device shared takes a key off `pending` here: the person confirms a new device
+/// once, on any of their devices.
/// What `GET /api/device-keys?since=` answered; null from the fetcher when there is no log to read.
typedef DeviceLogFetched = ({String acct, DevLogHead head, List<Object?> entries});
@@ -29,6 +33,32 @@ typedef DeviceLogAppendAnswer = ({DevLogHead? head, String? error});
typedef DeviceLogFetch = Future<DeviceLogFetched?> Function(int since);
typedef DeviceLogAppend = Future<DeviceLogAppendAnswer?> Function(DevLogEntry entry);
+/// `GET /api/device-keys/acks?since=`: the acknowledgements of keys added after entry `since`, unchecked
+/// (every one is judged here); null when there are none to read (a backend from before them: 404).
+typedef DeviceLogFetchAcks = Future<List<Object?>?> Function(int since);
+
+/// `POST /api/device-keys/acks`: whether the backend kept one this app signed.
+typedef DeviceLogPostAck = Future<bool> Function(DevAck ack);
+
+/// Another of the person's trusted devices said "It's mine" for a key that was new here, so it is not New
+/// here any more: which device ([by]), what it was called then, and when this app read it. Trusts nothing.
+class DeviceLogConfirmed {
+ const DeviceLogConfirmed({required this.by, required this.label, required this.at});
+
+ final String by;
+ final String label;
+ final int at;
+
+ Map<String, Object?> toJson() => {'by': by, 'label': label, 'at': at};
+
+ static DeviceLogConfirmed? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final by = raw['by'], label = raw['label'], at = raw['at'];
+ if (by is! String || label is! String || at is! int) return null;
+ return DeviceLogConfirmed(by: by, label: label, at: at);
+ }
+}
+
class DeviceLogFreeze {
const DeviceLogFreeze(this.reason, this.at, this.lastGoodHead);
@@ -64,6 +94,7 @@ class _File {
this.owner,
this.joining = false,
this.departed = const [],
+ this.confirmed = const {},
});
DevLogState? state;
@@ -108,6 +139,10 @@ class _File {
/// New keys removed before anyone looked (oldest first, at most [_departedKept]).
List<DeviceLogDeparted> departed;
+ /// New keys another trusted device confirmed, by pub: "Confirmed on <label>". Only ever the reason a
+ /// key left [pending]; it trusts nothing.
+ Map<String, DeviceLogConfirmed> confirmed;
+
Map<String, Object?> toJson() => {
'state': state?.toJson(),
'recent': [for (final e in recent.skip(max(0, recent.length - _recentKept))) e.toJson()],
@@ -128,6 +163,13 @@ class _File {
'looseRemoved': [for (final e in looseRemoved.skip(max(0, looseRemoved.length - _recentKept))) e.toJson()],
if (departed.isNotEmpty)
'departed': [for (final d in departed.skip(max(0, departed.length - _departedKept))) d.toJson()],
+ if (confirmed.isNotEmpty) 'confirmed': {for (final e in confirmed.entries) e.key: e.value.toJson()},
+ };
+
+ static Map<String, DeviceLogConfirmed> _confirmed(Object? raw) => {
+ if (raw is Map)
+ for (final e in raw.entries)
+ if (e.key is String) e.key as String: ?DeviceLogConfirmed.fromJson(e.value),
};
static List<String> _strings(Object? raw) => raw is List ? [for (final v in raw) if (v is String) v] : <String>[];
@@ -152,6 +194,7 @@ class _File {
owner: raw['owner'] is String && (raw['owner'] as String).isNotEmpty ? raw['owner'] as String : null,
joining: raw['joining'] == true,
departed: DeviceLogDeparted.listFromJson(raw['departed']),
+ confirmed: _confirmed(raw['confirmed']),
);
}
}
@@ -186,6 +229,7 @@ class DeviceLogRow {
required this.self,
this.pending = false,
this.suspended = false,
+ this.confirmed,
});
final DevLogMember member;
@@ -197,6 +241,9 @@ class DeviceLogRow {
/// Not trusted here after a fork, until the list is reviewed.
final bool suspended;
+
+ /// Another trusted device said "It's mine" for it while it was new here; null when none did.
+ final DeviceLogConfirmed? confirmed;
}
class DeviceLogListing {
@@ -328,6 +375,8 @@ class ViewerDeviceLog {
required this.fetch,
required this.append,
required this.label,
+ this.fetchAcks,
+ this.postAck,
this.onAnnounce,
this.onRemoved,
this.onSignedOut,
@@ -341,6 +390,12 @@ class ViewerDeviceLog {
final DeviceLogFetch fetch;
final DeviceLogAppend append;
+ /// The acknowledgements beside the log ("It's mine" said on another device); null: none are read.
+ final DeviceLogFetchAcks? fetchAcks;
+
+ /// Where this app's own "It's mine" is shared; null: it stays here.
+ final DeviceLogPostAck? postAck;
+
/// How this app calls itself in the account's list of devices.
final String Function() label;
@@ -864,6 +919,86 @@ class ViewerDeviceLog {
await _endJoin();
if (expecting && !_registering && round == _signInRound) _signingInAgain = false;
}
+ // After the entries, so a key added and confirmed while this app was closed is first announced, as
+ // every new key is — the one-time "New device: X" never waits on, or is skipped for, anyone's word —
+ // and only then taken off the list.
+ await _applyAcks();
+ }
+
+ /// [marks] cut to the keys still active, as a file's [_File.confirmed].
+ Map<String, DeviceLogConfirmed> _keptConfirmed(Map<String, DeviceLogConfirmed> marks, DevLogState state) => {
+ for (final e in marks.entries)
+ if (state.active.containsKey(e.key)) e.key: e.value,
+ };
+
+ /// The keys an acknowledgement could take off `pending` in [file]: new here, still active, not
+ /// suspended, not this app — and none at all from a log that is frozen or not this sign-in's.
+ Future<List<DevLogMember>> _ackable(_File file) async {
+ final state = file.state;
+ if (state == null || file.frozen != null || !await _ownsFile(file)) return const [];
+ final selfPub = await _selfPub();
+ final suspended = await suspendedPubs();
+ return [
+ for (final k in file.pending.toSet())
+ if (state.active[k] case final m? when m.pub != selfPub && !suspended.contains(k)) m,
+ ];
+ }
+
+ /// Take off `pending` every key another of the person's trusted devices said "It's mine" for
+ /// (device_ack.dart), and remember which device did ("Confirmed on <label>").
+ ///
+ /// The backend's word counts for nothing: each acknowledgement must check out against the log as THIS
+ /// app verified it ([checkDevAck]: signature, a signer active on it, the key added at the entry it
+ /// names), and against this app's own marks. The key must still be new here and not suspended — an
+ /// acknowledgement never lifts a suspension; only the person does, here, with "It's mine" on that very
+ /// device. The signer must be a device this app trusts: not new here itself (two new devices must not
+ /// vouch for each other), not suspended, not removed (a departed key is not active), not tombstoned in
+ /// the trust group, and not this app (its own "It's mine" already took the key off). Nothing is read
+ /// while the log is frozen or not yet this sign-in's. Never throws.
+ Future<void> _applyAcks() async {
+ final read = fetchAcks;
+ if (read == null) return;
+ try {
+ final candidates = await _ackable(await _read());
+ // Nothing new here: nothing to ask (and no request at all, on every read, for most of an app's life).
+ if (candidates.isEmpty) return;
+ final raw = await read(candidates.map((m) => m.seq).reduce(min) - 1);
+ if (raw == null || raw.isEmpty) return;
+ final confirmed = await _locked(() async {
+ // Judged against the file as it is NOW: the log may have moved, or a key been looked at, meanwhile.
+ final file = await _read();
+ final state = file.state;
+ final open = {for (final m in await _ackable(file)) m.pub};
+ final out = <String, DeviceLogConfirmed>{};
+ if (state == null || open.isEmpty) return out;
+ final selfPub = await _selfPub();
+ final pending = file.pending.toSet();
+ final suspended = await suspendedPubs();
+ final roster = GroupRoster.parse(await keys.groupRoster());
+ final inRoster = {for (final m in roster.members) m.pub};
+ final tombstoned = {for (final t in roster.removed) if (!inRoster.contains(t.pub)) t.pub};
+ for (final r in raw) {
+ final ack = (await checkDevAck(state, r)).ack;
+ if (ack == null || !open.contains(ack.pub) || out.containsKey(ack.pub)) continue;
+ if (ack.signer == selfPub ||
+ pending.contains(ack.signer) ||
+ suspended.contains(ack.signer) ||
+ tombstoned.contains(ack.signer)) {
+ continue;
+ }
+ out[ack.pub] = DeviceLogConfirmed(by: ack.signer, label: state.active[ack.signer]!.label, at: _now());
+ }
+ if (out.isEmpty) return out;
+ file
+ ..pending = [for (final k in file.pending) if (!out.containsKey(k)) k]
+ ..confirmed = _keptConfirmed({...file.confirmed, ...out}, state);
+ await _write(file);
+ return out;
+ });
+ if (confirmed.isNotEmpty) onChanged?.call();
+ } catch (_) {
+ // Unreadable now: the list stays as it was, and the next read asks again.
+ }
}
Future<void> _readPages() async {
@@ -1085,7 +1220,8 @@ class ViewerDeviceLog {
..pending = _prune(pendingNow, applied.state)
..announced = _prune([...file.announced, for (final m in toAnnounce) m.pub], applied.state)
..suspended = _prune(file.suspended, applied.state)
- ..departed = _withDeparted(file.departed, departed);
+ ..departed = _withDeparted(file.departed, departed)
+ ..confirmed = _keptConfirmed(file.confirmed, applied.state);
await _carrySuspensionsIn(file);
await _write(file);
await _trust(bootstrap ? applied.state.active.values.toList() : [...applied.added, ...applied.relabeled]);
@@ -1479,11 +1615,20 @@ class ViewerDeviceLog {
/// [pub] — "It's mine" on that very device — is the person vouching for it, and lifts its suspension
/// (here and in every kept account's log). A key that joined and left before anyone looked
/// ([DeviceLogListing.departed]) is cleared the same way: named, or every one.
- Future<void> dismiss({String? pub, List<String>? pubs}) async {
+ ///
+ /// [confirm] — "It's mine", pressed for ONE device ([pub], or [pubs] naming only it) — also tells the
+ /// account's other devices, with an acknowledgement this app signs (device_ack.dart): they stop showing
+ /// it as New too. Never for a list that was only looked at, or every device at once: only an explicit
+ /// "It's mine" vouches. Marking it seen here is done first; the result says whether the other devices
+ /// were told (false: the backend did not take it, or there was nothing to tell).
+ Future<bool> dismiss({String? pub, List<String>? pubs, bool confirm = false}) async {
+ final one = pub ?? (pubs != null && pubs.length == 1 ? pubs.first : null);
+ var share = false;
final lifted = <DevLogMember>[];
final changed = await _locked(() async {
final file = await _marksIn();
if (file.state == null) return false;
+ final wasNew = one != null && file.pending.contains(one);
final named = pub != null || pubs != null;
final gone = {...?pubs, ?pub};
file.pending = [
@@ -1503,9 +1648,38 @@ class ViewerDeviceLog {
await _write(file);
if (lifting != null) await _unsuspendArchivedIn([lifting]);
if (lifted.isNotEmpty) await _trust(lifted);
+ // Only a key that was new here, and that this app trusts now: one a fork suspended here (and
+ // "It's mine" did not lift) is not this app's to vouch for.
+ share = confirm && wasNew && !(await suspendedPubs()).contains(one);
return true;
});
if (changed) onChanged?.call();
+ return share ? _shareAck(one!) : false;
+ }
+
+ /// Sign "It's mine" for [pub] and hand it to the backend for the account's other devices. Only from a
+ /// log this app verified, is on, and that is not frozen (a frozen list is not one to vouch from), about
+ /// a key on it that is not this app. Never throws.
+ Future<bool> _shareAck(String pub) async {
+ final post = postAck;
+ if (post == null) return false;
+ try {
+ final file = await _read();
+ final state = file.state;
+ final identity = await keys.identity();
+ final selfPub = b64e(identity.pub);
+ if (state == null || file.frozen != null || !await _ownsFile(file)) return false;
+ if (pub == selfPub || state.active[selfPub] == null) return false;
+ final member = state.active[pub];
+ if (member == null) return false;
+ final ack = await signDevAck(
+ DevAck(v: devAckVersion, acct: state.acct, pub: pub, addSeq: member.seq, signer: selfPub, at: _now()),
+ identity,
+ );
+ return await post(ack);
+ } catch (_) {
+ return false;
+ }
}
/// The "Already on your account" list was acknowledged: the first read is over, whatever comes after
@@ -1621,6 +1795,7 @@ class ViewerDeviceLog {
self: m.pub == selfPub,
pending: file.pending.contains(m.pub),
suspended: file.suspended.contains(m.pub),
+ confirmed: file.confirmed[m.pub],
),
],
frozen: file.frozen,
diff --git a/desktop/test/account_device_detail_test.dart b/desktop/test/account_device_detail_test.dart
index 9d5b88b53..a0858ca90 100644
--- a/desktop/test/account_device_detail_test.dart
+++ b/desktop/test/account_device_detail_test.dart
@@ -73,8 +73,27 @@ void main() {
testWidgets('a device that is not new offers no It’s mine', (tester) async {
await open(tester, pub: 'p1', device: fakeDevice('p1'));
expect(find.byKey(const Key('device-detail-mine')), findsNothing);
+ expect(find.byKey(const Key('device-detail-confirmed')), findsNothing);
});
+ testWidgets(
+ 'a device another of the person’s devices confirmed says where, in place of a banner',
+ (tester) async {
+ AccountDevice confirmedOn(String on) => AccountDevice(
+ pub: 'p1', label: 'iPad', kind: 'viewer', machineId: '', addedAt: DateTime(2026, 9, 1),
+ fingerprint: fp, self: false, confirmedOn: on,
+ );
+ await open(tester, pub: 'p1', device: confirmedOn('studio-mac'));
+ expect(find.text('Confirmed'), findsOneWidget);
+ expect(find.text('on studio-mac'), findsOneWidget);
+ expect(find.byKey(const Key('device-detail-mine')), findsNothing);
+ await tester.tap(find.byKey(const Key('device-detail-close')));
+ await tester.pumpAndSettle();
+ await open(tester, pub: 'p1', device: confirmedOn(''));
+ expect(find.text('on another device'), findsOneWidget);
+ },
+ );
+
testWidgets(
'an app: kind, added, last active, the code and how to check it on the app',
(tester) async {
diff --git a/desktop/test/device_notice_bands_shell_test.dart b/desktop/test/device_notice_bands_shell_test.dart
index d939a263d..f5b73ae32 100644
--- a/desktop/test/device_notice_bands_shell_test.dart
+++ b/desktop/test/device_notice_bands_shell_test.dart
@@ -32,6 +32,7 @@ class _QuietApi extends ApiClient {
String? pub,
List<String>? pubs,
bool baseline = false,
+ bool confirm = false,
}) async => true;
}
diff --git a/desktop/test/device_pending_sync_test.dart b/desktop/test/device_pending_sync_test.dart
index 48182ed32..88a0ae011 100644
--- a/desktop/test/device_pending_sync_test.dart
+++ b/desktop/test/device_pending_sync_test.dart
@@ -51,7 +51,7 @@ class _DaemonApi extends ApiClient {
/// Whether marking DEVICES seen succeeds; "Got it" on the baseline panel is a write of its own.
bool dismissWorks = true;
bool baselineWorks = true;
- final dismissed = <({String? pub, List<String>? pubs, bool baseline})>[];
+ final dismissed = <({String? pub, List<String>? pubs, bool baseline, bool confirm})>[];
final rebaselines = <({bool confirm, Map<String, Object?>? head})>[];
Map<String, dynamic>? rebaselineAnswer;
@@ -73,8 +73,9 @@ class _DaemonApi extends ApiClient {
String? pub,
List<String>? pubs,
bool baseline = false,
+ bool confirm = false,
}) async {
- dismissed.add((pub: pub, pubs: pubs, baseline: baseline));
+ dismissed.add((pub: pub, pubs: pubs, baseline: baseline, confirm: confirm));
if (dismissWorks && !baseline && listing?['pending'] is List) {
listing!['pending'] = [
for (final p in listing!['pending'] as List)
@@ -488,6 +489,63 @@ void main() {
expect(app.newDevices, isEmpty);
});
+ test('"It\'s mine" asks the daemon to tell the other devices; opening the list and "Got it" do not', () async {
+ api.listing = {
+ 'members': [
+ _member('me', 1, self: true),
+ _member('a', 3),
+ _member('b', 4),
+ _member('c', 5),
+ ],
+ 'pending': ['a', 'b', 'c'],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ app.dismissNewDevice('a');
+ app.dismissNewDevice('b', liftSuspension: true);
+ await Future<void>.delayed(Duration.zero);
+ // The banner's through `pubs` (a fork's suspension kept), the device's own page through `pub`: both
+ // are "It's mine" for that one device.
+ expect(api.dismissed.map((d) => d.confirm), [true, true]);
+ expect(api.dismissed.first.pubs, ['a']);
+ expect(api.dismissed.last.pub, 'b');
+ app.seenNewDevices();
+ app.dismissDepartedAll(['gone']);
+ await app.seeDeviceBaseline();
+ await Future<void>.delayed(Duration.zero);
+ expect(api.dismissed.skip(2).map((d) => d.confirm), [false, false, false]);
+ });
+
+ test('a device another of the person\'s devices confirmed leaves the banner, and says where', () async {
+ api.listing = {
+ 'members': [
+ _member('me', 1, self: true),
+ _member('a', 3),
+ ],
+ 'pending': ['a'],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices.map((d) => d.pub), ['a']);
+ // The daemon read an acknowledgement it checked against its own log: the key is not new there.
+ api.listing = {
+ 'members': [
+ _member('me', 1, self: true),
+ {
+ ..._member('a', 3),
+ 'confirmed': {'by': 'k', 'label': 'box2', 'at': 9},
+ },
+ ],
+ 'pending': <String>[],
+ };
+ await frame('device_keys_changed');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.newDevices, isEmpty);
+ final devices = (await app.loadDevices())!;
+ expect(devices.devices.firstWhere((d) => d.pub == 'a').confirmedOn, 'box2');
+ expect(devices.devices.firstWhere((d) => d.pub == 'me').confirmedOn, isNull);
+ });
+
test('a fork-suspended entry is marked so on the banner, and follows the listing', () async {
api.listing = {
'members': [
@@ -623,7 +681,7 @@ void main() {
test('"Got it" on the baseline panel is written to the daemon', () async {
await app.seeDeviceBaseline();
- expect(api.dismissed.single, (pub: null, pubs: null, baseline: true));
+ expect(api.dismissed.single, (pub: null, pubs: null, baseline: true, confirm: false));
expect(app.baselineSeenLocally, isTrue);
});
diff --git a/desktop/test/device_viewer_notices_test.dart b/desktop/test/device_viewer_notices_test.dart
index c4078c5c1..69084dcbb 100644
--- a/desktop/test/device_viewer_notices_test.dart
+++ b/desktop/test/device_viewer_notices_test.dart
@@ -16,6 +16,7 @@ import 'package:harness/e2ee/bytes.dart';
import 'package:harness/e2ee/keys.dart';
import 'package:harness/state/account_devices.dart' show NewDeviceNotice;
import 'package:harness/state/app_state.dart';
+import 'package:harness/viewer/device_ack.dart';
import 'package:harness/viewer/device_log.dart';
import 'package:harness/viewer/device_log_sync.dart';
import 'package:harness/viewer/direct_auth_api.dart' show IssuedTokens;
@@ -156,6 +157,24 @@ class _Api extends ApiClient {
Future<DeviceLogAppendAnswer?> appendDeviceKey(DevLogEntry entry) =>
backend.append(entry);
+ /// The acknowledgements the backend keeps ("It's mine" said on a device), as it serves them.
+ final acks = <Object?>[];
+
+ /// What this app shared.
+ final posted = <DevAck>[];
+
+ @override
+ Future<List<Object?>?> deviceAcks(int since) async =>
+ offline ? null : [...acks];
+
+ @override
+ Future<bool> postDeviceAck(DevAck ack) async {
+ if (offline) return false;
+ posted.add(ack);
+ acks.add(ack.toJson());
+ return true;
+ }
+
@override
Future<Map<String, int>> deviceKeysSeen() async {
await seenGate?.future;
@@ -479,6 +498,47 @@ void main() {
expect(again.newDevices.map((d) => d.label), ['box2']);
});
+ test('"It’s mine" is shared with the account; one another trusted device shared takes the banner down, and says where', () async {
+ final app = start();
+ addTearDown(app.dispose);
+ final api = app.api as _Api;
+ final tablet = await E2eeIdentity.fromSeed(List.filled(32, 6));
+ await backend.add(box2, 'machine', 'b' * 32, 'box2');
+ await logOf(app).register();
+ await backend.add(phone, 'viewer', '', 'Phone');
+ await backend.add(intruder, 'viewer', '', 'Chrome');
+ await backend.add(tablet, 'viewer', '', 'Tablet');
+ await logOf(app).refresh();
+ await settle();
+ expect(app.newDevices.map((d) => d.label), ['Phone', 'Chrome', 'Tablet']);
+
+ // "It's mine" here: marked here, and shared for the account's other devices.
+ app.dismissNewDevice(b64e(phone.pub));
+ await settle();
+ expect(api.posted.map((a) => a.pub), [b64e(phone.pub)]);
+ expect(api.posted.single.signer, b64e((await keys.identity()).pub));
+
+ // box2 (on the account before this app) confirmed the tablet; the log is read again (the push).
+ api.acks.add(
+ (await signDevAck(
+ DevAck(v: 1, acct: _acct, pub: b64e(tablet.pub), addSeq: backend.state.active[b64e(tablet.pub)]!.seq, signer: b64e(box2.pub), at: 9000),
+ box2,
+ )).toJson(),
+ );
+ await logOf(app).refresh();
+ await settle();
+ expect(app.newDevices.map((d) => d.label), ['Chrome']);
+ final devices = (await app.loadDevices())!;
+ expect(devices.devices.firstWhere((d) => d.pub == b64e(tablet.pub)).confirmedOn, 'box2');
+ expect(devices.devices.firstWhere((d) => d.pub == b64e(phone.pub)).confirmedOn, isNull);
+
+ // Opening the list (Review) marks what it showed as seen here, and tells nobody.
+ app.seenNewDevices();
+ await settle();
+ expect((await logOf(app).list()).pending, isEmpty);
+ expect(api.posted, hasLength(1));
+ });
+
test('opening the list writes back what it read as pending even with no banner up', () async {
final app = start();
addTearDown(app.dispose);
diff --git a/desktop/test/viewer/deviceAck.vectors.json b/desktop/test/viewer/deviceAck.vectors.json
new file mode 100644
index 000000000..838e0d1a2
--- /dev/null
+++ b/desktop/test/viewer/deviceAck.vectors.json
@@ -0,0 +1,271 @@
+{
+ "comment": "Generated by cli/scripts/gen-devack-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4). `message` is the hex of devAckMessage(valid[0]).",
+ "acct": "acct-vectors-1",
+ "seeds": {
+ "box1": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
+ "box2": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=",
+ "browser": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "stranger": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ="
+ },
+ "pubs": {
+ "box1": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "box2": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "browser": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "stranger": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw="
+ },
+ "log": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 1000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "PQ79548gYy1fR00xYYrAqGYQer//uS3fGo1Xwwih7v6Jpw8lLHsM/plOYoenu8qjIWhPTSPlVSghlAt9C6MMCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 2000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "bHi9oSluvJ/RKgTw7RZrPaplcR45FGkVMmnOjm4dQnTzchKsMN6D6WKTNphHLjthUYhcznmjIJDLjplJ5TKsAg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 3000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "browser",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "vYm6LtYV1vK3yQR7Sp1/EPFoiFTOyM+7zhsnDUCXZUDeYJ1e9SL7m3xjEGdgo3x9Fd6DPwM51bkDwz9JstSpCQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "vMPGnQgYDO21pqy7wyaTJJGLaHpCdXDVAIkJrfJ7KUA=",
+ "at": 4000,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "gYDuihZziynx5hm1/FB2kZUKs+qZzVT1CZ4MbtjCSdKJEYM/736O4oKgFCnzg6RdHlGLcqUTRhkq3xZ3sqxuCA=="
+ }
+ ],
+ "message": "000000116861726e6573732d64657661636b2d763100000001310000000e616363742d766563746f72732d3100000020ed4928c628d1c2c6eae90338905995612959273a5c63f93636c14614ac8737d10000000133000000208a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c0000000435303030",
+ "valid": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "addSeq": 1,
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "at": 6000,
+ "sig": "Tvs71LrL6KUWDTzt8vqopLsIubbiEF+Q+wHMjPNappC+jCvHUXvOuUwnPHAIovDQGhCnOybac7StvvHFm0k1Bg=="
+ }
+ ],
+ "invalid": [
+ {
+ "name": "tampered time",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5001,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "signed under the device log tag",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "UiDLPvPt03A2Am5iDEakR3ilJc/OC1cfF2jhL7n3a+4UJN+pFFENwJPRTWodgahPRyw9SeyB0LOue6L4FzFQDw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "signed by another key than the signer",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "eqjcnHjAWOjrRa1aGALmlEzLhVZR1QkzxNsCxV+l/8/wlbK+NoHtTnR/+tlhxXmhCMdrTVuZSS4Q0HZESphFDw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "a key acknowledging itself",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "at": 5000,
+ "sig": "Cmg55AVm78H0Uvm25ugS1dX8QncK0jVBztdkmP2mMfY/2Ze+NaBSWCkX35MXiAO5JjdGwT7oNIdjN0egnm26BA=="
+ },
+ "code": "SELF_ACK"
+ },
+ {
+ "name": "signer not in the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "at": 5000,
+ "sig": "MGKqHpl4Oe701BsU7aWlmsgOUDnJ7WqOQjbWmBvGiPqM26/5MPuT8fHqHTgMqfbzC2U0K5YBKlKqbK1hwjl1Bw=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "signer removed from the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "at": 5000,
+ "sig": "y2HnM3LiMr69YaXjuNNsWNE0iLwQ3ZfzFzyLYck9SPbOa6Orz3lPI/32MzN0UCC4Ng/EQySy5XYFZAeLbQf0AA=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "wrong add entry",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 2,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "3dCkpuz6Tu5XEmvFIGnFQaiLin+Ninldkrmvp6K/a9g1EqEJ4uTds8dMdtqZKjsAIZpMEKKQUGbrL3wWeBOBCg=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "key removed from the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "addSeq": 2,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "/GLyfKMRBF4JXwbg07KnkIB1wHMnZHkwIs4+utnxwJrobNkI9kaf0GdcBewxkt9F0MJ5MvWqWpwuQGraVpo9BA=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "key never in the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "U+ud4hDLUP1a4uAJY8+oPqBCho6vndu3AflTI7NhfUYcIukAH65jtjM3WArUDhO3iM8+GG9XYvBz66o+Pf8kDw=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "another account",
+ "ack": {
+ "v": 1,
+ "acct": "acct-other",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "cTBr1vv9/MOr3txBo0ZoPG7RK+YvqsxfNGyCG1bv5djsBaIAOHh9JeW0PEse15pstinySS5fZfcscgMhmbJEBg=="
+ },
+ "code": "WRONG_ACCOUNT"
+ },
+ {
+ "name": "unknown version",
+ "ack": {
+ "v": 2,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "add entry zero",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 0,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "848QPR9kk82i9U1SGs7xcG7cZDAq8M6a7erc9FFGQk9QQui8X/HoCMzdmydlVxy4jvGHvNGepQ41htILwCvvDw=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "key of the wrong length",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "not an object",
+ "ack": "ack",
+ "code": "BAD_ACK"
+ }
+ ]
+}
diff --git a/desktop/test/viewer/device_ack_test.dart b/desktop/test/viewer/device_ack_test.dart
new file mode 100644
index 000000000..32306011f
--- /dev/null
+++ b/desktop/test/viewer/device_ack_test.dart
@@ -0,0 +1,63 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/viewer/device_ack.dart';
+import 'package:harness/viewer/device_log.dart';
+
+/// The Dart port of the device acknowledgement, held to the fixture every implementation shares
+/// (cli/scripts/gen-devack-vectors.ts).
+void main() {
+ final vectors = jsonDecode(File('test/viewer/deviceAck.vectors.json').readAsStringSync()) as Map<String, dynamic>;
+ final acct = vectors['acct'] as String;
+ final seeds = (vectors['seeds'] as Map).cast<String, String>();
+ final pubs = (vectors['pubs'] as Map).cast<String, String>();
+ final valid = (vectors['valid'] as List).cast<Map<String, dynamic>>();
+ Future<DevLogState> state() async =>
+ (await applyDevLogEntries(DevLogState.empty(acct), (vectors['log'] as List).cast<Object?>())).state;
+
+ test('encodes the first acknowledgement to the fixture bytes', () {
+ expect(hexOf(devAckMessage(DevAck.parse(valid.first)!)), vectors['message']);
+ });
+
+ test('re-signs every valid acknowledgement to the same signature, and accepts it', () async {
+ final byPub = {for (final n in seeds.keys) pubs[n]!: seeds[n]!};
+ final s = await state();
+ for (final raw in valid) {
+ final a = DevAck.parse(raw)!;
+ final id = await E2eeIdentity.fromSeed(b64d(byPub[a.signer]!));
+ expect(b64e(id.pub), a.signer);
+ expect((await signDevAck(a.withSig(''), id)).sig, a.sig);
+ final checked = await checkDevAck(s, raw);
+ expect(checked.code, isNull);
+ expect(checked.ack?.toJson(), raw);
+ }
+ });
+
+ for (final c in (vectors['invalid'] as List).cast<Map<String, dynamic>>()) {
+ test('refuses: ${c['name']} (${c['code']})', () async {
+ final checked = await checkDevAck(await state(), c['ack']);
+ expect(checked.ack, isNull);
+ expect(checked.code, c['code']);
+ });
+ }
+
+ test('refuses each field out of bounds', () {
+ final good = valid.first;
+ for (final bad in <Object?>[
+ null,
+ {...good, 'acct': ''},
+ {...good, 'acct': 'x' * 129},
+ {...good, 'signer': 'not base64!'},
+ {...good, 'pub': 'A' * 200},
+ {...good, 'addSeq': 1.5},
+ {...good, 'addSeq': '3'},
+ {...good, 'at': 0},
+ ]) {
+ expect(DevAck.parse(bad), isNull, reason: '$bad');
+ }
+ expect(DevAck.parse({...good, 'extra': 1})?.toJson(), good);
+ });
+}
diff --git a/desktop/test/viewer/device_log_acks_test.dart b/desktop/test/viewer/device_log_acks_test.dart
new file mode 100644
index 000000000..5a4d826d7
--- /dev/null
+++ b/desktop/test/viewer/device_log_acks_test.dart
@@ -0,0 +1,370 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/viewer/device_ack.dart';
+import 'package:harness/viewer/device_log.dart';
+import 'package:harness/viewer/device_log_sync.dart';
+import 'package:harness/viewer/group_sync.dart';
+import 'package:harness/viewer/viewer_key_store.dart';
+
+/// "It's mine", once for the account (`lib/viewer/device_ack.dart`), as this app's copy of the device
+/// key log takes it: an acknowledgement another trusted device signed takes a new key off the list here;
+/// one this app is asked to share is signed and handed to the backend. Mirrors the CLI's
+/// deviceLogSyncer.spec.ts ("It's mine", once for the account).
+
+class _Memory implements LocalKeyValueStore {
+ final values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+const _acct = 'acct-1';
+final _mid2 = 'b' * 32;
+
+/// The backend: keeps the log honestly, and serves whatever acknowledgements it holds, checked or not.
+class _Backend {
+ DevLogState state = DevLogState.empty(_acct);
+ final entries = <DevLogEntry>[];
+ final acks = <Object?>[];
+ final askedAcks = <int>[];
+ final posted = <DevAck>[];
+
+ /// False: a backend from before acknowledgements (404 on both routes).
+ bool ackRoute = true;
+ bool ackReadThrows = false;
+
+ Future<void> add(E2eeIdentity who, String kind, String machineId, String label) async {
+ final pub = b64e(who.pub);
+ await _push(await signDevLogEntry(
+ nextDevLogEntry(state, op: 'add', pub: pub, kind: kind, machineId: machineId, label: label, signer: pub, at: 1000),
+ who,
+ ));
+ }
+
+ Future<void> removeBy(String target, E2eeIdentity by) async {
+ final t = state.active[target]!;
+ await _push(await signDevLogEntry(
+ nextDevLogEntry(state, op: 'remove', pub: t.pub, kind: t.kind, machineId: t.machineId, label: t.label, signer: b64e(by.pub), at: 2000),
+ by,
+ ));
+ }
+
+ Future<void> _push(DevLogEntry e) async {
+ state = (await applyDevLogEntries(state, [e.toJson()])).state;
+ entries.add(e);
+ }
+
+ Future<DeviceLogFetched?> fetch(int since) async =>
+ (acct: _acct, head: state.head, entries: [for (final e in entries) if (e.seq > since) e.toJson()]);
+
+ Future<DeviceLogAppendAnswer?> append(DevLogEntry entry) async {
+ if (entry.seq != state.head.seq + 1 || entry.prev != state.head.hash) return (head: state.head, error: 'STALE_HEAD');
+ await _push(entry);
+ return (head: state.head, error: null);
+ }
+
+ Future<List<Object?>?> fetchAcks(int since) async {
+ askedAcks.add(since);
+ if (ackReadThrows) throw StateError('down');
+ if (!ackRoute) return null;
+ return [...acks];
+ }
+
+ Future<bool> postAck(DevAck ack) async {
+ if (!ackRoute) return false;
+ posted.add(ack);
+ acks.add(ack.toJson());
+ return true;
+ }
+
+ /// An acknowledgement of [of] by [by], for the entry that added it unless [addSeq] says otherwise.
+ Future<Map<String, Object?>> ack(E2eeIdentity by, String of, {int? addSeq, String acct = _acct}) async =>
+ (await signDevAck(
+ DevAck(v: 1, acct: acct, pub: of, addSeq: addSeq ?? state.active[of]?.seq ?? 1, signer: b64e(by.pub), at: 7000),
+ by,
+ )).toJson();
+}
+
+void main() {
+ late _Backend backend;
+ late ViewerKeyStore keys;
+ late List<DevLogMember> announced;
+ late int changed;
+ late E2eeIdentity box2, phone, later;
+
+ ViewerDeviceLog makeLog({bool acks = true}) => ViewerDeviceLog(
+ keys: keys,
+ fetch: backend.fetch,
+ append: backend.append,
+ fetchAcks: acks ? backend.fetchAcks : null,
+ postAck: acks ? backend.postAck : null,
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onChanged: () => changed++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Future<Map<String, Object?>> file() async => ((await keys.deviceLog()) as Map).cast<String, Object?>();
+ Future<String> self() async => b64e((await keys.identity()).pub);
+ String pubOf(E2eeIdentity id) => b64e(id.pub);
+
+ setUp(() async {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ announced = [];
+ changed = 0;
+ box2 = await E2eeIdentity.fromSeed(List.filled(32, 2));
+ phone = await E2eeIdentity.fromSeed(List.filled(32, 3));
+ later = await E2eeIdentity.fromSeed(List.filled(32, 5));
+ });
+
+ /// box2 was on the account before this app joined (never new here); the phone joined after (new).
+ Future<ViewerDeviceLog> joined({bool acks = true}) async {
+ final log = makeLog(acks: acks);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(phone, 'viewer', '', 'phone');
+ await log.refresh();
+ expect((await log.list()).pending, [pubOf(phone)]);
+ announced.clear();
+ changed = 0;
+ backend.askedAcks.clear();
+ return log;
+ }
+
+ test('a trusted older device\'s "It\'s mine" takes the new key off the list here, and says on which', () async {
+ final log = await joined();
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.pending, isEmpty);
+ final row = listing.members.firstWhere((r) => r.member.pub == pubOf(phone));
+ expect(row.pending, isFalse);
+ expect(row.confirmed?.toJson(), {'by': pubOf(box2), 'label': 'box2', 'at': 5000});
+ expect(listing.members.firstWhere((r) => r.member.pub == pubOf(box2)).confirmed, isNull);
+ expect(changed, greaterThan(0));
+ });
+
+ test('asks from just below the oldest key new here, and not at all while nothing is new', () async {
+ final log = await joined();
+ await log.refresh();
+ expect(backend.askedAcks, [backend.state.active[pubOf(phone)]!.seq - 1]);
+ await log.dismiss(pub: pubOf(phone));
+ backend.askedAcks.clear();
+ await log.refresh();
+ expect(backend.askedAcks, isEmpty);
+ });
+
+ test('a device confirmed while this app was closed is announced once, as every new key is, then taken off the list', () async {
+ final log = makeLog();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.add(later, 'viewer', '', 'later');
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ // The one-time "New device" never waits on, or is skipped for, anyone's word.
+ expect(announced.map((m) => m.label), ['phone', 'later']);
+ expect((await log.list()).pending, [pubOf(later)]);
+ await log.refresh();
+ expect(announced, hasLength(2));
+ });
+
+ test('stays as before when the acknowledgements cannot be read, or the read fails', () async {
+ for (final fail in ['no route', 'throws']) {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ announced = [];
+ final log = makeLog();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ if (fail == 'no route') {
+ backend.ackRoute = false;
+ } else {
+ backend.ackReadThrows = true;
+ }
+ await backend.add(phone, 'viewer', '', 'phone');
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['phone'], reason: fail);
+ expect((await log.list()).pending, [pubOf(phone)], reason: fail);
+ }
+ });
+
+ group('what is ignored', () {
+ test('a key vouching for itself, a bad signature, the wrong entry, another account, this app\'s own', () async {
+ final log = await joined();
+ final good = await backend.ack(box2, pubOf(phone));
+ backend.acks.addAll([
+ await backend.ack(phone, pubOf(phone)),
+ {...good, 'at': 7001},
+ await backend.ack(box2, pubOf(phone), addSeq: backend.state.active[pubOf(phone)]!.seq - 1),
+ await backend.ack(box2, pubOf(phone), acct: 'acct-2'),
+ (await signDevAck(
+ DevAck(v: 1, acct: _acct, pub: pubOf(phone), addSeq: backend.state.active[pubOf(phone)]!.seq, signer: await self(), at: 7000),
+ await keys.identity(),
+ )).toJson(),
+ {'junk': true},
+ ]);
+ await log.refresh();
+ expect((await log.list()).pending, [pubOf(phone)]);
+ expect((await file())['confirmed'], isNull);
+ expect(changed, 0);
+ });
+
+ test('a signer that is itself new here: two new devices must not vouch for each other', () async {
+ final log = await joined();
+ await backend.add(later, 'viewer', '', 'later');
+ await log.refresh();
+ backend.acks.addAll([await backend.ack(later, pubOf(phone)), await backend.ack(phone, pubOf(later))]);
+ await log.refresh();
+ expect((await log.list()).pending, [pubOf(phone), pubOf(later)]);
+ });
+
+ test('a signer that is gone (removed, or joined and left before anyone looked)', () async {
+ final log = await joined();
+ await backend.add(later, 'viewer', '', 'later');
+ await log.refresh();
+ final fromLater = await backend.ack(later, pubOf(phone));
+ final fromBox2 = await backend.ack(box2, pubOf(phone));
+ await backend.removeBy(pubOf(later), later);
+ await backend.removeBy(pubOf(box2), box2);
+ backend.acks.addAll([fromLater, fromBox2]);
+ await log.refresh();
+ expect((await log.list()).departed.map((d) => d.pub), [pubOf(later)]);
+ expect((await log.list()).pending, [pubOf(phone)]);
+ });
+
+ test('a signer suspended here, or tombstoned in the trust group here', () async {
+ for (final how in ['suspended', 'tombstoned']) {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final log = await joined();
+ if (how == 'suspended') {
+ await keys.writeDeviceLog({...await file(), 'suspended': [pubOf(box2)]});
+ } else {
+ await keys.writeGroupRoster(GroupRoster(const [], [GroupTombstone(pubOf(box2), 1000)]).toJson());
+ }
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect((await log.list()).pending, [pubOf(phone)], reason: how);
+ }
+ });
+
+ test('never lifts a suspension: a key a fork suspended here stays new and suspended', () async {
+ final log = await joined();
+ await keys.writeDeviceLog({...await file(), 'suspended': [pubOf(phone)]});
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect(backend.askedAcks, isEmpty);
+ final listing = await log.list();
+ expect(listing.pending, [pubOf(phone)]);
+ expect(listing.suspended, [pubOf(phone)]);
+ });
+
+ test('nothing at all while the log is frozen here', () async {
+ final log = await joined();
+ await keys.writeDeviceLog({
+ ...await file(),
+ 'frozen': {'reason': 'fork', 'at': 1, 'lastGoodHead': backend.state.head.toJson()},
+ });
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect(backend.askedAcks, isEmpty);
+ expect((await log.list()).pending, [pubOf(phone)]);
+ });
+ });
+
+ test('the mark goes with the key: a confirmed key removed later leaves none behind, and is not departed', () async {
+ final log = await joined();
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect((await file())['confirmed'], isA<Map>());
+ await backend.removeBy(pubOf(phone), box2);
+ await log.refresh();
+ expect((await file())['confirmed'], isNull);
+ expect((await log.list()).departed, isEmpty);
+ });
+
+ group('"It\'s mine" here is shared', () {
+ test('for the one device the person pressed it for, signed by this app for the entry that added it', () async {
+ for (final one in [true, false]) {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final log = await joined();
+ final shared = one
+ ? await log.dismiss(pub: pubOf(phone), confirm: true)
+ : await log.dismiss(pubs: [pubOf(phone)], confirm: true);
+ expect(shared, isTrue);
+ expect((await log.list()).pending, isEmpty);
+ expect(backend.posted, hasLength(1));
+ final ack = backend.posted.single;
+ expect(ack.signer, await self());
+ expect(ack.pub, pubOf(phone));
+ expect(ack.addSeq, backend.state.active[pubOf(phone)]!.seq);
+ // What every other device checks it against: the same log.
+ expect((await checkDevAck(backend.state, ack.toJson())).code, isNull);
+ }
+ });
+
+ test('never for a list looked at, every device at once, or without "It\'s mine"', () async {
+ final log = await joined();
+ await backend.add(later, 'viewer', '', 'later');
+ await log.refresh();
+ expect(await log.dismiss(pubs: [pubOf(phone), pubOf(later)], confirm: true), isFalse);
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final again = await joined();
+ expect(await again.dismiss(pub: pubOf(phone)), isFalse);
+ expect(await again.dismiss(confirm: true), isFalse);
+ expect(backend.posted, isEmpty);
+ });
+
+ test('never for a key that was not new here, or this app\'s own', () async {
+ final log = await joined();
+ expect(await log.dismiss(pub: pubOf(box2), confirm: true), isFalse);
+ expect(await log.dismiss(pub: await self(), confirm: true), isFalse);
+ await log.dismiss(pub: pubOf(phone));
+ expect(await log.dismiss(pub: pubOf(phone), confirm: true), isFalse);
+ expect(backend.posted, isEmpty);
+ });
+
+ test('for a suspended key only when "It\'s mine" lifted the suspension here', () async {
+ final log = await joined();
+ await keys.writeDeviceLog({...await file(), 'suspended': [pubOf(phone)]});
+ expect(await log.dismiss(pubs: [pubOf(phone)], confirm: true), isFalse);
+ expect((await log.list()).suspended, [pubOf(phone)]);
+ expect(await log.dismiss(pub: pubOf(phone), confirm: true), isTrue);
+ expect((await log.list()).suspended, isEmpty);
+ });
+
+ test('not from a frozen log — the key is marked seen here all the same', () async {
+ final log = await joined();
+ await keys.writeDeviceLog({
+ ...await file(),
+ 'frozen': {'reason': 'fork', 'at': 1, 'lastGoodHead': backend.state.head.toJson()},
+ });
+ expect(await log.dismiss(pub: pubOf(phone), confirm: true), isFalse);
+ expect((await log.list()).pending, isEmpty);
+ expect(backend.posted, isEmpty);
+ });
+
+ test('a backend that does not take it, or none to take it, leaves the dismissal here', () async {
+ final log = await joined();
+ backend.ackRoute = false;
+ expect(await log.dismiss(pub: pubOf(phone), confirm: true), isFalse);
+ expect((await log.list()).pending, isEmpty);
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final alone = await joined(acks: false);
+ expect(await alone.dismiss(pub: pubOf(phone), confirm: true), isFalse);
+ expect((await alone.list()).pending, isEmpty);
+ });
+ });
+}
diff --git a/docs/cli.md b/docs/cli.md
index eba2ee5d3..05e5bb973 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -112,8 +112,14 @@ confirm a device; instead every device shows you each one it did not know before
`harness devices` is this machine's view, the same one Settings ▸ Your devices shows in the app.
- **New.** A device added after this machine joined the account is flagged `new` (an OS notification
- in the apps) and stays flagged across restarts until you look: `harness devices dismiss` marks every
- one seen, `dismiss <#|fp>` just one; opening Your devices does the same in the apps.
+ in the apps) and stays flagged across restarts until you confirm it on one of your trusted devices,
+ or review it on each. Confirming is "It's mine" in the apps, or `harness devices dismiss <#|fp>`
+ here: it marks that device seen here and tells your other devices, which stop flagging it and show
+ where it was confirmed (`harness devices show`: `confirmed on <device>`). Each device checks that
+ confirmation itself: it counts only when signed by a device that device already trusts — not one
+ that is itself new, suspended or removed there — and it never lifts a suspension. Reviewing
+ (`harness devices dismiss` with no device, or opening Your devices in the apps) marks every one seen
+ on that device only.
- **Already on your account.** The first time a device reads the log it announces nothing; the apps
show the devices that were already there once, until you press Got it.
- **Joined and left before you looked.** A new device that was removed before you saw it stays listed,
diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dart
index 219208b7b..5d77cf9e0 100644
--- a/mobile/lib/api/api_client.dart
+++ b/mobile/lib/api/api_client.dart
@@ -6,6 +6,7 @@ import '../auth/auth_session.dart';
import '../core/config.dart';
import '../core/models.dart';
import '../logging/http_log.dart';
+import '../viewer/device_ack.dart';
import '../viewer/device_log.dart';
import '../viewer/device_log_sync.dart' show DeviceLogAppendAnswer, DeviceLogFetched;
import 'access_token_source.dart';
@@ -129,6 +130,37 @@ class ApiClient {
}
}
+ /// `GET /api/device-keys/acks?since=` — the acknowledgements ("It's mine" said on another device,
+ /// `viewer/device_ack.dart`) of keys added after entry [since], unchecked: the device log judges each.
+ /// Null when there are none to read (a backend from before them, signed out, or unreachable). A short
+ /// deadline: while it runs, the read of the log that asked holds back its "New device" notices.
+ Future<List<Object?>?> deviceAcks(int since) async {
+ try {
+ final res = await _dio.get(
+ '/api/device-keys/acks',
+ queryParameters: {'since': since},
+ options: Options(receiveTimeout: const Duration(seconds: 5)),
+ );
+ if (res.statusCode != 200) return null;
+ final data = unwrapApiResponse(res);
+ final acks = data is Map ? data['acks'] : null;
+ return acks is List ? acks.cast<Object?>() : null;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// `POST /api/device-keys/acks` — share this phone's "It's mine" for a device with the account's
+ /// other devices. False when the backend did not keep it (or predates it).
+ Future<bool> postDeviceAck(DevAck ack) async {
+ try {
+ final res = await _dio.post('/api/device-keys/acks', data: {'ack': ack.toJson()});
+ return res.statusCode == 200;
+ } catch (_) {
+ return false;
+ }
+ }
+
/// `GET /api/device-keys/seen` — when each key last opened a session, `{pub: ms}`; empty when it
/// cannot be read. A hint for offering to remove apps not used in a long while.
Future<Map<String, int>> deviceKeysSeen() async {
diff --git a/mobile/lib/phone/device_detail_page.dart b/mobile/lib/phone/device_detail_page.dart
index 7e45a77fc..7ae6a6f68 100644
--- a/mobile/lib/phone/device_detail_page.dart
+++ b/mobile/lib/phone/device_detail_page.dart
@@ -136,6 +136,14 @@ class _DeviceDetailPageState extends State<DeviceDetailPage> {
member.machineId.length < 8 ? member.machineId.length : 8,
),
),
+ // Another of the person's devices said "It's mine" for it while it was new here: where
+ // the banner would have been, the page says where it was settled.
+ if (_row.confirmed case final confirmed?)
+ SettingsRow(
+ key: const Key('device-detail-confirmed'),
+ title: 'Confirmed',
+ value: 'on ${confirmed.label.trim().isEmpty ? 'another device' : confirmed.label.trim()}',
+ ),
],
),
if (fp.isNotEmpty) ...[
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index aa8986cad..1dba0a282 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -2302,11 +2302,13 @@ class AppNotifier extends ChangeNotifier {
/// on the next read of `pending`. Gone with the sign-in, or when the key is announced afresh.
final Set<String> _failedDismissals = {};
- Future<void> _dismissInLog({String? pub, List<String>? pubs}) async {
+ /// [confirm]: "It's mine" for the one device named — the account's other devices are told too, and
+ /// stop showing it as new.
+ Future<void> _dismissInLog({String? pub, List<String>? pubs, bool confirm = false}) async {
final log = _deviceLog;
if (log == null) return;
try {
- await log.dismiss(pub: pub, pubs: pubs);
+ await log.dismiss(pub: pub, pubs: pubs, confirm: confirm);
} catch (error) {
debugPrint('devices: could not save the dismissal: $error');
_failedDismissals.addAll([...?pubs, ?pub]);
@@ -2322,6 +2324,9 @@ class AppNotifier extends ChangeNotifier {
self: await viewer.keys.identity().then<String?>((i) => b64e(i.pub), onError: (Object _) => null),
),
append: (entry) => api.appendDeviceKey(entry),
+ // "It's mine", once for the account: read what other devices confirmed, share what this one does.
+ fetchAcks: (since) => api.deviceAcks(since),
+ postAck: (ack) => api.postDeviceAck(ack),
label: () => phoneClientDescriptor().name,
// The log saves "announced" before it calls back, so a call that found the app still starting
// up and was dropped would never be made again: [_whenSignedIn] parks it instead. Only a
@@ -2501,7 +2506,8 @@ class AppNotifier extends ChangeNotifier {
/// "It's mine" on [pub]. Only the device's own page, which shows why a key is Suspended, passes
/// [liftSuspension]: that is the person vouching for it. Anywhere else the key stays suspended —
- /// the banner never said so.
+ /// the banner never said so. Either way the account's other devices are told, and stop showing it as
+ /// new (opening the list, [seenNewDevices], tells nobody).
void dismissNewDevice(String pub, {bool liftSuspension = false}) {
newDevices.removeWhere((d) => d.pub == pub);
// A key that joined and left before anyone looked: a "New device" for it is a stale replay, and its
@@ -2512,7 +2518,7 @@ class AppNotifier extends ChangeNotifier {
return;
}
_pendingSyncGen++;
- unawaited(liftSuspension ? _dismissInLog(pub: pub) : _dismissInLog(pubs: [pub]));
+ unawaited(liftSuspension ? _dismissInLog(pub: pub, confirm: true) : _dismissInLog(pubs: [pub], confirm: true));
notifyListeners();
}
diff --git a/mobile/lib/viewer/device_ack.dart b/mobile/lib/viewer/device_ack.dart
new file mode 100644
index 000000000..307754768
--- /dev/null
+++ b/mobile/lib/viewer/device_ack.dart
@@ -0,0 +1,113 @@
+import 'dart:typed_data';
+
+import '../e2ee/bytes.dart';
+import '../e2ee/keys.dart';
+import 'device_log.dart';
+
+/// "It's mine", said once for the whole account: a device's signed acknowledgement that another device
+/// on the account's device key log is the person's own (cli/src/lib/e2ee/deviceAck.ts, ported). One
+/// trusted device confirming a new one is enough for the others to stop showing it as New.
+///
+/// Kept OUTSIDE the hash chain: an op the log does not know would make every older client freeze the
+/// whole log as invalid. An acknowledgement never adds trust — it only takes a key the log already
+/// leaves active off the "New" list — and this app never takes the backend's word for one: [checkDevAck]
+/// verifies it against this app's own verified log, and [ViewerDeviceLog] adds its own marks (the signer
+/// must not be new, suspended or gone here; a suspended key stays suspended).
+///
+/// Pure: no I/O. The signature covers [devAckMessage] — the fields length-prefixed in a fixed order,
+/// headed by its own domain tag, never the device log's — never JSON. ⚠️ Held, with the CLI, the
+/// backend and the other app's copy (desktop/ and mobile/lib/viewer/device_ack.dart, byte-identical), to
+/// `test/viewer/deviceAck.vectors.json`: change the format in every copy together.
+
+const devAckVersion = 1;
+const devAckTag = 'harness-devack-v1';
+const _maxSafe = 9007199254740991;
+
+class DevAck {
+ const DevAck({
+ required this.v,
+ required this.acct,
+ required this.pub,
+ required this.addSeq,
+ required this.signer,
+ required this.at,
+ this.sig = '',
+ });
+
+ final int v;
+ final String acct;
+
+ /// The device being acknowledged.
+ final String pub;
+
+ /// The seq of the log entry that added [pub].
+ final int addSeq;
+
+ /// The device that acknowledges it, and signs it.
+ final String signer;
+
+ /// When, as the signer's clock read it. Shown, never trusted for anything.
+ final int at;
+ final String sig;
+
+ DevAck withSig(String sig) =>
+ DevAck(v: v, acct: acct, pub: pub, addSeq: addSeq, signer: signer, at: at, sig: sig);
+
+ Map<String, Object?> toJson() =>
+ {'v': v, 'acct': acct, 'pub': pub, 'addSeq': addSeq, 'signer': signer, 'at': at, 'sig': sig};
+
+ /// deviceAck.ts `parseDevAck`: every field present, of its type and within bounds.
+ static DevAck? parse(Object? raw) {
+ if (raw is! Map) return null;
+ final v = raw['v'], acct = raw['acct'], pub = raw['pub'], addSeq = raw['addSeq'];
+ final signer = raw['signer'], at = raw['at'], sig = raw['sig'];
+ if (v != devAckVersion) return null;
+ if (acct is! String || acct.isEmpty || acct.length > 128) return null;
+ if (!_isBytes(pub, 32) || !_isBytes(signer, 32) || !_isBytes(sig, 64)) return null;
+ if (addSeq is! int || addSeq < 1 || addSeq > _maxSafe) return null;
+ if (at is! int || at <= 0 || at > _maxSafe) return null;
+ return DevAck(
+ v: v as int, acct: acct, pub: pub as String, addSeq: addSeq, signer: signer as String, at: at,
+ sig: sig as String,
+ );
+ }
+}
+
+/// base64 of exactly [n] bytes, in its one canonical spelling.
+bool _isBytes(Object? s, int n) {
+ if (s is! String || s.length > 128) return false;
+ try {
+ final u = b64d(s);
+ return u.length == n && b64e(u) == s;
+ } catch (_) {
+ return false;
+ }
+}
+
+/// The bytes a signature covers.
+Uint8List devAckMessage(DevAck a) => lvCat([
+ devAckTag, '${a.v}', a.acct, b64d(a.pub), '${a.addSeq}', b64d(a.signer), '${a.at}',
+]);
+
+Future<DevAck> signDevAck(DevAck unsigned, E2eeIdentity identity) async =>
+ unsigned.withSig(b64e(await identity.sign(devAckMessage(unsigned))));
+
+/// What [checkDevAck] made of an acknowledgement: [ack] when it holds, else [code] says why not.
+typedef DevAckCheck = ({DevAck? ack, String? code});
+
+/// deviceAck.ts `checkDevAck`: well formed, of [state]'s account, signed by its signer, not a key
+/// vouching for itself, the signer active on [state], and the key active on it and added at `addSeq`.
+/// Whether the signer is new, suspended or gone here is the caller's to judge.
+Future<DevAckCheck> checkDevAck(DevLogState state, Object? raw) async {
+ final ack = DevAck.parse(raw);
+ if (ack == null) return (ack: null, code: 'BAD_ACK');
+ if (ack.acct != state.acct) return (ack: null, code: 'WRONG_ACCOUNT');
+ if (!await verifySignature(b64d(ack.signer), devAckMessage(ack), b64d(ack.sig))) {
+ return (ack: null, code: 'BAD_SIGNATURE');
+ }
+ // A key saying it is its own owner's says nothing: whoever added it would sign that too.
+ if (ack.signer == ack.pub) return (ack: null, code: 'SELF_ACK');
+ if (state.active[ack.signer] == null) return (ack: null, code: 'SIGNER_NOT_ACTIVE');
+ if (state.active[ack.pub]?.seq != ack.addSeq) return (ack: null, code: 'NOT_ADDED_THERE');
+ return (ack: ack, code: null);
+}
diff --git a/mobile/lib/viewer/device_log_sync.dart b/mobile/lib/viewer/device_log_sync.dart
index c9452dcde..fe2264e1c 100644
--- a/mobile/lib/viewer/device_log_sync.dart
+++ b/mobile/lib/viewer/device_log_sync.dart
@@ -3,6 +3,7 @@ import 'dart:math';
import '../e2ee/bytes.dart';
import '../e2ee/keys.dart';
+import 'device_ack.dart';
import 'device_history.dart';
import 'device_log.dart';
import 'group_sync.dart';
@@ -19,6 +20,9 @@ export 'device_history.dart'
/// log or rolls it back FREEZES it here: nothing more is pinned from it until someone reviews what
/// changed ([rebaseline]). A key added after this app joined the log is announced ("New device: X") and
/// stays pending until it is marked seen; what the log says is never read against what the roster holds.
+/// "It's mine" here ([dismiss] with `confirm`) is signed and shared beside the log (device_ack.dart), and
+/// one another trusted device shared takes a key off `pending` here: the person confirms a new device
+/// once, on any of their devices.
/// What `GET /api/device-keys?since=` answered; null from the fetcher when there is no log to read.
typedef DeviceLogFetched = ({String acct, DevLogHead head, List<Object?> entries});
@@ -29,6 +33,32 @@ typedef DeviceLogAppendAnswer = ({DevLogHead? head, String? error});
typedef DeviceLogFetch = Future<DeviceLogFetched?> Function(int since);
typedef DeviceLogAppend = Future<DeviceLogAppendAnswer?> Function(DevLogEntry entry);
+/// `GET /api/device-keys/acks?since=`: the acknowledgements of keys added after entry `since`, unchecked
+/// (every one is judged here); null when there are none to read (a backend from before them: 404).
+typedef DeviceLogFetchAcks = Future<List<Object?>?> Function(int since);
+
+/// `POST /api/device-keys/acks`: whether the backend kept one this app signed.
+typedef DeviceLogPostAck = Future<bool> Function(DevAck ack);
+
+/// Another of the person's trusted devices said "It's mine" for a key that was new here, so it is not New
+/// here any more: which device ([by]), what it was called then, and when this app read it. Trusts nothing.
+class DeviceLogConfirmed {
+ const DeviceLogConfirmed({required this.by, required this.label, required this.at});
+
+ final String by;
+ final String label;
+ final int at;
+
+ Map<String, Object?> toJson() => {'by': by, 'label': label, 'at': at};
+
+ static DeviceLogConfirmed? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final by = raw['by'], label = raw['label'], at = raw['at'];
+ if (by is! String || label is! String || at is! int) return null;
+ return DeviceLogConfirmed(by: by, label: label, at: at);
+ }
+}
+
class DeviceLogFreeze {
const DeviceLogFreeze(this.reason, this.at, this.lastGoodHead);
@@ -64,6 +94,7 @@ class _File {
this.owner,
this.joining = false,
this.departed = const [],
+ this.confirmed = const {},
});
DevLogState? state;
@@ -108,6 +139,10 @@ class _File {
/// New keys removed before anyone looked (oldest first, at most [_departedKept]).
List<DeviceLogDeparted> departed;
+ /// New keys another trusted device confirmed, by pub: "Confirmed on <label>". Only ever the reason a
+ /// key left [pending]; it trusts nothing.
+ Map<String, DeviceLogConfirmed> confirmed;
+
Map<String, Object?> toJson() => {
'state': state?.toJson(),
'recent': [for (final e in recent.skip(max(0, recent.length - _recentKept))) e.toJson()],
@@ -128,6 +163,13 @@ class _File {
'looseRemoved': [for (final e in looseRemoved.skip(max(0, looseRemoved.length - _recentKept))) e.toJson()],
if (departed.isNotEmpty)
'departed': [for (final d in departed.skip(max(0, departed.length - _departedKept))) d.toJson()],
+ if (confirmed.isNotEmpty) 'confirmed': {for (final e in confirmed.entries) e.key: e.value.toJson()},
+ };
+
+ static Map<String, DeviceLogConfirmed> _confirmed(Object? raw) => {
+ if (raw is Map)
+ for (final e in raw.entries)
+ if (e.key is String) e.key as String: ?DeviceLogConfirmed.fromJson(e.value),
};
static List<String> _strings(Object? raw) => raw is List ? [for (final v in raw) if (v is String) v] : <String>[];
@@ -152,6 +194,7 @@ class _File {
owner: raw['owner'] is String && (raw['owner'] as String).isNotEmpty ? raw['owner'] as String : null,
joining: raw['joining'] == true,
departed: DeviceLogDeparted.listFromJson(raw['departed']),
+ confirmed: _confirmed(raw['confirmed']),
);
}
}
@@ -186,6 +229,7 @@ class DeviceLogRow {
required this.self,
this.pending = false,
this.suspended = false,
+ this.confirmed,
});
final DevLogMember member;
@@ -197,6 +241,9 @@ class DeviceLogRow {
/// Not trusted here after a fork, until the list is reviewed.
final bool suspended;
+
+ /// Another trusted device said "It's mine" for it while it was new here; null when none did.
+ final DeviceLogConfirmed? confirmed;
}
class DeviceLogListing {
@@ -328,6 +375,8 @@ class ViewerDeviceLog {
required this.fetch,
required this.append,
required this.label,
+ this.fetchAcks,
+ this.postAck,
this.onAnnounce,
this.onRemoved,
this.onSignedOut,
@@ -341,6 +390,12 @@ class ViewerDeviceLog {
final DeviceLogFetch fetch;
final DeviceLogAppend append;
+ /// The acknowledgements beside the log ("It's mine" said on another device); null: none are read.
+ final DeviceLogFetchAcks? fetchAcks;
+
+ /// Where this app's own "It's mine" is shared; null: it stays here.
+ final DeviceLogPostAck? postAck;
+
/// How this app calls itself in the account's list of devices.
final String Function() label;
@@ -864,6 +919,86 @@ class ViewerDeviceLog {
await _endJoin();
if (expecting && !_registering && round == _signInRound) _signingInAgain = false;
}
+ // After the entries, so a key added and confirmed while this app was closed is first announced, as
+ // every new key is — the one-time "New device: X" never waits on, or is skipped for, anyone's word —
+ // and only then taken off the list.
+ await _applyAcks();
+ }
+
+ /// [marks] cut to the keys still active, as a file's [_File.confirmed].
+ Map<String, DeviceLogConfirmed> _keptConfirmed(Map<String, DeviceLogConfirmed> marks, DevLogState state) => {
+ for (final e in marks.entries)
+ if (state.active.containsKey(e.key)) e.key: e.value,
+ };
+
+ /// The keys an acknowledgement could take off `pending` in [file]: new here, still active, not
+ /// suspended, not this app — and none at all from a log that is frozen or not this sign-in's.
+ Future<List<DevLogMember>> _ackable(_File file) async {
+ final state = file.state;
+ if (state == null || file.frozen != null || !await _ownsFile(file)) return const [];
+ final selfPub = await _selfPub();
+ final suspended = await suspendedPubs();
+ return [
+ for (final k in file.pending.toSet())
+ if (state.active[k] case final m? when m.pub != selfPub && !suspended.contains(k)) m,
+ ];
+ }
+
+ /// Take off `pending` every key another of the person's trusted devices said "It's mine" for
+ /// (device_ack.dart), and remember which device did ("Confirmed on <label>").
+ ///
+ /// The backend's word counts for nothing: each acknowledgement must check out against the log as THIS
+ /// app verified it ([checkDevAck]: signature, a signer active on it, the key added at the entry it
+ /// names), and against this app's own marks. The key must still be new here and not suspended — an
+ /// acknowledgement never lifts a suspension; only the person does, here, with "It's mine" on that very
+ /// device. The signer must be a device this app trusts: not new here itself (two new devices must not
+ /// vouch for each other), not suspended, not removed (a departed key is not active), not tombstoned in
+ /// the trust group, and not this app (its own "It's mine" already took the key off). Nothing is read
+ /// while the log is frozen or not yet this sign-in's. Never throws.
+ Future<void> _applyAcks() async {
+ final read = fetchAcks;
+ if (read == null) return;
+ try {
+ final candidates = await _ackable(await _read());
+ // Nothing new here: nothing to ask (and no request at all, on every read, for most of an app's life).
+ if (candidates.isEmpty) return;
+ final raw = await read(candidates.map((m) => m.seq).reduce(min) - 1);
+ if (raw == null || raw.isEmpty) return;
+ final confirmed = await _locked(() async {
+ // Judged against the file as it is NOW: the log may have moved, or a key been looked at, meanwhile.
+ final file = await _read();
+ final state = file.state;
+ final open = {for (final m in await _ackable(file)) m.pub};
+ final out = <String, DeviceLogConfirmed>{};
+ if (state == null || open.isEmpty) return out;
+ final selfPub = await _selfPub();
+ final pending = file.pending.toSet();
+ final suspended = await suspendedPubs();
+ final roster = GroupRoster.parse(await keys.groupRoster());
+ final inRoster = {for (final m in roster.members) m.pub};
+ final tombstoned = {for (final t in roster.removed) if (!inRoster.contains(t.pub)) t.pub};
+ for (final r in raw) {
+ final ack = (await checkDevAck(state, r)).ack;
+ if (ack == null || !open.contains(ack.pub) || out.containsKey(ack.pub)) continue;
+ if (ack.signer == selfPub ||
+ pending.contains(ack.signer) ||
+ suspended.contains(ack.signer) ||
+ tombstoned.contains(ack.signer)) {
+ continue;
+ }
+ out[ack.pub] = DeviceLogConfirmed(by: ack.signer, label: state.active[ack.signer]!.label, at: _now());
+ }
+ if (out.isEmpty) return out;
+ file
+ ..pending = [for (final k in file.pending) if (!out.containsKey(k)) k]
+ ..confirmed = _keptConfirmed({...file.confirmed, ...out}, state);
+ await _write(file);
+ return out;
+ });
+ if (confirmed.isNotEmpty) onChanged?.call();
+ } catch (_) {
+ // Unreadable now: the list stays as it was, and the next read asks again.
+ }
}
Future<void> _readPages() async {
@@ -1085,7 +1220,8 @@ class ViewerDeviceLog {
..pending = _prune(pendingNow, applied.state)
..announced = _prune([...file.announced, for (final m in toAnnounce) m.pub], applied.state)
..suspended = _prune(file.suspended, applied.state)
- ..departed = _withDeparted(file.departed, departed);
+ ..departed = _withDeparted(file.departed, departed)
+ ..confirmed = _keptConfirmed(file.confirmed, applied.state);
await _carrySuspensionsIn(file);
await _write(file);
await _trust(bootstrap ? applied.state.active.values.toList() : [...applied.added, ...applied.relabeled]);
@@ -1479,11 +1615,20 @@ class ViewerDeviceLog {
/// [pub] — "It's mine" on that very device — is the person vouching for it, and lifts its suspension
/// (here and in every kept account's log). A key that joined and left before anyone looked
/// ([DeviceLogListing.departed]) is cleared the same way: named, or every one.
- Future<void> dismiss({String? pub, List<String>? pubs}) async {
+ ///
+ /// [confirm] — "It's mine", pressed for ONE device ([pub], or [pubs] naming only it) — also tells the
+ /// account's other devices, with an acknowledgement this app signs (device_ack.dart): they stop showing
+ /// it as New too. Never for a list that was only looked at, or every device at once: only an explicit
+ /// "It's mine" vouches. Marking it seen here is done first; the result says whether the other devices
+ /// were told (false: the backend did not take it, or there was nothing to tell).
+ Future<bool> dismiss({String? pub, List<String>? pubs, bool confirm = false}) async {
+ final one = pub ?? (pubs != null && pubs.length == 1 ? pubs.first : null);
+ var share = false;
final lifted = <DevLogMember>[];
final changed = await _locked(() async {
final file = await _marksIn();
if (file.state == null) return false;
+ final wasNew = one != null && file.pending.contains(one);
final named = pub != null || pubs != null;
final gone = {...?pubs, ?pub};
file.pending = [
@@ -1503,9 +1648,38 @@ class ViewerDeviceLog {
await _write(file);
if (lifting != null) await _unsuspendArchivedIn([lifting]);
if (lifted.isNotEmpty) await _trust(lifted);
+ // Only a key that was new here, and that this app trusts now: one a fork suspended here (and
+ // "It's mine" did not lift) is not this app's to vouch for.
+ share = confirm && wasNew && !(await suspendedPubs()).contains(one);
return true;
});
if (changed) onChanged?.call();
+ return share ? _shareAck(one!) : false;
+ }
+
+ /// Sign "It's mine" for [pub] and hand it to the backend for the account's other devices. Only from a
+ /// log this app verified, is on, and that is not frozen (a frozen list is not one to vouch from), about
+ /// a key on it that is not this app. Never throws.
+ Future<bool> _shareAck(String pub) async {
+ final post = postAck;
+ if (post == null) return false;
+ try {
+ final file = await _read();
+ final state = file.state;
+ final identity = await keys.identity();
+ final selfPub = b64e(identity.pub);
+ if (state == null || file.frozen != null || !await _ownsFile(file)) return false;
+ if (pub == selfPub || state.active[selfPub] == null) return false;
+ final member = state.active[pub];
+ if (member == null) return false;
+ final ack = await signDevAck(
+ DevAck(v: devAckVersion, acct: state.acct, pub: pub, addSeq: member.seq, signer: selfPub, at: _now()),
+ identity,
+ );
+ return await post(ack);
+ } catch (_) {
+ return false;
+ }
}
/// The "Already on your account" list was acknowledged: the first read is over, whatever comes after
@@ -1621,6 +1795,7 @@ class ViewerDeviceLog {
self: m.pub == selfPub,
pending: file.pending.contains(m.pub),
suspended: file.suspended.contains(m.pub),
+ confirmed: file.confirmed[m.pub],
),
],
frozen: file.frozen,
diff --git a/mobile/test/phone/device_detail_page_test.dart b/mobile/test/phone/device_detail_page_test.dart
index 5d802a365..b7354d27f 100644
--- a/mobile/test/phone/device_detail_page_test.dart
+++ b/mobile/test/phone/device_detail_page_test.dart
@@ -111,6 +111,29 @@ void main() {
expect(find.byKey(const Key('device-detail-remove')), findsOneWidget);
});
+ testWidgets('a device another of the person’s devices confirmed says where, '
+ 'in place of a banner', (tester) async {
+ final notifier = DevicesApp();
+ addTearDown(notifier.dispose);
+ final r = app();
+ final confirmed = DeviceLogRow(
+ r.member,
+ fingerprint: r.fingerprint,
+ self: false,
+ confirmed: const DeviceLogConfirmed(by: 'k', label: 'studio-mac', at: 1),
+ );
+ await pump(tester, notifier, confirmed);
+ expect(find.byKey(const Key('device-detail-confirmed')), findsOneWidget);
+ expect(find.text('on studio-mac'), findsOneWidget);
+ });
+
+ testWidgets('a device nobody confirmed elsewhere says nothing of it', (tester) async {
+ final notifier = DevicesApp();
+ addTearDown(notifier.dispose);
+ await pump(tester, notifier, app());
+ expect(find.byKey(const Key('device-detail-confirmed')), findsNothing);
+ });
+
testWidgets('an app: no machine row, no last active when never seen, and the '
'app wording', (tester) async {
final notifier = DevicesApp();
diff --git a/mobile/test/state/device_pending_sync_test.dart b/mobile/test/state/device_pending_sync_test.dart
index 816f2553c..c44de0f78 100644
--- a/mobile/test/state/device_pending_sync_test.dart
+++ b/mobile/test/state/device_pending_sync_test.dart
@@ -11,6 +11,7 @@ import 'package:harness_mobile/e2ee/keys.dart';
import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/state/pane_layout_store.dart';
+import 'package:harness_mobile/viewer/device_ack.dart';
import 'package:harness_mobile/viewer/device_log.dart';
import 'package:harness_mobile/viewer/device_log_sync.dart';
import 'package:harness_mobile/viewer/direct_auth_api.dart';
@@ -133,6 +134,22 @@ class _Api extends FakeApi {
@override
Future<DeviceLogAppendAnswer?> appendDeviceKey(DevLogEntry entry) =>
backend.append(entry);
+
+ /// The acknowledgements the backend keeps ("It's mine" said on a device), as it serves them.
+ final acks = <Object?>[];
+
+ /// What this phone shared.
+ final posted = <DevAck>[];
+
+ @override
+ Future<List<Object?>?> deviceAcks(int since) async => [...acks];
+
+ @override
+ Future<bool> postDeviceAck(DevAck ack) async {
+ posted.add(ack);
+ acks.add(ack.toJson());
+ return true;
+ }
}
/// The phone's own storage, kept across "restarts". [holdDevLogRead] parks one read of the device log
@@ -351,6 +368,39 @@ void main() {
expect(pubs(second.newDevices), [b64e(box3.pub)]);
});
+ test('"It’s mine" is shared with the account; one another trusted device shared takes the banner down', () async {
+ final older = await E2eeIdentity.fromSeed(List.filled(32, 4));
+ // On the account before this phone: a device it trusts to vouch.
+ await backend.add(older, 'machine', 'd' * 32, 'older');
+ final (app, _) = await launch();
+ final api = app.api as _Api;
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await backend.add(box3, 'machine', _mid3, 'box3');
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(pubs(app.newDevices), [b64e(box2.pub), b64e(box3.pub)]);
+
+ app.dismissNewDevice(b64e(box2.pub));
+ await settle();
+ expect(api.posted.map((a) => a.pub), [b64e(box2.pub)]);
+
+ api.acks.add(
+ (await signDevAck(
+ DevAck(v: 1, acct: _acct, pub: b64e(box3.pub), addSeq: backend.state.active[b64e(box3.pub)]!.seq, signer: b64e(older.pub), at: 9000),
+ older,
+ )).toJson(),
+ );
+ await app.deviceLog!.refresh();
+ await settle();
+ expect(app.newDevices, isEmpty);
+ final row = (await app.deviceListing()).members.firstWhere((r) => r.member.pub == b64e(box3.pub));
+ expect(row.confirmed?.label, 'older');
+ // Opening the list tells nobody.
+ app.seenNewDevices(pending: [b64e(box3.pub)]);
+ await settle();
+ expect(api.posted, hasLength(1));
+ });
+
test('opening the list (seenNewDevices) holds across a restart', () async {
final (first, _) = await launch();
await backend.add(box3, 'machine', _mid3, 'box3');
diff --git a/mobile/test/viewer/deviceAck.vectors.json b/mobile/test/viewer/deviceAck.vectors.json
new file mode 100644
index 000000000..838e0d1a2
--- /dev/null
+++ b/mobile/test/viewer/deviceAck.vectors.json
@@ -0,0 +1,271 @@
+{
+ "comment": "Generated by cli/scripts/gen-devack-vectors.ts. Keys are Ed25519 seeds of 32 identical bytes (box1=1, box2=2, browser=3, stranger=4). `message` is the hex of devAckMessage(valid[0]).",
+ "acct": "acct-vectors-1",
+ "seeds": {
+ "box1": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
+ "box2": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=",
+ "browser": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "stranger": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ="
+ },
+ "pubs": {
+ "box1": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "box2": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "browser": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "stranger": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw="
+ },
+ "log": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 1,
+ "prev": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "at": 1000,
+ "op": "add",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "kind": "machine",
+ "machineId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "label": "box1",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "PQ79548gYy1fR00xYYrAqGYQer//uS3fGo1Xwwih7v6Jpw8lLHsM/plOYoenu8qjIWhPTSPlVSghlAt9C6MMCA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 2,
+ "prev": "Yo5gmHPDzOXL7LVbIkPSvoq4QoU4Nid/y+QxS7hZfuU=",
+ "at": 2000,
+ "op": "add",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "sig": "bHi9oSluvJ/RKgTw7RZrPaplcR45FGkVMmnOjm4dQnTzchKsMN6D6WKTNphHLjthUYhcznmjIJDLjplJ5TKsAg=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 3,
+ "prev": "Fs58Qy1DxTZ4qwRNQ8DTMtegmWDdiFYrAGzyalsc2SU=",
+ "at": 3000,
+ "op": "add",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "kind": "viewer",
+ "machineId": "",
+ "label": "browser",
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "sig": "vYm6LtYV1vK3yQR7Sp1/EPFoiFTOyM+7zhsnDUCXZUDeYJ1e9SL7m3xjEGdgo3x9Fd6DPwM51bkDwz9JstSpCQ=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "seq": 4,
+ "prev": "vMPGnQgYDO21pqy7wyaTJJGLaHpCdXDVAIkJrfJ7KUA=",
+ "at": 4000,
+ "op": "remove",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "kind": "machine",
+ "machineId": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "label": "box2",
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "sig": "gYDuihZziynx5hm1/FB2kZUKs+qZzVT1CZ4MbtjCSdKJEYM/736O4oKgFCnzg6RdHlGLcqUTRhkq3xZ3sqxuCA=="
+ }
+ ],
+ "message": "000000116861726e6573732d64657661636b2d763100000001310000000e616363742d766563746f72732d3100000020ed4928c628d1c2c6eae90338905995612959273a5c63f93636c14614ac8737d10000000133000000208a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c0000000435303030",
+ "valid": [
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "addSeq": 1,
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "at": 6000,
+ "sig": "Tvs71LrL6KUWDTzt8vqopLsIubbiEF+Q+wHMjPNappC+jCvHUXvOuUwnPHAIovDQGhCnOybac7StvvHFm0k1Bg=="
+ }
+ ],
+ "invalid": [
+ {
+ "name": "tampered time",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5001,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "signed under the device log tag",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "UiDLPvPt03A2Am5iDEakR3ilJc/OC1cfF2jhL7n3a+4UJN+pFFENwJPRTWodgahPRyw9SeyB0LOue6L4FzFQDw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "signed by another key than the signer",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "eqjcnHjAWOjrRa1aGALmlEzLhVZR1QkzxNsCxV+l/8/wlbK+NoHtTnR/+tlhxXmhCMdrTVuZSS4Q0HZESphFDw=="
+ },
+ "code": "BAD_SIGNATURE"
+ },
+ {
+ "name": "a key acknowledging itself",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "at": 5000,
+ "sig": "Cmg55AVm78H0Uvm25ugS1dX8QncK0jVBztdkmP2mMfY/2Ze+NaBSWCkX35MXiAO5JjdGwT7oNIdjN0egnm26BA=="
+ },
+ "code": "SELF_ACK"
+ },
+ {
+ "name": "signer not in the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "at": 5000,
+ "sig": "MGKqHpl4Oe701BsU7aWlmsgOUDnJ7WqOQjbWmBvGiPqM26/5MPuT8fHqHTgMqfbzC2U0K5YBKlKqbK1hwjl1Bw=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "signer removed from the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "at": 5000,
+ "sig": "y2HnM3LiMr69YaXjuNNsWNE0iLwQ3ZfzFzyLYck9SPbOa6Orz3lPI/32MzN0UCC4Ng/EQySy5XYFZAeLbQf0AA=="
+ },
+ "code": "SIGNER_NOT_ACTIVE"
+ },
+ {
+ "name": "wrong add entry",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 2,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "3dCkpuz6Tu5XEmvFIGnFQaiLin+Ninldkrmvp6K/a9g1EqEJ4uTds8dMdtqZKjsAIZpMEKKQUGbrL3wWeBOBCg=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "key removed from the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=",
+ "addSeq": 2,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "/GLyfKMRBF4JXwbg07KnkIB1wHMnZHkwIs4+utnxwJrobNkI9kaf0GdcBewxkt9F0MJ5MvWqWpwuQGraVpo9BA=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "key never in the log",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "U+ud4hDLUP1a4uAJY8+oPqBCho6vndu3AflTI7NhfUYcIukAH65jtjM3WArUDhO3iM8+GG9XYvBz66o+Pf8kDw=="
+ },
+ "code": "NOT_ADDED_THERE"
+ },
+ {
+ "name": "another account",
+ "ack": {
+ "v": 1,
+ "acct": "acct-other",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "cTBr1vv9/MOr3txBo0ZoPG7RK+YvqsxfNGyCG1bv5djsBaIAOHh9JeW0PEse15pstinySS5fZfcscgMhmbJEBg=="
+ },
+ "code": "WRONG_ACCOUNT"
+ },
+ {
+ "name": "unknown version",
+ "ack": {
+ "v": 2,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "add entry zero",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=",
+ "addSeq": 0,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "848QPR9kk82i9U1SGs7xcG7cZDAq8M6a7erc9FFGQk9QQui8X/HoCMzdmydlVxy4jvGHvNGepQ41htILwCvvDw=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "key of the wrong length",
+ "ack": {
+ "v": 1,
+ "acct": "acct-vectors-1",
+ "pub": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
+ "addSeq": 3,
+ "signer": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
+ "at": 5000,
+ "sig": "wqSGD3AQuoRHxghh+SnjOdwjvZvSlKGINPw/Z+mWfuA6TQLK3PwR49Qn6X9KxFAY+iCBzs7TviQeZpxIn5k4DA=="
+ },
+ "code": "BAD_ACK"
+ },
+ {
+ "name": "not an object",
+ "ack": "ack",
+ "code": "BAD_ACK"
+ }
+ ]
+}
diff --git a/mobile/test/viewer/device_ack_test.dart b/mobile/test/viewer/device_ack_test.dart
new file mode 100644
index 000000000..5b221e846
--- /dev/null
+++ b/mobile/test/viewer/device_ack_test.dart
@@ -0,0 +1,63 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/e2ee/bytes.dart';
+import 'package:harness_mobile/e2ee/keys.dart';
+import 'package:harness_mobile/viewer/device_ack.dart';
+import 'package:harness_mobile/viewer/device_log.dart';
+
+/// The Dart port of the device acknowledgement, held to the fixture every implementation shares
+/// (cli/scripts/gen-devack-vectors.ts).
+void main() {
+ final vectors = jsonDecode(File('test/viewer/deviceAck.vectors.json').readAsStringSync()) as Map<String, dynamic>;
+ final acct = vectors['acct'] as String;
+ final seeds = (vectors['seeds'] as Map).cast<String, String>();
+ final pubs = (vectors['pubs'] as Map).cast<String, String>();
+ final valid = (vectors['valid'] as List).cast<Map<String, dynamic>>();
+ Future<DevLogState> state() async =>
+ (await applyDevLogEntries(DevLogState.empty(acct), (vectors['log'] as List).cast<Object?>())).state;
+
+ test('encodes the first acknowledgement to the fixture bytes', () {
+ expect(hexOf(devAckMessage(DevAck.parse(valid.first)!)), vectors['message']);
+ });
+
+ test('re-signs every valid acknowledgement to the same signature, and accepts it', () async {
+ final byPub = {for (final n in seeds.keys) pubs[n]!: seeds[n]!};
+ final s = await state();
+ for (final raw in valid) {
+ final a = DevAck.parse(raw)!;
+ final id = await E2eeIdentity.fromSeed(b64d(byPub[a.signer]!));
+ expect(b64e(id.pub), a.signer);
+ expect((await signDevAck(a.withSig(''), id)).sig, a.sig);
+ final checked = await checkDevAck(s, raw);
+ expect(checked.code, isNull);
+ expect(checked.ack?.toJson(), raw);
+ }
+ });
+
+ for (final c in (vectors['invalid'] as List).cast<Map<String, dynamic>>()) {
+ test('refuses: ${c['name']} (${c['code']})', () async {
+ final checked = await checkDevAck(await state(), c['ack']);
+ expect(checked.ack, isNull);
+ expect(checked.code, c['code']);
+ });
+ }
+
+ test('refuses each field out of bounds', () {
+ final good = valid.first;
+ for (final bad in <Object?>[
+ null,
+ {...good, 'acct': ''},
+ {...good, 'acct': 'x' * 129},
+ {...good, 'signer': 'not base64!'},
+ {...good, 'pub': 'A' * 200},
+ {...good, 'addSeq': 1.5},
+ {...good, 'addSeq': '3'},
+ {...good, 'at': 0},
+ ]) {
+ expect(DevAck.parse(bad), isNull, reason: '$bad');
+ }
+ expect(DevAck.parse({...good, 'extra': 1})?.toJson(), good);
+ });
+}
diff --git a/mobile/test/viewer/device_log_acks_test.dart b/mobile/test/viewer/device_log_acks_test.dart
new file mode 100644
index 000000000..c11152325
--- /dev/null
+++ b/mobile/test/viewer/device_log_acks_test.dart
@@ -0,0 +1,370 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/local_key_value_store.dart';
+import 'package:harness_mobile/e2ee/bytes.dart';
+import 'package:harness_mobile/e2ee/keys.dart';
+import 'package:harness_mobile/viewer/device_ack.dart';
+import 'package:harness_mobile/viewer/device_log.dart';
+import 'package:harness_mobile/viewer/device_log_sync.dart';
+import 'package:harness_mobile/viewer/group_sync.dart';
+import 'package:harness_mobile/viewer/viewer_key_store.dart';
+
+/// "It's mine", once for the account (`lib/viewer/device_ack.dart`), as this app's copy of the device
+/// key log takes it: an acknowledgement another trusted device signed takes a new key off the list here;
+/// one this app is asked to share is signed and handed to the backend. Mirrors the CLI's
+/// deviceLogSyncer.spec.ts ("It's mine", once for the account).
+
+class _Memory implements LocalKeyValueStore {
+ final values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+const _acct = 'acct-1';
+final _mid2 = 'b' * 32;
+
+/// The backend: keeps the log honestly, and serves whatever acknowledgements it holds, checked or not.
+class _Backend {
+ DevLogState state = DevLogState.empty(_acct);
+ final entries = <DevLogEntry>[];
+ final acks = <Object?>[];
+ final askedAcks = <int>[];
+ final posted = <DevAck>[];
+
+ /// False: a backend from before acknowledgements (404 on both routes).
+ bool ackRoute = true;
+ bool ackReadThrows = false;
+
+ Future<void> add(E2eeIdentity who, String kind, String machineId, String label) async {
+ final pub = b64e(who.pub);
+ await _push(await signDevLogEntry(
+ nextDevLogEntry(state, op: 'add', pub: pub, kind: kind, machineId: machineId, label: label, signer: pub, at: 1000),
+ who,
+ ));
+ }
+
+ Future<void> removeBy(String target, E2eeIdentity by) async {
+ final t = state.active[target]!;
+ await _push(await signDevLogEntry(
+ nextDevLogEntry(state, op: 'remove', pub: t.pub, kind: t.kind, machineId: t.machineId, label: t.label, signer: b64e(by.pub), at: 2000),
+ by,
+ ));
+ }
+
+ Future<void> _push(DevLogEntry e) async {
+ state = (await applyDevLogEntries(state, [e.toJson()])).state;
+ entries.add(e);
+ }
+
+ Future<DeviceLogFetched?> fetch(int since) async =>
+ (acct: _acct, head: state.head, entries: [for (final e in entries) if (e.seq > since) e.toJson()]);
+
+ Future<DeviceLogAppendAnswer?> append(DevLogEntry entry) async {
+ if (entry.seq != state.head.seq + 1 || entry.prev != state.head.hash) return (head: state.head, error: 'STALE_HEAD');
+ await _push(entry);
+ return (head: state.head, error: null);
+ }
+
+ Future<List<Object?>?> fetchAcks(int since) async {
+ askedAcks.add(since);
+ if (ackReadThrows) throw StateError('down');
+ if (!ackRoute) return null;
+ return [...acks];
+ }
+
+ Future<bool> postAck(DevAck ack) async {
+ if (!ackRoute) return false;
+ posted.add(ack);
+ acks.add(ack.toJson());
+ return true;
+ }
+
+ /// An acknowledgement of [of] by [by], for the entry that added it unless [addSeq] says otherwise.
+ Future<Map<String, Object?>> ack(E2eeIdentity by, String of, {int? addSeq, String acct = _acct}) async =>
+ (await signDevAck(
+ DevAck(v: 1, acct: acct, pub: of, addSeq: addSeq ?? state.active[of]?.seq ?? 1, signer: b64e(by.pub), at: 7000),
+ by,
+ )).toJson();
+}
+
+void main() {
+ late _Backend backend;
+ late ViewerKeyStore keys;
+ late List<DevLogMember> announced;
+ late int changed;
+ late E2eeIdentity box2, phone, later;
+
+ ViewerDeviceLog makeLog({bool acks = true}) => ViewerDeviceLog(
+ keys: keys,
+ fetch: backend.fetch,
+ append: backend.append,
+ fetchAcks: acks ? backend.fetchAcks : null,
+ postAck: acks ? backend.postAck : null,
+ label: () => 'my-phone',
+ onAnnounce: announced.add,
+ onChanged: () => changed++,
+ now: () => 5000,
+ sleep: (_) async {},
+ );
+
+ Future<Map<String, Object?>> file() async => ((await keys.deviceLog()) as Map).cast<String, Object?>();
+ Future<String> self() async => b64e((await keys.identity()).pub);
+ String pubOf(E2eeIdentity id) => b64e(id.pub);
+
+ setUp(() async {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ announced = [];
+ changed = 0;
+ box2 = await E2eeIdentity.fromSeed(List.filled(32, 2));
+ phone = await E2eeIdentity.fromSeed(List.filled(32, 3));
+ later = await E2eeIdentity.fromSeed(List.filled(32, 5));
+ });
+
+ /// box2 was on the account before this app joined (never new here); the phone joined after (new).
+ Future<ViewerDeviceLog> joined({bool acks = true}) async {
+ final log = makeLog(acks: acks);
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(phone, 'viewer', '', 'phone');
+ await log.refresh();
+ expect((await log.list()).pending, [pubOf(phone)]);
+ announced.clear();
+ changed = 0;
+ backend.askedAcks.clear();
+ return log;
+ }
+
+ test('a trusted older device\'s "It\'s mine" takes the new key off the list here, and says on which', () async {
+ final log = await joined();
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ final listing = await log.list();
+ expect(listing.pending, isEmpty);
+ final row = listing.members.firstWhere((r) => r.member.pub == pubOf(phone));
+ expect(row.pending, isFalse);
+ expect(row.confirmed?.toJson(), {'by': pubOf(box2), 'label': 'box2', 'at': 5000});
+ expect(listing.members.firstWhere((r) => r.member.pub == pubOf(box2)).confirmed, isNull);
+ expect(changed, greaterThan(0));
+ });
+
+ test('asks from just below the oldest key new here, and not at all while nothing is new', () async {
+ final log = await joined();
+ await log.refresh();
+ expect(backend.askedAcks, [backend.state.active[pubOf(phone)]!.seq - 1]);
+ await log.dismiss(pub: pubOf(phone));
+ backend.askedAcks.clear();
+ await log.refresh();
+ expect(backend.askedAcks, isEmpty);
+ });
+
+ test('a device confirmed while this app was closed is announced once, as every new key is, then taken off the list', () async {
+ final log = makeLog();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ await backend.add(phone, 'viewer', '', 'phone');
+ await backend.add(later, 'viewer', '', 'later');
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ // The one-time "New device" never waits on, or is skipped for, anyone's word.
+ expect(announced.map((m) => m.label), ['phone', 'later']);
+ expect((await log.list()).pending, [pubOf(later)]);
+ await log.refresh();
+ expect(announced, hasLength(2));
+ });
+
+ test('stays as before when the acknowledgements cannot be read, or the read fails', () async {
+ for (final fail in ['no route', 'throws']) {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ announced = [];
+ final log = makeLog();
+ await backend.add(box2, 'machine', _mid2, 'box2');
+ await log.register(freshSignIn: true);
+ if (fail == 'no route') {
+ backend.ackRoute = false;
+ } else {
+ backend.ackReadThrows = true;
+ }
+ await backend.add(phone, 'viewer', '', 'phone');
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect(announced.map((m) => m.label), ['phone'], reason: fail);
+ expect((await log.list()).pending, [pubOf(phone)], reason: fail);
+ }
+ });
+
+ group('what is ignored', () {
+ test('a key vouching for itself, a bad signature, the wrong entry, another account, this app\'s own', () async {
+ final log = await joined();
+ final good = await backend.ack(box2, pubOf(phone));
+ backend.acks.addAll([
+ await backend.ack(phone, pubOf(phone)),
+ {...good, 'at': 7001},
+ await backend.ack(box2, pubOf(phone), addSeq: backend.state.active[pubOf(phone)]!.seq - 1),
+ await backend.ack(box2, pubOf(phone), acct: 'acct-2'),
+ (await signDevAck(
+ DevAck(v: 1, acct: _acct, pub: pubOf(phone), addSeq: backend.state.active[pubOf(phone)]!.seq, signer: await self(), at: 7000),
+ await keys.identity(),
+ )).toJson(),
+ {'junk': true},
+ ]);
+ await log.refresh();
+ expect((await log.list()).pending, [pubOf(phone)]);
+ expect((await file())['confirmed'], isNull);
+ expect(changed, 0);
+ });
+
+ test('a signer that is itself new here: two new devices must not vouch for each other', () async {
+ final log = await joined();
+ await backend.add(later, 'viewer', '', 'later');
+ await log.refresh();
+ backend.acks.addAll([await backend.ack(later, pubOf(phone)), await backend.ack(phone, pubOf(later))]);
+ await log.refresh();
+ expect((await log.list()).pending, [pubOf(phone), pubOf(later)]);
+ });
+
+ test('a signer that is gone (removed, or joined and left before anyone looked)', () async {
+ final log = await joined();
+ await backend.add(later, 'viewer', '', 'later');
+ await log.refresh();
+ final fromLater = await backend.ack(later, pubOf(phone));
+ final fromBox2 = await backend.ack(box2, pubOf(phone));
+ await backend.removeBy(pubOf(later), later);
+ await backend.removeBy(pubOf(box2), box2);
+ backend.acks.addAll([fromLater, fromBox2]);
+ await log.refresh();
+ expect((await log.list()).departed.map((d) => d.pub), [pubOf(later)]);
+ expect((await log.list()).pending, [pubOf(phone)]);
+ });
+
+ test('a signer suspended here, or tombstoned in the trust group here', () async {
+ for (final how in ['suspended', 'tombstoned']) {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final log = await joined();
+ if (how == 'suspended') {
+ await keys.writeDeviceLog({...await file(), 'suspended': [pubOf(box2)]});
+ } else {
+ await keys.writeGroupRoster(GroupRoster(const [], [GroupTombstone(pubOf(box2), 1000)]).toJson());
+ }
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect((await log.list()).pending, [pubOf(phone)], reason: how);
+ }
+ });
+
+ test('never lifts a suspension: a key a fork suspended here stays new and suspended', () async {
+ final log = await joined();
+ await keys.writeDeviceLog({...await file(), 'suspended': [pubOf(phone)]});
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect(backend.askedAcks, isEmpty);
+ final listing = await log.list();
+ expect(listing.pending, [pubOf(phone)]);
+ expect(listing.suspended, [pubOf(phone)]);
+ });
+
+ test('nothing at all while the log is frozen here', () async {
+ final log = await joined();
+ await keys.writeDeviceLog({
+ ...await file(),
+ 'frozen': {'reason': 'fork', 'at': 1, 'lastGoodHead': backend.state.head.toJson()},
+ });
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect(backend.askedAcks, isEmpty);
+ expect((await log.list()).pending, [pubOf(phone)]);
+ });
+ });
+
+ test('the mark goes with the key: a confirmed key removed later leaves none behind, and is not departed', () async {
+ final log = await joined();
+ backend.acks.add(await backend.ack(box2, pubOf(phone)));
+ await log.refresh();
+ expect((await file())['confirmed'], isA<Map>());
+ await backend.removeBy(pubOf(phone), box2);
+ await log.refresh();
+ expect((await file())['confirmed'], isNull);
+ expect((await log.list()).departed, isEmpty);
+ });
+
+ group('"It\'s mine" here is shared', () {
+ test('for the one device the person pressed it for, signed by this app for the entry that added it', () async {
+ for (final one in [true, false]) {
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final log = await joined();
+ final shared = one
+ ? await log.dismiss(pub: pubOf(phone), confirm: true)
+ : await log.dismiss(pubs: [pubOf(phone)], confirm: true);
+ expect(shared, isTrue);
+ expect((await log.list()).pending, isEmpty);
+ expect(backend.posted, hasLength(1));
+ final ack = backend.posted.single;
+ expect(ack.signer, await self());
+ expect(ack.pub, pubOf(phone));
+ expect(ack.addSeq, backend.state.active[pubOf(phone)]!.seq);
+ // What every other device checks it against: the same log.
+ expect((await checkDevAck(backend.state, ack.toJson())).code, isNull);
+ }
+ });
+
+ test('never for a list looked at, every device at once, or without "It\'s mine"', () async {
+ final log = await joined();
+ await backend.add(later, 'viewer', '', 'later');
+ await log.refresh();
+ expect(await log.dismiss(pubs: [pubOf(phone), pubOf(later)], confirm: true), isFalse);
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final again = await joined();
+ expect(await again.dismiss(pub: pubOf(phone)), isFalse);
+ expect(await again.dismiss(confirm: true), isFalse);
+ expect(backend.posted, isEmpty);
+ });
+
+ test('never for a key that was not new here, or this app\'s own', () async {
+ final log = await joined();
+ expect(await log.dismiss(pub: pubOf(box2), confirm: true), isFalse);
+ expect(await log.dismiss(pub: await self(), confirm: true), isFalse);
+ await log.dismiss(pub: pubOf(phone));
+ expect(await log.dismiss(pub: pubOf(phone), confirm: true), isFalse);
+ expect(backend.posted, isEmpty);
+ });
+
+ test('for a suspended key only when "It\'s mine" lifted the suspension here', () async {
+ final log = await joined();
+ await keys.writeDeviceLog({...await file(), 'suspended': [pubOf(phone)]});
+ expect(await log.dismiss(pubs: [pubOf(phone)], confirm: true), isFalse);
+ expect((await log.list()).suspended, [pubOf(phone)]);
+ expect(await log.dismiss(pub: pubOf(phone), confirm: true), isTrue);
+ expect((await log.list()).suspended, isEmpty);
+ });
+
+ test('not from a frozen log — the key is marked seen here all the same', () async {
+ final log = await joined();
+ await keys.writeDeviceLog({
+ ...await file(),
+ 'frozen': {'reason': 'fork', 'at': 1, 'lastGoodHead': backend.state.head.toJson()},
+ });
+ expect(await log.dismiss(pub: pubOf(phone), confirm: true), isFalse);
+ expect((await log.list()).pending, isEmpty);
+ expect(backend.posted, isEmpty);
+ });
+
+ test('a backend that does not take it, or none to take it, leaves the dismissal here', () async {
+ final log = await joined();
+ backend.ackRoute = false;
+ expect(await log.dismiss(pub: pubOf(phone), confirm: true), isFalse);
+ expect((await log.list()).pending, isEmpty);
+ backend = _Backend();
+ keys = ViewerKeyStore(storage: _Memory());
+ final alone = await joined(acks: false);
+ expect(await alone.dismiss(pub: pubOf(phone), confirm: true), isFalse);
+ expect((await alone.list()).pending, isEmpty);
+ });
+ });
+}
diff --git a/mobile/test/viewer_app_fixture.dart b/mobile/test/viewer_app_fixture.dart
index 70bd3e094..e896140f6 100644
--- a/mobile/test/viewer_app_fixture.dart
+++ b/mobile/test/viewer_app_fixture.dart
@@ -19,6 +19,7 @@ import 'package:harness_mobile/state/desk_sync.dart';
import 'package:harness_mobile/state/pane_layout_store.dart';
import 'package:harness_mobile/terminal/terminal_binary.dart';
import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:harness_mobile/viewer/device_ack.dart';
import 'package:harness_mobile/viewer/direct_auth.dart';
import 'package:harness_mobile/viewer/direct_auth_api.dart';
import 'package:harness_mobile/viewer/direct_link.dart';
@@ -143,6 +144,13 @@ class FakeApi extends ApiClient {
return onMachines();
}
+ // No acknowledgements ("It's mine" said on another device) unless a test serves some: never the network.
+ @override
+ Future<List<Object?>?> deviceAcks(int since) async => null;
+
+ @override
+ Future<bool> postDeviceAck(DevAck ack) async => false;
+
/// Answers `/api/auth/me` in place of [profile] when set — held open, or
/// throwing.
Future<Map<String, dynamic>?> Function()? onProfile;