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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <room> 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
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down
82 changes: 76 additions & 6 deletions packages/extension/src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -71,6 +72,7 @@ import {
mergeRoomNames,
roomNamesKey,
ROOM_CONSENT_PREFIX,
ROOM_GRANTS_PREFIX,
type RoomGrant,
type RoomShareConsentView,
type RoomWriteConsentView,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -815,15 +820,36 @@ async function ensureOffscreenDocument(): Promise<void> {
// 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<void> {
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) {
await chrome.action.setBadgeText({ text: String(waiting) });
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
Expand Down Expand Up @@ -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);
Expand All @@ -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" });
});
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions packages/extension/src/bridge-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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 }
Expand Down
3 changes: 2 additions & 1 deletion packages/extension/src/confirm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1488,12 +1488,13 @@ if (root) {
) : isRoomConsent ? (
<RoomConsent
consentId={consentId}
decide={(ok, rooms, reactionGrant) =>
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 } : {}),
})
}
/>
Expand Down
3 changes: 3 additions & 0 deletions packages/extension/src/consent-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -166,6 +167,7 @@ export function deliverConsentResult(
selectedCredential?: string;
ballot?: unknown;
reactionGrant?: boolean;
sessionGrant?: boolean;
},
): boolean {
const decision = pending.get(result.consentId);
Expand All @@ -188,6 +190,7 @@ export function deliverConsentResult(
credential,
ballot,
result.approved && result.reactionGrant === true,
result.approved && result.sessionGrant === true,
);
return true;
}
14 changes: 13 additions & 1 deletion packages/extension/src/manager/panes/rooms-communities.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand Down Expand Up @@ -233,8 +233,20 @@ function websiteStep(row: LaneRow, shares: RoomSharesState): Step {
</span>,
]
: [];
const live = sessionFor(shares.sessions, s.grant);
const session = live
? [
<span>
Sends without asking while open ·{" "}
<button onClick={() => void shares.stopSession(live.id)} style={linkButton}>
Stop
</button>
</span>,
]
: [];
return [
`${host(s.grant.origin)} · until ${new Date(s.grant.expiresAt).toLocaleDateString()}`,
...session,
...reactions,
<button onClick={() => void shares.revoke(s)} style={linkButton}>
Stop sharing
Expand Down
Loading