diff --git a/CLAUDE.md b/CLAUDE.md index 6ef94c2a..8b916c1a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1048,7 +1048,7 @@ without checking it is the request that was built (`roomsKeysAct` does). ## A portal page uses rooms through the wallet's own methods (P7b) `window.vtaWallet.rooms.{list, choose, forget, info, browse, read, conversation, -putNote, putMessage, getFile, putFile}` is how a community's member portal shows a member their rooms +putNote, putMessage, react, unreact, watch, getFile, putFile}` is how a community's member portal shows a member their rooms (VTI `data-rooms-files.md` §8.5). It does **not** loosen "a page is not a member": `requestTask` and `signTrustTask` still refuse the whole `rooms/` family. The methods fix the verb, run the flow in the extension, and return @@ -1107,6 +1107,36 @@ wallet's window like a note, worded as a message. Keep `putNote`'s title required: a note and a message are different records, and a page choosing between them says which. +**A page replies and reacts through the wallet, and only where the room takes +it.** `putMessage({ replyTo })` writes `inReplyTo`; `react` writes a record of +kind `reaction` (the value as `body`, naming the record — exactly what +`assembleRoomRecords` counts); `unreact` writes an empty version over each of +the member's own live reactions with that value on that record +(`ownReactions`), which only their author may. Before the member is asked, the +background reads the room's profile as the member (`recordMembers`) and +refuses with `recordMembersNotListed` where it does not list what the write +needs — a reply is never sent without `inReplyTo`, a reaction never as a +message. The confirm window shows the record answered or reacted to **as the +wallet read it** (`rooms/keys/read`, `glimpseOf`), never anything the page +said about it. Each reaction is confirmed like any write: no "remember". + +**A page learns a shared room moved over a port, never a broadcast.** +`rooms.watch` opens one `ROOM_WATCH_PAGE_PORT` per watch (the content script +relays `roomWatch` frames as it relays `roomFile` ones). The background checks +the port's browser-attested origin and the share exactly as for a call, holds +the watch in its own `RoomWatcher` (one per background, so two tabs share a +room's watch), arms it through the member's VTA (`rooms/keys/watch/0.1`, the +offscreen `watch` op) after each read the page reports, and passes the room's +`rooms/keys/changed` — taken only from the offscreen document — to the ports +that armed it, as `{ kind: "changed", latestVersion }` and nothing more, after +checking the share is still live. Closing the port (`stop`, the tab going) +releases it; the last release cancels it at the VTA. The page pings the port +every 20 s, which keeps the worker alive while it watches; a worker restart +closes the port, and the page watches again. **What breaks it:** sending a +room's signal through `RUNTIME_BROADCAST_EVENT` (it reaches every tab of every +origin); passing a signal for a watch no page armed, or after the share went; +re-arming on a signal rather than after the page's read. + **An open room's file carries its own key.** With no storage key to derive from, `putRoomFile` mints 32 random bytes for the file, seals the blob exactly as on a sealed tier, and writes `rooms/records/put/0.4` with the manifest — `fileKey` included — in diff --git a/docs/page-bridge-errors.md b/docs/page-bridge-errors.md index e33d1066..6bd4ecf5 100644 --- a/docs/page-bridge-errors.md +++ b/docs/page-bridge-errors.md @@ -86,6 +86,7 @@ source; a test fails if this table and that list differ. | `notShared` | A room the page asked about is not shared with it, or its share ran out: ask the member to share it again (`rooms.choose`). | | `offerNotListed` | Rooms: the community lists no such offer to the member now. | | `offerInProgress` | Rooms: this offer is being accepted already, from another surface. | +| `recordMembersNotListed` | Rooms: the room's profile does not list the record members this write needs — `inReplyTo` for a reply, `kind` and `inReplyTo` for a reaction — so nothing was written. Someone holding `curate` or `admin` in the room turns them on. Offer the plain write (a message without the reply) instead. | | `membershipNotHeld` | Elections: the member holds no membership credential issued by the party the election is put to, so they are not a member of that party here. | | `credentialNotHeld` | Directory: the member's wallet holds no credential the fields can be filled from. | | `disclosureExceeded` | Directory: the credential would disclose more than the member agreed to in the wallet's window; nothing was presented. | diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index 23332cf4..a8c7c7d6 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -15,6 +15,17 @@ For history before this file, see `git log` on `packages/core`. room's profile lists them (`MESSAGE_KIND`). A room listing neither takes it as an untitled record, which readers show as a message. Sealed on `attributed` / `private`, in the clear on `open`; create-only. +- **Replies and reactions, written as the member.** `writeMessageAsMember` + takes `replyTo` (written as `inReplyTo`); `writeReactionAsMember` writes a + record of kind `reaction` (`REACTION_KIND`) — the value as its `body`, naming + the record it reacts to — and `withdrawReactionAsMember` takes one back with + an empty version of the member's own record, over the version read. + `ownReactions` finds the member's live reactions with a value on a record, + by the reading rules. A room whose profile does not list what a write needs + (`inReplyTo`; `kind` and `inReplyTo`) refuses it before anything is sealed or + sent: `RecordWriteRefused` with `code: "recordMembersNotListed"` + (`recordMembersRefusal`). `UnsignedRecordBody` and `putCleartextAsMember` + carry `inReplyTo`. ### Changed diff --git a/packages/core/src/rooms/act.ts b/packages/core/src/rooms/act.ts index dea02a17..d1d898b1 100644 --- a/packages/core/src/rooms/act.ts +++ b/packages/core/src/rooms/act.ts @@ -43,6 +43,7 @@ import { memberNameRewriteDue, memberNameWriteRefusal, } from "./member-name.js"; +import { reactionValue } from "./record-view.js"; import { TYPE_URI as KEYS_ACT, @@ -71,6 +72,7 @@ import { TYPE_URI as RECORDS_PUT, RESPONSE_TYPE_URI as RECORDS_PUT_RESPONSE, type RoomsRecordsPutResponsePayload, + type RecordReference, } from "../specs/rooms/records/put/0.5/payload.js"; import { TYPE_URI as RECORDS_CURATE, @@ -329,6 +331,8 @@ export interface UnsignedRecordBody { writtenAt?: string; /** When the author edited it (`RecordEditedAt`). Written only where the room's profile lists `editedAt`. */ editedAt?: string; + /** The record this one answers or, on a reaction, responds to (`RecordReference`). Written only where the room's profile lists `inReplyTo`. */ + inReplyTo?: RecordReference; } /** Thrown when a record landed at a version it was not sealed for, every time. */ @@ -415,10 +419,11 @@ export async function putCleartextAsMember( body?: string; description?: string; tags?: string[]; - /** `kind`, `writtenAt` and `editedAt` (`rooms/records/put/0.5`): only where the room's profile lists them. */ + /** `kind`, `writtenAt`, `editedAt` and `inReplyTo` (`rooms/records/put/0.5`): only where the room's profile lists them. */ kind?: string; writtenAt?: string; editedAt?: string; + inReplyTo?: RecordReference; replaces?: number; file?: { manifest: Record; blobRef: string }; }, @@ -428,6 +433,7 @@ export async function putCleartextAsMember( if (params.title !== undefined) cleartext.title = params.title; if (params.writtenAt !== undefined) cleartext.writtenAt = params.writtenAt; if (params.editedAt !== undefined) cleartext.editedAt = params.editedAt; + if (params.inReplyTo !== undefined) cleartext.inReplyTo = { ...params.inReplyTo }; if (params.description !== undefined) cleartext.description = params.description; if (params.tags !== undefined) cleartext.tags = params.tags; const payload: Record = { @@ -503,6 +509,7 @@ function wireBody(body: UnsignedRecordBody & { version: number }): Record !(listed ?? []).includes(m)); + if (missing.length === 0) return undefined; + return new RecordWriteRefused( + `Not written: this room does not take ${what} — its profile does not list ${missing.join(" and ")} in its record members.`, + "recordMembersNotListed", + ); +} + /** A name record a member already holds in the room: the one a new name is written over. */ export interface HeldMemberName { author: string; @@ -605,14 +636,19 @@ export async function writeMemberNameAsMember( */ export async function writeMessageAsMember( room: PersonaRoom, - params: { body: string; now?: () => Date }, + params: { body: string; replyTo?: RecordReference; now?: () => Date }, ): Promise<{ principal: string; key: string; version: number }> { if (params.body.trim() === "") throw new RecordWriteRefused("Not written: a message needs some text."); const listed = (await roomRecordMembersAsMember(room)) ?? []; + if (params.replyTo !== undefined) { + const refused = recordMembersRefusal(listed, ["inReplyTo"], "replies"); + if (refused) throw refused; + } const now = (params.now ?? (() => new Date()))().toISOString().replace(/\.\d{3}Z$/, "Z"); const shape = { ...(listed.includes("kind") ? { kind: MESSAGE_KIND } : {}), ...(listed.includes("writtenAt") ? { writtenAt: now } : {}), + ...(params.replyTo !== undefined ? { inReplyTo: replyReference(params.replyTo) } : {}), }; const { principal, info } = await roomInfoAsMember(room); const key = opaqueRecordKey(); @@ -626,6 +662,94 @@ export async function writeMessageAsMember( /** `RecordKind` for a chat message. */ export const MESSAGE_KIND = "message"; +/** `RecordKind` for a reaction. */ +export const REACTION_KIND = "reaction"; + +/** A reference as written: the key, and the version only when one was given. */ +function replyReference(r: RecordReference): RecordReference { + return { key: r.key, ...(r.version !== undefined ? { version: r.version } : {}) }; +} + +/** + * React to a record, as the member: a new record of kind `reaction` whose + * `body` is the value and whose `inReplyTo` names the record (*Reactions*, + * `SealedRecordBody`) — the shape {@link assembleRoomRecords} counts, once per + * author, value and target. + * + * **Refused before anything is sent** unless the room's profile lists `kind` + * and `inReplyTo` (a reader that predates them would show the reaction as a + * message), and unless `value` is a reaction's value: not empty, no line break, + * at most 64 code points once normalised. `writtenAt` where the profile lists + * it. Sealed and signed by the VTA as the member on `attributed` and `private`, + * in the clear on `open`. Create-only. + */ +export async function writeReactionAsMember( + room: PersonaRoom, + params: { target: RecordReference; value: string; now?: () => Date }, +): Promise<{ principal: string; key: string; version: number }> { + const value = reactionValue(params.value); + if (value.kind === "empty") throw new RecordWriteRefused("Not written: a reaction needs a value."); + if (value.kind === "invalid") throw new RecordWriteRefused(`Not written: the reaction's ${value.reason.replace(/^its /, "")}.`); + const listed = await roomRecordMembersAsMember(room); + const refused = recordMembersRefusal(listed, ["kind", "inReplyTo"], "reactions"); + if (refused) throw refused; + const now = (params.now ?? (() => new Date()))().toISOString().replace(/\.\d{3}Z$/, "Z"); + const shape = { + kind: REACTION_KIND, + inReplyTo: replyReference(params.target), + ...(listed!.includes("writtenAt") ? { writtenAt: now } : {}), + }; + const { principal, info } = await roomInfoAsMember(room); + const key = opaqueRecordKey(); + const version = + info.visibility === "open" + ? await putCleartextAsMember(room, { key, body: params.value, ...shape }) + : await writeSealedAsMember(room, { roomId: room.roomId, key, author: principal, body: params.value, ...shape }); + return { principal, key, version }; +} + +/** The member's own reaction record, as the reading of the room found it: the one a withdrawal is written over. */ +export interface HeldReaction { + key: string; + version: number; + /** The record it reacts to: a withdrawal keeps it (*What a new version keeps*). */ + target: RecordReference; +} + +/** + * Withdraw the member's own reaction: a new version of the same record, still + * of kind `reaction` and naming the same record, with an empty `body` — which + * only the reaction's own author may write to withdraw it (*Withdrawing a + * reaction*). It `replaces` the version read, so a concurrent change wins and + * this writes nothing over it. `editedAt` where the profile lists it. + */ +export async function withdrawReactionAsMember( + room: PersonaRoom, + held: HeldReaction, + params: { now?: () => Date } = {}, +): Promise<{ principal: string; key: string; version: number }> { + const listed = await roomRecordMembersAsMember(room); + const refused = recordMembersRefusal(listed, ["kind", "inReplyTo"], "reactions"); + if (refused) throw refused; + const now = (params.now ?? (() => new Date()))().toISOString().replace(/\.\d{3}Z$/, "Z"); + const shape = { + kind: REACTION_KIND, + inReplyTo: replyReference(held.target), + ...(listed!.includes("editedAt") ? { editedAt: now } : {}), + }; + const { principal, info } = await roomInfoAsMember(room); + const version = + info.visibility === "open" + ? await putCleartextAsMember(room, { key: held.key, body: "", ...shape, replaces: held.version }) + : await writeSealedAsMember( + room, + { roomId: room.roomId, key: held.key, author: principal, body: "", ...shape }, + undefined, + { replaces: held.version }, + ); + return { principal, key: held.key, version }; +} + /** The member's own name record, as rule 2 gives it from the records its client holds: what a rewrite near the head writes again. */ export interface OwnMemberName { key: string; diff --git a/packages/core/src/rooms/record-view.ts b/packages/core/src/rooms/record-view.ts index 55bb601e..e0ae2ce0 100644 --- a/packages/core/src/rooms/record-view.ts +++ b/packages/core/src/rooms/record-view.ts @@ -660,3 +660,37 @@ export function assembleRoomRecords(inputs: readonly RecordInput[], opts: { now: nameRecords, }; } + +/** One of the member's own reactions, as the room's records show it now. */ +export interface OwnReaction { + key: string; + version: number; + target: RecordReference; +} + +/** + * The member's own reactions with `value` on the record at `target`, as the + * records read now show them: each a record of kind `reaction` whose current + * version is readable, is by `author`, names `target` and carries `value` once + * normalised (*A reaction's value*). What a withdrawal is written over — every + * one of them, since each counts until it is withdrawn. An empty (withdrawn) + * one is not among them. + */ +export function ownReactions( + inputs: readonly RecordInput[], + match: { author: string; target: string; value: string }, +): OwnReaction[] { + const wanted = reactionValue(match.value); + if (wanted.kind !== "value") return []; + const out: OwnReaction[] = []; + for (const input of inputs) { + if (input.reading.state !== "read") continue; + const c = input.reading.content; + if (c.kind !== "reaction" || c.author !== match.author || c.inReplyTo?.key !== match.target) continue; + const v = reactionValue(c.body); + if (v.kind === "value" && v.normalised === wanted.normalised) { + out.push({ key: input.key, version: input.version, target: { ...c.inReplyTo } }); + } + } + return out; +} diff --git a/packages/core/tests/rooms.reply-react.mjs b/packages/core/tests/rooms.reply-react.mjs new file mode 100644 index 00000000..d742f2f6 --- /dev/null +++ b/packages/core/tests/rooms.reply-react.mjs @@ -0,0 +1,227 @@ +// Replies and reactions, written as the member (`writeMessageAsMember`'s +// `replyTo`, `writeReactionAsMember`, `withdrawReactionAsMember`), and the +// member's own reactions as the reading rules find them (`ownReactions`). +// +// The writer's rule throughout: a member a room's profile does not list is +// never written (`SealedRecordBody`, *When a writer may use these members*) — +// a reply or a reaction is refused before anything is sealed or sent, never +// written without what makes it one. + +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { base64url } from "@openvtc/vti-didcomm-js"; + +import { + assembleRoomRecords, + ownReactions, + recordMembersRefusal, + RecordWriteRefused, + withdrawReactionAsMember, + writeMessageAsMember, + writeReactionAsMember, +} from "../dist/rooms/index.js"; + +const ALICE = "did:webvh:QmAlice:people.example:alice-room"; +const BOB = "did:webvh:QmBob:people.example:bob-room"; +const WALLET = { did: "did:key:zWallet" }; +const VTA = "did:webvh:QmAgent:agent.example"; +const HOST = "did:webvh:QmHost:host.example"; +const ROOM = "did:webvh:QmRoom:rooms.example"; +const NOW = () => new Date("2026-11-25T12:00:00.456Z"); + +/** A room whose profile lists `recordMembers`, on a tier, with a VTA acting as ALICE. */ +function room({ recordMembers, visibility = "attributed", head = 6 } = {}) { + const vtaAsked = []; + const sent = []; + const sealed = []; + let sealedFor = 0; + const agent = { + async send(envelope) { + vtaAsked.push(envelope.type); + if (envelope.type.includes("rooms/keys/profile/read/")) { + return recordMembers === undefined + ? { roomId: ROOM, status: "absent" } + : { roomId: ROOM, status: "found", profile: { name: "R", recordMembers } }; + } + if (envelope.type.includes("rooms/keys/seal/")) { + sealedFor = envelope.payload.version; + sealed.push(JSON.parse(new TextDecoder().decode(base64url.decode(envelope.payload.plaintext)))); + return { sealed: { ciphertext: "c", nonce: "n", epoch: 1 } }; + } + const doc = structuredClone(envelope.payload.document); + doc.issuer = ALICE; + doc.proof = { type: "DataIntegrityProof" }; + return { principal: ALICE, document: doc }; + }, + }; + const host = { + async sendCompleted(doc) { + sent.push(doc); + if (doc.type.includes("rooms/info/")) return { roomId: ROOM, visibility }; + if (doc.type.includes("rooms/records/list/")) return { roomId: ROOM, records: [], headVersion: head }; + if (doc.type.includes("rooms/records/put/")) return { key: doc.payload.key, version: visibility === "open" ? head + 1 : sealedFor }; + throw new Error(`unexpected ${doc.type}`); + }, + }; + return { + vtaAsked, + sent, + sealed, + room: { roomId: ROOM, member: ALICE, holder: WALLET, vta: { did: VTA, sender: agent }, host: { did: HOST, sender: host } }, + }; +} +const puts = (sent) => sent.filter((d) => d.type.includes("rooms/records/put/")); +const nothingWritten = (r) => { + assert.deepEqual(puts(r.sent), [], "nothing reached the host"); + assert.ok(!r.vtaAsked.some((t) => t.includes("seal")), "nothing was sealed"); +}; + +// ── The gate ───────────────────────────────────────────────────────────────── + +test("recordMembersRefusal names what is missing, with the code a page reads", () => { + assert.equal(recordMembersRefusal(["kind", "inReplyTo"], ["kind", "inReplyTo"], "reactions"), undefined); + const e = recordMembersRefusal(["kind"], ["kind", "inReplyTo"], "reactions"); + assert.ok(e instanceof RecordWriteRefused); + assert.equal(e.code, "recordMembersNotListed"); + assert.match(e.message, /inReplyTo/); + assert.match(recordMembersRefusal(undefined, ["inReplyTo"], "replies").message, /replies/); +}); + +// ── A reply ────────────────────────────────────────────────────────────────── + +test("a reply carries inReplyTo — the key, and the version where given — beside kind and writtenAt", async () => { + const r = room({ recordMembers: ["kind", "inReplyTo", "writtenAt"] }); + await writeMessageAsMember(r.room, { body: "Yes", replyTo: { key: "m1", version: 3 }, now: NOW }); + const [body] = r.sealed; + assert.deepEqual(body.inReplyTo, { key: "m1", version: 3 }); + assert.equal(body.kind, "message"); + assert.equal(body.writtenAt, "2026-11-25T12:00:00Z"); + assert.equal(body.title, undefined); +}); + +test("a reply in a room that takes none is refused, and nothing is sealed or sent — never written without it", async () => { + for (const recordMembers of [undefined, ["kind", "writtenAt"]]) { + const r = room({ recordMembers }); + await assert.rejects( + writeMessageAsMember(r.room, { body: "Yes", replyTo: { key: "m1" } }), + (e) => e instanceof RecordWriteRefused && e.code === "recordMembersNotListed", + ); + nothingWritten(r); + } +}); + +test("a reply on an open room is inReplyTo in the clear", async () => { + const r = room({ recordMembers: ["inReplyTo"], visibility: "open" }); + await writeMessageAsMember(r.room, { body: "Yes", replyTo: { key: "m1" } }); + assert.deepEqual(puts(r.sent)[0].payload.cleartext, { body: "Yes", inReplyTo: { key: "m1" } }); + assert.deepEqual(r.sealed, []); +}); + +test("a message with no replyTo needs no inReplyTo, as before", async () => { + const r = room({ recordMembers: ["kind"] }); + await writeMessageAsMember(r.room, { body: "hi" }); + assert.equal(r.sealed[0].inReplyTo, undefined); +}); + +// ── A reaction ─────────────────────────────────────────────────────────────── + +test("a reaction is a record of kind reaction, the value as its body, naming the record; create-only", async () => { + const r = room({ recordMembers: ["kind", "inReplyTo", "writtenAt"] }); + const out = await writeReactionAsMember(r.room, { target: { key: "m1", version: 2 }, value: "👍", now: NOW }); + assert.equal(out.principal, ALICE); + const [body] = r.sealed; + assert.deepEqual(Object.keys(body).sort(), ["author", "body", "inReplyTo", "key", "kind", "roomId", "version", "writtenAt"]); + assert.equal(body.kind, "reaction"); + assert.equal(body.body, "👍"); + assert.deepEqual(body.inReplyTo, { key: "m1", version: 2 }); + assert.equal(puts(r.sent)[0].payload.expectedVersion, 0); + + // It is exactly what the reading rules count. + const view = assembleRoomRecords( + [ + { key: "m1", version: 2, status: "active", updatedAt: "2026-11-25T11:00:00Z", reading: { state: "read", content: { author: BOB, kind: "message", body: "hi", hasFile: false, bodyVersion: 2 } } }, + { key: body.key, version: 7, status: "active", updatedAt: "2026-11-25T12:00:00Z", reading: { state: "read", content: { author: ALICE, kind: "reaction", body: "👍", inReplyTo: { key: "m1", version: 2 }, hasFile: false, bodyVersion: 7 } } }, + ], + { now: Date.parse("2026-11-25T12:30:00Z") }, + ); + assert.deepEqual(view.records[0].reactions.map((x) => [x.value, x.count, x.authors]), [["👍", 1, [ALICE]]]); +}); + +test("a reaction in a room without kind and inReplyTo is refused before anything is sealed or sent", async () => { + for (const recordMembers of [undefined, ["kind"], ["inReplyTo"]]) { + const r = room({ recordMembers }); + await assert.rejects( + writeReactionAsMember(r.room, { target: { key: "m1" }, value: "👍" }), + (e) => e instanceof RecordWriteRefused && e.code === "recordMembersNotListed", + ); + nothingWritten(r); + } +}); + +test("a reaction's value is the reading rules' own: not empty, no line break, at most 64 characters", async () => { + for (const value of ["", " ", "a\nb", "x".repeat(65)]) { + const r = room({ recordMembers: ["kind", "inReplyTo"] }); + await assert.rejects(writeReactionAsMember(r.room, { target: { key: "m1" }, value }), RecordWriteRefused); + assert.deepEqual(r.vtaAsked, [], "refused before the profile is read"); + } +}); + +test("a reaction on an open room is in the clear", async () => { + const r = room({ recordMembers: ["kind", "inReplyTo"], visibility: "open" }); + await writeReactionAsMember(r.room, { target: { key: "m1" }, value: "❤️" }); + assert.deepEqual(puts(r.sent)[0].payload.cleartext, { body: "❤️", kind: "reaction", inReplyTo: { key: "m1" } }); +}); + +// ── Taking one back ────────────────────────────────────────────────────────── + +test("a withdrawal is a new version of the member's own reaction: empty body, same kind and target, over the version read", async () => { + const r = room({ recordMembers: ["kind", "inReplyTo", "editedAt"] }); + await withdrawReactionAsMember(r.room, { key: "rx", version: 4, target: { key: "m1" } }, { now: NOW }); + const [body] = r.sealed; + assert.equal(body.key, "rx"); + assert.equal(body.kind, "reaction"); + assert.equal(body.body, ""); + assert.deepEqual(body.inReplyTo, { key: "m1" }); + assert.equal(body.editedAt, "2026-11-25T12:00:00Z"); + assert.equal(puts(r.sent)[0].payload.expectedVersion, 4, "replaces exactly the version read"); +}); + +test("a withdrawal reads, by the reading rules, as no reaction", () => { + const msg = { key: "m1", version: 1, status: "active", updatedAt: "2026-11-25T11:00:00Z", reading: { state: "read", content: { author: BOB, kind: "message", body: "hi", hasFile: false, bodyVersion: 1 } } }; + const was = { author: ALICE, kind: "reaction", body: "👍", inReplyTo: { key: "m1" }, hasFile: false, bodyVersion: 2 }; + const now = { author: ALICE, kind: "reaction", body: "", inReplyTo: { key: "m1" }, hasFile: false, bodyVersion: 3 }; + const view = assembleRoomRecords( + [msg, { key: "rx", version: 3, status: "active", updatedAt: "2026-11-25T12:00:00Z", held: { version: 2, content: was }, reading: { state: "read", content: now } }], + { now: Date.parse("2026-11-25T12:30:00Z") }, + ); + assert.deepEqual(view.records[0].reactions, []); +}); + +// ── The member's own reactions ─────────────────────────────────────────────── + +test("ownReactions finds the member's live reactions with that value on that record — by its normalised value, nobody else's", () => { + const rx = (key, author, body, target = "m1", version = 2) => ({ + key, + version, + status: "active", + reading: { state: "read", content: { author, kind: "reaction", body, inReplyTo: { key: target }, hasFile: false, bodyVersion: version } }, + }); + const inputs = [ + rx("a", ALICE, "❤️"), + rx("b", ALICE, "❤"), // the same value without its variation selector + rx("c", BOB, "❤️"), + rx("d", ALICE, "👍"), + rx("e", ALICE, "❤️", "m2"), + rx("f", ALICE, ""), // withdrawn already + { key: "g", version: 1, status: "active", reading: { state: "refused", reason: "signature" } }, + ]; + assert.deepEqual( + ownReactions(inputs, { author: ALICE, target: "m1", value: "❤️" }).map((r) => [r.key, r.version, r.target.key]), + [ + ["a", 2, "m1"], + ["b", 2, "m1"], + ], + ); + assert.deepEqual(ownReactions(inputs, { author: ALICE, target: "m1", value: "" }), []); +}); diff --git a/packages/extension/src/background.ts b/packages/extension/src/background.ts index 53bb0cb1..758cff26 100644 --- a/packages/extension/src/background.ts +++ b/packages/extension/src/background.ts @@ -183,6 +183,9 @@ import { type RuntimeRoomOffersRequest, type RuntimeRoomOffersResponse, ROOM_FILES_PAGE_PORT, + ROOM_WATCH_PAGE_PORT, + RUNTIME_ROOMS_KEYS_CHANGED, + type RuntimeRoomsKeysChanged, OFFSCREEN_ROOMS_PAGE, type OffscreenRoomsPageResponse, type RuntimeRoomsPageRequest, @@ -1244,6 +1247,30 @@ chrome.runtime.onConnect.addListener((port) => { roomPageGates.servePort(port as unknown as PortLike, origin); }); +// One page's watch on one room (`rooms.watch`). The origin is the port's +// browser-attested one; a port from an extension page is not a page's and is refused. +chrome.runtime.onConnect.addListener((port) => { + if (port.name !== ROOM_WATCH_PAGE_PORT) return; + const origin = port.sender ? attestedOrigin(port.sender) : undefined; + if (!origin || !port.sender?.tab || isExtensionPageSender(port.sender)) { + port.disconnect(); + return; + } + roomPageGates.serveWatchPort(port as unknown as PortLike, origin); +}); + +// A watched room moved (`rooms/keys/changed/0.1`), as the offscreen document +// received it from the member's VTA. Taken only from the offscreen document +// itself — a content script carries this extension's id too — and passed on +// only to a page that armed that watch. Never answered. +chrome.runtime.onMessage.addListener((message, sender) => { + const m = message as Partial | undefined; + if (m?.type !== RUNTIME_ROOMS_KEYS_CHANGED || typeof m.vtaDid !== "string" || !m.signal) return false; + if (sender.tab !== undefined || sender.url !== chrome.runtime.getURL("offscreen.html")) return false; + roomPageGates.deliverRoomSignal(m.vtaDid, m.signal); + return false; +}); + chrome.runtime.onConnect.addListener((port) => { if (port.name !== CONSENT_KEEPALIVE_PORT) return; // A consent port opening means a request was just durably recorded; a diff --git a/packages/extension/src/bridge-protocol.ts b/packages/extension/src/bridge-protocol.ts index bfeeed44..1d57c839 100644 --- a/packages/extension/src/bridge-protocol.ts +++ b/packages/extension/src/bridge-protocol.ts @@ -2502,8 +2502,18 @@ export type RoomsPageOp = description?: string; tags?: string[]; } - /** A chat message: text and no title (`writeMessageAsMember`). Confirmed like a note. */ - | { op: "putMessage"; hostDid: string; roomId: string; body: string }; + /** A chat message: text and no title (`writeMessageAsMember`). Confirmed like a note. + * `replyTo` names the record it answers: written as `inReplyTo` only where the + * room's profile lists it, else refused (`recordMembersNotListed`) — never sent + * without it. The wallet shows the member what is being answered. */ + | { op: "putMessage"; hostDid: string; roomId: string; body: string; replyTo?: { key: string; version?: number } } + /** React to a record with `value` (an emoji, at most 64 code points): a record of + * kind `reaction` naming it (`writeReactionAsMember`). Confirmed in the wallet; + * refused (`recordMembersNotListed`) where the profile lists no `kind` and `inReplyTo`. */ + | { op: "react"; hostDid: string; roomId: string; key: string; version?: number; value: string } + /** Withdraw the member's own reaction `value` on a record (`withdrawReactionAsMember`). + * Confirmed in the wallet. Answers `{ withdrawn: 0 }` when they have none there. */ + | { op: "unreact"; hostDid: string; roomId: string; key: string; value: string }; export interface RuntimeRoomsPageRequest { type: typeof RUNTIME_ROOMS_PAGE; @@ -2704,6 +2714,33 @@ export interface PageConversationView { /** page ⇄ background: one file transfer, over a port the content script opens. */ export const ROOM_FILES_PAGE_PORT = "vta-wallet/room-files-page" as const; +/** + * page ⇄ background: one room's change signal, over a port the content script + * opens (`rooms.watch`). The background checks the port's browser-attested + * origin and the member's share, arms a watch on the room through the member's + * VTA (`rooms/keys/watch/0.1`), and relays the room's `rooms/keys/changed` + * signal — content-free: that the room moved, and to which version — until the + * port closes, when the watch is cancelled. + */ +export const ROOM_WATCH_PAGE_PORT = "vta-wallet/room-watch-page" as const; + +/** page → background. `watch` first, once; then `read` after each read of the room, and `ping` to keep the port. */ +export type RoomWatchPageMessage = + | { kind: "watch"; hostDid: string; roomId: string; sinceVersion?: number } + /** The page read the room to `version`: a watch that fired or lapsed is armed again from there. */ + | { kind: "read"; version?: number } + | { kind: "ping" }; + +/** Where a page's watch stands (`RoomWatchState`, by name only). */ +export type PageRoomWatchState = "arming" | "armed" | "fired" | "refused" | "unavailable" | "lapsed"; + +/** background → page. */ +export type RoomWatchPageEvent = + | { kind: "state"; state: PageRoomWatchState } + /** The room moved past what the page read: read it again, then say `read`. Nothing of what changed. */ + | { kind: "changed"; latestVersion: number } + | { kind: "failed"; error: string; code: PageErrorCode }; + /** page → background, once, as the port's first message. */ export type RoomFilesPageOpen = | { kind: "get"; hostDid: string; roomId: string; key: string } @@ -3664,7 +3701,35 @@ export type OffscreenRoomsPageOp = description?: string; tags?: string[]; } - | { op: "putMessage"; hostDid: string; roomId: string; member: string; body: string }; + | { + op: "putMessage"; + hostDid: string; + roomId: string; + member: string; + body: string; + replyTo?: { key: string; version?: number }; + } + /** The room's `recordMembers`, as its current profile lists them, read as the member. `[]`: none. */ + | { op: "recordMembers"; hostDid: string; roomId: string; member: string } + | { + op: "react"; + hostDid: string; + roomId: string; + member: string; + target: { key: string; version?: number }; + value: string; + } + /** Withdraw every reaction of the member's with `value` on `target`, as the room reads now. */ + | { op: "unreact"; hostDid: string; roomId: string; member: string; target: string; value: string } + /** Arm or cancel watches on rooms through the member's VTA (`rooms/keys/watch/0.1`): one request, one host, one member. */ + | { + op: "watch"; + hostDid: string; + member: string; + rooms: { roomId: string; sinceVersion?: number }[]; + leaseSeconds?: number; + cancel?: true; + }; export interface OffscreenRoomsPageRequest { target: typeof OFFSCREEN_TARGET; diff --git a/packages/extension/src/content.ts b/packages/extension/src/content.ts index dc0b973b..83601168 100644 --- a/packages/extension/src/content.ts +++ b/packages/extension/src/content.ts @@ -55,6 +55,8 @@ const RUNTIME_DIRECTORY_PAGE = "vta-wallet/directory-page"; const RUNTIME_GIT_PAGE = "vta-wallet/git-page"; const RUNTIME_ELECTIONS_PAGE = "vta-wallet/elections-page"; const ROOM_FILES_PAGE_PORT = "vta-wallet/room-files-page"; +/** `ROOM_WATCH_PAGE_PORT` in bridge-protocol.ts, inlined for the same reason. */ +const ROOM_WATCH_PAGE_PORT = "vta-wallet/room-watch-page"; // ─── 1. Inject the provider into the page world. ─── // The content script runs in an isolated world, so assigning @@ -117,6 +119,10 @@ window.addEventListener("message", (event: MessageEvent) => { relayRoomFile(req as unknown as RoomFileFrame); return; } + if ((req as unknown as { kind?: unknown }).kind === "roomWatch") { + relayRoomWatch(req as unknown as RoomFileFrame); + return; + } void (async () => { let response: ContentResponse; @@ -213,6 +219,45 @@ function relayRoomFile(frame: RoomFileFrame): void { port.postMessage(frame.msg); } +// ─── 2c. Room watches: one port per watch, page ⇄ background. ─── +// +// `window.vtaWallet.rooms.watch` (P7b). The page's frames carry a watch id and +// one message (`RoomWatchPageMessage`); each watch gets its own port to the +// background, which checks the page's portal and share on the port's +// browser-attested origin, never on a frame. What comes back — the watch's +// state, and that the room changed — is posted to the page as it arrives. +// Closing the port (the page's `stop`, or the tab going away) cancels the watch. +const roomWatchPorts = new Map(); + +function relayRoomWatch(frame: RoomFileFrame): void { + if (typeof frame.id !== "string" || !frame.msg || typeof frame.msg !== "object") return; + const back = (msg: unknown) => + window.postMessage({ source: CONTENT_SOURCE, kind: "roomWatch", id: frame.id, msg }, window.origin); + let port = roomWatchPorts.get(frame.id); + if (frame.msg.kind === "stop") { + port?.disconnect(); + roomWatchPorts.delete(frame.id); + return; + } + if (!port) { + try { + port = chrome.runtime.connect({ name: ROOM_WATCH_PAGE_PORT }); + } catch (e) { + back({ kind: "failed", error: e instanceof Error ? e.message : String(e), code: "walletUnavailable" }); + back({ kind: "closed" }); + return; + } + roomWatchPorts.set(frame.id, port); + port.onMessage.addListener((m: unknown) => back(m)); + port.onDisconnect.addListener(() => { + void chrome.runtime.lastError; + roomWatchPorts.delete(frame.id); + back({ kind: "closed" }); + }); + } + port.postMessage(frame.msg); +} + // ─── 3. Forward background broadcasts (wallet lifecycle events) into // the page world. ─── // Background fires these on unlock / lock / connection change. Pages diff --git a/packages/extension/src/page-error.ts b/packages/extension/src/page-error.ts index cd92b09d..0f4c2694 100644 --- a/packages/extension/src/page-error.ts +++ b/packages/extension/src/page-error.ts @@ -63,6 +63,11 @@ export const WALLET_ERROR_CODES = { offerNotListed: "The community lists no such room offer to the member.", /** Rooms: this offer is being accepted already, from another surface. */ offerInProgress: "The offer is being accepted already.", + /** Rooms: the room's profile does not list the record members this write + * needs — `inReplyTo` for a reply, `kind` and `inReplyTo` for a reaction — so + * nothing was written. Someone holding `curate` or `admin` in the room turns + * them on. Offer the plain write (a message without the reply) instead. */ + recordMembersNotListed: "The room does not take this kind of record yet.", /** The member holds no membership credential issued by the party an election * is put to, so they are not a member of that party here. */ membershipNotHeld: "The member holds no membership credential of that party.", diff --git a/packages/extension/src/provider.ts b/packages/extension/src/provider.ts index 6d131ccc..7618fce4 100644 --- a/packages/extension/src/provider.ts +++ b/packages/extension/src/provider.ts @@ -54,6 +54,8 @@ import type { PageConversationView, PageRecordView, RoomFilesPageMessage, + PageRoomWatchState, + RoomWatchPageEvent, } from "./bridge-protocol.js"; import type { PageOfferView } from "./room-offers-policy.js"; import type { PageErrorCode } from "./page-error.js"; @@ -372,8 +374,39 @@ export interface VtaWalletRooms { }): Promise<{ key: string; version: number }>; /** Write a chat message as the member — text, no title — after they confirm it. * It reads as a message in every reader (`kind: "message"` where the room - * takes it, else an untitled record). */ - putMessage(params: { hostDid: string; roomId: string; body: string }): Promise<{ key: string; version: number }>; + * takes it, else an untitled record). `replyTo` names the record it answers; + * the wallet shows the member what that is, and refuses with + * `recordMembersNotListed` — writing nothing — where the room takes no replies. */ + putMessage(params: { + hostDid: string; + roomId: string; + body: string; + replyTo?: { key: string; version?: number }; + }): Promise<{ key: string; version: number }>; + /** React to a record with `value` (one emoji or a short word: no line break, + * at most 64 characters), after the member confirms it. Refused with + * `recordMembersNotListed` where the room takes no reactions. */ + react(params: { hostDid: string; roomId: string; key: string; version?: number; value: string }): Promise<{ + key: string; + version: number; + }>; + /** Take back the member's own reaction `value` on a record, after they confirm + * it. `withdrawn` counts the reaction records taken back: 0 when they had none there. */ + unreact(params: { hostDid: string; roomId: string; key: string; value: string }): Promise<{ withdrawn: number }>; + /** + * Be told when a shared room changes, instead of reading it on a timer. The + * wallet asks the member's agent to watch the room, and `onEvent` hears: + * `changed` (the room moved past what was read — read it again, then call + * `read(version)`), `state` (where the watch stands: while it is `refused` or + * `unavailable`, fall back to reading on a timer), `failed` (with a + * `VtaWalletError`'s `code`: `notShared`, `originNotPermitted`, …) and + * `closed` (the watch ended: `stop`, the wallet restarted, or a failure — + * watch again to resume). Nothing of what changed is ever sent. + */ + watch( + params: { hostDid: string; roomId: string; sinceVersion?: number }, + onEvent: (e: RoomWatchEvent) => void, + ): RoomWatchHandle; /** A record's file, once the whole of it has verified against its author's digest. */ getFile(params: { hostDid: string; @@ -402,6 +435,21 @@ export interface VtaWalletRooms { }): Promise<{ key: string; version: number; size: number }>; } +/** What a page's room watch hears (`rooms.watch`). */ +export type RoomWatchEvent = + | { type: "changed"; latestVersion: number } + | { type: "state"; state: PageRoomWatchState } + | { type: "failed"; error: VtaWalletError } + | { type: "closed" }; + +/** A page's hold on one room's watch. */ +export interface RoomWatchHandle { + /** Say the room was read to `version` (the highest record version read): a watch that fired or lapsed is armed again from there. */ + read(version?: number): void; + /** End the watch. The wallet cancels it at the member's agent. */ + stop(): void; +} + declare global { interface Window { vtaWallet?: VtaWallet; @@ -464,6 +512,12 @@ window.addEventListener("message", (event: MessageEvent) => { return; } + if ("kind" in data && (data as { kind?: unknown }).kind === "roomWatch") { + const frame = data as unknown as { id: string; msg: RoomWatchPageEvent | { kind: "closed" } }; + watches.get(frame.id)?.(frame.msg); + return; + } + // Otherwise it's a request/response — fulfil the pending promise. if (!("id" in data)) return; const entry = pending.get(data.id); @@ -521,6 +575,74 @@ function legacy(method: "login" | "loginDidcomm" | "proxyLogin", run: () => P return run(); } +// ── Room watches ───────────────────────────────────────────────────────────── +// +// One id per watch; the content script opens one port per id. The page pings +// the port while it watches, which keeps the wallet's background awake to pass +// the signal on; it carries nothing. + +const watches = new Map void>(); +const WATCH_PING_MS = 20_000; + +function postWatchFrame(id: string, msg: unknown): void { + window.postMessage({ source: INPAGE_SOURCE, kind: "roomWatch", id, msg }, window.origin); +} + +function watchRoom( + params: Parameters[0], + onEvent: Parameters[1], +): RoomWatchHandle { + const id = crypto.randomUUID(); + let ended = false; + const emit = (e: RoomWatchEvent) => { + try { + onEvent(e); + } catch { + // The page's handler threw: its problem, not the watch's. + } + }; + const end = () => { + if (ended) return; + ended = true; + clearInterval(ping); + watches.delete(id); + }; + watches.set(id, (msg) => { + switch (msg.kind) { + case "changed": + emit({ type: "changed", latestVersion: msg.latestVersion }); + return; + case "state": + emit({ type: "state", state: msg.state }); + return; + case "failed": + emit({ type: "failed", error: walletError(msg.error, msg.code) }); + return; + case "closed": + end(); + emit({ type: "closed" }); + return; + } + }); + const ping = setInterval(() => postWatchFrame(id, { kind: "ping" }), WATCH_PING_MS); + postWatchFrame(id, { + kind: "watch", + hostDid: params.hostDid, + roomId: params.roomId, + ...(params.sinceVersion !== undefined ? { sinceVersion: params.sinceVersion } : {}), + }); + return { + read: (version) => { + if (!ended) postWatchFrame(id, { kind: "read", ...(version !== undefined ? { version } : {}) }); + }, + stop: () => { + if (ended) return; + postWatchFrame(id, { kind: "stop" }); + end(); + }, + }; +} + // ── Room-file transfers ────────────────────────────────────────────────────── // // One id per transfer; the content script opens one port per id. Bytes cross @@ -679,7 +801,25 @@ if (!window.vtaWallet) { read: (p) => call("rooms", { op: "read", hostDid: p.hostDid, roomId: p.roomId, key: p.key }), conversation: (p) => call("rooms", { op: "conversation", hostDid: p.hostDid, roomId: p.roomId }), putNote: (p) => call("rooms", { ...p, op: "putNote" }), - putMessage: (p) => call("rooms", { op: "putMessage", hostDid: p.hostDid, roomId: p.roomId, body: p.body }), + putMessage: (p) => + call("rooms", { + op: "putMessage", + hostDid: p.hostDid, + roomId: p.roomId, + body: p.body, + ...(p.replyTo !== undefined ? { replyTo: p.replyTo } : {}), + }), + react: (p) => + call("rooms", { + op: "react", + hostDid: p.hostDid, + roomId: p.roomId, + key: p.key, + ...(p.version !== undefined ? { version: p.version } : {}), + value: p.value, + }), + unreact: (p) => call("rooms", { op: "unreact", hostDid: p.hostDid, roomId: p.roomId, key: p.key, value: p.value }), + watch: watchRoom, offers: (p) => call("rooms", { op: "offers", hostDid: p.hostDid }), acceptOffer: (p) => call("rooms", { diff --git a/packages/extension/src/room-consent.tsx b/packages/extension/src/room-consent.tsx index 7a0b8b53..fd1cb075 100644 --- a/packages/extension/src/room-consent.tsx +++ b/packages/extension/src/room-consent.tsx @@ -17,6 +17,7 @@ import { requestOriginPermission } from "./host-permissions.js"; import { ROOM_CONSENT_PREFIX, type RoomShareConsentView, + type RecordGlimpse, type RoomShareRow, type RoomWriteConsentView, shareButtonWords, @@ -217,14 +218,34 @@ function Share({ ); } +/** The record a reply or a reaction is about, as the wallet read it. */ +function Glimpse({ of }: { of: RecordGlimpse }) { + return ( +
+ {of.author ? ( +
+ By +
+ ) : null} + {of.excerpt || (nothing to show)} +
+ ); +} + function Write({ view, decide }: { view: RoomWriteConsentView; decide: (approved: boolean) => void }) { + if ("reaction" in view.what) return ; const isFile = "file" in view.what; const isMessage = "message" in view.what; - const thing = isFile ? "file" : isMessage ? "message" : "note"; + const replyingTo = "message" in view.what ? view.what.replyingTo : undefined; + const thing = isFile ? "file" : isMessage ? (replyingTo ? "reply" : "message") : "note"; return ( <> - {isMessage ? "Send this message to the room as you?" : `Add a ${thing} to this room as you?`} + {isMessage + ? replyingTo + ? "Send this reply to the room as you?" + : "Send this message to the room as you?" + : `Add a ${thing} to this room as you?`}
{originHost(view.origin)} asks to write to a room, signed as you. Every member of the room will read it as @@ -251,6 +272,12 @@ function Write({ view, decide }: { view: RoomWriteConsentView; decide: (approved
+ {replyingTo ? ( +
+
In reply to
+ +
+ ) : null}
What will be written
@@ -282,7 +309,45 @@ function Write({ view, decide }: { view: RoomWriteConsentView; decide: (approved - decide(true)}>{isMessage ? "Send message" : `Add ${thing}`} + decide(true)}>{isMessage ? (replyingTo ? "Send reply" : "Send message") : `Add ${thing}`} +
+ + ); +} + +/** A reaction, or taking one back: short, since it is one value on one record. */ +function React({ + view, + what, + decide, +}: { + view: RoomWriteConsentView; + what: Extract; + decide: (approved: boolean) => void; +}) { + return ( + <> + + {what.withdraw ? "Take back your reaction" : "React"} {what.value}{" "} + {what.withdraw ? "from" : "to"} this, as you? + +
+ {originHost(view.origin)} asks to {what.withdraw ? "take back a reaction you made" : "add a reaction"} in a room, + signed as you. Every member of the room will see it as yours. + {view.visibility === "open" ? " This room is open: its host can see it too." : ""} +
+ +
+
Signed as
+
+ +
+
+
+ + decide(true)}>{what.withdraw ? "Take back" : "React"}
); diff --git a/packages/extension/src/room-page-background.ts b/packages/extension/src/room-page-background.ts index d7eedf96..3808deaf 100644 --- a/packages/extension/src/room-page-background.ts +++ b/packages/extension/src/room-page-background.ts @@ -22,6 +22,7 @@ import type { OffscreenRoomsPageOp, OffscreenRoomsPageResponse, + PageRecordView, PageRoomInfoView, PageRoomView, RoomFilesMessage, @@ -30,17 +31,22 @@ import type { RoomFilesPageOpen, RoomProfileSummary, RoomsPageOp, + RoomWatchPageEvent, + RuntimeRoomsKeysChanged, RuntimeRoomsPageResponse, } from "./bridge-protocol.js"; +import { RoomWatcher, roomWatchId, type RoomWatchKey, type RoomWatchBatch } from "@openvtc/pnm-core/rooms"; import { PageRefusal, forwardedCode, pageFailure, type PageErrorCode } from "./page-error.js"; import { excerpt, + glimpseOf, liveGrants, mergeRoomNames, storedRoomState, type RoomOwnerState, portalRefusal, roomFilesPageOpenRefusal, + roomWatchPageOpenRefusal, roomGrant, roomsPageParamsRefusal, selectedShares, @@ -50,6 +56,7 @@ import { withoutGrant, type RememberedRoomName, type RoomGrant, + type RecordGlimpse, type RoomShareConsentView, type RoomWriteConsentView, } from "./room-page-policy.js"; @@ -96,6 +103,8 @@ export interface RoomPageBackgroundDeps { /** The room names remembered for one community under one VTA (`roomNamesKey`). Absent: none kept. */ loadRoomNames?(vtaDid: string, hostDid: string): Promise; saveRoomNames?(vtaDid: string, hostDid: string, names: Record): Promise; + /** Timers for the watches pages hold, injectable for tests. Default `setTimeout`. */ + setTimer?(fn: () => void, ms: number): unknown; } /** A room's name, as a page or the share prompt is shown it. */ @@ -154,6 +163,17 @@ export class RoomPageGates { */ private readonly profiles = new Map(); + /** + * The rooms pages are watching, armed through the member's VTA. One watcher + * for the background: two tabs on one room share its watch, and the last to + * close cancels it. + */ + private watcher: RoomWatcher | undefined; + /** The VTA each watched room is armed through, by `vtaDid`. */ + private readonly watchVtas = new Map(); + /** Each page port's signal handler, by watch id. */ + private readonly watchers = new Map void>>(); + constructor(private readonly deps: RoomPageBackgroundDeps) {} /** `hostDid`'s portal and endpoint, resolved through the offscreen document and cached briefly. */ @@ -197,6 +217,37 @@ export class RoomPageGates { return r.grant.member; } + /** + * Refuse, before the member is asked anything, a write the room's profile + * does not take: a writer MUST NOT use a record member the room's current + * profile does not list (`SealedRecordBody`). + */ + private async needsRecordMembers( + vta: ActiveVta, + at: { hostDid: string; roomId: string; member: string }, + needed: readonly string[], + what: string, + ): Promise { + const listed = (await this.offscreen(vta, { op: "recordMembers", ...at })) as string[]; + const missing = needed.filter((m) => !listed.includes(m)); + if (missing.length > 0) { + throw new RoomPageRefusal( + `This room does not take ${what}: its profile does not list ${missing.join(" and ")} in its record members.`, + "recordMembersNotListed", + ); + } + } + + /** The record at `key`, read by the wallet as the member, as a prompt names it. */ + private async glimpse( + vta: ActiveVta, + at: { hostDid: string; roomId: string; member: string }, + key: string, + ): Promise { + const read = (await this.offscreen(vta, { op: "read", ...at, key })) as PageRecordView; + return glimpseOf(read); + } + private async offscreen(vta: ActiveVta, op: OffscreenRoomsPageOp): Promise { const res = await this.deps.offscreen(vta, op); if (!res.ok) throw new RoomPageRefusal(res.error, forwardedCode(res.code)); @@ -310,12 +361,45 @@ export class RoomPageGates { case "putMessage": { const { vta } = await this.atPortal(origin, p.hostDid, { needReach: true }); const member = await this.granted(origin, p.hostDid, vta, p.roomId); - const info = (await this.offscreen(vta, { - op: "info", + const at = { hostDid: p.hostDid, roomId: p.roomId, member }; + // A reply is refused before the member is asked where the room takes none: + // never sent without what makes it one. + if (p.replyTo !== undefined) await this.needsRecordMembers(vta, at, ["inReplyTo"], "replies"); + const info = (await this.offscreen(vta, { op: "info", ...at })) as PageRoomInfoView; + const replyingTo = p.replyTo !== undefined ? await this.glimpse(vta, at, p.replyTo.key) : undefined; + const decision = await this.deps.prompt({ + kind: "write", + origin, hostDid: p.hostDid, roomId: p.roomId, - member, - })) as PageRoomInfoView; + member: info.member, + visibility: info.visibility, + what: { + message: true, + excerpt: excerpt(p.body), + bodyChars: [...p.body].length, + ...(replyingTo !== undefined ? { replyingTo } : {}), + }, + }); + if (!decision.approved) throw new RoomPageRefusal("the member declined to send this message", "declined"); + return this.offscreen(vta, { + op: "putMessage", + ...at, + body: p.body, + ...(p.replyTo !== undefined + ? { replyTo: { key: p.replyTo.key, ...(p.replyTo.version !== undefined ? { version: p.replyTo.version } : {}) } } + : {}), + }); + } + case "react": + case "unreact": { + const { vta } = await this.atPortal(origin, p.hostDid, { needReach: true }); + const member = await this.granted(origin, p.hostDid, vta, p.roomId); + const at = { hostDid: p.hostDid, roomId: p.roomId, member }; + await this.needsRecordMembers(vta, at, ["kind", "inReplyTo"], "reactions"); + const info = (await this.offscreen(vta, { op: "info", ...at })) as PageRoomInfoView; + const on = await this.glimpse(vta, at, p.key); + const withdraw = p.op === "unreact"; const decision = await this.deps.prompt({ kind: "write", origin, @@ -323,10 +407,22 @@ export class RoomPageGates { roomId: p.roomId, member: info.member, visibility: info.visibility, - what: { message: true, excerpt: excerpt(p.body), bodyChars: [...p.body].length }, + what: { reaction: true, value: p.value, on, ...(withdraw ? { withdraw: true as const } : {}) }, }); - if (!decision.approved) throw new RoomPageRefusal("the member declined to send this message", "declined"); - return this.offscreen(vta, { op: "putMessage", hostDid: p.hostDid, roomId: p.roomId, member, body: p.body }); + if (!decision.approved) { + throw new RoomPageRefusal( + withdraw ? "the member declined to take back this reaction" : "the member declined to react", + "declined", + ); + } + return withdraw + ? this.offscreen(vta, { op: "unreact", ...at, target: p.key, value: p.value }) + : this.offscreen(vta, { + op: "react", + ...at, + target: { key: p.key, ...(p.version !== undefined ? { version: p.version } : {}) }, + value: p.value, + }); } } } @@ -555,6 +651,155 @@ export class RoomPageGates { // ── Files ───────────────────────────────────────────────────────────────── + // ── Change signals ────────────────────────────────────────────────────────── + + private roomWatcher(): RoomWatcher { + this.watcher ??= new RoomWatcher({ + send: async (batch: RoomWatchBatch) => { + const vta = this.watchVtas.get(batch.vtaDid); + if (!vta) throw new Error("no agent for this watch"); + return (await this.offscreen(vta, { + op: "watch", + hostDid: batch.host, + member: batch.member, + rooms: batch.rooms, + ...(batch.leaseSeconds !== undefined ? { leaseSeconds: batch.leaseSeconds } : {}), + ...(batch.cancel ? { cancel: true as const } : {}), + })) as Awaited[0]["send"]>>; + }, + ...(this.deps.setTimer ? { setTimer: this.deps.setTimer } : {}), + now: () => this.deps.now(), + }); + return this.watcher; + } + + /** + * A room's signal, as the offscreen document received it from the member's + * VTA (`RUNTIME_ROOMS_KEYS_CHANGED`; the caller checks it came from the + * offscreen document). Handed to the pages watching that room only when a + * page armed it; anything else is dropped. Answers whether one took it. + */ + deliverRoomSignal(vtaDid: string, signal: RuntimeRoomsKeysChanged["signal"]): boolean { + const key = this.watcher?.accept(vtaDid, signal); + if (!key) return false; + for (const fn of this.watchers.get(roomWatchId(key)) ?? []) fn(signal.latestVersion); + return true; + } + + /** + * Serve one page's watch on `page`, a port from a content script at `origin` + * (browser-attested). The first message names the room; the page must be the + * community's portal and the room shared with it, as for every room call. + * Then: the watch is armed through the member's VTA after each read the page + * reports, the room's signal is passed on — that it moved, and to which + * version, nothing else — and the watch is cancelled when the port closes. + * The share is checked again before every signal is passed on. + */ + serveWatchPort(page: PortLike, origin: string): void { + let open = true; + let held: { key: RoomWatchKey; release: () => void } | undefined; + const post = (m: RoomWatchPageEvent) => { + if (!open) return; + try { + page.postMessage(m); + } catch { + close(); + } + }; + const close = () => { + if (!open) return; + open = false; + held?.release(); + held = undefined; + }; + const fail = (e: unknown) => { + post({ kind: "failed", ...failedOf(e) }); + close(); + try { + page.disconnect(); + } catch { + // Already gone. + } + }; + page.onDisconnect.addListener(close); + + let started = false; + page.onMessage.addListener((raw: unknown) => { + if (!open) return; + if (!started) { + started = true; + void this.startWatch(origin, raw, post, fail).then((h) => { + if (!h) return; + if (open) held = h; + else h.release(); + }); + return; + } + const m = raw as { kind?: unknown; version?: unknown }; + if (m?.kind === "ping") return; + if (m?.kind === "read" && (m.version === undefined || (Number.isSafeInteger(m.version) && (m.version as number) >= 0))) { + if (held) this.roomWatcher().afterRead(held.key, m.version as number | undefined); + return; + } + fail(new RoomPageRefusal("a watch takes read and ping after it starts", "invalidCall")); + }); + } + + private async startWatch( + origin: string, + raw: unknown, + post: (m: RoomWatchPageEvent) => void, + fail: (e: unknown) => void, + ): Promise<{ key: RoomWatchKey; release: () => void } | undefined> { + const malformed = roomWatchPageOpenRefusal(raw); + if (malformed) { + fail(new RoomPageRefusal(malformed, "invalidCall")); + return undefined; + } + const o = raw as { hostDid: string; roomId: string; sinceVersion?: number }; + let vta: ActiveVta; + let member: string; + try { + // The VTA arms the watch at the host, not the wallet: no host permission is needed. + ({ vta } = await this.atPortal(origin, o.hostDid, { needReach: false })); + member = await this.granted(origin, o.hostDid, vta, o.roomId); + } catch (e) { + fail(e); + return undefined; + } + const watcher = this.roomWatcher(); + const key: RoomWatchKey = { vtaDid: vta.vtaDid, member, host: o.hostDid, roomId: o.roomId }; + const id = roomWatchId(key); + this.watchVtas.set(vta.vtaDid, vta); + const onSignal = (latestVersion: number) => { + // The share may have been forgotten or run out since the watch began. + void this.granted(origin, o.hostDid, vta, o.roomId).then( + () => post({ kind: "changed", latestVersion }), + (e: unknown) => fail(e), + ); + }; + const set = this.watchers.get(id) ?? new Set(); + set.add(onSignal); + this.watchers.set(id, set); + const unsubscribe = watcher.subscribe((changed, state) => { + if (changed === id && state) post({ kind: "state", state: state.state }); + }); + watcher.hold(key); + watcher.afterRead(key, o.sinceVersion); + let released = false; + return { + key, + release: () => { + if (released) return; + released = true; + unsubscribe(); + set.delete(onSignal); + if (set.size === 0) this.watchers.delete(id); + watcher.release(key); + }, + }; + } + /** * Serve one page file transfer on `page`, a port from a content script at * `origin` (browser-attested). The offscreen document does the work; this diff --git a/packages/extension/src/room-page-offscreen.ts b/packages/extension/src/room-page-offscreen.ts index a4115443..f609cd01 100644 --- a/packages/extension/src/room-page-offscreen.ts +++ b/packages/extension/src/room-page-offscreen.ts @@ -36,8 +36,14 @@ import { readSealedVersion, roomProfileView, roomsKeysProfileRead, + ownReactions, + roomRecordMembersAsMember, + roomsKeysWatch, + withdrawReactionAsMember, writeMessageAsMember, + writeReactionAsMember, writeSealedAsMember, + type RecordInput, type PersonaRoom, } from "@openvtc/pnm-core/rooms"; import { RecordBodyError, RoomHostChannel, verifyRecordBody, type ResolveDidAt } from "@openvtc/pnm-core/rooms/files"; @@ -286,9 +292,56 @@ export async function runRoomsPageOp( return { key, version }; } case "putMessage": { - const { key, version } = await writeMessageAsMember(await room(op.roomId, op.member), { body: op.body }); + const { key, version } = await writeMessageAsMember(await room(op.roomId, op.member), { + body: op.body, + ...(op.replyTo !== undefined ? { replyTo: op.replyTo } : {}), + }); + return { key, version }; + } + case "recordMembers": + return (await roomRecordMembersAsMember(await room(op.roomId, op.member))) ?? []; + case "react": { + const { key, version } = await writeReactionAsMember(await room(op.roomId, op.member), { + target: op.target, + value: op.value, + }); return { key, version }; } + case "unreact": { + // The member's own reactions with this value on that record, as the room + // reads now — each one counts until withdrawn, so each is withdrawn. + const r = await room(op.roomId, op.member); + const { principal } = await roomInfoAsMember(r); + const at = { ...parties, roomId: op.roomId, host: op.hostDid, member: op.member }; + const inputs = await readInputs(at, op.roomId); + const mine = ownReactions(inputs, { author: principal, target: op.target, value: op.value }); + for (const held of mine) await withdrawReactionAsMember(r, held); + return { withdrawn: mine.length }; + } + case "watch": { + return roomsKeysWatch(sender, { + ...parties, + member: op.member, + host: op.hostDid, + rooms: op.rooms, + ...(op.leaseSeconds !== undefined ? { leaseSeconds: op.leaseSeconds } : {}), + ...(op.cancel ? { cancel: true as const } : {}), + }); + } + } + + /** Every record of the room, listed, read and verified as the reading rules take them. */ + async function readInputs( + at: { holder: { did: string }; service: { did: string }; roomId: string; host: string; member: string }, + roomId: string, + ): Promise { + const listing = await roomsKeysBrowse(sender, at); + const rows = (listing.records ?? []) as unknown as ListedRecord[]; + const toRead = rows.filter((r) => r.status !== "retracted").map((r) => r.key); + const answers = toRead.length === 0 ? [] : await roomsKeysReadMany(sender, { ...at, keys: toRead }); + const byKey = new Map(answers.map((a) => [a.key, a])); + const resolve = memoResolveDidDocumentAt(); + return Promise.all(rows.map(async (row) => (await recordInputFromRead(roomId, row, byKey.get(row.key), resolve)).input)); } } diff --git a/packages/extension/src/room-page-policy.ts b/packages/extension/src/room-page-policy.ts index 45c09726..922c6842 100644 --- a/packages/extension/src/room-page-policy.ts +++ b/packages/extension/src/room-page-policy.ts @@ -41,6 +41,7 @@ // wallet builds (`PageRoomView` and friends in `bridge-protocol.ts`). import type { RoomsPageOp, RoomFilesPageOpen } from "./bridge-protocol.js"; +import { reactionValue } from "@openvtc/pnm-core/rooms"; /** How long a share lasts before the member is asked again. */ export const ROOM_GRANT_TTL_MS = 30 * 24 * 60 * 60 * 1000; @@ -346,7 +347,43 @@ function tags(v: unknown): string | null { return null; } -const OPS = new Set(["list", "choose", "forget", "info", "browse", "read", "conversation", "putNote", "putMessage", "offers", "acceptOffer"]); +const OPS = new Set([ + "list", + "choose", + "forget", + "info", + "browse", + "read", + "conversation", + "putNote", + "putMessage", + "react", + "unreact", + "offers", + "acceptOffer", +]); + +/** A reaction's value, as a page may send it: the reading rules' own test (*A reaction's value*). */ +function reaction(v: unknown): string | null { + if (typeof v !== "string") return "value must be a string"; + const r = reactionValue(v); + if (r.kind === "empty") return "value is required"; + if (r.kind === "invalid") return `value: ${r.reason}`; + return null; +} + +function version(v: unknown, what: string): string | null { + return v === undefined || (Number.isSafeInteger(v) && (v as number) >= 1) ? null : `${what} must be a whole number of at least 1`; +} + +/** A record reference a page names: a key, and a version where it gives one. */ +function reference(v: unknown, what: string): string | null { + if (v === undefined) return null; + if (!v || typeof v !== "object" || Array.isArray(v)) return `${what} must be { key, version? }`; + const r = v as Record; + if (Object.keys(r).some((k) => k !== "key" && k !== "version")) return `${what} must be { key, version? }`; + return text(r.key, `${what}.key`, MAX_KEY, true) ?? version(r.version, `${what}.version`); +} /** Why a page's room call is malformed, or `null` when it is well formed. Checked before anything else. */ export function roomsPageParamsRefusal(raw: unknown): string | null { @@ -378,12 +415,33 @@ export function roomsPageParamsRefusal(raw: unknown): string | null { tags(op.tags) ); case "putMessage": - return text(op.body, "body", MAX_BODY, true); + return text(op.body, "body", MAX_BODY, true) ?? reference(op.replyTo, "replyTo"); + case "react": + return text(op.key, "key", MAX_KEY, true) ?? version(op.version, "version") ?? reaction(op.value); + case "unreact": + return text(op.key, "key", MAX_KEY, true) ?? reaction(op.value); default: return null; } } +/** Why a page's watch is malformed, or `null` when it is well formed: `{ kind: "watch", hostDid, roomId, sinceVersion? }`. */ +export function roomWatchPageOpenRefusal(raw: unknown): string | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return "a watch starts with watch"; + const o = raw as Record; + if (o.kind !== "watch") return "a watch starts with watch"; + if (Object.keys(o).some((k) => !["kind", "hostDid", "roomId", "sinceVersion"].includes(k))) { + return "a watch names hostDid, roomId and sinceVersion only"; + } + return ( + did(o.hostDid, "hostDid") ?? + did(o.roomId, "roomId") ?? + (o.sinceVersion !== undefined && !(Number.isSafeInteger(o.sinceVersion) && (o.sinceVersion as number) >= 0) + ? "sinceVersion must be a whole number" + : null) + ); +} + /** Why a page's file transfer is malformed, or `null` when it is well formed. */ export function roomFilesPageOpenRefusal(raw: unknown): string | null { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return "a transfer starts with get or put"; @@ -454,10 +512,30 @@ export interface RoomWriteConsentView { visibility: string; what: | { note: true; title: string; excerpt: string; bodyChars: number } - | { message: true; excerpt: string; bodyChars: number } + | { + message: true; + excerpt: string; + bodyChars: number; + /** The record the message answers, as the wallet read it — never the page's word. */ + replyingTo?: RecordGlimpse; + } + /** A reaction, or (`withdraw`) taking one back, on the record the wallet read. */ + | { reaction: true; value: string; withdraw?: true; on: RecordGlimpse } | { file: true; name: string; size: number; mediaType?: string; title?: string }; } +/** Another record, as a write prompt names it: who wrote it and how it starts. Read by the wallet. */ +export interface RecordGlimpse { + author?: string; + excerpt: string; +} + +/** A record the wallet read, as a prompt names it: its title, else the start of its text, else its file. */ +export function glimpseOf(r: { author?: string; title?: string; body?: string; file?: { name: string } }): RecordGlimpse { + const text = (r.title || r.body || r.file?.name || "").replace(/\s+/g, " ").trim(); + return { ...(r.author !== undefined ? { author: r.author } : {}), excerpt: excerpt(text, 120) }; +} + /** The first `n` characters of a note's body, for the write prompt. */ export function excerpt(body: string | undefined, n = 280): string { if (!body) return ""; diff --git a/packages/extension/tests/room-page-reply-react-watch.test.mts b/packages/extension/tests/room-page-reply-react-watch.test.mts new file mode 100644 index 00000000..391887c2 --- /dev/null +++ b/packages/extension/tests/room-page-reply-react-watch.test.mts @@ -0,0 +1,523 @@ +// A portal page replies, reacts and watches a room (P7b; VTI `data-rooms-files.md` §8.5). +// +// The same gates as every room call — the page is the community's portal by its +// DID document, the member shared the room with it — then, for a write, the +// room's profile must take what is written (`recordMembersNotListed`, checked +// before the member is asked) and the member confirms it, seeing the record it +// answers or reacts to as the wallet read it, never the page's word. A watch is +// a port: armed through the member's VTA, passed on only for a room the page +// armed and is still shared, cancelled when the port closes. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +import { RoomPageGates, type PortLike, type RoomPageBackgroundDeps } from "../src/room-page-background.ts"; +import { + glimpseOf, + roomWatchPageOpenRefusal, + roomsPageParamsRefusal, + type RoomShareConsentView, + type RoomWriteConsentView, +} from "../src/room-page-policy.ts"; +import { WALLET_ERROR_CODES } from "../src/page-error.ts"; + +const PORTAL = "https://members.northwind.example"; +const HOST = "did:webvh:QmHost:northwind.example"; +const VTA = "did:webvh:QmAgent:agent.example"; +const ROOM = "did:webvh:QmRoom:rooms.example"; +const MEMBER = "did:webvh:QmAlice:people.example"; +const BOB = "did:webvh:QmBob:people.example"; +const NOW = 1_800_000_000_000; + +class FakePort implements PortLike { + posted: unknown[] = []; + connected = true; + private onMsg: ((m: unknown) => void)[] = []; + private onDisc: (() => void)[] = []; + postMessage(m: unknown) { + this.posted.push(m); + } + disconnect() { + if (!this.connected) return; + this.connected = false; + for (const f of this.onDisc) f(); + } + onMessage = { addListener: (fn: (m: unknown) => void) => void this.onMsg.push(fn) }; + onDisconnect = { addListener: (fn: () => void) => void this.onDisc.push(fn) }; + receive(m: unknown) { + for (const f of this.onMsg) f(m); + } +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +interface Harness { + gates: RoomPageGates; + prompts: (RoomShareConsentView | RoomWriteConsentView)[]; + asked: { op: string; [k: string]: unknown }[]; + answer: { approved: boolean; selectedRooms?: string[] }; + recordMembers: string[]; + /** What the VTA answers a watch request with, per room. */ + watch: (rooms: { roomId: string }[], cancel: boolean) => unknown; + shared: boolean; +} + +function harness(over: Partial = {}): Harness { + const h: Harness = { + gates: undefined as never, + prompts: [], + asked: [], + answer: { approved: true }, + recordMembers: ["kind", "inReplyTo", "writtenAt"], + watch: (rooms, cancel) => rooms.map((r) => ({ roomId: r.roomId, armed: !cancel, ...(!cancel ? { expiresAt: "2030-01-01T00:00:00Z" } : {}) })), + shared: true, + }; + const deps: RoomPageBackgroundDeps = { + active: async () => ({ ok: true, vta: { vtaDid: VTA } }), + async offscreen(_vta, op) { + h.asked.push(op as never); + switch (op.op) { + case "portal": + return { ok: true, result: { portalOrigin: PORTAL, endpoint: `${PORTAL}/v1/trust-tasks` } }; + case "info": + return { ok: true, result: { roomId: op.roomId, visibility: "attributed", epoch: 3, member: op.member, limits: {}, usage: {} } }; + case "recordMembers": + return { ok: true, result: h.recordMembers }; + case "read": + return { + ok: true, + result: { key: op.key, version: 2, status: "active", updatedAt: "2026-11-25T10:00:00Z", author: BOB, kind: "message", body: "Lunch at one?" }, + }; + case "watch": + return { ok: true, result: h.watch(op.rooms, op.cancel === true) }; + default: + return { ok: true, result: { did: op.op } }; + } + }, + canReach: async () => true, + loadGrants: async () => + h.shared + ? [{ origin: PORTAL, hostDid: HOST, vtaDid: VTA, roomId: ROOM, member: MEMBER, grantedAt: NOW - 1000, expiresAt: NOW + 86_400_000 }] + : [], + saveGrants: async () => undefined, + prompt: async (view) => { + h.prompts.push(view); + return h.answer; + }, + openTransfer: async () => new FakePort(), + now: () => NOW, + setTimer: (fn, ms) => { + const t = setTimeout(fn, ms); + (t as { unref?: () => void }).unref?.(); + return t; + }, + ...over, + }; + h.gates = new RoomPageGates(deps); + return h; +} + +const writes = (h: Harness) => h.asked.filter((a) => ["putMessage", "react", "unreact"].includes(a.op)); + +// ── Shapes ────────────────────────────────────────────────────────────────── + +test("a reply, a reaction and a watch are checked for shape before anything else", () => { + const ok = { hostDid: HOST, roomId: ROOM }; + assert.equal(roomsPageParamsRefusal({ op: "putMessage", ...ok, body: "Yes", replyTo: { key: "m1", version: 2 } }), null); + assert.match(roomsPageParamsRefusal({ op: "putMessage", ...ok, body: "Yes", replyTo: { key: "" } })!, /replyTo.key is required/); + assert.match(roomsPageParamsRefusal({ op: "putMessage", ...ok, body: "Yes", replyTo: { key: "m", extra: 1 } })!, /replyTo must be/); + assert.match(roomsPageParamsRefusal({ op: "putMessage", ...ok, body: "Yes", replyTo: { key: "m", version: 0 } })!, /version/); + assert.equal(roomsPageParamsRefusal({ op: "react", ...ok, key: "m1", value: "👍" }), null); + assert.match(roomsPageParamsRefusal({ op: "react", ...ok, key: "m1", value: " " })!, /value is required/); + assert.match(roomsPageParamsRefusal({ op: "react", ...ok, key: "m1", value: "a\nb" })!, /line break/); + assert.match(roomsPageParamsRefusal({ op: "react", ...ok, key: "m1", value: "x".repeat(65) })!, /longer than 64/); + assert.match(roomsPageParamsRefusal({ op: "react", ...ok, value: "👍" })!, /key is required/); + assert.equal(roomsPageParamsRefusal({ op: "unreact", ...ok, key: "m1", value: "👍" }), null); + assert.equal(roomWatchPageOpenRefusal({ kind: "watch", ...ok, sinceVersion: 12 }), null); + assert.match(roomWatchPageOpenRefusal({ kind: "watch", ...ok, sinceVersion: -1 })!, /whole number/); + assert.match(roomWatchPageOpenRefusal({ kind: "watch", ...ok, member: MEMBER })!, /only/); + assert.match(roomWatchPageOpenRefusal({ kind: "read" })!, /starts with watch/); +}); + +test("recordMembersNotListed is a wallet code, documented with the same words", () => { + assert.ok("recordMembersNotListed" in WALLET_ERROR_CODES); + const doc = readFileSync(fileURLToPath(new URL("../../../docs/page-bridge-errors.md", import.meta.url)), "utf8"); + assert.match(doc, /\| `recordMembersNotListed` \|/); +}); + +test("a prompt names another record by its title, else its text, else its file — bounded", () => { + assert.deepEqual(glimpseOf({ author: BOB, body: "a\n b" }), { author: BOB, excerpt: "a b" }); + assert.equal(glimpseOf({ title: "T", body: "b" }).excerpt, "T"); + assert.equal(glimpseOf({ file: { name: "f.pdf" } }).excerpt, "f.pdf"); + assert.equal([...glimpseOf({ body: "x".repeat(500) }).excerpt].length, 121); +}); + +// ── A reply ───────────────────────────────────────────────────────────────── + +test("a reply is confirmed showing what it answers, as the wallet read it — never the page's word", async () => { + const h = harness(); + const res = await h.gates.handle(PORTAL, { op: "putMessage", hostDid: HOST, roomId: ROOM, body: "Yes", replyTo: { key: "m1", version: 2 } }); + assert.ok(res.ok); + const view = h.prompts.at(-1) as RoomWriteConsentView; + assert.deepEqual(view.what, { message: true, excerpt: "Yes", bodyChars: 3, replyingTo: { author: BOB, excerpt: "Lunch at one?" } }); + const read = h.asked.find((a) => a.op === "read"); + assert.deepEqual(read, { op: "read", hostDid: HOST, roomId: ROOM, member: MEMBER, key: "m1" }, "read as the share's member"); + const put = writes(h)[0]; + assert.deepEqual(put, { op: "putMessage", hostDid: HOST, roomId: ROOM, member: MEMBER, body: "Yes", replyTo: { key: "m1", version: 2 } }); +}); + +test("a reply in a room that takes none is refused before the member is asked, and nothing is written", async () => { + const h = harness(); + h.recordMembers = ["kind", "writtenAt"]; + const res = await h.gates.handle(PORTAL, { op: "putMessage", hostDid: HOST, roomId: ROOM, body: "Yes", replyTo: { key: "m1" } }); + assert.equal(res.ok, false); + assert.equal((res as { code?: string }).code, "recordMembersNotListed"); + assert.equal(h.prompts.length, 0, "nobody was asked"); + assert.deepEqual(writes(h), []); + // A message that answers nothing is not held to it. + const plain = await h.gates.handle(PORTAL, { op: "putMessage", hostDid: HOST, roomId: ROOM, body: "Yes" }); + assert.ok(plain.ok); + assert.ok(!h.asked.some((a) => a.op === "recordMembers" && h.asked.indexOf(a) > 3), "no profile check for a plain message"); +}); + +test("a reply to a room not shared with the page is refused, and the room is not read", async () => { + const h = harness(); + h.shared = false; + const res = await h.gates.handle(PORTAL, { op: "putMessage", hostDid: HOST, roomId: ROOM, body: "Yes", replyTo: { key: "m1" } }); + assert.equal((res as { code?: string }).code, "notShared"); + assert.ok(!h.asked.some((a) => a.op === "read" || a.op === "recordMembers")); +}); + +// ── A reaction ────────────────────────────────────────────────────────────── + +test("a reaction is confirmed — the value and the record it is on — and only then written", async () => { + const h = harness(); + h.answer = { approved: false }; + const denied = await h.gates.handle(PORTAL, { op: "react", hostDid: HOST, roomId: ROOM, key: "m1", version: 2, value: "👍" }); + assert.deepEqual(denied, { ok: false, error: "the member declined to react", code: "declined" }); + assert.deepEqual(writes(h), []); + assert.deepEqual((h.prompts.at(-1) as RoomWriteConsentView).what, { + reaction: true, + value: "👍", + on: { author: BOB, excerpt: "Lunch at one?" }, + }); + + h.answer = { approved: true }; + const ok = await h.gates.handle(PORTAL, { op: "react", hostDid: HOST, roomId: ROOM, key: "m1", version: 2, value: "👍" }); + assert.ok(ok.ok); + assert.deepEqual(writes(h)[0], { op: "react", hostDid: HOST, roomId: ROOM, member: MEMBER, target: { key: "m1", version: 2 }, value: "👍" }); +}); + +test("a reaction in a room without kind and inReplyTo is refused before the member is asked", async () => { + for (const recordMembers of [[], ["kind"], ["inReplyTo"]]) { + const h = harness(); + h.recordMembers = recordMembers; + const res = await h.gates.handle(PORTAL, { op: "react", hostDid: HOST, roomId: ROOM, key: "m1", value: "👍" }); + assert.equal((res as { code?: string }).code, "recordMembersNotListed"); + assert.equal(h.prompts.length, 0); + assert.deepEqual(writes(h), []); + } +}); + +test("taking a reaction back is confirmed as that, and names the record and the value", async () => { + const h = harness(); + const res = await h.gates.handle(PORTAL, { op: "unreact", hostDid: HOST, roomId: ROOM, key: "m1", value: "👍" }); + assert.ok(res.ok); + assert.deepEqual((h.prompts.at(-1) as RoomWriteConsentView).what, { + reaction: true, + value: "👍", + on: { author: BOB, excerpt: "Lunch at one?" }, + withdraw: true, + }); + assert.deepEqual(writes(h)[0], { op: "unreact", hostDid: HOST, roomId: ROOM, member: MEMBER, target: "m1", value: "👍" }); +}); + +// ── A watch ───────────────────────────────────────────────────────────────── + +const state = (p: FakePort) => p.posted.filter((m) => (m as { kind: string }).kind === "state").map((m) => (m as { state: string }).state); +const watchAsks = (h: Harness) => h.asked.filter((a) => a.op === "watch"); + +test("a watch is armed through the member's VTA as the share's member, and its signal reaches the page — nothing else of it", async () => { + const h = harness(); + const page = new FakePort(); + h.gates.serveWatchPort(page, PORTAL); + page.receive({ kind: "watch", hostDid: HOST, roomId: ROOM, sinceVersion: 40 }); + await sleep(80); + assert.deepEqual(watchAsks(h)[0], { + op: "watch", + hostDid: HOST, + member: MEMBER, + rooms: [{ roomId: ROOM, sinceVersion: 40 }], + leaseSeconds: 86_400, + }); + assert.deepEqual(state(page), ["arming", "armed"]); + + assert.equal(h.gates.deliverRoomSignal(VTA, { roomId: ROOM, member: MEMBER, host: HOST, latestVersion: 43 }), true); + await sleep(0); + assert.deepEqual(page.posted.at(-1), { kind: "changed", latestVersion: 43 }); + assert.equal(state(page).at(-1), "fired"); + + // Fired once: a second signal before the page reads again is dropped. + assert.equal(h.gates.deliverRoomSignal(VTA, { roomId: ROOM, member: MEMBER, host: HOST, latestVersion: 44 }), false); + + // The page read the room: armed again from there. + page.receive({ kind: "read", version: 43 }); + await sleep(80); + assert.deepEqual(watchAsks(h).at(-1)?.rooms, [{ roomId: ROOM, sinceVersion: 43 }]); + assert.equal(state(page).at(-1), "armed"); +}); + +test("a signal for a watch no page armed, or for another member or host, goes nowhere", async () => { + const h = harness(); + assert.equal(h.gates.deliverRoomSignal(VTA, { roomId: ROOM, member: MEMBER, host: HOST, latestVersion: 1 }), false); + const page = new FakePort(); + h.gates.serveWatchPort(page, PORTAL); + page.receive({ kind: "watch", hostDid: HOST, roomId: ROOM }); + await sleep(80); + assert.equal(h.gates.deliverRoomSignal(VTA, { roomId: ROOM, member: BOB, host: HOST, latestVersion: 1 }), false); + assert.equal(h.gates.deliverRoomSignal(VTA, { roomId: ROOM, member: MEMBER, host: "did:web:other.example", latestVersion: 1 }), false); + assert.equal(h.gates.deliverRoomSignal("did:key:zOtherVta", { roomId: ROOM, member: MEMBER, host: HOST, latestVersion: 1 }), false); + assert.ok(!page.posted.some((m) => (m as { kind: string }).kind === "changed")); +}); + +test("closing the port cancels the watch at the VTA", async () => { + const h = harness(); + const page = new FakePort(); + h.gates.serveWatchPort(page, PORTAL); + page.receive({ kind: "watch", hostDid: HOST, roomId: ROOM }); + await sleep(80); + page.disconnect(); + await sleep(80); + const cancel = watchAsks(h).at(-1); + assert.equal(cancel?.cancel, true); + assert.deepEqual(cancel?.rooms, [{ roomId: ROOM }]); + assert.equal(h.gates.deliverRoomSignal(VTA, { roomId: ROOM, member: MEMBER, host: HOST, latestVersion: 9 }), false); +}); + +test("two pages on one room share its watch; the last to close cancels it", async () => { + const h = harness(); + const a = new FakePort(); + const b = new FakePort(); + h.gates.serveWatchPort(a, PORTAL); + h.gates.serveWatchPort(b, PORTAL); + a.receive({ kind: "watch", hostDid: HOST, roomId: ROOM }); + b.receive({ kind: "watch", hostDid: HOST, roomId: ROOM }); + await sleep(80); + assert.equal(h.gates.deliverRoomSignal(VTA, { roomId: ROOM, member: MEMBER, host: HOST, latestVersion: 5 }), true); + await sleep(0); + for (const p of [a, b]) assert.deepEqual(p.posted.filter((m) => (m as { kind: string }).kind === "changed"), [{ kind: "changed", latestVersion: 5 }]); + // The signal spent that arming; a read arms it again (a fired watch has nothing to cancel). + b.receive({ kind: "read", version: 5 }); + await sleep(80); + a.disconnect(); + await sleep(80); + assert.ok(!watchAsks(h).some((w) => w.cancel), "still held by the other page"); + b.disconnect(); + await sleep(80); + assert.ok(watchAsks(h).some((w) => w.cancel)); +}); + +test("a page that is not the portal, or a room not shared, gets no watch — and the VTA is not asked", async () => { + for (const [origin, shared, code] of [ + ["https://evil.example", true, "originNotPermitted"], + [PORTAL, false, "notShared"], + ] as const) { + const h = harness(); + h.shared = shared; + const page = new FakePort(); + h.gates.serveWatchPort(page, origin); + page.receive({ kind: "watch", hostDid: HOST, roomId: ROOM }); + await sleep(80); + assert.deepEqual(watchAsks(h), []); + assert.equal((page.posted[0] as { kind: string; code: string }).code, code); + assert.equal(page.connected, false, "the port is closed"); + } +}); + +test("a signal after the share was taken back is not passed on, and the watch ends", async () => { + const h = harness(); + const page = new FakePort(); + h.gates.serveWatchPort(page, PORTAL); + page.receive({ kind: "watch", hostDid: HOST, roomId: ROOM }); + await sleep(80); + h.shared = false; + h.gates.deliverRoomSignal(VTA, { roomId: ROOM, member: MEMBER, host: HOST, latestVersion: 7 }); + await sleep(80); + assert.ok(!page.posted.some((m) => (m as { kind: string }).kind === "changed")); + assert.equal((page.posted.at(-1) as { code?: string }).code, "notShared"); + assert.equal(page.connected, false); +}); + +test("a VTA that cannot watch leaves the page told so — it falls back to reading on a timer", async () => { + const h = harness(); + h.watch = () => { + throw new Error("unsupportedType"); + }; + const page = new FakePort(); + h.gates.serveWatchPort(page, PORTAL); + page.receive({ kind: "watch", hostDid: HOST, roomId: ROOM }); + await sleep(80); + assert.equal(state(page).at(-1), "unavailable"); + assert.equal(page.connected, true, "the port stays: a later read may arm it"); +}); + +test("after it starts, a watch takes only read and ping", async () => { + const h = harness(); + const page = new FakePort(); + h.gates.serveWatchPort(page, PORTAL); + page.receive({ kind: "watch", hostDid: HOST, roomId: ROOM }); + await sleep(80); + page.receive({ kind: "ping" }); + assert.equal(page.connected, true); + page.receive({ kind: "watch", hostDid: HOST, roomId: "did:webvh:QmElse:rooms.example" }); + assert.equal(page.connected, false, "a second room on one port is refused"); + assert.equal((page.posted.at(-1) as { code?: string }).code, "invalidCall"); +}); + +test("the content script's inlined port names match the protocol's", () => { + const read = (n: string) => readFileSync(fileURLToPath(new URL(`../src/${n}`, import.meta.url)), "utf8"); + const content = read("content.ts"); + const protocol = read("bridge-protocol.ts"); + for (const name of ["ROOM_FILES_PAGE_PORT", "ROOM_WATCH_PAGE_PORT"]) { + const re = new RegExp(`const ${name} =\\s*"([^"]+)"`); + assert.equal(re.exec(content)?.[1], re.exec(protocol)?.[1], name); + } +}); + +// ── The offscreen half ───────────────────────────────────────────────────── + +import { runRoomsPageOp } from "../src/room-page-offscreen.ts"; + +const OPEN_ROOM = "did:webvh:QmOpen:rooms.example"; + +/** An open room whose records are `records` (cleartext, by `author`), as the member's VTA lists and reads them. */ +function openRoomDeps(records: { key: string; version: number; author: string; cleartext: Record }[]) { + const sent: Record[] = []; + const vtaAsked: string[] = []; + const deps = { + agent: async () => ({ + holderDid: "did:key:zWallet", + sender: { + async send(envelope: { type: string; payload: Record & { document?: Record } }) { + vtaAsked.push(envelope.type); + if (envelope.type.includes("rooms/keys/profile/read/")) { + return { roomId: OPEN_ROOM, status: "found", profile: { name: "R", recordMembers: ["kind", "inReplyTo"] } } as Res; + } + if (envelope.type.includes("rooms/keys/browse/")) { + return { + roomId: OPEN_ROOM, + records: records.map((r) => ({ key: r.key, version: r.version, status: "active", author: r.author, updatedAt: "2026-11-25T10:00:00Z" })), + complete: true, + verification: { priorRoots: "noneHeld", count: "agrees" }, + } as Res; + } + if (envelope.type.includes("rooms/keys/read/")) { + const keys = envelope.payload.keys as string[]; + return { + roomId: OPEN_ROOM, + results: keys.map((k) => { + const r = records.find((x) => x.key === k)!; + return { key: r.key, version: r.version, status: "active", author: r.author, updatedAt: "2026-11-25T10:00:00Z", cleartext: r.cleartext }; + }), + } as Res; + } + if (!envelope.type.includes("rooms/keys/act/")) throw new Error(`unexpected ${envelope.type}`); + const doc = structuredClone(envelope.payload.document!); + doc.proof = { type: "DataIntegrityProof" }; + return { principal: doc.issuer, document: doc } as Res; + }, + } as never, + }), + portal: async () => ({ portalOrigin: PORTAL, endpoint: `${PORTAL}/v1/trust-tasks` }), + completed: () => ({ + async sendCompleted(doc: Record) { + sent.push(doc); + const type = String(doc.type); + const payload = doc.payload as { roomId: string; key?: string }; + if (type.includes("rooms/info/")) return { roomId: payload.roomId, visibility: "open", epoch: 1, limits: {}, usage: {} } as Res; + if (type.includes("rooms/records/put/")) return { key: payload.key, version: 9 } as Res; + throw new Error(`unexpected ${type}`); + }, + }), + }; + return { deps, sent, vtaAsked }; +} +const putsOf = (sent: Record[]) => + sent.filter((d) => String(d.type).includes("rooms/records/put/")).map((d) => d.payload as Record); + +test("offscreen react writes a reaction record naming the target, as the member", async () => { + const r = openRoomDeps([]); + const out = await runRoomsPageOp(r.deps as never, { vtaDid: VTA }, { + op: "react", + hostDid: HOST, + roomId: OPEN_ROOM, + member: MEMBER, + target: { key: "m1", version: 2 }, + value: "👍", + }); + const [put] = putsOf(r.sent); + assert.deepEqual(put!.cleartext, { body: "👍", kind: "reaction", inReplyTo: { key: "m1", version: 2 } }); + assert.equal(put!.expectedVersion, 0); + assert.deepEqual(out, { key: put!.key, version: 9 }); +}); + +test("offscreen unreact withdraws exactly the member's own reactions with that value on that record", async () => { + const r = openRoomDeps([ + { key: "m1", version: 1, author: BOB, cleartext: { body: "hi", kind: "message" } }, + { key: "mine", version: 3, author: MEMBER, cleartext: { body: "👍", kind: "reaction", inReplyTo: { key: "m1" } } }, + { key: "mine-heart", version: 4, author: MEMBER, cleartext: { body: "❤️", kind: "reaction", inReplyTo: { key: "m1" } } }, + { key: "bobs", version: 5, author: BOB, cleartext: { body: "👍", kind: "reaction", inReplyTo: { key: "m1" } } }, + ]); + const out = await runRoomsPageOp(r.deps as never, { vtaDid: VTA }, { + op: "unreact", + hostDid: HOST, + roomId: OPEN_ROOM, + member: MEMBER, + target: "m1", + value: "👍", + }); + assert.deepEqual(out, { withdrawn: 1 }); + const puts = putsOf(r.sent); + assert.equal(puts.length, 1); + assert.equal(puts[0]!.key, "mine"); + assert.equal(puts[0]!.expectedVersion, 3, "over the version read"); + assert.deepEqual(puts[0]!.cleartext, { body: "", kind: "reaction", inReplyTo: { key: "m1" } }); +}); + +test("offscreen unreact with nothing to take back writes nothing", async () => { + const r = openRoomDeps([{ key: "m1", version: 1, author: BOB, cleartext: { body: "hi", kind: "message" } }]); + const out = await runRoomsPageOp(r.deps as never, { vtaDid: VTA }, { + op: "unreact", + hostDid: HOST, + roomId: OPEN_ROOM, + member: MEMBER, + target: "m1", + value: "👍", + }); + assert.deepEqual(out, { withdrawn: 0 }); + assert.deepEqual(putsOf(r.sent), []); +}); + +test("offscreen watch asks the member's VTA, as the wallet, naming the member and host", async () => { + const asked: { type: string; payload: Record }[] = []; + const out = await runRoomsPageOp( + { + agent: async () => ({ + holderDid: "did:key:zWallet", + sender: { + async send(envelope: { type: string; payload: Record }) { + asked.push(envelope); + return { member: MEMBER, host: HOST, watches: [{ roomId: ROOM, armed: true, expiresAt: "2030-01-01T00:00:00Z" }] } as Res; + }, + } as never, + }), + }, + { vtaDid: VTA }, + { op: "watch", hostDid: HOST, member: MEMBER, rooms: [{ roomId: ROOM, sinceVersion: 3 }], leaseSeconds: 3600 }, + ); + assert.match(asked[0]!.type, /rooms\/keys\/watch\/0\.1/); + assert.deepEqual(asked[0]!.payload, { member: MEMBER, host: HOST, rooms: [{ roomId: ROOM, sinceVersion: 3 }], leaseSeconds: 3600 }); + assert.deepEqual(out, [{ roomId: ROOM, armed: true, expiresAt: "2030-01-01T00:00:00Z" }]); +});