From 45965ad10c5f3287a3bb584679c0c3c87d598be1 Mon Sep 17 00:00:00 2001 From: Glenn Gore Date: Wed, 25 Nov 2026 21:47:09 -0800 Subject: [PATCH] feat(rooms): a member may let a portal react in one room for 30 minutes without asking Every page write is confirmed in the wallet's own window, so a portal chat asked for a confirm on every emoji. The member now chooses, in a reaction's own confirm (made compact: the emoji, the message as the wallet read it, who signs), an unticked box: "let add and remove your reactions in for 30 minutes without asking". - The grant is `reactionsUntil` on the share itself, so it is keyed exactly as the share is (origin, community, VTA, room, member) and ends with it: Stop sharing, the page's `forget`, a fresh `choose`, or the share lapsing. Capped at 30 minutes and at the share's own expiry; never extended by use. - While it is live, `react` / `unreact` from that origin for that room run with no window. Gates 1-3, the value checks and `recordMembersNotListed` still apply. Messages, notes and files are always confirmed. - Only that box on an approval grants it: `deliverConsentResult` passes it only with `approved`, and `requestRoomConsent` only from a prompt that offered it. The page cannot ask for or see a grant; the page contract is unchanged. - The console's Communities tab lists a live grant with the minutes left and a Stop, beside Stop sharing. - CLAUDE.md: "no remember" now names this one bounded exception, and widening it (beyond reactions, one room, 30 minutes, or renewing without the box) joins "What breaks it". Signed-off-by: Glenn Gore --- CLAUDE.md | 24 +- packages/extension/src/background.ts | 20 +- packages/extension/src/bridge-protocol.ts | 4 + packages/extension/src/confirm.tsx | 9 +- packages/extension/src/consent-window.ts | 14 +- .../src/manager/panes/rooms-communities.tsx | 47 +++- .../src/manager/panes/rooms-shares.tsx | 20 +- packages/extension/src/room-consent.tsx | 70 ++++-- .../extension/src/room-page-background.ts | 89 +++++-- packages/extension/src/room-page-policy.ts | 72 +++++- .../tests/room-page-reaction-grant.test.mts | 226 ++++++++++++++++++ .../room-page-reply-react-watch.test.mts | 2 + 12 files changed, 528 insertions(+), 69 deletions(-) create mode 100644 packages/extension/tests/room-page-reaction-grant.test.mts diff --git a/CLAUDE.md b/CLAUDE.md index 8b916c1a..15247d56 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1066,7 +1066,8 @@ call is well formed. (2) The page is the community's portal: every call names that DID document's first usable `SignInPortal`, resolved and verified as the trigger-link sign-in does (domain-linked contacts also need their DID Configuration); host requests go to the same document's `TrustTaskHTTPS`. (3) -The member shared the room with that origin. (4) A write is confirmed. +The member shared the room with that origin. (4) A write is confirmed — the +one exception is a reaction under a live reaction grant (below). **Rooms are shared by the member, one by one, because nothing else can say which rooms a community hosts.** A room's DID names no host (deliberately: a @@ -1118,7 +1119,19 @@ 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". +said about it. Each reaction is confirmed like any write, with one bounded, +revocable exception: the reaction prompt offers an **unticked** box, "let this +portal add and remove your reactions in for 30 minutes" +(`REACTION_GRANT_TTL_MS`). Ticking it sets `reactionsUntil` on the share itself +(`withReactionGrant`), so it is keyed exactly as the share is — origin, +community, VTA, room and member — and ends with it (`Stop sharing`, the page's +`forget`, a fresh `choose`, the share lapsing). While `reactionGrantLive`, a +`react`/`unreact` from that origin for that room runs with no window; gates 1–3, +the value checks and `recordMembersNotListed` still apply. It is never extended +by use, never set by anything but that box on an approval (`deliverConsentResult` +passes it only with `approved`, and `requestRoomConsent` only from a prompt that +offered it), and the console's Communities tab lists it with the minutes left +and a Stop. Messages, notes and files are always confirmed. **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 @@ -1230,7 +1243,8 @@ signed in. **Reads ride the share; every write is confirmed**, in a window naming the room, the persona that will sign and what will be written (title and excerpt, -or file name and size), with no "remember". A file's bytes reach the page only +or file name and size), with no "remember" — except the bounded, revocable +reaction grant (≤30 min, one room, reactions only). A file's bytes reach the page only after the whole file verified against its author's digest: the background holds the offscreen document's provisional pieces and releases them on `got`, and drops them on anything else. @@ -1239,7 +1253,9 @@ drops them on anything else. DID document, or comparing origins loosely; letting a page name a room's host for a room it was not shared; passing a VTA or host reply to the page as is (views are built member by member); a share prompt that the page can -pre-approve, or a write with a "remember" box; posting a provisional download +pre-approve, or a write with a "remember" box (the reaction grant is the one +exception, and widening it — beyond reactions, beyond one room, beyond 30 +minutes, or renewing it without a fresh confirm's box — breaks it too); posting a provisional download byte; offering a room as the community's own DID, or as any identity the member does not use at that community; sending a room request for a page or a console row without naming its member (the VTA refuses, and it must); keying a diff --git a/packages/extension/src/background.ts b/packages/extension/src/background.ts index 758cff26..534204df 100644 --- a/packages/extension/src/background.ts +++ b/packages/extension/src/background.ts @@ -869,21 +869,33 @@ void refreshPendingBadge(); /** Raise a room prompt (share, write or accept an offer) and wait. Closed or unopened is a denial. */ async function requestRoomConsent( view: RoomShareConsentView | RoomWriteConsentView | RoomOfferConsentView, -): Promise<{ approved: boolean; selectedRooms?: string[] }> { +): Promise<{ approved: boolean; selectedRooms?: string[]; reactionGrant?: boolean }> { const consentId = crypto.randomUUID(); await chrome.storage.session.set({ [`${ROOM_CONSENT_PREFIX}${consentId}`]: view }); + // A reaction grant is honoured only from a prompt that offered one. + const offersGrant = view.kind === "write" && "reaction" in view.what && view.what.grant !== undefined; const url = `${chrome.runtime.getURL("confirm.html")}?cid=${consentId}&kind=room`; const bounds = await consentWindowBounds(view.kind === "share" ? 640 : 560); return new Promise((resolve) => { let settled = false; - const settle = (approved: boolean, selectedRooms?: string[]) => { + const settle = (approved: boolean, selectedRooms?: string[], reactionGrant?: boolean) => { if (settled) return; settled = true; pendingConsents.delete(consentId); void chrome.storage.session.remove(`${ROOM_CONSENT_PREFIX}${consentId}`); - resolve(approved ? { approved: true, ...(selectedRooms ? { selectedRooms } : {}) } : { approved: false }); + resolve( + approved + ? { + approved: true, + ...(selectedRooms ? { selectedRooms } : {}), + ...(offersGrant && reactionGrant === true ? { reactionGrant: true } : {}), + } + : { approved: false }, + ); }; - pendingConsents.set(consentId, (approved, _remember, _prf, _did, selectedRooms) => settle(approved, selectedRooms)); + pendingConsents.set(consentId, (approved, _remember, _prf, _did, selectedRooms, _credential, _ballot, reactionGrant) => + settle(approved, selectedRooms, reactionGrant), + ); openConsentWindow({ url, bounds, deny: () => settle(false), tag: "[pnm rooms]", what: "room window" }); }); } diff --git a/packages/extension/src/bridge-protocol.ts b/packages/extension/src/bridge-protocol.ts index 1d57c839..350eba55 100644 --- a/packages/extension/src/bridge-protocol.ts +++ b/packages/extension/src/bridge-protocol.ts @@ -677,6 +677,10 @@ export interface RuntimeConsentResult { * window (`voting/ballot/cast` `Ballot`). Checked again by the background * against the election before anything is built. Ignored on a denial. */ ballot?: unknown; + /** Reaction prompt only: the member ticked "let this portal add and remove + * your reactions in this room for 30 minutes". Ignored on a denial, and on + * any prompt that did not offer it. */ + reactionGrant?: boolean; } /** confirm popup → background: resolve + verify an RP DID. */ diff --git a/packages/extension/src/confirm.tsx b/packages/extension/src/confirm.tsx index acdf9fda..e3d7fe7b 100644 --- a/packages/extension/src/confirm.tsx +++ b/packages/extension/src/confirm.tsx @@ -1488,8 +1488,13 @@ if (root) { ) : isRoomConsent ? ( - void sendConsentResult({ approved: ok, remember: false, ...(ok && rooms ? { selectedRooms: rooms } : {}) }) + decide={(ok, rooms, reactionGrant) => + void sendConsentResult({ + approved: ok, + remember: false, + ...(ok && rooms ? { selectedRooms: rooms } : {}), + ...(ok && reactionGrant === true ? { reactionGrant: true } : {}), + }) } /> ) : isStepUpApproverConsent ? ( diff --git a/packages/extension/src/consent-window.ts b/packages/extension/src/consent-window.ts index 49ff0c19..4aad61b8 100644 --- a/packages/extension/src/consent-window.ts +++ b/packages/extension/src/consent-window.ts @@ -50,6 +50,7 @@ export type ConsentDecision = ( selectedRooms?: string[], selectedCredential?: string, ballot?: unknown, + reactionGrant?: boolean, ) => void; /** The subset of `chrome.windows` this file drives — narrow so a test can @@ -164,6 +165,7 @@ export function deliverConsentResult( selectedRooms?: string[]; selectedCredential?: string; ballot?: unknown; + reactionGrant?: boolean; }, ): boolean { const decision = pending.get(result.consentId); @@ -176,6 +178,16 @@ export function deliverConsentResult( // against the election by the gate that asked for it. const ballot = result.ballot !== null && typeof result.ballot === "object" && !Array.isArray(result.ballot) ? result.ballot : undefined; - decision(result.approved, !!result.remember, result.prfOutputB64u, result.selectedDid, rooms, credential, ballot); + // Only an explicit `true` from the reaction prompt's own box grants anything. + decision( + result.approved, + !!result.remember, + result.prfOutputB64u, + result.selectedDid, + rooms, + credential, + ballot, + result.approved && result.reactionGrant === true, + ); return true; } diff --git a/packages/extension/src/manager/panes/rooms-communities.tsx b/packages/extension/src/manager/panes/rooms-communities.tsx index 53bf2c46..2b4b098b 100644 --- a/packages/extension/src/manager/panes/rooms-communities.tsx +++ b/packages/extension/src/manager/panes/rooms-communities.tsx @@ -20,11 +20,12 @@ // share stops the portal reading the room at once and cannot recall what it was // already shown. -import type { ReactNode } from "react"; +import type { CSSProperties, ReactNode } from "react"; import type { RoomProfileView } from "@openvtc/pnm-core/rooms"; import { displayAgentName, type AgentName } from "../../agent-name.js"; import { didHost } from "../../did-display.js"; import { isActionable, type OfferView } from "../../room-offers-policy.js"; +import { reactionGrantLive } from "../../room-page-policy.js"; import { Button, Did, Note, Pill } from "../../ui.js"; import { c, t } from "../../theme.js"; import { communityLanes, joinedOpen, rowStage, type Lane, type LaneRow } from "../community-lanes.js"; @@ -197,6 +198,22 @@ const WEBSITE_HINT = "The community's member site can list and read this room while you are signed in there. " + "Anything it asks to write is still confirmed in the wallet's own window."; +const linkButton: CSSProperties = { + font: "inherit", + fontSize: t.xs, + fontWeight: 600, + padding: 0, + border: "none", + background: "transparent", + color: c.danger, + cursor: "pointer", +}; + +/** Whole minutes left until `until`, at least 1 while it is live. */ +export function minutesLeft(until: number, now: number): number { + return Math.max(1, Math.ceil((until - now) / 60_000)); +} + function websiteStep(row: LaneRow, shares: RoomSharesState): Step { if (row.shares.length === 0) { return { label: "On its website", hint: WEBSITE_HINT, state: "todo", lines: ["not shared"] }; @@ -205,15 +222,25 @@ function websiteStep(row: LaneRow, shares: RoomSharesState): Step { label: "On its website", hint: WEBSITE_HINT, state: "done", - lines: row.shares.flatMap((s: ShareRow) => [ - `${host(s.grant.origin)} · until ${new Date(s.grant.expiresAt).toLocaleDateString()}`, - , - ]), + lines: row.shares.flatMap((s: ShareRow) => { + const reactions = reactionGrantLive(s.grant, Date.now()) + ? [ + + Reacts without asking for {minutesLeft(s.grant.reactionsUntil!, Date.now())} more min ·{" "} + + , + ] + : []; + return [ + `${host(s.grant.origin)} · until ${new Date(s.grant.expiresAt).toLocaleDateString()}`, + ...reactions, + , + ]; + }), }; } diff --git a/packages/extension/src/manager/panes/rooms-shares.tsx b/packages/extension/src/manager/panes/rooms-shares.tsx index 5a1fa245..e6adf3e1 100644 --- a/packages/extension/src/manager/panes/rooms-shares.tsx +++ b/packages/extension/src/manager/panes/rooms-shares.tsx @@ -4,11 +4,13 @@ // asks (`window.vtaWallet.rooms.choose`), and lasts 30 days. This reads every // live one and revokes any of them; `rooms-communities.tsx` draws each beside // the room it shares. Revoking stops the page reading the room at once; it -// cannot recall what the page was already shown. +// cannot recall what the page was already shown. A share may carry a reaction +// grant (`reactionsUntil`, at most 30 minutes): listed with its time left and +// stopped on its own, and gone with the share. import { useCallback, useEffect, useState } from "react"; -import { ROOM_GRANTS_PREFIX, type RoomGrant } from "../../room-page-policy.js"; +import { ROOM_GRANTS_PREFIX, withoutReactionGrant, type RoomGrant } from "../../room-page-policy.js"; /** One live share, and the storage key it sits under. */ export interface ShareRow { @@ -20,6 +22,8 @@ export interface RoomSharesState { /** `null` while reading. */ shares: ShareRow[] | null; revoke: (row: ShareRow) => Promise; + /** Stop the share's reaction grant, keeping the share. */ + stopReactions: (row: ShareRow) => Promise; } async function readLive(now: number): Promise { @@ -56,5 +60,15 @@ export function useRoomShares(): RoomSharesState { [load], ); - return { shares, revoke }; + const stopReactions = useCallback( + async ({ key, grant }: ShareRow) => { + const current = (await chrome.storage.local.get(key))[key]; + const next = withoutReactionGrant(Array.isArray(current) ? (current as RoomGrant[]) : [], grant, grant.roomId); + await chrome.storage.local.set({ [key]: next }); + await load(); + }, + [load], + ); + + return { shares, revoke, stopReactions }; } diff --git a/packages/extension/src/room-consent.tsx b/packages/extension/src/room-consent.tsx index fd1cb075..5dff7dfb 100644 --- a/packages/extension/src/room-consent.tsx +++ b/packages/extension/src/room-consent.tsx @@ -9,9 +9,11 @@ // is shared here afterwards. A page cannot see this list, only what it is // given. // - **Write**: one note or one file, in one room, signed as the member. The -// prompt says what will be written, and there is no "remember". +// prompt says what will be written, and there is no "remember" — except on a +// reaction, which may offer one bounded, revocable grant: this portal may add +// and take back the member's reactions in this one room for 30 minutes. -import { useEffect, useState } from "react"; +import { useEffect, useId, useState } from "react"; import { requestOriginPermission } from "./host-permissions.js"; import { @@ -86,7 +88,7 @@ export function RoomConsent({ decide, }: { consentId: string; - decide: (approved: boolean, selectedRooms?: string[]) => void; + decide: (approved: boolean, selectedRooms?: string[], reactionGrant?: boolean) => void; }) { const [view, setView] = useState(null); useEffect(() => { @@ -104,7 +106,7 @@ export function RoomConsent({ ) : view.kind === "offer" ? ( ) : ( - + decide(ok, undefined, reactionGrant)} /> )} ); @@ -232,7 +234,13 @@ function Glimpse({ of }: { of: RecordGlimpse }) { ); } -function Write({ view, decide }: { view: RoomWriteConsentView; decide: (approved: boolean) => void }) { +function Write({ + view, + decide, +}: { + view: RoomWriteConsentView; + decide: (approved: boolean, reactionGrant?: boolean) => void; +}) { if ("reaction" in view.what) return ; const isFile = "file" in view.what; const isMessage = "message" in view.what; @@ -315,7 +323,12 @@ function Write({ view, decide }: { view: RoomWriteConsentView; decide: (approved ); } -/** A reaction, or taking one back: short, since it is one value on one record. */ +/** + * A reaction, or taking one back: compact, since it is one value on one record. + * Where the background offers it, one unticked box lets this portal add and take + * back the member's reactions in this one room for a bounded time — never + * messages, notes or files, never another room, never renewed without this box. + */ function React({ view, what, @@ -323,31 +336,44 @@ function React({ }: { view: RoomWriteConsentView; what: Extract; - decide: (approved: boolean) => void; + decide: (approved: boolean, reactionGrant?: boolean) => void; }) { + const [grant, setGrant] = useState(false); + const boxId = useId(); + const room = what.grant?.roomLabel ? `“${what.grant.roomLabel}”` : "this room"; return ( <> - - {what.withdraw ? "Take back your reaction" : "React"} {what.value}{" "} - {what.withdraw ? "from" : "to"} this, as you? + + + + {what.withdraw ? "Take back your reaction" : `React ${what.value}`} 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
-
- -
+
+ Asked by {originHost(view.origin)}. Every member of the room sees it as yours, signed as{" "} + . + {view.visibility === "open" ? " This room is open: its host can see it too." : ""}
-
+ {what.grant && ( + + )} +
- decide(true)}>{what.withdraw ? "Take back" : "React"} + decide(true, what.grant ? grant : undefined)}>{what.withdraw ? "Take back" : "React"}
); diff --git a/packages/extension/src/room-page-background.ts b/packages/extension/src/room-page-background.ts index 3808deaf..7f6af550 100644 --- a/packages/extension/src/room-page-background.ts +++ b/packages/extension/src/room-page-background.ts @@ -11,7 +11,10 @@ // except for `list`, `choose` and `forget`, which manage the shares. // // Writes take a fourth: the member confirms that one write, in the wallet's -// own window, seeing the room, who will sign and what will be written. +// own window, seeing the room, who will sign and what will be written. The one +// exception is a reaction under a live reaction grant (`reactionGrantLive`): +// the member ticked, in a reaction's own confirm, "let this portal react in this +// room for 30 minutes". Gates 1–3 and the record-members check still apply. // // What goes back is a view the offscreen document built; an error is a // sentence, never the agent's or the host's `code` and `details`. @@ -59,6 +62,9 @@ import { type RecordGlimpse, type RoomShareConsentView, type RoomWriteConsentView, + REACTION_GRANT_TTL_MS, + reactionGrantLive, + withReactionGrant, } from "./room-page-policy.js"; /** One entry of the VTA's listing, as the offscreen document reports it — or an @@ -93,8 +99,11 @@ export interface RoomPageBackgroundDeps { canReach(url: string): Promise; loadGrants(origin: string, vtaDid: string): Promise; saveGrants(origin: string, vtaDid: string, grants: RoomGrant[]): Promise; - /** Raise a room prompt and wait. A closed window is a denial. */ - prompt(view: RoomShareConsentView | RoomWriteConsentView): Promise<{ approved: boolean; selectedRooms?: string[] }>; + /** Raise a room prompt and wait. A closed window is a denial. `reactionGrant`: the + * member ticked a reaction prompt's grant box (only ever from a prompt offering one). */ + prompt( + view: RoomShareConsentView | RoomWriteConsentView, + ): Promise<{ approved: boolean; selectedRooms?: string[]; reactionGrant?: boolean }>; /** Open a transfer with the offscreen document (`ROOM_FILES_PORT`). */ openTransfer(): Promise; /** The community's offers of its rooms (`room-offers-background.ts`). Absent: the portal sees none. */ @@ -211,10 +220,34 @@ export class RoomPageGates { /** Gate 3. Returns the member the share acts as: every request for the page names it. */ private async granted(origin: string, hostDid: string, vta: ActiveVta, roomId: string): Promise { + return (await this.share(origin, hostDid, vta, roomId)).member; + } + + /** Gate 3, answering the share itself. */ + private async share(origin: string, hostDid: string, vta: ActiveVta, roomId: string): Promise { const grants = await this.deps.loadGrants(origin, vta.vtaDid); const r = roomGrant(grants, { origin, hostDid, vtaDid: vta.vtaDid }, roomId, this.deps.now()); if (!r.ok) throw new RoomPageRefusal(r.error, "notShared"); - return r.grant.member; + return r.grant; + } + + /** The member's explicit reaction grant, recorded on the share it rides on. */ + private async grantReactions(origin: string, hostDid: string, vta: ActiveVta, roomId: string, member: string): Promise { + const grants = await this.deps.loadGrants(origin, vta.vtaDid); + await this.deps.saveGrants( + origin, + vta.vtaDid, + withReactionGrant(grants, { origin, hostDid, vtaDid: vta.vtaDid }, roomId, member, this.deps.now()), + ); + } + + /** The room's name for a prompt, where the wallet knows one. Never throws. */ + private async roomLabel(vta: ActiveVta, hostDid: string, roomId: string, member: string): Promise { + try { + return (await this.displayNames(vta, hostDid, [member], [{ roomId, member }]))[roomId]?.label; + } catch { + return undefined; + } } /** @@ -394,26 +427,40 @@ export class RoomPageGates { 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 share = await this.share(origin, p.hostDid, vta, p.roomId); + const member = share.member; 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, - hostDid: p.hostDid, - roomId: p.roomId, - member: info.member, - visibility: info.visibility, - what: { reaction: true, value: p.value, on, ...(withdraw ? { withdraw: true as const } : {}) }, - }); - if (!decision.approved) { - throw new RoomPageRefusal( - withdraw ? "the member declined to take back this reaction" : "the member declined to react", - "declined", - ); + // Under a live reaction grant — this origin, this community, this VTA, + // this room, as this member: the share it rides on — no window. Nothing + // else is waived, and nothing extends the grant. + if (!reactionGrantLive(share, this.deps.now())) { + const info = (await this.offscreen(vta, { op: "info", ...at })) as PageRoomInfoView; + const on = await this.glimpse(vta, at, p.key); + const roomLabel = await this.roomLabel(vta, p.hostDid, p.roomId, member); + const decision = await this.deps.prompt({ + kind: "write", + origin, + hostDid: p.hostDid, + roomId: p.roomId, + member: info.member, + visibility: info.visibility, + what: { + reaction: true, + value: p.value, + on, + ...(withdraw ? { withdraw: true as const } : {}), + grant: { minutes: REACTION_GRANT_TTL_MS / 60_000, ...(roomLabel ? { roomLabel } : {}) }, + }, + }); + if (!decision.approved) { + throw new RoomPageRefusal( + withdraw ? "the member declined to take back this reaction" : "the member declined to react", + "declined", + ); + } + if (decision.reactionGrant === true) await this.grantReactions(origin, p.hostDid, vta, p.roomId, member); } return withdraw ? this.offscreen(vta, { op: "unreact", ...at, target: p.key, value: p.value }) diff --git a/packages/extension/src/room-page-policy.ts b/packages/extension/src/room-page-policy.ts index 922c6842..c4c334a8 100644 --- a/packages/extension/src/room-page-policy.ts +++ b/packages/extension/src/room-page-policy.ts @@ -67,6 +67,64 @@ export interface RoomGrant { member: string; grantedAt: number; expiresAt: number; + /** + * Until when this page may add and take back the member's reactions in this + * room without a window (`REACTION_GRANT_TTL_MS` from the confirm that granted + * it). Set only by the member ticking the box in a reaction's own confirm, + * never renewed by use, and gone with the share: revoking, re-sharing or the + * share lapsing ends it. Reactions only — every other write still confirms. + */ + reactionsUntil?: number; +} + +/** How long a reaction grant lasts. Never longer, never extended by use. */ +export const REACTION_GRANT_TTL_MS = 30 * 60 * 1000; + +/** Whether `grant` lets its page react without a window now. */ +export function reactionGrantLive(grant: Pick, now: number): boolean { + const until = grant.reactionsUntil; + return ( + typeof until === "number" && + until > now && + // Never beyond the share, and never more than one grant's length ahead: + // a stored value from anything but `withReactionGrant` grants nothing. + until <= grant.expiresAt && + until - now <= REACTION_GRANT_TTL_MS + ); +} + +/** + * `grants` with the share of `roomId` to `at`, as `member`, granted reactions + * for {@link REACTION_GRANT_TTL_MS} from `now` — the member's explicit choice in + * a reaction's confirm. No share, or a share as another member: unchanged. + */ +export function withReactionGrant( + grants: readonly RoomGrant[], + at: { origin: string; hostDid: string; vtaDid: string }, + roomId: string, + member: string, + now: number, +): RoomGrant[] { + return grants.map((g) => + g.origin === at.origin && g.hostDid === at.hostDid && g.vtaDid === at.vtaDid && g.roomId === roomId && g.member === member + ? { ...g, reactionsUntil: Math.min(now + REACTION_GRANT_TTL_MS, g.expiresAt) } + : g, + ); +} + +/** `grants` with the share of `roomId` to `at` keeping its share but no reaction grant. */ +export function withoutReactionGrant( + grants: readonly RoomGrant[], + at: { origin: string; hostDid: string; vtaDid?: string }, + roomId: string, +): RoomGrant[] { + return grants.map((g) => { + if (!(g.origin === at.origin && g.hostDid === at.hostDid && (at.vtaDid === undefined || g.vtaDid === at.vtaDid) && g.roomId === roomId)) { + return g; + } + const { reactionsUntil: _gone, ...rest } = g; + return rest; + }); } // ── The names of a community's rooms ─────────────────────────────────────── @@ -519,8 +577,18 @@ export interface RoomWriteConsentView { /** 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 } + /** + * A reaction, or (`withdraw`) taking one back, on the record the wallet read. + * `grant`: the prompt may offer to let this page react in this room without + * asking for `minutes`, naming the room by `roomLabel` where the wallet knows it. + */ + | { + reaction: true; + value: string; + withdraw?: true; + on: RecordGlimpse; + grant?: { minutes: number; roomLabel?: string }; + } | { file: true; name: string; size: number; mediaType?: string; title?: string }; } diff --git a/packages/extension/tests/room-page-reaction-grant.test.mts b/packages/extension/tests/room-page-reaction-grant.test.mts new file mode 100644 index 00000000..5d8b8fed --- /dev/null +++ b/packages/extension/tests/room-page-reaction-grant.test.mts @@ -0,0 +1,226 @@ +// A reaction grant: the one bounded, revocable exception to "every page write is +// confirmed" (P7b; VTI `data-rooms-files.md` §8.5). +// +// In a reaction's own confirm the member may tick "let this portal add and +// remove your reactions in this room for 30 minutes". Only that box grants it; +// it rides on the share (this origin, community, VTA, room and member), is never +// extended by use, and ends with the share. Reactions only: a message or a note +// under a live grant is still confirmed, and every other gate still applies. + +import test from "node:test"; +import assert from "node:assert/strict"; + +import { deliverConsentResult, type ConsentDecision } from "../src/consent-window.ts"; +import { RoomPageGates, type PortLike, type RoomPageBackgroundDeps } from "../src/room-page-background.ts"; +import { + REACTION_GRANT_TTL_MS, + reactionGrantLive, + withGrants, + withReactionGrant, + withoutGrant, + withoutReactionGrant, + type RoomGrant, + type RoomShareConsentView, + type RoomWriteConsentView, +} from "../src/room-page-policy.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 ROOM2 = "did:webvh:QmRoom2:rooms.example"; +const MEMBER = "did:webvh:QmAlice:people.example"; +const BOB = "did:webvh:QmBob:people.example"; +const T0 = 1_800_000_000_000; +const AT = { origin: PORTAL, hostDid: HOST, vtaDid: VTA }; + +function share(roomId: string, member = MEMBER, extra: Partial = {}): RoomGrant { + return { ...AT, roomId, member, grantedAt: T0 - 1000, expiresAt: T0 + 30 * 86_400_000, ...extra }; +} + +interface Harness { + gates: RoomPageGates; + prompts: (RoomShareConsentView | RoomWriteConsentView)[]; + asked: { op: string; [k: string]: unknown }[]; + answer: { approved: boolean; reactionGrant?: boolean }; + grants: RoomGrant[]; + now: number; +} + +function harness(grants: RoomGrant[] = [share(ROOM), share(ROOM2)]): Harness { + const h: Harness = { gates: undefined as never, prompts: [], asked: [], answer: { approved: true }, grants, now: T0 }; + 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: ["kind", "inReplyTo", "writtenAt"] }; + 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?" }, + }; + default: + return { ok: true, result: { did: op.op } }; + } + }, + canReach: async () => true, + loadGrants: async () => h.grants, + saveGrants: async (_o, _v, g) => { + h.grants = g; + }, + prompt: async (view) => { + h.prompts.push(view); + return h.answer; + }, + openTransfer: async () => ({}) as PortLike, + now: () => h.now, + }; + h.gates = new RoomPageGates(deps); + return h; +} + +const react = (h: Harness, roomId = ROOM, op: "react" | "unreact" = "react") => + h.gates.handle(PORTAL, { op, hostDid: HOST, roomId, key: "m1", value: "👍" }); +const writes = (h: Harness) => h.asked.filter((a) => ["putMessage", "putNote", "react", "unreact"].includes(a.op)); + +test("the reaction prompt offers the grant, unticked, for 30 minutes", async () => { + const h = harness(); + await react(h); + const what = (h.prompts[0] as RoomWriteConsentView).what as { grant?: { minutes: number } }; + assert.deepEqual(what.grant, { minutes: 30 }); + assert.equal(REACTION_GRANT_TTL_MS, 30 * 60 * 1000); +}); + +test("only the explicit box grants: an approval without it leaves every reaction confirmed", async () => { + const h = harness(); + h.answer = { approved: true }; + assert.ok((await react(h)).ok); + assert.ok((await react(h)).ok); + assert.equal(h.prompts.length, 2); + assert.equal(h.grants.find((g) => g.roomId === ROOM)!.reactionsUntil, undefined); +}); + +test("a denial with the box ticked grants nothing, at the consent window too", async () => { + const h = harness(); + h.answer = { approved: false, reactionGrant: true }; + const res = await react(h); + assert.equal((res as { code?: string }).code, "declined"); + assert.equal(h.grants.find((g) => g.roomId === ROOM)!.reactionsUntil, undefined); + // The consent window itself never passes a grant on a denial. + const got: unknown[][] = []; + const pending = new Map([["c1", (...a) => void got.push(a)]]); + deliverConsentResult(pending, { consentId: "c1", approved: false, reactionGrant: true }); + assert.equal(got[0]![7], false); + deliverConsentResult(new Map([["c2", (...a) => void got.push(a)]]), { consentId: "c2", approved: true, reactionGrant: true }); + assert.equal(got[1]![7], true); +}); + +test("under a live grant a reaction and taking one back run without a window, and are still written as the member", async () => { + const h = harness(); + h.answer = { approved: true, reactionGrant: true }; + assert.ok((await react(h)).ok); + assert.equal(h.grants.find((g) => g.roomId === ROOM)!.reactionsUntil, T0 + REACTION_GRANT_TTL_MS); + h.now = T0 + 10 * 60_000; + assert.ok((await react(h)).ok); + assert.ok((await react(h, ROOM, "unreact")).ok); + assert.equal(h.prompts.length, 1); + assert.deepEqual( + writes(h).map((w) => [w.op, w.member]), + [ + ["react", MEMBER], + ["react", MEMBER], + ["unreact", MEMBER], + ], + ); + // The record-members gate still ran for every one. + assert.equal(h.asked.filter((a) => a.op === "recordMembers").length, 3); +}); + +test("using a grant never extends it, and it ends at 30 minutes", async () => { + const h = harness(); + h.answer = { approved: true, reactionGrant: true }; + await react(h); + h.now = T0 + REACTION_GRANT_TTL_MS - 1; + await react(h); + assert.equal(h.grants.find((g) => g.roomId === ROOM)!.reactionsUntil, T0 + REACTION_GRANT_TTL_MS); + h.now = T0 + REACTION_GRANT_TTL_MS; + h.answer = { approved: true }; + await react(h); + assert.equal(h.prompts.length, 2); +}); + +test("a grant is for one room: another shared room still asks", async () => { + const h = harness(); + h.answer = { approved: true, reactionGrant: true }; + await react(h, ROOM); + h.answer = { approved: true }; + await react(h, ROOM2); + assert.equal(h.prompts.length, 2); + assert.equal((h.prompts[1] as RoomWriteConsentView).roomId, ROOM2); +}); + +test("a message or a note under a live grant is still confirmed", async () => { + const h = harness(); + h.answer = { approved: true, reactionGrant: true }; + await react(h); + h.answer = { approved: false }; + const msg = await h.gates.handle(PORTAL, { op: "putMessage", hostDid: HOST, roomId: ROOM, body: "Hi" }); + const note = await h.gates.handle(PORTAL, { op: "putNote", hostDid: HOST, roomId: ROOM, title: "T", body: "B" }); + assert.equal((msg as { code?: string }).code, "declined"); + assert.equal((note as { code?: string }).code, "declined"); + assert.equal(h.prompts.length, 3); + assert.deepEqual( + writes(h).map((w) => w.op), + ["react"], + ); +}); + +test("a grant ends with its share: stopped on its own, revoked with the share, or the room shared afresh", async () => { + // Stopped on its own (the console's Stop): the share stays, the grant goes. + let h = harness(); + h.answer = { approved: true, reactionGrant: true }; + await react(h); + h.grants = withoutReactionGrant(h.grants, AT, ROOM); + h.answer = { approved: true }; + await react(h); + assert.equal(h.prompts.length, 2); + + // Revoked with the share (the console's Stop sharing, or the page's `forget`). + h = harness(); + h.answer = { approved: true, reactionGrant: true }; + await react(h); + h.grants = withoutGrant(h.grants, AT, ROOM); + assert.equal((await react(h) as { code?: string }).code, "notShared"); + + // Shared afresh, here as another member: a new share carries no grant. + h = harness(); + h.answer = { approved: true, reactionGrant: true }; + await react(h); + h.grants = withGrants(h.grants, AT, [{ roomId: ROOM, member: BOB }], T0); + h.answer = { approved: true }; + await react(h); + assert.equal(h.prompts.length, 2); +}); + +test("a grant applies only to its own origin, community, VTA, room and member, and never past its share", () => { + const grants = [share(ROOM), { ...share(ROOM), origin: "https://other.example" }, { ...share(ROOM), member: BOB }]; + const after = withReactionGrant(grants, AT, ROOM, MEMBER, T0); + assert.equal(after[0]!.reactionsUntil, T0 + REACTION_GRANT_TTL_MS); + assert.equal(after[1]!.reactionsUntil, undefined); + assert.equal(after[2]!.reactionsUntil, undefined); + // A share ending sooner caps it. + const short = withReactionGrant([share(ROOM, MEMBER, { expiresAt: T0 + 60_000 })], AT, ROOM, MEMBER, T0); + assert.equal(short[0]!.reactionsUntil, T0 + 60_000); + // A stored value no grant could have made is no grant. + assert.equal(reactionGrantLive({ reactionsUntil: T0 + REACTION_GRANT_TTL_MS + 1, expiresAt: T0 + 86_400_000 }, T0), false); + assert.equal(reactionGrantLive({ reactionsUntil: T0 + 1000, expiresAt: T0 + 500 }, T0), false); + assert.equal(reactionGrantLive({ reactionsUntil: T0, expiresAt: T0 + 86_400_000 }, T0), false); + assert.equal(reactionGrantLive({ expiresAt: T0 + 86_400_000 }, T0), false); + assert.equal(reactionGrantLive({ reactionsUntil: T0 + 1000, expiresAt: T0 + 86_400_000 }, T0), true); +}); diff --git a/packages/extension/tests/room-page-reply-react-watch.test.mts b/packages/extension/tests/room-page-reply-react-watch.test.mts index 391887c2..971cc9c4 100644 --- a/packages/extension/tests/room-page-reply-react-watch.test.mts +++ b/packages/extension/tests/room-page-reply-react-watch.test.mts @@ -202,6 +202,7 @@ test("a reaction is confirmed — the value and the record it is on — and only reaction: true, value: "👍", on: { author: BOB, excerpt: "Lunch at one?" }, + grant: { minutes: 30 }, }); h.answer = { approved: true }; @@ -230,6 +231,7 @@ test("taking a reaction back is confirmed as that, and names the record and the value: "👍", on: { author: BOB, excerpt: "Lunch at one?" }, withdraw: true, + grant: { minutes: 30 }, }); assert.deepEqual(writes(h)[0], { op: "unreact", hostDid: HOST, roomId: ROOM, member: MEMBER, target: "m1", value: "👍" }); });