diff --git a/CLAUDE.md b/CLAUDE.md index d3ac3265..b1e43973 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1047,15 +1047,18 @@ 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, putNote, -getFile, putFile}` is how a community's member portal shows a member their rooms +`window.vtaWallet.rooms.{list, choose, forget, info, browse, read, conversation, +putNote, 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 views the wallet built (`PageRoomView`, `PageRecordView`, … in `bridge-protocol.ts`) — never a task reply, a presentation, a signed document or a key. The gates are `room-page-background.ts` (`RoomPageGates`), the rules -`room-page-policy.ts`, the work `room-page-offscreen.ts`. +`room-page-policy.ts`, the work `room-page-offscreen.ts`. `conversation` hands a +page the room as the reading rules show it (`assembleRoomRecords`), read and +verified by `recordInputFromRead` — the console's own path, so a portal and the +console never disagree about who said what. **Four gates, in order, before the offscreen document does anything.** (1) The call is well formed. (2) The page is the community's portal: every call names diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index 02556b34..4fb846ba 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -38,6 +38,13 @@ For history before this file, see `git log` on `packages/core`. ### Added +- **`recordInputFromRead`** (`@openvtc/pnm-core/rooms`): one listed record and + its `rooms/keys/read` answer made into what `assembleRoomRecords` takes — a + sealed body verified against its author's document at `bodyStoredAt`, the + place it was sealed for and the author the host listed; an open room's + cleartext checked; a failed read `unreadable`; no body a tombstone. The + wallet's console and the member-portal `rooms.conversation` now share it. + - **Checking a vote after close** (VTI-VOT-053). `pcsVoterReceiptsList` (`vta/pcs/voter/receipts/list/0.1`) reads the receipts the member's VTA keeps for an election and its ballot box; `fetchInclusion` asks the ballot diff --git a/packages/core/src/rooms/index.ts b/packages/core/src/rooms/index.ts index 1b62bf81..47c6cce1 100644 --- a/packages/core/src/rooms/index.ts +++ b/packages/core/src/rooms/index.ts @@ -85,6 +85,9 @@ async function call( import { ROOMS_MEMBER_EXT, memberExt } from "./member.js"; export { ROOMS_MEMBER_EXT, memberExt }; +import { base64url } from "@openvtc/vti-didcomm-js"; +import { RecordBodyError, verifyRecordBody, type ResolveDidAt, type VerifiedRecordBody } from "./record-body.js"; +import { contentFromBody, readingFromCleartext, type RecordInput } from "./record-view.js"; export type { PersonalLabel }; @@ -695,6 +698,105 @@ export async function roomsKeysReadMany( return params.keys.map((key) => answers.get(key)!); } +/** One row of a room's listing (`rooms/keys/browse/0.4`, `RecordMetadataV3`), as {@link recordInputFromRead} reads it. */ +export interface ListedRecord { + key: string; + version: number; + status?: string; + updatedAt?: string; + author?: string; + createdAt?: string; + createdBy?: string; + bodyStoredAt?: string; + /** Served on an `open` room's listing only. */ + kind?: string; +} + +/** + * One listed record and its read answer, made into what the reading rules take + * (`assembleRoomRecords`) — the one place a surface turns a read into a + * {@link RecordInput}, so the wallet's console and a community's portal show a + * room alike. + * + * A sealed body is verified before anything of it is read (`SealedRecordBody`, + * *Reading*): the author's proof against their DID document as it stood at + * `bodyStoredAt` (`resolveDidAt`, shared by one listing's reads), the room, key + * and the version it was sealed at, and — where the host named one, on the read + * or the listing for the same version — that the signer is that author. A body + * that fails is `refused`, or a `placeholder` where its author cannot be + * verified; `reasonOf` words why (default: the error's message). An open room's + * cleartext is checked by `readingFromCleartext`. No answer, or a retracted + * record, is a tombstone; a failed read is `unreadable`. + * + * `body` is the verified sealed body, `cleartext` the open room's, for a + * surface that shows more of a record than the reading rules carry (its file). + */ +export async function recordInputFromRead( + roomId: string, + row: ListedRecord, + res: ReadManyResult | undefined, + resolveDidAt: ResolveDidAt, + reasonOf: (e: unknown) => string = (e) => (e instanceof Error ? e.message : String(e)), +): Promise<{ input: RecordInput; body?: VerifiedRecordBody; cleartext?: Record }> { + const version = res?.version ?? row.version; + const status = res?.status ?? row.status; + const updatedAt = res?.updatedAt ?? row.updatedAt; + const createdAt = res?.createdAt ?? row.createdAt; + const createdBy = res?.createdBy ?? row.createdBy; + const bodyStoredAt = res?.bodyStoredAt ?? row.bodyStoredAt; + const meta = { + key: row.key, + version, + ...(status !== undefined ? { status } : {}), + ...(updatedAt !== undefined ? { updatedAt } : {}), + ...(createdAt !== undefined ? { createdAt } : {}), + ...(createdBy !== undefined ? { createdBy } : {}), + ...(bodyStoredAt !== undefined ? { bodyStoredAt } : {}), + ...(row.kind !== undefined ? { listedKind: row.kind } : {}), + }; + if (res === undefined) return { input: { ...meta, reading: { state: "tombstone" } } }; + if (res.error) { + return { input: { ...meta, reading: { state: "unreadable", reason: res.error.message ?? res.error.code } } }; + } + // The listing's word, used only for the version it listed. + const sameVersion = version === row.version; + const hostAuthor = res.author ?? (sameVersion ? row.author : undefined); + if (res.plaintext !== undefined) { + try { + let bytes: Uint8Array; + try { + bytes = base64url.decode(res.plaintext); + } catch { + throw new RecordBodyError("malformed", "the record body is not base64url"); + } + const body = await verifyRecordBody( + bytes, + { roomId, key: row.key, version: readSealedVersion({ version, ...(res.ext !== undefined ? { ext: res.ext } : {}) }) }, + res.author, + { resolveDidAt, ...(bodyStoredAt !== undefined ? { bodyStoredAt } : {}) }, + ); + const listedAuthor = sameVersion ? row.author : undefined; + if (listedAuthor !== undefined && listedAuthor !== body.author) { + throw new RecordBodyError( + "authorMismatch", + `the record body is signed by ${body.author}, but the host listed ${listedAuthor} as its author`, + ); + } + if (body.roomProfile) return { input: { ...meta, reading: { state: "profile" } }, body }; + return { input: { ...meta, reading: { state: "read", content: contentFromBody(body) } }, body }; + } catch (e) { + const state = e instanceof RecordBodyError && e.placeholder ? "placeholder" : "refused"; + return { input: { ...meta, reading: { state, reason: reasonOf(e) } } }; + } + } + if (res.cleartext) { + const reading = readingFromCleartext(res.cleartext, hostAuthor ?? createdBy ?? "", version); + return { input: { ...meta, reading }, cleartext: res.cleartext }; + } + // A retracted record has no body, and that is an answer rather than a failure. + return { input: { ...meta, reading: { state: "tombstone" } } }; +} + /** * Ask this agent to list a room's records at its host, and to check the listing * against what the host committed to. diff --git a/packages/extension/src/bridge-protocol.ts b/packages/extension/src/bridge-protocol.ts index d814c027..fcc0bb7f 100644 --- a/packages/extension/src/bridge-protocol.ts +++ b/packages/extension/src/bridge-protocol.ts @@ -2485,6 +2485,9 @@ export type RoomsPageOp = | { op: "info"; hostDid: string; roomId: string } | { op: "browse"; hostDid: string; roomId: string; prefix?: string; sinceVersion?: number } | { op: "read"; hostDid: string; roomId: string; key: string } + /** The room as a reader shows it: every record listed, read, verified and + * put through the reading rules (`assembleRoomRecords`). Never prompts. */ + | { op: "conversation"; hostDid: string; roomId: string } /** This community's offers of its rooms to the identities the member uses here. Never prompts. */ | { op: "offers"; hostDid: string } /** Ask to accept one: the member decides in the wallet's own window. `member` @@ -2646,6 +2649,56 @@ export interface PageRecordView { verification: unknown; } +/** + * One record of `rooms.conversation`, as the reading rules show it + * (`RoomRecordView`, `@openvtc/pnm-core/rooms`). Only a `note` and a `message` + * carry content; every other `shown` carries none of the record. Every text + * member is another member's words: plain text on a message, markdown rendered + * inert on a note, and never a link the page follows unasked. + */ +export interface PageConversationRecord { + key: string; + version: number; + status?: string; + shown: "note" | "message" | "withdrawn" | "retracted" | "placeholder" | "refused" | "unreadable"; + /** The verified signer (sealed), or the host's record of the writer (`open`). */ + author?: string; + title?: string; + description?: string; + body?: string; + tags?: string[]; + /** The record carries a file: what the page shows of it. Fetched with `getFile`. */ + file?: { name: string; mediaType?: string; size: number }; + /** When it was written, as far as the reading rules let it be said: `at` the + * author's claim where plausible; `implausible` with no time; `arrivedLate` + * when the claim is more than 24 hours before the room received it. */ + written: { at?: string; implausible?: true; arrivedLate?: { claimed: string; received: string } }; + /** The instant it is ordered by (ISO), and which one that is. */ + orderAt: string; + orderedBy: "writtenAt" | "createdAt" | "updatedAt" | "readAt"; + /** This version is an edit; `at` absent when the claim is implausible. */ + edited?: { at?: string }; + /** The record this one answers; `available: false` when it cannot be shown. */ + replyTo?: { key: string; version?: number; available: boolean; changed?: "edited" }; + /** Reactions to it, each value counted once per author. */ + reactions: { value: string; count: number; authors: string[] }[]; + /** A version by someone other than the record's earlier author: never shown as theirs. */ + rewrite?: { by: string; original: string }; + /** Why it is refused, unreadable or a placeholder. */ + reason?: string; +} + +/** `rooms.conversation`: the room's records, oldest first, and its members' own names. */ +export interface PageConversationView { + records: PageConversationRecord[]; + /** Each author's name in this room, by DID, as they gave it themselves (`memberProfile`). Their claim, not a verified name. */ + names: Record; + /** False when the listing stopped at a page bound: older records are missing. */ + complete: boolean; + /** The member's VTA's account of the listing. A verdict, never a failure. */ + verification: unknown; +} + /** 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; @@ -3598,6 +3651,7 @@ export type OffscreenRoomsPageOp = | { op: "info"; hostDid: string; roomId: string; member: string } | { op: "browse"; hostDid: string; roomId: string; member: string; prefix?: string; sinceVersion?: number } | { op: "read"; hostDid: string; roomId: string; member: string; key: string } + | { op: "conversation"; hostDid: string; roomId: string; member: string } | { op: "putNote"; hostDid: string; diff --git a/packages/extension/src/manager/panes/rooms-records.tsx b/packages/extension/src/manager/panes/rooms-records.tsx index 7cf4aa5a..ae1b4a30 100644 --- a/packages/extension/src/manager/panes/rooms-records.tsx +++ b/packages/extension/src/manager/panes/rooms-records.tsx @@ -60,13 +60,10 @@ import { memoResolveDidDocumentAt } from "@openvtc/pnm-core"; import { assembleRoomRecords, authorLabels, - contentFromBody, - readingFromCleartext, - readSealedVersion, + recordInputFromRead, RecordBodyError, roomsKeysBrowse, roomsKeysReadMany, - verifyRecordBody, latestMessageTime, unreadMessages, watchCovers, @@ -78,7 +75,6 @@ import { type RecordInput, type RoomRecordsView, type RoomRecordView, - type VerifiedRecordBody, } from "@openvtc/pnm-core/rooms"; import { base64url } from "@openvtc/vti-didcomm-js"; import type { RoomPlace } from "../room-groups.js"; @@ -341,41 +337,6 @@ function refusalWords(e: unknown): string { return e instanceof Error ? e.message : String(e); } -/** - * Verify a sealed body before anything in it is read (`SealedRecordBody`, - * *Reading*). `hostAuthor` is the read's author; `listedAuthor` the listing's - * for the same version — both are the host's, and on an `attributed` room both - * must be the signer. `bodyStoredAt` is when the host stored this body: the - * author's DID document is the one that stood then (*Which DID document*), - * resolved by `resolveDidAt` where the author's method keeps its history. - */ -async function verifySealed( - plaintext: string, - at: { roomId: string; key: string; version: number }, - hostAuthor: string | undefined, - listedAuthor: string | undefined, - bodyStoredAt: string | undefined, - resolveDidAt: ResolveDidAt, -): Promise { - let bytes: Uint8Array; - try { - bytes = base64url.decode(plaintext); - } catch { - throw new RecordBodyError("malformed", "the record body is not base64url"); - } - const body = await verifyRecordBody(bytes, at, hostAuthor, { - resolveDidAt, - ...(bodyStoredAt !== undefined ? { bodyStoredAt } : {}), - }); - if (listedAuthor !== undefined && listedAuthor !== body.author) { - throw new RecordBodyError( - "authorMismatch", - `the record body is signed by ${body.author}, but the host listed ${listedAuthor} as its author`, - ); - } - return body; -} - /** * An open room's cleartext with its file's `fileKey` left out. The key is in the * record by design — the host and every member may open the file — but nobody @@ -406,56 +367,14 @@ async function readOne( resolveDidAt: ResolveDidAt, ): Promise<{ opened: Opened; input: RecordInput }> { const verification = (res.verification as unknown as Verification | undefined) ?? null; - const version = res.version ?? row.version; - const meta = { - key: row.key, - version, - ...((res.status ?? row.status) !== undefined ? { status: res.status ?? row.status } : {}), - ...((res.updatedAt ?? row.updatedAt) !== undefined ? { updatedAt: res.updatedAt ?? row.updatedAt } : {}), - ...((res.createdAt ?? row.createdAt) !== undefined ? { createdAt: res.createdAt ?? row.createdAt } : {}), - ...((res.createdBy ?? row.createdBy) !== undefined ? { createdBy: res.createdBy ?? row.createdBy } : {}), - ...((res.bodyStoredAt ?? row.bodyStoredAt) !== undefined ? { bodyStoredAt: res.bodyStoredAt ?? row.bodyStoredAt } : {}), - ...(row.kind !== undefined ? { listedKind: row.kind } : {}), - }; - const nothing = { text: "", signed: false, verification }; - if (res.error) { - const why = res.error.message ?? res.error.code; - return { opened: nothing, input: { ...meta, reading: { state: "unreadable", reason: why } } }; + const { input, body, cleartext } = await recordInputFromRead(roomId, row, res, resolveDidAt, refusalWords); + if (body !== undefined && !body.roomProfile && res.plaintext !== undefined) { + return { opened: { text: new TextDecoder().decode(base64url.decode(res.plaintext)), signed: true, verification }, input }; } - // The listing's word, used only for the version it listed. - const sameVersion = version === row.version; - const hostAuthor = res.author ?? (sameVersion ? row.author : undefined); - if (res.plaintext !== undefined) { - // Sealed: nothing of the body before its author's signature holds. - try { - const verified = await verifySealed( - res.plaintext, - { roomId, key: row.key, version: readSealedVersion({ version, ...(res.ext !== undefined ? { ext: res.ext } : {}) }) }, - res.author, - sameVersion ? row.author : undefined, - res.bodyStoredAt ?? (sameVersion ? row.bodyStoredAt : undefined), - resolveDidAt, - ); - if (verified.roomProfile) return { opened: nothing, input: { ...meta, reading: { state: "profile" } } }; - return { - opened: { text: new TextDecoder().decode(base64url.decode(res.plaintext)), signed: true, verification }, - input: { ...meta, reading: { state: "read", content: contentFromBody(verified) } }, - }; - } catch (e) { - const reason = refusalWords(e); - const state = e instanceof RecordBodyError && e.placeholder ? "placeholder" : "refused"; - return { opened: nothing, input: { ...meta, reading: { state, reason } } }; - } - } - if (res.cleartext) { - const reading = readingFromCleartext(res.cleartext, hostAuthor ?? meta.createdBy ?? "", version); - return { - opened: { text: JSON.stringify(withoutFileKey(res.cleartext), null, 2), signed: false, verification }, - input: { ...meta, reading }, - }; + if (cleartext !== undefined) { + return { opened: { text: JSON.stringify(withoutFileKey(cleartext), null, 2), signed: false, verification }, input }; } - // A retracted record has no body, and that is an answer rather than a failure. - return { opened: nothing, input: { ...meta, reading: { state: "tombstone" } } }; + return { opened: { text: "", signed: false, verification }, input }; } /** What a reply line calls the record it answers. */ diff --git a/packages/extension/src/provider.ts b/packages/extension/src/provider.ts index c195963a..946aad8b 100644 --- a/packages/extension/src/provider.ts +++ b/packages/extension/src/provider.ts @@ -51,6 +51,7 @@ import type { PageRoomView, PageRoomInfoView, PageListingView, + PageConversationView, PageRecordView, RoomFilesPageMessage, } from "./bridge-protocol.js"; @@ -355,6 +356,11 @@ export interface VtaWalletRooms { epoch?: number; resumed: boolean; }>; + /** The room as a reader shows it — its records listed, read, verified and put + * through the reading rules: notes and messages, replies, reactions, + * withdrawals, `writtenAt` ordering, edits, and members' own names. Oldest + * first. Never prompts. */ + conversation(params: { hostDid: string; roomId: string }): Promise; /** Write a note as the member, after they confirm it. */ putNote(params: { hostDid: string; @@ -667,6 +673,7 @@ if (!window.vtaWallet) { info: (p) => call("rooms", { op: "info", hostDid: p.hostDid, roomId: p.roomId }), browse: (p) => call("rooms", { ...p, op: "browse" }), 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" }), offers: (p) => call("rooms", { op: "offers", hostDid: p.hostDid }), acceptOffer: (p) => diff --git a/packages/extension/src/room-page-background.ts b/packages/extension/src/room-page-background.ts index e2d95fe7..c449f534 100644 --- a/packages/extension/src/room-page-background.ts +++ b/packages/extension/src/room-page-background.ts @@ -232,7 +232,8 @@ export class RoomPageGates { } case "info": case "browse": - case "read": { + case "read": + case "conversation": { const { vta } = await this.atPortal(origin, p.hostDid, { needReach: true }); const member = await this.granted(origin, p.hostDid, vta, p.roomId); // Rebuilt member by member: nothing the page added rides along. @@ -243,7 +244,9 @@ export class RoomPageGates { ? { op: "info", ...at } : p.op === "read" ? { op: "read", ...at, key: p.key } - : { + : p.op === "conversation" + ? { op: "conversation", ...at } + : { op: "browse", ...at, ...(p.prefix !== undefined ? { prefix: p.prefix } : {}), diff --git a/packages/extension/src/room-page-offscreen.ts b/packages/extension/src/room-page-offscreen.ts index f40f6338..b1d143be 100644 --- a/packages/extension/src/room-page-offscreen.ts +++ b/packages/extension/src/room-page-offscreen.ts @@ -15,7 +15,7 @@ // persona (`@openvtc/pnm-core/rooms`'s `actAndSend`); the VTA's own reads // (`rooms/keys/{browse,read}`) go out as the persona too. -import { CONTACT_METHODS, resolveDidDocumentAt, type TrustTaskSender } from "@openvtc/pnm-core"; +import { CONTACT_METHODS, memoResolveDidDocumentAt, resolveDidDocumentAt, type TrustTaskSender } from "@openvtc/pnm-core"; import { resolveCommunityDocument, selectSignInServices, verifyDomainLinkage } from "@openvtc/pnm-core/vtc"; import { communityRoomMemberships, @@ -24,9 +24,15 @@ import { roomInfoAsMember, roomNamesFromOffers, type CommunityRoomName, + assembleRoomRecords, + recordInputFromRead, roomsKeysBrowse, roomsKeysList, roomsKeysRead, + roomsKeysReadMany, + type ListedRecord, + type ReadManyResult, + type RoomRecordView, readSealedVersion, roomProfileView, roomsKeysProfileRead, @@ -39,6 +45,8 @@ import { base64url } from "@openvtc/vti-didcomm-js"; import { admittedOpenRooms, membersAt } from "./room-page-policy.js"; import type { OffscreenRoomsPageOp, + PageConversationRecord, + PageConversationView, PageListingView, PageRecordSummary, PageRecordView, @@ -231,6 +239,18 @@ export async function runRoomsPageOp( verification: listing.verification, } satisfies PageListingView; } + case "conversation": { + const at = { ...parties, roomId: op.roomId, host: op.hostDid, member: op.member }; + 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 }); + return { + ...(await conversationView(op.roomId, rows, answers, memoResolveDidDocumentAt(), now())), + complete: listing.complete === true, + verification: listing.verification, + } satisfies PageConversationView; + } case "read": return readView( op.roomId, @@ -267,6 +287,70 @@ export async function runRoomsPageOp( } } +/** + * A room's listing and its batch read, as the reading rules show it: each + * record verified (`recordInputFromRead` — the wallet console's own path), then + * `assembleRoomRecords`. Records past their `validUntil` are left out, as a + * default listing leaves them; members' names travel apart from the records, + * and a name record is never one of them. + */ +export async function conversationView( + roomId: string, + rows: readonly ListedRecord[], + answers: readonly ReadManyResult[], + resolveDidAt: ResolveDidAt, + now: number, +): Promise> { + const byKey = new Map(answers.map((a) => [a.key, a])); + const files = new Map>(); + const inputs = await Promise.all( + rows.map(async (row) => { + const { input, body, cleartext } = await recordInputFromRead(roomId, row, byKey.get(row.key), resolveDidAt); + const f = body?.file ?? (cleartext?.file && typeof cleartext.file === "object" ? (cleartext.file as Record) : undefined); + // What the page shows of a file — never an open room's `fileKey`. + if (f && typeof f.name === "string" && typeof f.size === "number" && Number.isSafeInteger(f.size) && f.size >= 0) { + files.set(row.key, { name: f.name, size: f.size, ...(typeof f.mediaType === "string" ? { mediaType: f.mediaType } : {}) }); + } + return input; + }), + ); + const view = assembleRoomRecords(inputs, { now }); + const names: Record = {}; + for (const [author, record] of Object.entries(view.names)) { + if (record.name !== undefined) names[author] = record.name; + } + return { records: view.records.map((r) => conversationRecord(r, files.get(r.key))), names }; +} + +function conversationRecord(r: RoomRecordView, file: PageConversationRecord["file"]): PageConversationRecord { + const c = r.content; + const shows = r.shown === "note" || r.shown === "message"; + return { + key: r.key, + version: r.version, + ...(r.status !== undefined ? { status: r.status } : {}), + shown: r.shown, + ...(c && shows ? { author: c.author } : {}), + ...(c?.title !== undefined && shows ? { title: c.title } : {}), + ...(c?.description !== undefined && shows ? { description: c.description } : {}), + ...(c?.body !== undefined && shows ? { body: c.body } : {}), + ...(c?.tags !== undefined && shows ? { tags: [...c.tags] } : {}), + ...(file !== undefined && shows ? { file } : {}), + written: { + ...(r.written.at !== undefined ? { at: r.written.at } : {}), + ...(r.written.implausible ? { implausible: true as const } : {}), + ...(r.written.arrivedLate !== undefined ? { arrivedLate: { ...r.written.arrivedLate } } : {}), + }, + orderAt: new Date(r.orderAt).toISOString(), + orderedBy: r.orderedBy, + ...(r.edited !== undefined ? { edited: { ...r.edited } } : {}), + ...(r.replyTo !== undefined ? { replyTo: { ...r.replyTo } } : {}), + reactions: r.reactions.map((x) => ({ value: x.value, count: x.count, authors: [...x.authors] })), + ...(r.rewrite !== undefined ? { rewrite: { ...r.rewrite } } : {}), + ...(r.reason !== undefined ? { reason: r.reason } : {}), + }; +} + /** A listing row, member by member: nothing the host sent beyond these. */ function summary(r: Record): PageRecordSummary { const out: PageRecordSummary = { diff --git a/packages/extension/src/room-page-policy.ts b/packages/extension/src/room-page-policy.ts index d052e168..2d65ad33 100644 --- a/packages/extension/src/room-page-policy.ts +++ b/packages/extension/src/room-page-policy.ts @@ -346,7 +346,7 @@ function tags(v: unknown): string | null { return null; } -const OPS = new Set(["list", "choose", "forget", "info", "browse", "read", "putNote", "offers", "acceptOffer"]); +const OPS = new Set(["list", "choose", "forget", "info", "browse", "read", "conversation", "putNote", "offers", "acceptOffer"]); /** 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 { diff --git a/packages/extension/tests/room-page.test.mts b/packages/extension/tests/room-page.test.mts index 4475b6bf..60c24bf2 100644 --- a/packages/extension/tests/room-page.test.mts +++ b/packages/extension/tests/room-page.test.mts @@ -40,7 +40,7 @@ import { type RoomShareConsentView, type RoomWriteConsentView, } from "../src/room-page-policy.ts"; -import { readView, runRoomsPageOp } from "../src/room-page-offscreen.ts"; +import { conversationView, readView, runRoomsPageOp } from "../src/room-page-offscreen.ts"; import { signRecordBody } from "@openvtc/pnm-core/rooms/files"; import type { RoomProfileSummary } from "../src/bridge-protocol.ts"; import { signingIdentityFromSecret } from "@openvtc/pnm-core"; @@ -388,6 +388,9 @@ test("list never prompts, and reads need a share", async () => { assert.equal(read.ok, false); assert.equal((read as { code?: string }).code, "notShared"); assert.ok(!h.asked.some((a) => a.op === "read")); + const chat = await h.gates.handle(PORTAL, { op: "conversation", hostDid: HOST, roomId: ROOM }); + assert.equal((chat as { code?: string }).code, "notShared", "a conversation needs a share like a read"); + assert.ok(!h.asked.some((a) => a.op === "conversation")); h.answer = { approved: true, selectedRooms: [as(ROOM)] }; await h.gates.handle(PORTAL, { op: "choose", hostDid: HOST }); @@ -582,6 +585,81 @@ test("an open room's file reaches the page as its name, size and type — never assert.ok(!JSON.stringify(view).includes("K".repeat(43)), "the key stays with the wallet"); }); +// ── A room as a conversation (`rooms.conversation`) ──────────────────────── +// +// The reading rules' view, built by the same path the wallet's console reads a +// room with: who said what, in which order, under whose own name. + +test("a conversation: messages and notes by kind, in writtenAt order, under members' own names", async () => { + const alice = signingIdentityFromSecret(new Uint8Array(32).fill(4)); + const sealed = async (key: string, body: Record) => ({ + key, + version: 1, + status: "active", + updatedAt: "2026-11-17T23:54:30Z", + createdAt: "2026-11-17T23:54:30Z", + author: alice.did, + plaintext: Buffer.from(await signRecordBody({ roomId: ROOM, key, version: 1, author: alice.did, ...body }, alice)).toString("base64url"), + verification: {}, + }); + const answers = [ + await sealed("hi", { kind: "message", body: "Hi", writtenAt: "2026-11-17T23:54:00Z" }), + await sealed("q", { body: "Do you have correlation off?", writtenAt: "2026-11-17T23:54:10Z" }), + await sealed("note", { title: "test1", body: "the note", writtenAt: "2026-11-24T17:18:00Z" }), + await sealed("name", { kind: "memberProfile", title: "Alberto Leon" }), + await sealed("thumb", { kind: "reaction", body: "👍", inReplyTo: { key: "hi" }, writtenAt: "2026-11-17T23:55:00Z" }), + { key: "forged", error: { code: "x", message: "the agent could not open it" } }, + ]; + // The listing in key order: the reading rules, not the listing, put them in order. + const rows = answers + .map((a) => ({ key: a.key, version: 1, status: "active", updatedAt: "2026-11-17T23:54:30Z" })) + .sort((a, b) => a.key.localeCompare(b.key)); + const view = await conversationView(ROOM, rows, answers as never, async () => undefined, Date.parse("2026-11-24T18:00:00Z")); + + assert.deepEqual(view.names, { [alice.did]: "Alberto Leon" }); + const shown = view.records.map((r) => [r.key, r.shown]); + assert.deepEqual(shown, [ + ["hi", "message"], + ["q", "message"], + // One that did not open keeps its place by the host's time, with nothing of it. + ["forged", "unreadable"], + ["note", "note"], + ], "the name and the reaction are records of no row; an untitled record without a kind is a message"); + const hi = view.records.find((r) => r.key === "hi")!; + assert.equal(hi.body, "Hi"); + assert.equal(hi.author, alice.did); + assert.equal(hi.written.at, "2026-11-17T23:54:00Z"); + assert.deepEqual(hi.reactions, [{ value: "👍", count: 1, authors: [alice.did] }]); + assert.equal(view.records.find((r) => r.key === "note")!.title, "test1"); + const forged = view.records.find((r) => r.key === "forged")!; + assert.equal(forged.body, undefined); + assert.equal(forged.author, undefined, "nothing of a record that did not open"); +}); + +test("a conversation refuses a body its author did not sign for this place, and shows an open room's file without its key", async () => { + const alice = signingIdentityFromSecret(new Uint8Array(32).fill(4)); + const relocated = Buffer.from( + await signRecordBody({ roomId: ROOM, key: "elsewhere", version: 1, author: alice.did, kind: "message", body: "moved" }, alice), + ).toString("base64url"); + const answers = [ + { key: "k", version: 1, status: "active", updatedAt: "2026-11-24T10:00:00Z", author: alice.did, plaintext: relocated, verification: {} }, + { + key: "f", version: 1, status: "active", updatedAt: "2026-11-24T11:00:00Z", author: MEMBER, verification: {}, + cleartext: { title: "Brochure", body: "", file: { name: "b.pdf", size: 42, blobRef: "zBlob", fileKey: "K".repeat(43) } }, + }, + ]; + const rows = answers.map((a) => ({ key: a.key, version: 1, status: "active", updatedAt: a.updatedAt })); + const view = await conversationView(ROOM, rows, answers as never, async () => undefined, Date.parse("2026-11-24T18:00:00Z")); + const k = view.records.find((r) => r.key === "k")!; + assert.equal(k.shown, "refused"); + assert.equal(k.body, undefined); + const f = view.records.find((r) => r.key === "f")!; + assert.equal(f.shown, "note"); + assert.equal(f.author, MEMBER); + assert.deepEqual(f.file, { name: "b.pdf", size: 42 }); + assert.ok(!JSON.stringify(view).includes("K".repeat(43)), "the key stays with the wallet"); +}); + // trust-tasks-tf #1027: what a record is and where it sits reach the page; a // record past its `validUntil`, or whose author cannot be verified, reaches it // with nothing of its content. @@ -724,9 +802,15 @@ test("a share names its member, and every request for the page carries it", asyn await h.gates.handle(PORTAL, { op: "info", hostDid: HOST, roomId: ROOM }); await h.gates.handle(PORTAL, { op: "browse", hostDid: HOST, roomId: ROOM }); await h.gates.handle(PORTAL, { op: "read", hostDid: HOST, roomId: ROOM, key: "k" }); + await h.gates.handle(PORTAL, { op: "conversation", hostDid: HOST, roomId: ROOM, member: "did:key:zSomeoneElse", extra: 1 }); h.answer = { approved: true }; await h.gates.handle(PORTAL, { op: "putNote", hostDid: HOST, roomId: ROOM, title: "t" }); - for (const op of ["info", "browse", "read", "putNote"]) { + assert.deepEqual( + h.asked.find((a) => a.op === "conversation"), + { op: "conversation", hostDid: HOST, roomId: ROOM, member: MEMBER }, + "the share's member, never the page's, and nothing else the page added", + ); + for (const op of ["info", "browse", "read", "conversation", "putNote"]) { const asked = h.asked.filter((a) => a.op === op); assert.ok(asked.length > 0, op); assert.ok(asked.every((a) => a.member === MEMBER), `${op} names the member`);