Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions packages/core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
102 changes: 102 additions & 0 deletions packages/core/src/rooms/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ async function call<Res>(

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 };

Expand Down Expand Up @@ -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<string, unknown> }> {
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.
Expand Down
54 changes: 54 additions & 0 deletions packages/extension/src/bridge-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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<string, string>;
/** 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;

Expand Down Expand Up @@ -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;
Expand Down
95 changes: 7 additions & 88 deletions packages/extension/src/manager/panes/rooms-records.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,10 @@ import { memoResolveDidDocumentAt } from "@openvtc/pnm-core";
import {
assembleRoomRecords,
authorLabels,
contentFromBody,
readingFromCleartext,
readSealedVersion,
recordInputFromRead,
RecordBodyError,
roomsKeysBrowse,
roomsKeysReadMany,
verifyRecordBody,
latestMessageTime,
unreadMessages,
watchCovers,
Expand All @@ -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";
Expand Down Expand Up @@ -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<VerifiedRecordBody> {
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
Expand Down Expand Up @@ -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. */
Expand Down
7 changes: 7 additions & 0 deletions packages/extension/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import type {
PageRoomView,
PageRoomInfoView,
PageListingView,
PageConversationView,
PageRecordView,
RoomFilesPageMessage,
} from "./bridge-protocol.js";
Expand Down Expand Up @@ -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<PageConversationView>;
/** Write a note as the member, after they confirm it. */
putNote(params: {
hostDid: string;
Expand Down Expand Up @@ -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) =>
Expand Down
Loading