From bcdfbe6a5aa8fa9cd9dc68bfc8375502e356bc51 Mon Sep 17 00:00:00 2001 From: Glenn Gore Date: Wed, 25 Nov 2026 23:06:39 -0800 Subject: [PATCH] feat(rooms): a member may let a portal send messages and reactions in a room without asking while it is open Every page write is confirmed in the wallet's own window, so a portal chat asked for a confirm on every message. A message's or a reaction's confirm now offers an unticked box: "Send messages and reactions in without asking while this room is open". - Bound to one page document: the tab and the browser's `documentId` (`pageSessionOf`), taken from the call's and the watch port's sender. A reload or navigation is a new document and asks again. - "While this room is open" is the document holding a `rooms.watch` port on that room (`roomOpened`): the last port closing (leaving the room, the tab closing, a reload, the worker sleeping) ends it. Offered only while one is. - Covers `putMessage` (replies too), `react` and `unreact` for that origin, community, VTA, room and member; never notes, files or other writes. Gates 1-3, `recordMembersNotListed` and the value checks still apply. - Also ends on `tabs.onRemoved`, the share ending (`reviewSessionGrants` on any share change), 30 minutes idle, 8 hours from the confirm however used, the wallet locking, or Stop in the Communities tab. - More than 10 writes in a rolling minute, or a message over 4,000 characters, is confirmed as usual; the grant stays. - Held in the background's memory only, never stored. While any is live the action's tooltip names the rooms and the badge reads LIVE. - The page cannot ask for, see or extend it; the page contract is unchanged. - CLAUDE.md names this second bounded exception, and widening it joins "What breaks it". Signed-off-by: Glenn Gore --- CLAUDE.md | 40 ++- packages/extension/src/background.ts | 82 ++++- packages/extension/src/bridge-protocol.ts | 22 ++ packages/extension/src/confirm.tsx | 3 +- packages/extension/src/consent-window.ts | 3 + .../src/manager/panes/rooms-communities.tsx | 14 +- .../src/manager/panes/rooms-shares.tsx | 53 ++- packages/extension/src/room-consent.tsx | 54 ++- .../extension/src/room-page-background.ts | 163 ++++++--- packages/extension/src/room-page-policy.ts | 13 + packages/extension/src/room-session-grant.ts | 244 ++++++++++++++ .../tests/room-page-session-grant.test.mts | 309 ++++++++++++++++++ 12 files changed, 941 insertions(+), 59 deletions(-) create mode 100644 packages/extension/src/room-session-grant.ts create mode 100644 packages/extension/tests/room-page-session-grant.test.mts diff --git a/CLAUDE.md b/CLAUDE.md index 917d74e..9534606 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1079,7 +1079,8 @@ 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 -one exception is a reaction under a live reaction grant (below). +two exceptions are a reaction under a live reaction grant, and a message or +reaction under a live session grant (both 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 @@ -1143,7 +1144,31 @@ 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. +and a Stop. Notes and files are always confirmed; messages are, except under a +session grant. + +**A session grant: "send messages and reactions in without asking while +this room is open"** (`room-session-grant.ts`). The second bounded exception, +offered as an **unticked** box on a message's or a reaction's confirm, and only +while the asking document holds that room open. It is bound to **one page +document** — the tab and the browser's `documentId` (`pageSessionOf`, from the +call's and the watch port's `sender`), which a reload or navigation replaces — +and lives only while that document holds a `ROOM_WATCH_PAGE_PORT` on that room +(`roomOpened`: the last such port closing ends it). It covers `putMessage` +(a reply included), `react` and `unreact` for that origin, community, VTA, +room and member — never a note, a file or any other write — and gates 1–3, +`recordMembersNotListed` and the value checks still apply. It ends at the +earliest of: the port closing (leaving the room, reload, navigation, the tab +closing, the worker sleeping), `tabs.onRemoved`, the share ending +(`reviewSessionGrants` on any share change), 30 minutes with no write under it, +8 hours from the confirm however used, the wallet locking, or Stop in the +Communities tab ("Sends without asking while open"). More than 10 writes under +it in a rolling minute, or a message over 4,000 characters, is confirmed as +usual (the grant stays). It is held in the background's memory only — never +stored — and while any is live the action's tooltip names the rooms and its +badge reads LIVE (below a waiting approval, above an offer). The page can +neither ask for, see, nor extend one; `sessionGrant` crosses the consent window +only with an approval, from a prompt that offered it. **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 @@ -1256,7 +1281,9 @@ 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" — except the bounded, revocable -reaction grant (≤30 min, one room, reactions only). A file's bytes reach the page only +reaction grant (≤30 min, one room, reactions only) and the session grant (one +room, one open page document, messages and reactions only, 30 min idle / 8 h +cap, rate-limited, revocable, shown by the LIVE badge). 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. @@ -1267,7 +1294,12 @@ 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 (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 +minutes, or renewing it without a fresh confirm's box — breaks it too; so does +widening the session grant to notes, files or any other write, letting it +outlive the one document holding the room open (storing it, keying it by tab +alone, keeping it past the port), lifting its idle limit, cap or rate limit, +removing the LIVE badge or tooltip, or renewing it without a fresh confirm's +box); 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 2a4b5d6..7ab4feb 100644 --- a/packages/extension/src/background.ts +++ b/packages/extension/src/background.ts @@ -49,6 +49,7 @@ import { } from "./active-vta.js"; import { checkOriginPin, pinOrigin, readOriginPin, type OriginPinStatus } from "./origin-pin.js"; import { RoomPageGates, type PortLike } from "./room-page-background.js"; +import type { PageSession } from "./room-session-grant.js"; import { DIRECTORY_CONSENT_PREFIX, DirectoryPageGates, @@ -71,6 +72,7 @@ import { mergeRoomNames, roomNamesKey, ROOM_CONSENT_PREFIX, + ROOM_GRANTS_PREFIX, type RoomGrant, type RoomShareConsentView, type RoomWriteConsentView, @@ -175,6 +177,9 @@ import { RUNTIME_ROOM_FILES_PREPARE, RUNTIME_ROOMS_PAGE, RUNTIME_ROOM_OFFERS, + RUNTIME_ROOM_SESSION_GRANTS, + type RuntimeRoomSessionGrantsRequest, + type RuntimeRoomSessionGrantsResponse, RUNTIME_NOTIFIED_ELECTION, type RuntimeNotifiedElectionRequest, type RuntimeNotifiedElectionResponse, @@ -815,8 +820,22 @@ async function ensureOffscreenDocument(): Promise { // Read from the same durable record the inbound path writes before it acks the // mediator (`pending.ts`), so the badge cannot claim a request the recipient // never durably held — nor miss one it did. +/** + * The rooms a page may write to without asking right now ("while this room is + * open", `room-session-grant.ts`), by name where known. While any is, the + * action says so — a tooltip naming them always, and LIVE on the badge unless + * an approval is waiting. + */ +let liveSessionRooms: string[] = []; + async function refreshPendingBadge(): Promise { try { + await chrome.action.setTitle({ + title: + liveSessionRooms.length > 0 + ? `VTA Wallet — sending without asking while open in: ${liveSessionRooms.join(", ")}` + : "VTA Wallet", + }); const pending = await listPendingInbound(new IndexedDBKVStore()); const waiting = pending.filter((p: { isApprover: boolean }) => p.isApprover).length; if (waiting > 0) { @@ -824,6 +843,13 @@ async function refreshPendingBadge(): Promise { await chrome.action.setBadgeBackgroundColor({ color: "#8B1A1A" }); return; } + // Above an offer: writing without asking is the member's own standing + // choice, and they must be able to see it is on. + if (liveSessionRooms.length > 0) { + await chrome.action.setBadgeText({ text: "LIVE" }); + await chrome.action.setBadgeBackgroundColor({ color: "#1E7B3A" }); + return; + } // Below an approval, never beside it: a room offer waits for the member, // where an approval holds up an operation. Its own colour, so the two are // not read as one count. Written by the last offers listing for the @@ -869,16 +895,19 @@ 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[]; reactionGrant?: boolean }> { +): Promise<{ approved: boolean; selectedRooms?: string[]; reactionGrant?: boolean; sessionGrant?: 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; + // So is a session grant ("while this room is open"). + const offersSession = + view.kind === "write" && ("message" in view.what || "reaction" in view.what) && view.what.session !== 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[], reactionGrant?: boolean) => { + const settle = (approved: boolean, selectedRooms?: string[], reactionGrant?: boolean, sessionGrant?: boolean) => { if (settled) return; settled = true; pendingConsents.delete(consentId); @@ -889,12 +918,15 @@ async function requestRoomConsent( approved: true, ...(selectedRooms ? { selectedRooms } : {}), ...(offersGrant && reactionGrant === true ? { reactionGrant: true } : {}), + ...(offersSession && sessionGrant === true ? { sessionGrant: true } : {}), } : { approved: false }, ); }; - pendingConsents.set(consentId, (approved, _remember, _prf, _did, selectedRooms, _credential, _ballot, reactionGrant) => - settle(approved, selectedRooms, reactionGrant), + pendingConsents.set( + consentId, + (approved, _remember, _prf, _did, selectedRooms, _credential, _ballot, reactionGrant, sessionGrant) => + settle(approved, selectedRooms, reactionGrant, sessionGrant), ); openConsentWindow({ url, bounds, deny: () => settle(false), tag: "[pnm rooms]", what: "room window" }); }); @@ -1000,9 +1032,33 @@ const roomPageGates = new RoomPageGates({ await ensureOffscreenDocument(); return chrome.runtime.connect({ name: ROOM_FILES_PORT }) as unknown as PortLike; }, + sessionsChanged(rows) { + liveSessionRooms = rows.map((r) => r.roomLabel ?? r.roomId); + void refreshPendingBadge(); + }, now: () => Date.now(), }); +/** + * The document a page call or port came from, as the browser reports it. Only a + * tab's document with an id can hold a session grant ("while this room is open"). + */ +function pageSessionOf(sender: chrome.runtime.MessageSender | undefined): PageSession | undefined { + const tabId = sender?.tab?.id; + const documentId = (sender as { documentId?: unknown } | undefined)?.documentId; + return typeof tabId === "number" && typeof documentId === "string" && documentId.length > 0 + ? { tabId, documentId } + : undefined; +} + +// A tab closing ends its session grants at once, whatever its ports do. +chrome.tabs.onRemoved.addListener((tabId) => roomPageGates.sessions.endForTab(tabId)); +// A share revoked, forgotten or replaced ends the session grants that rode on it. +chrome.storage.onChanged.addListener((changes, areaName) => { + if (areaName !== "local") return; + if (Object.keys(changes).some((k) => k.startsWith(ROOM_GRANTS_PREFIX))) void roomPageGates.reviewSessionGrants(); +}); + // ── A page's `window.vtaWallet.directory` ─────────────────────────────────── // // Publishing the member's directory card from the community's portal. The @@ -1268,7 +1324,7 @@ chrome.runtime.onConnect.addListener((port) => { port.disconnect(); return; } - roomPageGates.serveWatchPort(port as unknown as PortLike, origin); + roomPageGates.serveWatchPort(port as unknown as PortLike, origin, pageSessionOf(port.sender)); }); // A watched room moved (`rooms/keys/changed/0.1`), as the offscreen document @@ -4275,7 +4331,7 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { const req = message as RuntimeRoomsPageRequest; // `origin` was overwritten above with the browser-attested one. roomPageGates - .handle(req.origin, req.params) + .handle(req.origin, req.params, pageSessionOf(sender)) .then(sendResponse) .catch((e: unknown) => sendResponse(pageFailure(e))); return true; // async sendResponse @@ -4563,6 +4619,18 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { return true; // async sendResponse } + if ((message as { type?: string })?.type === RUNTIME_ROOM_SESSION_GRANTS) { + // Console only: a page can neither see nor stop a grant. + if (!isExtensionPageSender(sender)) { + sendResponse({ ok: false, error: "session grants are not page-reachable" } satisfies RuntimeRoomSessionGrantsResponse); + return false; + } + const { params } = message as RuntimeRoomSessionGrantsRequest; + if (params?.op === "stop" && typeof params.id === "string") roomPageGates.sessions.stop(params.id); + sendResponse({ ok: true, result: roomPageGates.sessions.list() } satisfies RuntimeRoomSessionGrantsResponse); + return false; + } + if ((message as { type?: string })?.type === RUNTIME_ROOM_OFFERS) { // Console only. A portal reaches its own community's offers through // `window.vtaWallet.rooms`, whose gates hold it to that community. @@ -4803,6 +4871,8 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if ((message as { type?: string })?.type === RUNTIME_LOCK_WALLET) { // SW-side lock — clears this context's key cache. WebAuthnPrfSecretWrap.lock(); + // A locked wallet sends nothing without asking: every session grant ends. + roomPageGates.sessions.endAll(); // Forward to the offscreen doc (if running) so its cache // is flushed too. The offscreen path is fire-and-forget; // a missing offscreen doc is fine (it'll mint a fresh diff --git a/packages/extension/src/bridge-protocol.ts b/packages/extension/src/bridge-protocol.ts index 8f9e1a7..a969c6d 100644 --- a/packages/extension/src/bridge-protocol.ts +++ b/packages/extension/src/bridge-protocol.ts @@ -681,6 +681,10 @@ export interface RuntimeConsentResult { * your reactions in this room for 30 minutes". Ignored on a denial, and on * any prompt that did not offer it. */ reactionGrant?: boolean; + /** Message or reaction prompt only: the member ticked "send messages and + * reactions in this room without asking while this room is open". Ignored on a + * denial, and on any prompt that did not offer it. */ + sessionGrant?: boolean; } /** confirm popup → background: resolve + verify an RP DID. */ @@ -4025,6 +4029,24 @@ export type RoomFilesMessage = /** console → background: list offers, or accept one. Extension pages only. */ export const RUNTIME_ROOM_OFFERS = "vta-wallet/room-offers" as const; +/** + * console → background: the live "while this room is open" grants + * (`room-session-grant.ts`), or Stop one. Extension pages only: they live in the + * worker's memory, never in storage. + */ +export const RUNTIME_ROOM_SESSION_GRANTS = "vta-wallet/room-session-grants" as const; + +export type RoomSessionGrantsOp = { op: "list" } | { op: "stop"; id: string }; + +export interface RuntimeRoomSessionGrantsRequest { + type: typeof RUNTIME_ROOM_SESSION_GRANTS; + params: RoomSessionGrantsOp; +} + +export type RuntimeRoomSessionGrantsResponse = + | { ok: true; result: import("./room-session-grant.js").SessionGrantRow[] } + | { ok: false; error: string }; + export type RoomOffersConsoleOp = /** Every community the member signs in to, and its offers to each identity used there. `force` reads afresh. */ | { op: "overview"; force?: boolean } diff --git a/packages/extension/src/confirm.tsx b/packages/extension/src/confirm.tsx index e3d7fe7..93e877b 100644 --- a/packages/extension/src/confirm.tsx +++ b/packages/extension/src/confirm.tsx @@ -1488,12 +1488,13 @@ if (root) { ) : isRoomConsent ? ( + decide={(ok, rooms, reactionGrant, sessionGrant) => void sendConsentResult({ approved: ok, remember: false, ...(ok && rooms ? { selectedRooms: rooms } : {}), ...(ok && reactionGrant === true ? { reactionGrant: true } : {}), + ...(ok && sessionGrant === true ? { sessionGrant: true } : {}), }) } /> diff --git a/packages/extension/src/consent-window.ts b/packages/extension/src/consent-window.ts index 4aad61b..aa71502 100644 --- a/packages/extension/src/consent-window.ts +++ b/packages/extension/src/consent-window.ts @@ -51,6 +51,7 @@ export type ConsentDecision = ( selectedCredential?: string, ballot?: unknown, reactionGrant?: boolean, + sessionGrant?: boolean, ) => void; /** The subset of `chrome.windows` this file drives — narrow so a test can @@ -166,6 +167,7 @@ export function deliverConsentResult( selectedCredential?: string; ballot?: unknown; reactionGrant?: boolean; + sessionGrant?: boolean; }, ): boolean { const decision = pending.get(result.consentId); @@ -188,6 +190,7 @@ export function deliverConsentResult( credential, ballot, result.approved && result.reactionGrant === true, + result.approved && result.sessionGrant === true, ); return true; } diff --git a/packages/extension/src/manager/panes/rooms-communities.tsx b/packages/extension/src/manager/panes/rooms-communities.tsx index 2b4b098..ae1e3cd 100644 --- a/packages/extension/src/manager/panes/rooms-communities.tsx +++ b/packages/extension/src/manager/panes/rooms-communities.tsx @@ -34,7 +34,7 @@ import type { KnownRoomHost } from "../room-hosts.js"; import { mostReadable } from "../room-groups.js"; import { placeWord, shortDid, standing } from "../room-words.js"; import { day, host, offerKey, type RoomOffersState } from "./rooms-offers.js"; -import type { RoomSharesState, ShareRow } from "./rooms-shares.js"; +import { sessionFor, type RoomSharesState, type ShareRow } from "./rooms-shares.js"; import { roomDisplayName } from "./rooms-profile.js"; /** @@ -233,8 +233,20 @@ function websiteStep(row: LaneRow, shares: RoomSharesState): Step { , ] : []; + const live = sessionFor(shares.sessions, s.grant); + const session = live + ? [ + + Sends without asking while open ·{" "} + + , + ] + : []; return [ `${host(s.grant.origin)} · until ${new Date(s.grant.expiresAt).toLocaleDateString()}`, + ...session, ...reactions, - decide(true)}>{isMessage ? (replyingTo ? "Send reply" : "Send message") : `Add ${thing}`} + decide(true, undefined, offer ? session : undefined)}> + {isMessage ? (replyingTo ? "Send reply" : "Send message") : `Add ${thing}`} + ); @@ -336,9 +376,10 @@ function React({ }: { view: RoomWriteConsentView; what: Extract; - decide: (approved: boolean, reactionGrant?: boolean) => void; + decide: (approved: boolean, reactionGrant?: boolean, sessionGrant?: boolean) => void; }) { const [grant, setGrant] = useState(false); + const [session, setSession] = useState(false); const boxId = useId(); const room = what.grant?.roomLabel ? `“${what.grant.roomLabel}”` : "this room"; return ( @@ -369,11 +410,12 @@ function React({ )} + {what.session ? : null}
- decide(true, what.grant ? grant : undefined)}>{what.withdraw ? "Take back" : "React"} + decide(true, what.grant ? grant : undefined, what.session ? session : 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 7f6af55..9181bbc 100644 --- a/packages/extension/src/room-page-background.ts +++ b/packages/extension/src/room-page-background.ts @@ -11,10 +11,13 @@ // 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. 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. +// own window, seeing the room, who will sign and what will be written. Two +// bounded exceptions, each granted only by a box the member ticked in a confirm: +// a reaction under a live reaction grant (`reactionGrantLive`: "let this portal +// react in this room for 30 minutes"), and a message or reaction under a live +// session grant (`room-session-grant.ts`: "send messages and reactions in this +// room without asking while this room is open" — bound to the one page document +// holding the room open). 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`. @@ -66,6 +69,7 @@ import { reactionGrantLive, withReactionGrant, } from "./room-page-policy.js"; +import { RoomSessionGrants, type PageSession, type SessionGrantRow, type SessionGrantScope } from "./room-session-grant.js"; /** One entry of the VTA's listing, as the offscreen document reports it — or an * open room the member is in (`openRooms`), which has no epoch. */ @@ -100,10 +104,13 @@ export interface RoomPageBackgroundDeps { 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. `reactionGrant`: the - * member ticked a reaction prompt's grant box (only ever from a prompt offering one). */ + * member ticked a reaction prompt's grant box; `sessionGrant`: a prompt's "while + * this room is open" box (each only ever from a prompt offering it). */ prompt( view: RoomShareConsentView | RoomWriteConsentView, - ): Promise<{ approved: boolean; selectedRooms?: string[]; reactionGrant?: boolean }>; + ): Promise<{ approved: boolean; selectedRooms?: string[]; reactionGrant?: boolean; sessionGrant?: boolean }>; + /** Told the live session grants whenever they may have changed (the action badge). */ + sessionsChanged?(rows: SessionGrantRow[]): void; /** 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. */ @@ -183,7 +190,42 @@ export class RoomPageGates { /** Each page port's signal handler, by watch id. */ private readonly watchers = new Map void>>(); - constructor(private readonly deps: RoomPageBackgroundDeps) {} + /** The live "while this room is open" grants, in memory only. */ + readonly sessions: RoomSessionGrants; + + constructor(private readonly deps: RoomPageBackgroundDeps) { + this.sessions = new RoomSessionGrants( + () => this.deps.now(), + () => this.sessionsChanged(), + ); + } + + /** Tell the background, and wake when the next grant runs out, so the badge clears on time. */ + private sessionsChanged(): void { + const rows = this.sessions.list(); + this.deps.sessionsChanged?.(rows); + if (rows.length === 0) return; + const next = Math.min(...rows.map((r) => r.endsBy)) - this.deps.now(); + const timer = this.deps.setTimer ?? ((fn: () => void, ms: number) => setTimeout(fn, ms)); + // Listing prunes what ran out, and a pruned grant calls back here. + timer(() => void this.sessions.list(), Math.max(1000, next + 1)); + } + + /** End the session grants whose share has gone (revoked, forgotten, lapsed). */ + async reviewSessionGrants(): Promise { + const rows = this.sessions.list(); + const live = new Set(); + for (const r of rows) { + try { + const grants = await this.deps.loadGrants(r.origin, r.vtaDid); + const g = roomGrant(grants, { origin: r.origin, hostDid: r.hostDid, vtaDid: r.vtaDid }, r.roomId, this.deps.now()); + if (g.ok && g.grant.member === r.member) live.add(r.id); + } catch { + // Unreadable: treated as gone. + } + } + this.sessions.endUnshared((scope) => rows.some((r) => live.has(r.id) && sameScopeRow(r, scope))); + } /** `hostDid`'s portal and endpoint, resolved through the offscreen document and cached briefly. */ private async portal(vta: ActiveVta, hostDid: string): Promise<{ portalOrigin: string; endpoint: string }> { @@ -287,18 +329,27 @@ export class RoomPageGates { return res.result; } - /** One `rooms.*` call from a page at `origin` (browser-attested). */ - async handle(origin: string, raw: unknown): Promise { + /** + * One `rooms.*` call from a page at `origin` (browser-attested). `session`: the + * document it came from, as the browser reports it — only a call that names one + * can be covered by, or offer, a session grant. + */ + async handle(origin: string, raw: unknown, session?: PageSession): Promise { try { const malformed = roomsPageParamsRefusal(raw); if (malformed) return { ok: false, error: malformed, code: "invalidCall" }; - return { ok: true, result: await this.run(origin, raw as RoomsPageOp) }; + return { ok: true, result: await this.run(origin, raw as RoomsPageOp, session) }; } catch (e) { return pageFailure(e); } } - private async run(origin: string, p: RoomsPageOp): Promise { + /** Whether a session grant may be offered on this prompt: the room is open in this document. */ + private sessionOffer(session: PageSession | undefined, origin: string, hostDid: string, roomId: string): boolean { + return session !== undefined && this.sessions.isOpen(session, origin, hostDid, roomId); + } + + private async run(origin: string, p: RoomsPageOp, session?: PageSession): Promise { switch (p.op) { case "list": { const { vta } = await this.atPortal(origin, p.hostDid, { needReach: false }); @@ -398,24 +449,35 @@ export class RoomPageGates { // 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: 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, { + const scope: SessionGrantScope = { origin, hostDid: p.hostDid, vtaDid: vta.vtaDid, roomId: p.roomId, member }; + const chars = [...p.body].length; + // Under a live session grant — this document, holding this room open, for + // this share — no window. Too fast, or too long, and the window is asked. + const cover = this.sessions.cover(scope, session, { messageChars: chars }); + if (cover !== "covered") { + 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 offerSession = cover === "none" && this.sessionOffer(session, origin, p.hostDid, p.roomId); + const roomLabel = offerSession ? await this.roomLabel(vta, p.hostDid, p.roomId, member) : undefined; + const decision = await this.deps.prompt({ + kind: "write", + origin, + hostDid: p.hostDid, + roomId: p.roomId, + member: info.member, + visibility: info.visibility, + what: { + message: true, + excerpt: excerpt(p.body), + bodyChars: chars, + ...(replyingTo !== undefined ? { replyingTo } : {}), + ...(offerSession ? { session: { ...(roomLabel ? { roomLabel } : {}) } } : {}), + }, + }); + if (!decision.approved) throw new RoomPageRefusal("the member declined to send this message", "declined"); + if (offerSession && decision.sessionGrant === true) this.sessions.grant(scope, session!, roomLabel); + } + const sent = await this.offscreen(vta, { op: "putMessage", ...at, body: p.body, @@ -423,6 +485,8 @@ export class RoomPageGates { ? { replyTo: { key: p.replyTo.key, ...(p.replyTo.version !== undefined ? { version: p.replyTo.version } : {}) } } : {}), }); + this.sessions.used(scope, session); + return sent; } case "react": case "unreact": { @@ -432,10 +496,14 @@ export class RoomPageGates { const at = { hostDid: p.hostDid, roomId: p.roomId, member }; await this.needsRecordMembers(vta, at, ["kind", "inReplyTo"], "reactions"); const withdraw = p.op === "unreact"; - // 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 scope: SessionGrantScope = { origin, hostDid: p.hostDid, vtaDid: vta.vtaDid, roomId: p.roomId, member }; + const cover = this.sessions.cover(scope, session); + // Under a live session grant (this document, holding this room open), or 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 either grant. + if (cover !== "covered" && !reactionGrantLive(share, this.deps.now())) { + const offerSession = cover === "none" && this.sessionOffer(session, origin, p.hostDid, p.roomId); 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); @@ -452,6 +520,7 @@ export class RoomPageGates { on, ...(withdraw ? { withdraw: true as const } : {}), grant: { minutes: REACTION_GRANT_TTL_MS / 60_000, ...(roomLabel ? { roomLabel } : {}) }, + ...(offerSession ? { session: { ...(roomLabel ? { roomLabel } : {}) } } : {}), }, }); if (!decision.approved) { @@ -461,15 +530,18 @@ export class RoomPageGates { ); } if (decision.reactionGrant === true) await this.grantReactions(origin, p.hostDid, vta, p.roomId, member); + if (offerSession && decision.sessionGrant === true) this.sessions.grant(scope, session!, roomLabel); } - return withdraw - ? this.offscreen(vta, { op: "unreact", ...at, target: p.key, value: p.value }) - : this.offscreen(vta, { + const done = withdraw + ? await this.offscreen(vta, { op: "unreact", ...at, target: p.key, value: p.value }) + : await this.offscreen(vta, { op: "react", ...at, target: { key: p.key, ...(p.version !== undefined ? { version: p.version } : {}) }, value: p.value, }); + this.sessions.used(scope, session); + return done; } } } @@ -742,9 +814,12 @@ export class RoomPageGates { * 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 { + serveWatchPort(page: PortLike, origin: string, session?: PageSession): void { let open = true; let held: { key: RoomWatchKey; release: () => void } | undefined; + // While this port holds the room, the room is open in this document: a + // session grant lives exactly that long. + let roomClosed: (() => void) | undefined; const post = (m: RoomWatchPageEvent) => { if (!open) return; try { @@ -758,6 +833,8 @@ export class RoomPageGates { open = false; held?.release(); held = undefined; + roomClosed?.(); + roomClosed = undefined; }; const fail = (e: unknown) => { post({ kind: "failed", ...failedOf(e) }); @@ -777,8 +854,12 @@ export class RoomPageGates { started = true; void this.startWatch(origin, raw, post, fail).then((h) => { if (!h) return; - if (open) held = h; - else h.release(); + if (!open) { + h.release(); + return; + } + held = h; + if (session) roomClosed = this.sessions.roomOpened(session, origin, h.key.host, h.key.roomId); }); return; } @@ -1061,3 +1142,7 @@ export function withProfiles( } return out; } + +function sameScopeRow(r: SessionGrantRow, s: SessionGrantScope): boolean { + return r.origin === s.origin && r.hostDid === s.hostDid && r.vtaDid === s.vtaDid && r.roomId === s.roomId && r.member === s.member; +} diff --git a/packages/extension/src/room-page-policy.ts b/packages/extension/src/room-page-policy.ts index c4c334a..db33581 100644 --- a/packages/extension/src/room-page-policy.ts +++ b/packages/extension/src/room-page-policy.ts @@ -576,6 +576,8 @@ export interface RoomWriteConsentView { bodyChars: number; /** The record the message answers, as the wallet read it — never the page's word. */ replyingTo?: RecordGlimpse; + /** The prompt may offer "send messages and reactions here without asking while this room is open". */ + session?: SessionGrantOffer; } /** * A reaction, or (`withdraw`) taking one back, on the record the wallet read. @@ -588,10 +590,21 @@ export interface RoomWriteConsentView { withdraw?: true; on: RecordGlimpse; grant?: { minutes: number; roomLabel?: string }; + /** The prompt may offer "send messages and reactions here without asking while this room is open". */ + session?: SessionGrantOffer; } | { file: true; name: string; size: number; mediaType?: string; title?: string }; } +/** + * A session grant a write prompt offers (`room-session-grant.ts`): offered only + * while the asking document holds the room open, naming the room by `roomLabel` + * where the wallet knows it. + */ +export interface SessionGrantOffer { + roomLabel?: 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; diff --git a/packages/extension/src/room-session-grant.ts b/packages/extension/src/room-session-grant.ts new file mode 100644 index 0000000..5a01566 --- /dev/null +++ b/packages/extension/src/room-session-grant.ts @@ -0,0 +1,244 @@ +// A session grant: "send messages and reactions in this room without asking +// while this room is open" (P7b; VTI `data-rooms-files.md` §8.5). +// +// The second bounded exception to "every page write is confirmed" (the first is +// the 30-minute reaction grant on the share, `reactionGrantLive`). Granted only +// by the member ticking the box in a message's or a reaction's own confirm, and +// covering only messages (`putMessage`, a reply included), `react` and +// `unreact` — never a note, a file or anything else. +// +// **"While this room is open" is a page session, not a clock.** The grant is +// bound to the one document that asked (its tab and the browser's `documentId`, +// which a reload or a navigation replaces) and lives only while that document +// holds a watch on that room (`rooms.watch`, the port a room page keeps open +// while it shows the room). The last such port closing — the member leaving the +// room, closing the tab, reloading, navigating away, or the wallet's worker +// being put to sleep — ends it. A new tab, or the same tab reloaded, is a new +// document and asks again. +// +// It also ends on: 30 minutes with no write under it, 8 hours from the confirm +// whatever the use, the share ending, the wallet locking, or Stop. Nothing +// extends it past those, and it is held in the worker's memory only — never +// stored, so nothing outlives the worker either. +// +// More than RATE_LIMIT writes under it in a rolling minute, or a message longer +// than SESSION_MESSAGE_MAX_CHARS, is asked for in the window as usual; the grant +// stays. + +/** No write under the grant for this long ends it. */ +export const SESSION_GRANT_IDLE_MS = 30 * 60 * 1000; +/** A grant never lasts longer than this from its confirm, however used. */ +export const SESSION_GRANT_CAP_MS = 8 * 60 * 60 * 1000; +/** Writes under one grant in any rolling minute before the window is asked again. */ +export const SESSION_GRANT_RATE_LIMIT = 10; +export const SESSION_GRANT_RATE_WINDOW_MS = 60 * 1000; +/** A message longer than this is always confirmed: a chat line, not a document. */ +export const SESSION_MESSAGE_MAX_CHARS = 4000; + +/** The page document a call or a port came from, as the browser reports it. */ +export interface PageSession { + tabId: number; + /** The browser's id for this document: a reload or a navigation gets a new one. */ + documentId: string; +} + +/** What a session grant is for: the share it rides on, exactly. */ +export interface SessionGrantScope { + origin: string; + hostDid: string; + vtaDid: string; + roomId: string; + member: string; +} + +/** A live session grant, as the console lists it. */ +export interface SessionGrantRow extends SessionGrantScope { + id: string; + roomLabel?: string; + grantedAt: number; + lastUsedAt: number; + /** When it ends at the latest if used no more: the earlier of idle and cap. */ + endsBy: number; +} + +interface Entry { + id: string; + scope: SessionGrantScope; + session: PageSession; + roomLabel?: string; + grantedAt: number; + lastUsedAt: number; + /** When each recent write under it ran, for the rate limit. */ + recent: number[]; +} + +/** Whether a write may run without a window, and if not, why. */ +export type SessionCover = "covered" | "none" | "ask"; + +function sameSession(a: PageSession, b: PageSession): boolean { + return a.tabId === b.tabId && a.documentId === b.documentId; +} + +function sameScope(a: SessionGrantScope, b: SessionGrantScope): boolean { + return ( + a.origin === b.origin && a.hostDid === b.hostDid && a.vtaDid === b.vtaDid && a.roomId === b.roomId && a.member === b.member + ); +} + +/** The key an open room is counted under: one document, one origin, one community, one room. */ +function openKey(session: PageSession, origin: string, hostDid: string, roomId: string): string { + return JSON.stringify([session.tabId, session.documentId, origin, hostDid, roomId]); +} + +export class RoomSessionGrants { + private readonly entries = new Map(); + /** How many watch ports each (document, origin, community, room) holds open. */ + private readonly open = new Map(); + private seq = 0; + + constructor( + private readonly now: () => number, + /** Told whenever the set of live grants may have changed (the action badge). */ + private readonly changed: () => void = () => undefined, + ) {} + + /** + * A page document began holding a watch on a room. Returns the function that + * ends it; the last one ending for that document and room ends its grants. + */ + roomOpened(session: PageSession, origin: string, hostDid: string, roomId: string): () => void { + const k = openKey(session, origin, hostDid, roomId); + this.open.set(k, (this.open.get(k) ?? 0) + 1); + let done = false; + return () => { + if (done) return; + done = true; + const n = (this.open.get(k) ?? 1) - 1; + if (n > 0) { + this.open.set(k, n); + return; + } + this.open.delete(k); + this.endWhere( + (e) => + sameSession(e.session, session) && e.scope.origin === origin && e.scope.hostDid === hostDid && e.scope.roomId === roomId, + ); + }; + } + + /** Whether `session` has `roomId` open now: the only time a grant may be offered or used. */ + isOpen(session: PageSession, origin: string, hostDid: string, roomId: string): boolean { + return (this.open.get(openKey(session, origin, hostDid, roomId)) ?? 0) > 0; + } + + /** + * Record the member's explicit grant, from a confirm's box. Refused (false) + * when the room is not open in that document — nothing would end it. + */ + grant(scope: SessionGrantScope, session: PageSession, roomLabel?: string): boolean { + if (!this.isOpen(session, scope.origin, scope.hostDid, scope.roomId)) return false; + // One grant per document and share: a second confirm replaces the first. + this.endWhere((e) => sameSession(e.session, session) && sameScope(e.scope, scope), false); + const now = this.now(); + const id = `sg-${++this.seq}-${now}`; + this.entries.set(id, { + id, + scope: { ...scope }, + session: { ...session }, + ...(roomLabel ? { roomLabel } : {}), + grantedAt: now, + lastUsedAt: now, + recent: [], + }); + this.changed(); + return true; + } + + /** + * Whether a write for `scope` from `session` runs without a window. Ends any + * grant that has run out. Does not record a use: `used` does, once it ran. + */ + cover(scope: SessionGrantScope, session: PageSession | undefined, opts: { messageChars?: number } = {}): SessionCover { + if (!session) return "none"; + this.prune(); + const e = this.find(scope, session); + if (!e) return "none"; + if (!this.isOpen(session, scope.origin, scope.hostDid, scope.roomId)) { + this.endWhere((x) => x.id === e.id); + return "none"; + } + if (opts.messageChars !== undefined && opts.messageChars > SESSION_MESSAGE_MAX_CHARS) return "ask"; + const now = this.now(); + e.recent = e.recent.filter((t) => now - t < SESSION_GRANT_RATE_WINDOW_MS); + if (e.recent.length >= SESSION_GRANT_RATE_LIMIT) return "ask"; + return "covered"; + } + + /** A write ran under `scope`'s grant (or was confirmed while it stood): it counts toward the rate and idle. */ + used(scope: SessionGrantScope, session: PageSession | undefined): void { + if (!session) return; + const e = this.find(scope, session); + if (!e) return; + const now = this.now(); + e.lastUsedAt = now; + e.recent.push(now); + } + + /** The live grants, for the console. */ + list(): SessionGrantRow[] { + this.prune(); + return [...this.entries.values()].map((e) => ({ + id: e.id, + ...e.scope, + ...(e.roomLabel ? { roomLabel: e.roomLabel } : {}), + grantedAt: e.grantedAt, + lastUsedAt: e.lastUsedAt, + endsBy: Math.min(e.lastUsedAt + SESSION_GRANT_IDLE_MS, e.grantedAt + SESSION_GRANT_CAP_MS), + })); + } + + /** The member pressed Stop. */ + stop(id: string): boolean { + return this.endWhere((e) => e.id === id) > 0; + } + + /** End every grant (the wallet locked, or the active agent changed). */ + endAll(): void { + this.endWhere(() => true); + } + + /** End every grant from one tab (it closed). */ + endForTab(tabId: number): void { + this.endWhere((e) => e.session.tabId === tabId); + } + + /** End the grants whose share is no longer live, by `stillShared`. */ + endUnshared(stillShared: (scope: SessionGrantScope) => boolean): void { + this.endWhere((e) => !stillShared(e.scope)); + } + + private find(scope: SessionGrantScope, session: PageSession): Entry | undefined { + for (const e of this.entries.values()) { + if (sameSession(e.session, session) && sameScope(e.scope, scope)) return e; + } + return undefined; + } + + /** End the grants past their idle limit or their cap. */ + private prune(): void { + const now = this.now(); + this.endWhere((e) => now - e.lastUsedAt >= SESSION_GRANT_IDLE_MS || now - e.grantedAt >= SESSION_GRANT_CAP_MS); + } + + private endWhere(pred: (e: Entry) => boolean, notify = true): number { + let n = 0; + for (const [id, e] of this.entries) { + if (pred(e)) { + this.entries.delete(id); + n++; + } + } + if (n > 0 && notify) this.changed(); + return n; + } +} diff --git a/packages/extension/tests/room-page-session-grant.test.mts b/packages/extension/tests/room-page-session-grant.test.mts new file mode 100644 index 0000000..6b0a769 --- /dev/null +++ b/packages/extension/tests/room-page-session-grant.test.mts @@ -0,0 +1,309 @@ +// A session grant: "send messages and reactions in this room without asking +// while this room is open" (P7b; VTI `data-rooms-files.md` §8.5). +// +// The second bounded exception to "every page write is confirmed". Only the box +// in a message's or reaction's own confirm grants it; it is bound to the one +// document (tab + documentId) that holds the room open through a watch port, +// covers messages and reactions only, and ends with that port, the tab, the +// share, 30 minutes idle, 8 hours, a lock, or Stop. Too many writes, or a long +// message, are asked for again. + +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 type { RoomShareConsentView, RoomWriteConsentView } from "../src/room-page-policy.ts"; +import { + RoomSessionGrants, + SESSION_GRANT_CAP_MS, + SESSION_GRANT_IDLE_MS, + SESSION_GRANT_RATE_LIMIT, + SESSION_MESSAGE_MAX_CHARS, + type PageSession, + type SessionGrantRow, +} from "../src/room-session-grant.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 T0 = 1_800_000_000_000; +const TAB: PageSession = { tabId: 7, documentId: "DOC-A" }; + +class FakePort implements PortLike { + connected = true; + private onMsg: ((m: unknown) => void)[] = []; + private onDisc: (() => void)[] = []; + postMessage() {} + 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; reactionGrant?: boolean; sessionGrant?: boolean }; + shared: boolean; + now: number; + badge: SessionGrantRow[][]; +} + +function harness(): Harness { + const h: Harness = { gates: undefined as never, prompts: [], asked: [], answer: { approved: true }, shared: true, now: T0, badge: [] }; + 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", body: "Lunch?" } }; + case "watch": + return { ok: true, result: op.rooms.map((r: { roomId: string }) => ({ roomId: r.roomId, armed: op.cancel !== true })) }; + default: + return { ok: true, result: { did: op.op } }; + } + }, + canReach: async () => true, + loadGrants: async () => + h.shared + ? [ROOM, ROOM2].map((roomId) => ({ + origin: PORTAL, + hostDid: HOST, + vtaDid: VTA, + roomId, + member: MEMBER, + grantedAt: T0 - 1000, + expiresAt: T0 + 30 * 86_400_000, + })) + : [], + saveGrants: async () => undefined, + prompt: async (view) => { + h.prompts.push(view); + return h.answer; + }, + openTransfer: async () => new FakePort(), + now: () => h.now, + setTimer: (fn, ms) => { + const t = setTimeout(fn, Math.min(ms, 5)); + (t as { unref?: () => void }).unref?.(); + return t; + }, + sessionsChanged: (rows) => void h.badge.push(rows), + }; + h.gates = new RoomPageGates(deps); + return h; +} + +/** The room open in `session`: a watch port held, as a room page holds one. */ +async function openRoom(h: Harness, session: PageSession = TAB, roomId = ROOM): Promise { + const port = new FakePort(); + h.gates.serveWatchPort(port, PORTAL, session); + port.receive({ kind: "watch", hostDid: HOST, roomId }); + await sleep(30); + return port; +} + +const message = (h: Harness, session: PageSession | undefined = TAB, body = "hello", roomId = ROOM) => + h.gates.handle(PORTAL, { op: "putMessage", hostDid: HOST, roomId, body }, session); +const react = (h: Harness, session: PageSession | undefined = TAB, op: "react" | "unreact" = "react") => + h.gates.handle(PORTAL, { op, hostDid: HOST, roomId: ROOM, key: "m1", value: "👍" }, session); +const note = (h: Harness, session: PageSession = TAB) => + h.gates.handle(PORTAL, { op: "putNote", hostDid: HOST, roomId: ROOM, title: "Minutes", body: "…" }, session); +const offered = (h: Harness, i = -1) => ((h.prompts.at(i) as RoomWriteConsentView).what as { session?: unknown }).session; + +/** Open the room in TAB and grant a session through a message's confirm. */ +async function granted(h: Harness): Promise { + const port = await openRoom(h); + h.answer = { approved: true, sessionGrant: true }; + assert.ok((await message(h)).ok); + h.answer = { approved: true }; + assert.equal(h.gates.sessions.list().length, 1); + return port; +} + +test("the box is offered only while the asking document holds the room open", async () => { + const h = harness(); + await message(h); + assert.equal(offered(h), undefined, "no watch port: nothing would end it"); + await message(h, undefined); + assert.equal(offered(h), undefined, "a call with no document"); + await openRoom(h); + await message(h); + assert.deepEqual(offered(h), {}); + await react(h); + assert.deepEqual(offered(h), {}, "a reaction's confirm offers it too, beside the 30-minute reaction box"); + assert.ok(((h.prompts.at(-1) as RoomWriteConsentView).what as { grant?: unknown }).grant); +}); + +test("only the explicit box grants: approving without it keeps every message confirmed", async () => { + const h = harness(); + await openRoom(h); + assert.ok((await message(h)).ok); + assert.ok((await message(h)).ok); + assert.equal(h.prompts.length, 2); + assert.equal(h.gates.sessions.list().length, 0); + // A denial with the box ticked grants nothing. + h.answer = { approved: false, sessionGrant: true }; + assert.equal(((await message(h)) as { code?: string }).code, "declined"); + assert.equal(h.gates.sessions.list().length, 0); + // The consent window passes the box only with an approval. + const got: unknown[][] = []; + deliverConsentResult(new Map([["c1", (...a) => void got.push(a)]]), { + consentId: "c1", + approved: false, + sessionGrant: true, + }); + deliverConsentResult(new Map([["c2", (...a) => void got.push(a)]]), { + consentId: "c2", + approved: true, + sessionGrant: true, + }); + assert.equal(got[0]![8], false); + assert.equal(got[1]![8], true); +}); + +test("while it is live, messages, replies and reactions run without a window — and notes are still asked", async () => { + const h = harness(); + await granted(h); + const before = h.prompts.length; + assert.ok((await message(h, TAB, "second")).ok); + assert.ok((await h.gates.handle(PORTAL, { op: "putMessage", hostDid: HOST, roomId: ROOM, body: "re", replyTo: { key: "m1" } }, TAB)).ok); + assert.ok((await react(h)).ok); + assert.ok((await react(h, TAB, "unreact")).ok); + assert.equal(h.prompts.length, before, "no window"); + // Every write still goes as the share's member. + assert.ok(h.asked.filter((a) => ["putMessage", "react", "unreact"].includes(a.op)).every((a) => a.member === MEMBER)); + await note(h); + assert.equal(h.prompts.length, before + 1, "a note is always confirmed"); +}); + +test("another room, another member, another tab or the same tab reloaded asks again", async () => { + const h = harness(); + await granted(h); + await openRoom(h, TAB, ROOM2); + const n = h.prompts.length; + await message(h, TAB, "x", ROOM2); + assert.equal(h.prompts.length, n + 1, "another room"); + await message(h, { tabId: 8, documentId: "DOC-B" }); + assert.equal(h.prompts.length, n + 2, "another tab"); + await message(h, { tabId: 7, documentId: "DOC-A2" }); + assert.equal(h.prompts.length, n + 3, "the same tab reloaded: a new document"); + // Another member, origin or community is another scope. + const s = new RoomSessionGrants(() => T0); + s.roomOpened(TAB, PORTAL, HOST, ROOM); + const scope = { origin: PORTAL, hostDid: HOST, vtaDid: VTA, roomId: ROOM, member: MEMBER }; + assert.ok(s.grant(scope, TAB)); + assert.equal(s.cover(scope, TAB), "covered"); + assert.equal(s.cover({ ...scope, member: "did:webvh:QmBob:people.example" }, TAB), "none"); + assert.equal(s.cover({ ...scope, origin: "https://elsewhere.example" }, TAB), "none"); + assert.equal(s.cover({ ...scope, vtaDid: "did:key:zOther" }, TAB), "none"); +}); + +test("leaving the room — the watch port closing — ends it", async () => { + const h = harness(); + const port = await granted(h); + port.disconnect(); + await message(h, TAB, "after"); + assert.equal(h.gates.sessions.list().length, 0); + assert.equal(offered(h), undefined, "and with the room closed, nothing is offered"); +}); + +test("two ports for one room in one document: the grant lives until the last closes", async () => { + const h = harness(); + const a = await granted(h); + const b = await openRoom(h); + a.disconnect(); + assert.equal(h.gates.sessions.list().length, 1); + b.disconnect(); + assert.equal(h.gates.sessions.list().length, 0); +}); + +test("the tab closing, a lock, Stop, or the share going each end it", async () => { + for (const end of ["tab", "lock", "stop", "share"] as const) { + const h = harness(); + await granted(h); + if (end === "tab") h.gates.sessions.endForTab(TAB.tabId); + if (end === "lock") h.gates.sessions.endAll(); + if (end === "stop") assert.ok(h.gates.sessions.stop(h.gates.sessions.list()[0]!.id)); + if (end === "share") { + h.shared = false; + await h.gates.reviewSessionGrants(); + } + assert.equal(h.gates.sessions.list().length, 0, end); + } +}); + +test("30 minutes without a write ends it; use keeps it, but never past 8 hours", async () => { + const h = harness(); + await granted(h); + h.now = T0 + SESSION_GRANT_IDLE_MS - 1000; + const n = h.prompts.length; + assert.ok((await message(h)).ok); + assert.equal(h.prompts.length, n, "still live just inside the idle limit"); + h.now += SESSION_GRANT_IDLE_MS; + await message(h); + assert.equal(h.prompts.length, n + 1, "idle: asked again"); + + const k = harness(); + await granted(k); + // A write every 20 minutes keeps it from idling, up to the cap. + for (let t = 20 * 60_000; t < SESSION_GRANT_CAP_MS; t += 20 * 60_000) { + k.now = T0 + t; + await message(k); + } + const m = k.prompts.length; + k.now = T0 + SESSION_GRANT_CAP_MS; + await message(k); + assert.equal(k.prompts.length, m + 1, "8 hours: asked again, however used"); +}); + +test("more than the rate in a minute, or a long message, is asked for — and the grant stays", async () => { + const h = harness(); + await granted(h); // the granting message counts as one + const n = h.prompts.length; + for (let i = 1; i < SESSION_GRANT_RATE_LIMIT; i++) await message(h, TAB, `m${i}`); + assert.equal(h.prompts.length, n); + await message(h, TAB, "one too many"); + assert.equal(h.prompts.length, n + 1); + h.now += 61_000; + await message(h, TAB, "a minute later"); + assert.equal(h.prompts.length, n + 1, "covered again"); + await message(h, TAB, "x".repeat(SESSION_MESSAGE_MAX_CHARS + 1)); + assert.equal(h.prompts.length, n + 2, "a long message is confirmed"); + assert.equal(h.gates.sessions.list().length, 1); +}); + +test("the badge is told when a grant starts and when it ends", async () => { + const h = harness(); + const port = await granted(h); + assert.equal(h.badge.at(-1)?.length, 1); + port.disconnect(); + assert.equal(h.badge.at(-1)?.length, 0); +}); + +test("a grant is refused for a document that does not hold the room open", () => { + const s = new RoomSessionGrants(() => T0); + const scope = { origin: PORTAL, hostDid: HOST, vtaDid: VTA, roomId: ROOM, member: MEMBER }; + assert.equal(s.grant(scope, TAB), false); + assert.equal(s.list().length, 0); +});